gt stringclasses 1
value | context stringlengths 2.05k 161k |
|---|---|
/**
* Copyright (C) 2009-2016 Dell, Inc.
* See annotations for authorship information
*
* ====================================================================
* 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.dasein.cloud.network;
import org.dasein.cloud.*;
import org.dasein.cloud.compute.ComputeServices;
import org.dasein.cloud.compute.VirtualMachine;
import org.dasein.cloud.compute.VirtualMachineSupport;
import org.dasein.cloud.identity.ServiceAction;
import org.dasein.cloud.util.TagUtils;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
/**
* Provides baseline support for functionality that is common among implementations, in particular for deprecated methods.
* <p>Created by George Reese: 1/29/13 9:56 AM</p>
* @author George Reese
* @version 2013.04
* @since 2013.04
*/
public abstract class AbstractVLANSupport<T extends CloudProvider> extends AbstractProviderService<T> implements VLANSupport {
protected AbstractVLANSupport(T provider) {
super(provider);
}
@Override
public Route addRouteToAddress(@Nonnull String routingTableId, @Nonnull IPVersion version, @Nullable String destinationCidr, @Nonnull String address) throws CloudException, InternalException {
throw new OperationNotSupportedException("Routing tables are not currently implemented for " + getProvider().getCloudName());
}
@Override
public Route addRouteToGateway(@Nonnull String routingTableId, @Nonnull IPVersion version, @Nullable String destinationCidr, @Nonnull String gatewayId) throws CloudException, InternalException {
throw new OperationNotSupportedException("Routing tables are not currently implemented for " + getProvider().getCloudName());
}
@Override
public Route addRouteToNetworkInterface(@Nonnull String routingTableId, @Nonnull IPVersion version, @Nullable String destinationCidr, @Nonnull String nicId) throws CloudException, InternalException {
throw new OperationNotSupportedException("Routing tables are not currently implemented for " + getProvider().getCloudName());
}
@Override
public Route addRouteToVirtualMachine(@Nonnull String routingTableId, @Nonnull IPVersion version, @Nullable String destinationCidr, @Nonnull String vmId) throws CloudException, InternalException {
throw new OperationNotSupportedException("Routing tables are not currently implemented for " + getProvider().getCloudName());
}
@Override
public void assignRoutingTableToSubnet(@Nonnull String subnetId, @Nonnull String routingTableId) throws CloudException, InternalException {
throw new OperationNotSupportedException("Routing tables are not currently implemented for " + getProvider().getCloudName());
}
@Override
public void disassociateRoutingTableFromSubnet(@Nonnull String subnetId, @Nonnull String routingTableId) throws CloudException, InternalException {
throw new OperationNotSupportedException("Routing tables are not currently implemented for " + getProvider().getCloudName());
}
@Override
public void assignRoutingTableToVlan(@Nonnull String vlanId, @Nonnull String routingTableId) throws CloudException, InternalException {
throw new OperationNotSupportedException("Routing tables are not currently implemented for " + getProvider().getCloudName());
}
@Override
public void attachNetworkInterface(@Nonnull String nicId, @Nonnull String vmId, int index) throws CloudException, InternalException {
throw new OperationNotSupportedException("Network interfaces are not currently implemented for " + getProvider().getCloudName());
}
@Override
public String createInternetGateway(@Nonnull String vlanId) throws CloudException, InternalException {
throw new OperationNotSupportedException("Internet gateways are not currently implemented for " + getProvider().getCloudName());
}
@Override
public @Nonnull String createRoutingTable(@Nonnull String vlanId, @Nonnull String name, @Nonnull String description) throws CloudException, InternalException {
throw new OperationNotSupportedException("Routing tables are not currently implemented for " + getProvider().getCloudName());
}
@Override
public @Nonnull NetworkInterface createNetworkInterface(@Nonnull NICCreateOptions options) throws CloudException, InternalException {
throw new OperationNotSupportedException("Network interfaces are not currently implemented for " + getProvider().getCloudName());
}
@Override
public @Nonnull Subnet createSubnet(@Nonnull SubnetCreateOptions options) throws CloudException, InternalException {
throw new OperationNotSupportedException("Subnets are not currently implemented for " + getProvider().getCloudName());
}
@Override
public @Nonnull VLAN createVlan(@Nonnull String cidr, @Nonnull String name, @Nonnull String description, @Nonnull String domainName, @Nonnull String[] dnsServers, @Nonnull String[] ntpServers) throws CloudException, InternalException {
throw new OperationNotSupportedException("VLANs are not currently implemented for " + getProvider().getCloudName());
}
@Override
public @Nonnull VLAN createVlan(@Nonnull VlanCreateOptions vco) throws CloudException, InternalException {
throw new OperationNotSupportedException("VLANs are not currently implemented for " + getProvider().getCloudName());
}
@Override
public void detachNetworkInterface(@Nonnull String nicId) throws CloudException, InternalException {
throw new OperationNotSupportedException("Network interfaces are not currently implemented for " + getProvider().getCloudName());
}
@Override
public NetworkInterface getNetworkInterface(@Nonnull String nicId) throws CloudException, InternalException {
for( NetworkInterface nic : listNetworkInterfaces() ) {
if( nicId.equals(nic.getProviderNetworkInterfaceId()) ) {
return nic;
}
}
return null;
}
@Override
public RoutingTable getRoutingTableForSubnet(@Nonnull String subnetId) throws CloudException, InternalException {
return null;
}
@Override
public RoutingTable getRoutingTableForVlan(@Nonnull String vlanId) throws CloudException, InternalException {
return null;
}
@Override
public RoutingTable getRoutingTable(@Nonnull String id) throws CloudException, InternalException {
return null;
}
@Override
public Subnet getSubnet(@Nonnull String subnetId) throws CloudException, InternalException {
for( VLAN vlan : listVlans() ) {
for( Subnet subnet : listSubnets(vlan.getProviderVlanId()) ) {
if( subnet.getProviderSubnetId().equals(subnetId) ) {
return subnet;
}
}
}
return null;
}
@Override
public VLAN getVlan(@Nonnull String vlanId) throws CloudException, InternalException {
for( VLAN vlan : listVlans() ) {
if( vlan.getProviderVlanId().equals(vlanId) ) {
return vlan;
}
}
return null;
}
@Override
public boolean isConnectedViaInternetGateway(@Nonnull String vlanId) throws CloudException, InternalException {
return false;
}
@Override
public @Nonnull Iterable<String> listFirewallIdsForNIC(@Nonnull String nicId) throws CloudException, InternalException {
return Collections.emptyList();
}
@Override
public @Nonnull Iterable<ResourceStatus> listNetworkInterfaceStatus() throws CloudException, InternalException {
List<ResourceStatus> status = new ArrayList<ResourceStatus>();
for( NetworkInterface nic : listNetworkInterfaces() ) {
status.add(new ResourceStatus(nic.getProviderNetworkInterfaceId(), nic.getCurrentState()));
}
return status;
}
@Override
public @Nonnull Iterable<NetworkInterface> listNetworkInterfaces() throws CloudException, InternalException {
return Collections.emptyList();
}
@Override
public @Nonnull Iterable<NetworkInterface> listNetworkInterfacesForVM(@Nonnull String forVmId) throws CloudException, InternalException {
List<NetworkInterface> nics = new ArrayList<NetworkInterface>();
for( NetworkInterface nic : listNetworkInterfaces() ) {
if( forVmId.equals(nic.getProviderVirtualMachineId()) ) {
nics.add(nic);
}
}
return nics;
}
@Override
public @Nonnull Iterable<NetworkInterface> listNetworkInterfacesInSubnet(@Nonnull String subnetId) throws CloudException, InternalException {
List<NetworkInterface> nics = new ArrayList<NetworkInterface>();
for( NetworkInterface nic : listNetworkInterfaces() ) {
if( subnetId.equals(nic.getProviderSubnetId()) ) {
nics.add(nic);
}
}
return nics;
}
@Override
public @Nonnull Iterable<NetworkInterface> listNetworkInterfacesInVLAN(@Nonnull String vlanId) throws CloudException, InternalException {
List<NetworkInterface> nics = new ArrayList<NetworkInterface>();
for( NetworkInterface nic : listNetworkInterfaces() ) {
if( vlanId.equals(nic.getProviderVlanId()) ) {
nics.add(nic);
}
}
return nics;
}
@Override
public @Nonnull Iterable<Networkable> listResources(@Nonnull String inVlanId) throws CloudException, InternalException {
List<Networkable> resources = new ArrayList<Networkable>();
NetworkServices network = getProvider().getNetworkServices();
if( network != null ) {
FirewallSupport fwSupport = network.getFirewallSupport();
if( fwSupport != null ) {
for( Firewall fw : fwSupport.list() ) {
if( inVlanId.equals(fw.getProviderVlanId()) ) {
resources.add(fw);
}
}
}
IpAddressSupport ipSupport = network.getIpAddressSupport();
if( ipSupport != null ) {
for( IPVersion version : ipSupport.getCapabilities().listSupportedIPVersions() ) {
for( IpAddress addr : ipSupport.listIpPool(version, false) ) {
if( inVlanId.equals(addr.getProviderVlanId()) ) {
resources.add(addr);
}
}
}
}
for( RoutingTable table : listRoutingTablesForVlan(inVlanId) ) {
resources.add(table);
}
ComputeServices compute = getProvider().getComputeServices();
VirtualMachineSupport vmSupport = compute == null ? null : compute.getVirtualMachineSupport();
Iterable<VirtualMachine> vms;
if( vmSupport == null ) {
vms = Collections.emptyList();
}
else {
vms = vmSupport.listVirtualMachines();
}
for( Subnet subnet : listSubnets(inVlanId) ) {
resources.add(subnet);
for( VirtualMachine vm : vms ) {
if( subnet.getProviderSubnetId().equals(vm.getProviderVlanId()) ) {
resources.add(vm);
}
}
}
}
return resources;
}
@Override
public @Nonnull Iterable<RoutingTable> listRoutingTablesForSubnet(@Nonnull String subnetId) throws CloudException, InternalException {
return Collections.emptyList();
}
@Override
public @Nonnull Iterable<RoutingTable> listRoutingTablesForVlan(@Nonnull String vlanId) throws CloudException, InternalException {
return Collections.emptyList();
}
@Override
public @Nonnull Iterable<Subnet> listSubnets(@Nullable String vlanId) throws CloudException, InternalException {
return Collections.emptyList();
}
@Override
public @Nonnull Iterable<ResourceStatus> listVlanStatus() throws CloudException, InternalException {
List<ResourceStatus> status = new ArrayList<ResourceStatus>();
for( VLAN vlan : listVlans() ) {
status.add(new ResourceStatus(vlan.getProviderVlanId(), vlan.getCurrentState()));
}
return status;
}
@Override
public @Nonnull Iterable<VLAN> listVlans() throws CloudException, InternalException {
return Collections.emptyList();
}
@Override
public @Nonnull String[] mapServiceAction(@Nonnull ServiceAction action) {
return new String[0];
}
@Override
public void removeInternetGateway(@Nonnull String vlanId) throws CloudException, InternalException {
throw new OperationNotSupportedException("Internet gateways are not currently implemented for " + getProvider().getCloudName());
}
@Override
public void removeNetworkInterface(@Nonnull String nicId) throws CloudException, InternalException {
throw new OperationNotSupportedException("Network interfaces are not currently implemented for " + getProvider().getCloudName());
}
@Override
public void removeRoute(@Nonnull String routingTableId, @Nonnull String destinationCidr) throws CloudException, InternalException {
throw new OperationNotSupportedException("Routing tables are not currently implemented for " + getProvider().getCloudName());
}
@Override
public void removeRoutingTable(@Nonnull String routingTableId) throws CloudException, InternalException {
throw new OperationNotSupportedException("Routing tables are not currently implemented for " + getProvider().getCloudName());
}
@Override
public void removeSubnet(String providerSubnetId) throws CloudException, InternalException {
throw new OperationNotSupportedException("Subnets are not currently implemented for " + getProvider().getCloudName());
}
@Override
public void removeVlan(String vlanId) throws CloudException, InternalException {
throw new OperationNotSupportedException("VLANs are not currently implemented for " + getProvider().getCloudName());
}
@Override
public void removeSubnetTags(@Nonnull String subnetId, @Nonnull Tag... tags) throws CloudException, InternalException {
// NO-OP
}
@Override
public void removeSubnetTags(@Nonnull String[] subnetIds, @Nonnull Tag... tags) throws CloudException, InternalException {
for( String id : subnetIds ) {
removeSubnetTags(id, tags);
}
}
@Override
public void removeVLANTags(@Nonnull String vlanId, @Nonnull Tag... tags) throws CloudException, InternalException {
// NO-OP
}
@Override
public void removeVLANTags(@Nonnull String[] vlanIds, @Nonnull Tag... tags) throws CloudException, InternalException {
for( String id : vlanIds ) {
removeVLANTags(id, tags);
}
}
@Override
public void updateRoutingTableTags(@Nonnull String routingTableId, @Nonnull Tag... tags) throws CloudException, InternalException{
throw new OperationNotSupportedException("Routing table tags are not supported in " + getProvider().getCloudName());
}
@Override
public void updateSubnetTags(@Nonnull String subnetId, @Nonnull Tag... tags) throws CloudException, InternalException {
// NO-OP
}
@Override
public void updateSubnetTags(@Nonnull String[] subnetIds, @Nonnull Tag... tags) throws CloudException, InternalException {
for( String id : subnetIds ) {
updateSubnetTags(id, tags);
}
}
@Override
public void updateVLANTags(@Nonnull String vlanId, @Nonnull Tag... tags) throws CloudException, InternalException {
// NO-OP
}
@Override
public void updateVLANTags(@Nonnull String[] vlanIds, @Nonnull Tag... tags) throws CloudException, InternalException {
for( String id : vlanIds ) {
updateVLANTags(id, tags);
}
}
@Override
public void updateInternetGatewayTags( @Nonnull String internetGatewayId, @Nonnull Tag... tags ) throws CloudException, InternalException {
throw new OperationNotSupportedException("Internet gateway tags are not supported in " + getProvider().getCloudName());
}
@Override
public void updateInternetGatewayTags(@Nonnull String[] internetGatewayIds, @Nonnull Tag... tags) throws CloudException, InternalException {
for (String internetGatewayId : internetGatewayIds) {
updateInternetGatewayTags(internetGatewayId, tags);
}
}
@Override
public void updateRoutingTableTags(@Nonnull String[] routingTableIds, @Nonnull Tag... tags) throws CloudException, InternalException {
for (String routingTableId : routingTableIds) {
updateRoutingTableTags(routingTableId, tags);
}
}
@Override
public void removeRoutingTableTags(@Nonnull String[] routingTableIds, @Nonnull Tag... tags) throws CloudException, InternalException {
for (String routingTableId : routingTableIds) {
removeRoutingTableTags(routingTableId, tags);
}
}
@Override
public void removeInternetGatewayTags(@Nonnull String internetGatewayId, @Nonnull Tag... tags) throws CloudException, InternalException{
throw new OperationNotSupportedException("Internet Gateway tags are not supported in " + getProvider().getCloudName());
}
@Override
public void removeInternetGatewayTags(@Nonnull String[] internetGatewayIds, @Nonnull Tag... tags) throws CloudException, InternalException {
for (String internetGatewayId : internetGatewayIds) {
removeInternetGatewayTags(internetGatewayId, tags);
}
}
@Override
public void setSubnetTags( @Nonnull String[] subnetIds, @Nonnull Tag... tags ) throws CloudException, InternalException {
for( String id : subnetIds ) {
Tag[] collectionForDelete = TagUtils.getTagsForDelete(getSubnet(id).getTags(), tags);
if( collectionForDelete.length != 0 ) {
removeSubnetTags(id, collectionForDelete);
}
updateSubnetTags(id, tags);
}
}
@Override
public void setRoutingTableTags( @Nonnull String[] routingTableIds, @Nonnull Tag... tags ) throws CloudException, InternalException {
for( String id : routingTableIds ) {
Tag[] collectionForDelete = TagUtils.getTagsForDelete(getRoutingTable(id).getTags(), tags);
if( collectionForDelete.length != 0 ) {
removeRoutingTableTags(id, collectionForDelete);
}
updateRoutingTableTags(id, tags);
}
}
@Override
public void setInternetGatewayTags( @Nonnull String[] internetGatewayIds, @Nonnull Tag... tags ) throws CloudException, InternalException {
for( String id : internetGatewayIds ) {
Tag[] collectionForDelete = TagUtils.getTagsForDelete(getInternetGatewayById(id).getTags(), tags);
if( collectionForDelete.length != 0 ) {
removeInternetGatewayTags(id, collectionForDelete);
}
updateInternetGatewayTags(id, tags);
}
}
@Override
public void setVLANTags( @Nonnull String[] vlanIds, @Nonnull Tag... tags ) throws CloudException, InternalException {
for( String id : vlanIds ) {
Tag[] collectionForDelete = TagUtils.getTagsForDelete(getVlan(id).getTags(), tags);
if( collectionForDelete.length != 0 ) {
removeVLANTags(id, collectionForDelete);
}
updateVLANTags(id, tags);
}
}
@Override
public void setVLANTags( @Nonnull String vlanId, @Nonnull Tag... tags ) throws CloudException, InternalException {
setVLANTags(new String[]{vlanId}, tags);
}
@Override
public void setSubnetTags( @Nonnull String subnetId, @Nonnull Tag... tags ) throws CloudException, InternalException {
setSubnetTags(new String[]{subnetId}, tags);
}
@Override
public void setRoutingTableTags( @Nonnull String routingTableId, @Nonnull Tag... tags ) throws CloudException, InternalException {
setRoutingTableTags(new String[]{routingTableId}, tags);
}
@Override
public void setInternetGatewayTags( @Nonnull String internetGatewayId, @Nonnull Tag... tags ) throws CloudException, InternalException {
setInternetGatewayTags(new String[]{internetGatewayId}, tags);
}
public void removeRoutingTableTags(@Nonnull String routingTableId, @Nonnull Tag... tags) throws CloudException, InternalException{
throw new OperationNotSupportedException("Routing table tags are not supported in " + getProvider().getCloudName());
}
@Override
public void removeInternetGatewayById( @Nonnull String id ) throws CloudException, InternalException {
throw new OperationNotSupportedException("Internet gateways are not currently implemented for " + getProvider().getCloudName());
}
@Override
public @Nonnull Iterable<InternetGateway> listInternetGateways( @Nullable String vlanId ) throws CloudException, InternalException {
throw new OperationNotSupportedException("Internet gateways are not currently implemented for " + getProvider().getCloudName());
}
@Override
public @Nullable InternetGateway getInternetGatewayById( @Nonnull String gatewayId ) throws CloudException, InternalException {
throw new OperationNotSupportedException("Internet gateways are not currently implemented for " + getProvider().getCloudName());
}
@Override
public @Nullable String getAttachedInternetGatewayId( @Nonnull String vlanId ) throws CloudException, InternalException {
throw new OperationNotSupportedException("Internet gateways are not currently implemented for " + getProvider().getCloudName());
}
}
| |
/**
* 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.joshua.tools;
import static org.apache.joshua.decoder.ff.tm.packed.PackedGrammar.VOCABULARY_FILENAME;
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.TreeMap;
import org.apache.joshua.corpus.Vocabulary;
import org.apache.joshua.decoder.ff.tm.Rule;
import org.apache.joshua.decoder.ff.tm.format.HieroFormatReader;
import org.apache.joshua.decoder.ff.tm.format.MosesFormatReader;
import org.apache.joshua.util.FormatUtils;
import org.apache.joshua.util.encoding.EncoderConfiguration;
import org.apache.joshua.util.encoding.FeatureTypeAnalyzer;
import org.apache.joshua.util.encoding.IntEncoder;
import org.apache.joshua.util.io.LineReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class GrammarPacker {
private static final Logger LOG = LoggerFactory.getLogger(GrammarPacker.class);
/**
* The packed grammar version number. Increment this any time you add new features, and update
* the documentation.
*
* Version history:
*
* - 2. The default version.
*
* - 3 (May 2016). This was the first version that was marked. It removed the special phrase-
* table packing that packed phrases without the [X,1] on the source and target sides, which
* then required special handling in the decoder to use for phrase-based decoding. So in this
* version, [X,1] is required to be presented on the source and target sides, and phrase-based
* decoding is implemented as a left-branching grammar.
*
* - 4 (August 2016). Phrase-based decoding was rewritten to represent phrases without a builtin
* nonterminal. Instead, cost-less glue rules are used in phrase-based decoding. This eliminates
* the need for special handling of phrase grammars (except for having to add a LHS), and lets
* phrase grammars be used in both hierarchical and phrase-based decoding without conversion.
*
*/
public static final int VERSION = 4;
// Size limit for slice in bytes.
private static final int DATA_SIZE_LIMIT = (int) (Integer.MAX_VALUE * 0.8);
// Estimated average number of feature entries for one rule.
private static final int DATA_SIZE_ESTIMATE = 20;
private static final String SOURCE_WORDS_SEPARATOR = " ||| ";
// Output directory name.
private final String output;
// Input grammar to be packed.
private final String grammar;
public String getGrammar() {
return grammar;
}
public String getOutputDirectory() {
return output;
}
// Approximate maximum size of a slice in number of rules
private int approximateMaximumSliceSize;
private final boolean labeled;
private final boolean packAlignments;
private final boolean grammarAlignments;
private final String alignments;
private final FeatureTypeAnalyzer types;
private EncoderConfiguration encoderConfig;
private final String dump;
private int max_source_len;
public GrammarPacker(String grammar_filename, String config_filename, String output_filename,
String alignments_filename, String featuredump_filename, boolean grammar_alignments,
int approximateMaximumSliceSize)
throws IOException {
this.labeled = true;
this.grammar = grammar_filename;
this.output = output_filename;
this.dump = featuredump_filename;
this.grammarAlignments = grammar_alignments;
this.approximateMaximumSliceSize = approximateMaximumSliceSize;
this.max_source_len = 0;
// TODO: Always open encoder config? This is debatable.
this.types = new FeatureTypeAnalyzer(true);
this.alignments = alignments_filename;
packAlignments = grammarAlignments || (alignments != null);
if (!packAlignments) {
LOG.info("No alignments file or grammar specified, skipping.");
} else if (alignments != null && !new File(alignments_filename).exists()) {
throw new RuntimeException("Alignments file does not exist: " + alignments);
}
if (config_filename != null) {
readConfig(config_filename);
types.readConfig(config_filename);
} else {
LOG.info("No config specified. Attempting auto-detection of feature types.");
}
LOG.info("Approximate maximum slice size (in # of rules) set to {}", approximateMaximumSliceSize);
File working_dir = new File(output);
working_dir.mkdir();
if (!working_dir.exists()) {
throw new RuntimeException("Failed creating output directory.");
}
}
private void readConfig(String config_filename) throws IOException {
try(LineReader reader = new LineReader(config_filename)) {
while (reader.hasNext()) {
// Clean up line, chop comments off and skip if the result is empty.
String line = reader.next().trim();
if (line.indexOf('#') != -1)
line = line.substring(0, line.indexOf('#'));
if (line.isEmpty())
continue;
String[] fields = line.split("[\\s]+");
if (fields.length < 2) {
throw new RuntimeException("Incomplete line in config.");
}
if ("slice_size".equals(fields[0])) {
// Number of records to concurrently load into memory for sorting.
approximateMaximumSliceSize = Integer.parseInt(fields[1]);
}
}
}
}
/**
* Executes the packing.
*
* @throws IOException if there is an error reading the grammar
*/
public void pack() throws IOException {
LOG.info("Beginning exploration pass.");
// Explore pass. Learn vocabulary and feature value histograms.
LOG.info("Exploring: {}", grammar);
HieroFormatReader grammarReader = getGrammarReader();
explore(grammarReader);
LOG.info("Exploration pass complete. Freezing vocabulary and finalizing encoders.");
if (dump != null) {
PrintWriter dump_writer = new PrintWriter(dump);
dump_writer.println(types.toString());
dump_writer.close();
}
types.inferTypes(this.labeled);
LOG.info("Type inference complete.");
LOG.info("Finalizing encoding.");
LOG.info("Writing encoding.");
types.write(output + File.separator + "encoding");
writeVocabulary();
String configFile = output + File.separator + "config";
LOG.info("Writing config to '{}'", configFile);
// Write config options
FileWriter config = new FileWriter(configFile);
config.write(String.format("version = %d\n", VERSION));
config.write(String.format("max-source-len = %d\n", max_source_len));
config.close();
// Read previously written encoder configuration to match up to changed
// vocabulary id's.
LOG.info("Reading encoding.");
encoderConfig = new EncoderConfiguration();
encoderConfig.load(output + File.separator + "encoding");
LOG.info("Beginning packing pass.");
// Actual binarization pass. Slice and pack source, target and data.
grammarReader = getGrammarReader();
LineReader alignment_reader = null;
if (packAlignments && !grammarAlignments)
alignment_reader = new LineReader(alignments);
binarize(grammarReader, alignment_reader);
LOG.info("Packing complete.");
LOG.info("Packed grammar in: {}", output);
LOG.info("Done.");
}
/**
* Returns a reader that turns whatever file format is found into Hiero grammar rules.
*
* @return a Hiero format reader
* @throws IOException
*/
private HieroFormatReader getGrammarReader() throws IOException {
try (LineReader reader = new LineReader(grammar)) {
String line = reader.next();
if (line.startsWith("[")) {
return new HieroFormatReader(grammar);
} else {
return new MosesFormatReader(grammar);
}
}
}
/**
* This first pass over the grammar
* @param reader the Hiero format reader
*/
private void explore(HieroFormatReader reader) {
// We always assume a labeled grammar. Unlabeled features are assumed to be dense and to always
// appear in the same order. They are assigned numeric names in order of appearance.
this.types.setLabeled(true);
for (Rule rule: reader) {
max_source_len = Math.max(max_source_len, rule.getFrench().length);
/* Add symbols to vocabulary.
* NOTE: In case of nonterminals, we add both stripped versions ("[X]")
* and "[X,1]" to the vocabulary.
*
* TODO: MJP May 2016: Is it necessary to add [X,1]? This is currently being done in
* {@link HieroFormatReader}, which is called by {@link MosesFormatReader}.
*/
// Add feature names to vocabulary and pass the value through the
// appropriate encoder.
int feature_counter = 0;
String[] features = rule.getFeatureString().split("\\s+");
for (String feature : features) {
if (feature.contains("=")) {
String[] fe = feature.split("=");
if (fe[0].equals("Alignment"))
continue;
types.observe(Vocabulary.id(fe[0]), Float.parseFloat(fe[1]));
} else {
types
.observe(Vocabulary.id(String.valueOf(feature_counter++)), Float.parseFloat(feature));
}
}
}
}
/**
* Returns a String encoding the first two source words.
* If there is only one source word, use empty string for the second.
*/
private String getFirstTwoSourceWords(final String[] source_words) {
return source_words[0] + SOURCE_WORDS_SEPARATOR + ((source_words.length > 1) ? source_words[1] : "");
}
private void binarize(HieroFormatReader grammarReader, LineReader alignment_reader) throws IOException {
int counter = 0;
int slice_counter = 0;
int num_slices = 0;
boolean ready_to_flush = false;
// to determine when flushing is possible
String prev_first_two_source_words = null;
PackingTrie<SourceValue> source_trie = new PackingTrie<>();
PackingTrie<TargetValue> target_trie = new PackingTrie<>();
FeatureBuffer feature_buffer = new FeatureBuffer();
AlignmentBuffer alignment_buffer = null;
if (packAlignments)
alignment_buffer = new AlignmentBuffer();
TreeMap<Integer, Float> features = new TreeMap<>();
for (Rule rule: grammarReader) {
counter++;
slice_counter++;
String lhs_word = Vocabulary.word(rule.getLHS());
String[] source_words = rule.getFrenchWords().split("\\s+");
String[] target_words = rule.getEnglishWords().split("\\s+");
String[] feature_entries = rule.getFeatureString().split("\\s+");
// Reached slice limit size, indicate that we're closing up.
if (!ready_to_flush
&& (slice_counter > approximateMaximumSliceSize
|| feature_buffer.overflowing()
|| (packAlignments && alignment_buffer.overflowing()))) {
ready_to_flush = true;
// store the first two source words when slice size limit was reached
prev_first_two_source_words = getFirstTwoSourceWords(source_words);
}
// ready to flush
if (ready_to_flush) {
final String first_two_source_words = getFirstTwoSourceWords(source_words);
// the grammar can only be partitioned at the level of first two source word changes.
// Thus, we can only flush if the current first two source words differ from the ones
// when the slice size limit was reached.
if (!first_two_source_words.equals(prev_first_two_source_words)) {
LOG.warn("ready to flush and first two words have changed ({} vs. {})",
prev_first_two_source_words, first_two_source_words);
LOG.info("flushing {} rules to slice.", slice_counter);
flush(source_trie, target_trie, feature_buffer, alignment_buffer, num_slices);
source_trie.clear();
target_trie.clear();
feature_buffer.clear();
if (packAlignments)
alignment_buffer.clear();
num_slices++;
slice_counter = 0;
ready_to_flush = false;
}
}
int alignment_index = -1;
// If present, process alignments.
if (packAlignments) {
String alignment_line;
if (grammarAlignments) {
alignment_line = rule.getAlignmentString();
} else {
if (!alignment_reader.hasNext()) {
LOG.error("No more alignments starting in line {}", counter);
throw new RuntimeException("No more alignments starting in line " + counter);
}
alignment_line = alignment_reader.next().trim();
}
String[] alignment_entries = alignment_line.split("\\s");
byte[] alignments = new byte[alignment_entries.length * 2];
if (alignment_line.length() > 0) {
for (int i = 0; i < alignment_entries.length; i++) {
String[] parts = alignment_entries[i].split("-");
alignments[2 * i] = Byte.parseByte(parts[0]);
alignments[2 * i + 1] = Byte.parseByte(parts[1]);
}
}
alignment_index = alignment_buffer.add(alignments);
}
// Process features.
// Implicitly sort via TreeMap, write to data buffer, remember position
// to pass on to the source trie node.
features.clear();
int feature_count = 0;
for (String feature_entry : feature_entries) {
int feature_id;
float feature_value;
if (feature_entry.contains("=")) {
String[] parts = feature_entry.split("=");
if (parts[0].equals("Alignment"))
continue;
feature_id = Vocabulary.id(parts[0]);
feature_value = Float.parseFloat(parts[1]);
} else {
feature_id = Vocabulary.id(String.valueOf(feature_count++));
feature_value = Float.parseFloat(feature_entry);
}
if (feature_value != 0)
features.put(encoderConfig.innerId(feature_id), feature_value);
}
int features_index = feature_buffer.add(features);
// Sanity check on the data block index.
if (packAlignments && features_index != alignment_index) {
LOG.error("Block index mismatch between features ({}) and alignments ({}).",
features_index, alignment_index);
throw new RuntimeException("Data block index mismatch.");
}
// Process source side.
SourceValue sv = new SourceValue(Vocabulary.id(lhs_word), features_index);
int[] source = new int[source_words.length];
for (int i = 0; i < source_words.length; i++) {
if (FormatUtils.isNonterminal(source_words[i]))
source[i] = Vocabulary.id(FormatUtils.stripNonTerminalIndex(source_words[i]));
else
source[i] = Vocabulary.id(source_words[i]);
}
source_trie.add(source, sv);
// Process target side.
TargetValue tv = new TargetValue(sv);
int[] target = new int[target_words.length];
for (int i = 0; i < target_words.length; i++) {
if (FormatUtils.isNonterminal(target_words[i])) {
target[target_words.length - (i + 1)] = -FormatUtils.getNonterminalIndex(target_words[i]);
} else {
target[target_words.length - (i + 1)] = Vocabulary.id(target_words[i]);
}
}
target_trie.add(target, tv);
}
// flush last slice and clear buffers
flush(source_trie, target_trie, feature_buffer, alignment_buffer, num_slices);
}
/**
* Serializes the source, target and feature data structures into interlinked binary files. Target
* is written first, into a skeletal (node don't carry any data) upward-pointing trie, updating
* the linking source trie nodes with the position once it is known. Source and feature data are
* written simultaneously. The source structure is written into a downward-pointing trie and
* stores the rule's lhs as well as links to the target and feature stream. The feature stream is
* prompted to write out a block
*
* @param source_trie the source Trie
* @param target_trie the target Trie
* @param feature_buffer the feature buffer
* @param id the id of the piece of grammar to flush
* @throws IOException
*/
private void flush(PackingTrie<SourceValue> source_trie,
PackingTrie<TargetValue> target_trie, FeatureBuffer feature_buffer,
AlignmentBuffer alignment_buffer, int id) throws IOException {
// Make a slice object for this piece of the grammar.
PackingFileTuple slice = new PackingFileTuple("slice_" + String.format("%05d", id));
// Pull out the streams for source, target and data output.
DataOutputStream source_stream = slice.getSourceOutput();
DataOutputStream target_stream = slice.getTargetOutput();
DataOutputStream target_lookup_stream = slice.getTargetLookupOutput();
DataOutputStream feature_stream = slice.getFeatureOutput();
DataOutputStream alignment_stream = slice.getAlignmentOutput();
Queue<PackingTrie<TargetValue>> target_queue;
Queue<PackingTrie<SourceValue>> source_queue;
// The number of bytes both written into the source stream and
// buffered in the source queue.
int source_position;
// The number of bytes written into the target stream.
int target_position;
// Add trie root into queue, set target position to 0 and set cumulated
// size to size of trie root.
target_queue = new LinkedList<>();
target_queue.add(target_trie);
target_position = 0;
// Target lookup table for trie levels.
int current_level_size = 1;
int next_level_size = 0;
ArrayList<Integer> target_lookup = new ArrayList<>();
// Packing loop for upwards-pointing target trie.
while (!target_queue.isEmpty()) {
// Pop top of queue.
PackingTrie<TargetValue> node = target_queue.poll();
// Register that this is where we're writing the node to.
node.address = target_position;
// Tell source nodes that we're writing to this position in the file.
for (TargetValue tv : node.values)
tv.parent.target = node.address;
// Write link to parent.
if (node.parent != null)
target_stream.writeInt(node.parent.address);
else
target_stream.writeInt(-1);
target_stream.writeInt(node.symbol);
// Enqueue children.
for (int k : node.children.descendingKeySet()) {
PackingTrie<TargetValue> child = node.children.get(k);
target_queue.add(child);
}
target_position += node.size(false, true);
next_level_size += node.children.descendingKeySet().size();
current_level_size--;
if (current_level_size == 0) {
target_lookup.add(target_position);
current_level_size = next_level_size;
next_level_size = 0;
}
}
target_lookup_stream.writeInt(target_lookup.size());
for (int i : target_lookup)
target_lookup_stream.writeInt(i);
target_lookup_stream.close();
// Setting up for source and data writing.
source_queue = new LinkedList<>();
source_queue.add(source_trie);
source_position = source_trie.size(true, false);
source_trie.address = target_position;
// Ready data buffers for writing.
feature_buffer.initialize();
if (packAlignments)
alignment_buffer.initialize();
// Packing loop for downwards-pointing source trie.
while (!source_queue.isEmpty()) {
// Pop top of queue.
PackingTrie<SourceValue> node = source_queue.poll();
// Write number of children.
source_stream.writeInt(node.children.size());
// Write links to children.
for (int k : node.children.descendingKeySet()) {
PackingTrie<SourceValue> child = node.children.get(k);
// Enqueue child.
source_queue.add(child);
// Child's address will be at the current end of the queue.
child.address = source_position;
// Advance cumulated size by child's size.
source_position += child.size(true, false);
// Write the link.
source_stream.writeInt(k);
source_stream.writeInt(child.address);
}
// Write number of data items.
source_stream.writeInt(node.values.size());
// Write lhs and links to target and data.
for (SourceValue sv : node.values) {
int feature_block_index = feature_buffer.write(sv.data);
if (packAlignments) {
int alignment_block_index = alignment_buffer.write(sv.data);
if (alignment_block_index != feature_block_index) {
LOG.error("Block index mismatch.");
throw new RuntimeException("Block index mismatch: alignment (" + alignment_block_index
+ ") and features (" + feature_block_index + ") don't match.");
}
}
source_stream.writeInt(sv.lhs);
source_stream.writeInt(sv.target);
source_stream.writeInt(feature_block_index);
}
}
// Flush the data stream.
feature_buffer.flush(feature_stream);
if (packAlignments)
alignment_buffer.flush(alignment_stream);
target_stream.close();
source_stream.close();
feature_stream.close();
if (packAlignments)
alignment_stream.close();
}
public void writeVocabulary() throws IOException {
final String vocabularyFilename = output + File.separator + VOCABULARY_FILENAME;
LOG.info("Writing vocabulary to {}", vocabularyFilename);
Vocabulary.write(vocabularyFilename);
}
/**
* Integer-labeled, doubly-linked trie with some provisions for packing.
*
* @author Juri Ganitkevitch
*
* @param <D> The trie's value type.
*/
class PackingTrie<D extends PackingTrieValue> {
int symbol;
PackingTrie<D> parent;
final TreeMap<Integer, PackingTrie<D>> children;
final List<D> values;
int address;
PackingTrie() {
address = -1;
symbol = 0;
parent = null;
children = new TreeMap<>();
values = new ArrayList<>();
}
PackingTrie(PackingTrie<D> parent, int symbol) {
this();
this.parent = parent;
this.symbol = symbol;
}
void add(int[] path, D value) {
add(path, 0, value);
}
private void add(int[] path, int index, D value) {
if (index == path.length)
this.values.add(value);
else {
PackingTrie<D> child = children.get(path[index]);
if (child == null) {
child = new PackingTrie<>(this, path[index]);
children.put(path[index], child);
}
child.add(path, index + 1, value);
}
}
/**
* Calculate the size (in ints) of a packed trie node. Distinguishes downwards pointing (parent
* points to children) from upwards pointing (children point to parent) tries, as well as
* skeletal (no data, just the labeled links) and non-skeletal (nodes have a data block)
* packing.
*
* @param downwards Are we packing into a downwards-pointing trie?
* @param skeletal Are we packing into a skeletal trie?
*
* @return Number of bytes the trie node would occupy.
*/
int size(boolean downwards, boolean skeletal) {
int size = 0;
if (downwards) {
// Number of children and links to children.
size = 1 + 2 * children.size();
} else {
// Link to parent.
size += 2;
}
// Non-skeletal packing: number of data items.
if (!skeletal)
size += 1;
// Non-skeletal packing: write size taken up by data items.
if (!skeletal && !values.isEmpty())
size += values.size() * values.get(0).size();
return size;
}
void clear() {
children.clear();
values.clear();
}
}
interface PackingTrieValue {
int size();
}
class SourceValue implements PackingTrieValue {
int lhs;
int data;
int target;
public SourceValue() {
}
SourceValue(int lhs, int data) {
this.lhs = lhs;
this.data = data;
}
void setTarget(int target) {
this.target = target;
}
@Override
public int size() {
return 3;
}
}
class TargetValue implements PackingTrieValue {
final SourceValue parent;
TargetValue(SourceValue parent) {
this.parent = parent;
}
@Override
public int size() {
return 0;
}
}
abstract class PackingBuffer<T> {
private byte[] backing;
protected ByteBuffer buffer;
protected final ArrayList<Integer> memoryLookup;
protected int totalSize;
protected final ArrayList<Integer> onDiskOrder;
PackingBuffer() {
allocate();
memoryLookup = new ArrayList<>();
onDiskOrder = new ArrayList<>();
totalSize = 0;
}
abstract int add(T item);
// Allocate a reasonably-sized buffer for the feature data.
private void allocate() {
backing = new byte[approximateMaximumSliceSize * DATA_SIZE_ESTIMATE];
buffer = ByteBuffer.wrap(backing);
}
// Reallocate the backing array and buffer, copies data over.
protected void reallocate() {
if (backing.length == Integer.MAX_VALUE)
return;
long attempted_length = backing.length * 2L;
int new_length;
// Detect overflow.
if (attempted_length >= Integer.MAX_VALUE)
new_length = Integer.MAX_VALUE;
else
new_length = (int) attempted_length;
byte[] new_backing = new byte[new_length];
System.arraycopy(backing, 0, new_backing, 0, backing.length);
int old_position = buffer.position();
ByteBuffer new_buffer = ByteBuffer.wrap(new_backing);
new_buffer.position(old_position);
buffer = new_buffer;
backing = new_backing;
}
/**
* Prepare the data buffer for disk writing.
*/
void initialize() {
onDiskOrder.clear();
}
/**
* Enqueue a data block for later writing.
*
* @param block_index The index of the data block to add to writing queue.
* @return The to-be-written block's output index.
*/
int write(int block_index) {
onDiskOrder.add(block_index);
return onDiskOrder.size() - 1;
}
/**
* Performs the actual writing to disk in the order specified by calls to write() since the last
* call to initialize().
*
* @param out
* @throws IOException
*/
void flush(DataOutputStream out) throws IOException {
writeHeader(out);
int size;
int block_address;
for (int block_index : onDiskOrder) {
block_address = memoryLookup.get(block_index);
size = blockSize(block_index);
out.write(backing, block_address, size);
}
}
void clear() {
buffer.clear();
memoryLookup.clear();
onDiskOrder.clear();
}
boolean overflowing() {
return (buffer.position() >= DATA_SIZE_LIMIT);
}
private void writeHeader(DataOutputStream out) throws IOException {
if (out.size() == 0) {
out.writeInt(onDiskOrder.size());
out.writeInt(totalSize);
int disk_position = headerSize();
for (int block_index : onDiskOrder) {
out.writeInt(disk_position);
disk_position += blockSize(block_index);
}
} else {
throw new RuntimeException("Got a used stream for header writing.");
}
}
private int headerSize() {
// One integer for each data block, plus number of blocks and total size.
return 4 * (onDiskOrder.size() + 2);
}
private int blockSize(int block_index) {
int block_address = memoryLookup.get(block_index);
return (block_index < memoryLookup.size() - 1 ? memoryLookup.get(block_index + 1) : totalSize)
- block_address;
}
}
class FeatureBuffer extends PackingBuffer<TreeMap<Integer, Float>> {
private IntEncoder idEncoder;
FeatureBuffer() throws IOException {
super();
idEncoder = types.getIdEncoder();
LOG.info("Encoding feature ids in: {}", idEncoder.getKey());
}
/**
* Add a block of features to the buffer.
*
* @param features TreeMap with the features for one rule.
* @return The index of the resulting data block.
*/
@Override
int add(TreeMap<Integer, Float> features) {
int data_position = buffer.position();
// Over-estimate how much room this addition will need: for each
// feature (ID_SIZE for label, "upper bound" of 4 for the value), plus ID_SIZE for
// the number of features. If this won't fit, reallocate the buffer.
int size_estimate = (4 + EncoderConfiguration.ID_SIZE) * features.size()
+ EncoderConfiguration.ID_SIZE;
if (buffer.capacity() - buffer.position() <= size_estimate)
reallocate();
// Write features to buffer.
idEncoder.write(buffer, features.size());
for (Integer k : features.descendingKeySet()) {
float v = features.get(k);
// Sparse features.
if (v != 0.0) {
idEncoder.write(buffer, k);
encoderConfig.encoder(k).write(buffer, v);
}
}
// Store position the block was written to.
memoryLookup.add(data_position);
// Update total size (in bytes).
totalSize = buffer.position();
// Return block index.
return memoryLookup.size() - 1;
}
}
class AlignmentBuffer extends PackingBuffer<byte[]> {
AlignmentBuffer() throws IOException {
super();
}
/**
* Add a rule alignments to the buffer.
*
* @param alignments a byte array with the alignment points for one rule.
* @return The index of the resulting data block.
*/
@Override
int add(byte[] alignments) {
int data_position = buffer.position();
int size_estimate = alignments.length + 1;
if (buffer.capacity() - buffer.position() <= size_estimate)
reallocate();
// Write alignment points to buffer.
buffer.put((byte) (alignments.length / 2));
buffer.put(alignments);
// Store position the block was written to.
memoryLookup.add(data_position);
// Update total size (in bytes).
totalSize = buffer.position();
// Return block index.
return memoryLookup.size() - 1;
}
}
class PackingFileTuple implements Comparable<PackingFileTuple> {
private final File sourceFile;
private final File targetLookupFile;
private final File targetFile;
private final File featureFile;
private File alignmentFile;
PackingFileTuple(String prefix) {
sourceFile = new File(output + File.separator + prefix + ".source");
targetFile = new File(output + File.separator + prefix + ".target");
targetLookupFile = new File(output + File.separator + prefix + ".target.lookup");
featureFile = new File(output + File.separator + prefix + ".features");
alignmentFile = null;
if (packAlignments)
alignmentFile = new File(output + File.separator + prefix + ".alignments");
LOG.info("Allocated slice: {}", sourceFile.getAbsolutePath());
}
DataOutputStream getSourceOutput() throws IOException {
return getOutput(sourceFile);
}
DataOutputStream getTargetOutput() throws IOException {
return getOutput(targetFile);
}
DataOutputStream getTargetLookupOutput() throws IOException {
return getOutput(targetLookupFile);
}
DataOutputStream getFeatureOutput() throws IOException {
return getOutput(featureFile);
}
DataOutputStream getAlignmentOutput() throws IOException {
if (alignmentFile != null)
return getOutput(alignmentFile);
return null;
}
private DataOutputStream getOutput(File file) throws IOException {
if (file.createNewFile()) {
return new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
} else {
throw new RuntimeException("File doesn't exist: " + file.getName());
}
}
long getSize() {
return sourceFile.length() + targetFile.length() + featureFile.length();
}
@Override
public int compareTo(PackingFileTuple o) {
if (getSize() > o.getSize()) {
return -1;
} else if (getSize() < o.getSize()) {
return 1;
} else {
return 0;
}
}
}
}
| |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.intellij.lang.xpath.xslt.refactoring;
import com.intellij.codeInsight.highlighting.HighlightManager;
import com.intellij.codeInsight.highlighting.HighlightManagerImpl;
import com.intellij.injected.editor.EditorWindow;
import com.intellij.lang.Language;
import com.intellij.lang.findUsages.LanguageFindUsages;
import com.intellij.lang.refactoring.InlineActionHandler;
import com.intellij.lang.xml.XMLLanguage;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.colors.EditorColors;
import com.intellij.openapi.editor.markup.RangeHighlighter;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiReference;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.LocalSearchScope;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.xml.XmlAttributeValue;
import com.intellij.psi.xml.XmlTag;
import com.intellij.refactoring.util.CommonRefactoringUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.Processor;
import com.intellij.util.Query;
import com.intellij.util.containers.ContainerUtil;
import org.intellij.lang.xpath.XPathFileType;
import org.intellij.lang.xpath.psi.XPathElement;
import org.intellij.lang.xpath.psi.XPathVariable;
import org.intellij.lang.xpath.psi.XPathVariableReference;
import org.intellij.lang.xpath.psi.impl.XPathChangeUtil;
import org.intellij.lang.xpath.xslt.XsltSupport;
import org.intellij.lang.xpath.xslt.psi.XsltElement;
import org.intellij.lang.xpath.xslt.psi.XsltParameter;
import org.intellij.lang.xpath.xslt.psi.XsltVariable;
import org.intellij.lang.xpath.xslt.psi.impl.XsltLanguage;
import org.intellij.lang.xpath.xslt.util.XsltCodeInsightUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.awt.*;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
public class VariableInlineHandler extends InlineActionHandler {
private static final String NAME = "Inline";
private static final String TITLE = "XSLT - " + NAME;
@Override
public boolean isEnabledForLanguage(Language l) {
return l == XPathFileType.XPATH.getLanguage() || l == XMLLanguage.INSTANCE || l == XsltLanguage.INSTANCE;
}
@Override
public boolean canInlineElement(PsiElement element) {
final XPathVariableReference reference = PsiTreeUtil.getParentOfType(element, XPathVariableReference.class, false);
if (reference != null) {
return canInline(reference.resolve());
}
return canInline(element);
}
private static boolean canInline(PsiElement element) {
return element instanceof XsltVariable && !(element instanceof XsltParameter);
}
@Override
public void inlineElement(Project project, Editor editor, PsiElement element) {
final XPathVariableReference reference = PsiTreeUtil.getParentOfType(element, XPathVariableReference.class, false);
if (reference != null) {
final XPathVariable variable = reference.resolve();
if (variable != null && canInline(variable)) {
invoke(variable, editor);
}
}
if (canInline(element)) {
invoke((XPathVariable)element, editor);
}
}
public static void invoke(@NotNull final XPathVariable variable, Editor editor) {
final String type = LanguageFindUsages.getType(variable);
final Project project = variable.getProject();
final XmlTag tag = ((XsltElement)variable).getTag();
final String expression = tag.getAttributeValue("select");
if (expression == null) {
CommonRefactoringUtil.showErrorHint(project, editor,
MessageFormat
.format("{0} ''{1}'' has no value.", StringUtil.capitalize(type), variable.getName()),
TITLE, null);
return;
}
final Collection<PsiReference> references =
ReferencesSearch.search(variable, new LocalSearchScope(tag.getParentTag()), false).findAll();
if (references.size() == 0) {
CommonRefactoringUtil.showErrorHint(project, editor,
MessageFormat.format("{0} ''{1}'' is never used.", variable.getName()),
TITLE, null);
return;
}
boolean hasExternalRefs = false;
if (XsltSupport.isTopLevelElement(tag)) {
final Query<PsiReference> query = ReferencesSearch.search(variable, GlobalSearchScope.allScope(project), false);
hasExternalRefs = !query.forEach(new Processor<PsiReference>() {
int allRefs = 0;
@Override
public boolean process(PsiReference psiReference) {
if (++allRefs > references.size()) {
return false;
}
else if (!references.contains(psiReference)) {
return false;
}
return true;
}
});
}
final HighlightManager highlighter = HighlightManager.getInstance(project);
final ArrayList<RangeHighlighter> highlighters = new ArrayList<>();
final PsiReference[] psiReferences = references.toArray(PsiReference.EMPTY_ARRAY);
TextRange[] ranges = ContainerUtil.map2Array(psiReferences, TextRange.class, s -> {
final PsiElement psiElement = s.getElement();
final XmlAttributeValue context = PsiTreeUtil.getContextOfType(psiElement, XmlAttributeValue.class, true);
if (psiElement instanceof XPathElement && context != null) {
return XsltCodeInsightUtil.getRangeInsideHostingFile((XPathElement)psiElement).cutOut(s.getRangeInElement());
}
return psiElement.getTextRange().cutOut(s.getRangeInElement());
});
final Editor e = editor instanceof EditorWindow ? ((EditorWindow)editor).getDelegate() : editor;
for (TextRange range : ranges) {
final TextAttributes textAttributes = EditorColors.SEARCH_RESULT_ATTRIBUTES.getDefaultAttributes();
final Color color = getScrollmarkColor(textAttributes);
highlighter.addOccurrenceHighlight(e, range.getStartOffset(), range.getEndOffset(), textAttributes,
HighlightManagerImpl.HIDE_BY_ESCAPE, highlighters, color);
}
highlighter.addOccurrenceHighlights(e, new PsiElement[]{((XsltVariable)variable).getNameIdentifier()},
EditorColors.WRITE_SEARCH_RESULT_ATTRIBUTES.getDefaultAttributes(), false, highlighters);
if (!hasExternalRefs) {
if (!ApplicationManager.getApplication().isUnitTestMode() &&
Messages.showYesNoDialog(MessageFormat.format("Inline {0} ''{1}''? ({2} occurrence{3})",
type,
variable.getName(),
String.valueOf(references.size()),
references.size() > 1 ? "s" : ""),
TITLE, Messages.getQuestionIcon()) != Messages.YES) {
return;
}
}
else {
if (!ApplicationManager.getApplication().isUnitTestMode() &&
Messages.showYesNoDialog(MessageFormat.format("Inline {0} ''{1}''? ({2} local occurrence{3})\n" +
"\nWarning: It is being used in external files. Its declaration will not be removed.",
type,
variable.getName(),
String.valueOf(references.size()),
references.size() > 1 ? "s" : ""),
TITLE, Messages.getWarningIcon()) != Messages.YES) {
return;
}
}
final boolean hasRefs = hasExternalRefs;
WriteCommandAction.writeCommandAction(project, tag.getContainingFile()).withName("XSLT.Inline").run(() -> {
try {
for (PsiReference psiReference : references) {
final PsiElement element = psiReference.getElement();
if (element instanceof XPathElement) {
final XPathElement newExpr = XPathChangeUtil.createExpression(element, expression);
element.replace(newExpr);
}
else {
assert false;
}
}
if (!hasRefs) {
tag.delete();
}
}
catch (IncorrectOperationException ex) {
Logger.getInstance(VariableInlineHandler.class.getName()).error(ex);
}
});
}
@Nullable
private static Color getScrollmarkColor(TextAttributes textAttributes) {
if (textAttributes.getErrorStripeColor() != null) {
return textAttributes.getErrorStripeColor();
} else if (textAttributes.getBackgroundColor() != null) {
return textAttributes.getBackgroundColor().darker();
} else {
return null;
}
}
}
| |
/*
* Licensed to The Apereo Foundation under one or more contributor license
* agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*
* The Apereo Foundation 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.unitime.timetable.gwt.client.rooms;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.unitime.timetable.gwt.client.ToolBox;
import org.unitime.timetable.gwt.client.page.UniTimeNotifications;
import org.unitime.timetable.gwt.client.page.UniTimePageLabel;
import org.unitime.timetable.gwt.client.rooms.RoomDetail.Check;
import org.unitime.timetable.gwt.client.widgets.ImageLink;
import org.unitime.timetable.gwt.client.widgets.LoadingWidget;
import org.unitime.timetable.gwt.client.widgets.NumberBox;
import org.unitime.timetable.gwt.client.widgets.P;
import org.unitime.timetable.gwt.client.widgets.SimpleForm;
import org.unitime.timetable.gwt.client.widgets.UniTimeFileUpload;
import org.unitime.timetable.gwt.client.widgets.UniTimeHeaderPanel;
import org.unitime.timetable.gwt.client.widgets.UniTimeTable;
import org.unitime.timetable.gwt.client.widgets.UniTimeTableHeader;
import org.unitime.timetable.gwt.client.widgets.UniTimeWidget;
import org.unitime.timetable.gwt.command.client.GwtRpcService;
import org.unitime.timetable.gwt.command.client.GwtRpcServiceAsync;
import org.unitime.timetable.gwt.resources.GwtConstants;
import org.unitime.timetable.gwt.resources.GwtMessages;
import org.unitime.timetable.gwt.resources.GwtResources;
import org.unitime.timetable.gwt.shared.RoomInterface;
import org.unitime.timetable.gwt.shared.RoomInterface.AcademicSessionInterface;
import org.unitime.timetable.gwt.shared.RoomInterface.AttachmentTypeInterface;
import org.unitime.timetable.gwt.shared.RoomInterface.BuildingInterface;
import org.unitime.timetable.gwt.shared.RoomInterface.DepartmentInterface;
import org.unitime.timetable.gwt.shared.RoomInterface.ExamTypeInterface;
import org.unitime.timetable.gwt.shared.RoomInterface.FeatureInterface;
import org.unitime.timetable.gwt.shared.RoomInterface.FeatureTypeInterface;
import org.unitime.timetable.gwt.shared.RoomInterface.FutureOperation;
import org.unitime.timetable.gwt.shared.RoomInterface.FutureRoomInterface;
import org.unitime.timetable.gwt.shared.RoomInterface.GroupInterface;
import org.unitime.timetable.gwt.shared.RoomInterface.PeriodPreferenceModel;
import org.unitime.timetable.gwt.shared.RoomInterface.RoomDetailInterface;
import org.unitime.timetable.gwt.shared.RoomInterface.RoomException;
import org.unitime.timetable.gwt.shared.RoomInterface.RoomPictureInterface;
import org.unitime.timetable.gwt.shared.RoomInterface.RoomPictureRequest;
import org.unitime.timetable.gwt.shared.RoomInterface.RoomPictureResponse;
import org.unitime.timetable.gwt.shared.RoomInterface.RoomPropertiesInterface;
import org.unitime.timetable.gwt.shared.RoomInterface.RoomSharingModel;
import org.unitime.timetable.gwt.shared.RoomInterface.RoomSharingOption;
import org.unitime.timetable.gwt.shared.RoomInterface.RoomTypeInterface;
import org.unitime.timetable.gwt.shared.RoomInterface.RoomUpdateRpcRequest;
import org.unitime.timetable.gwt.shared.RoomInterface.RoomsPageMode;
import com.google.gwt.core.client.Callback;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.ScriptInjector;
import com.google.gwt.dom.client.Element;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.event.dom.client.MouseOutEvent;
import com.google.gwt.event.dom.client.MouseOutHandler;
import com.google.gwt.event.dom.client.MouseOverEvent;
import com.google.gwt.event.dom.client.MouseOverHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteEvent;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteHandler;
/**
* @author Tomas Muller
*/
public class RoomEdit extends Composite {
private static final GwtRpcServiceAsync RPC = GWT.create(GwtRpcService.class);
private static final GwtConstants CONSTANTS = GWT.create(GwtConstants.class);
private static final GwtMessages MESSAGES = GWT.create(GwtMessages.class);
private static final GwtResources RESOURCES = GWT.create(GwtResources.class);
private SimpleForm iForm;
private UniTimeHeaderPanel iHeader, iFooter;
private RoomPropertiesInterface iProperties = null;
private RoomDetailInterface iRoom = null;
private DepartmentInterface iLastControllingDept = null, iLastEventDept = null;
private Long iLastSelectedDepartmentId = null;
private UniTimeWidget<ListBox> iType;
private UniTimeWidget<ListBox> iBuilding;
private int iBuildingRow;
private Label iNameLabel;
private UniTimeWidget<TextBox> iName;
private TextBox iDisplayName, iExternalId;
private UniTimeWidget<NumberBox> iCapacity, iExamCapacity;
private UniTimeWidget<ListBox> iControllingDepartment;
private NumberBox iX, iY;
private UniTimeWidget<P> iCoordinates;
private P iCoordinatesFormat;
private UniTimeWidget<P> iAreaPanel;
private NumberBox iArea;
private P iAreaFormat;
private CheckBox iDistanceCheck, iRoomCheck;
private AbsolutePanel iGoogleMap;
private AbsolutePanel iGoogleMapControl;
private boolean iGoogleMapInitialized = false;
private ListBox iEventDepartment;
private ListBox iEventStatus;
private P iBreakTimePanel;
private NumberBox iBreakTime;
private UniTimeWidget<TextArea> iNote;
private P iExaminationRoomsPanel;
private Map<Long, CheckBox> iExaminationRooms = new HashMap<Long, CheckBox>();
private Map<Long, CheckBox> iGroups = new HashMap<Long, CheckBox>();
private Map<Long, CheckBox> iFeatures = new HashMap<Long, CheckBox>();
private P iGlobalGroupsPanel;
private Map<Long, P> iGroupPanel = new HashMap<Long, P>();
private UniTimeHeaderPanel iRoomSharingHeader;
private RoomSharingWidget iRoomSharing;
private UniTimeHeaderPanel iPeriodPreferencesHeader;
private int iPeriodPreferencesHeaderRow;
private Map<Long, PeriodPreferencesWidget> iPeriodPreferences = new HashMap<Long, PeriodPreferencesWidget>();
private Map<Long, Integer> iPeriodPreferencesRow = new HashMap<Long, Integer>();
private UniTimeHeaderPanel iEventAvailabilityHeader;
private RoomSharingWidget iEventAvailability;
private UniTimeHeaderPanel iPicturesHeader;
private UniTimeFileUpload iFileUpload;
private UniTimeTable<RoomPictureInterface> iPictures;
private UniTimeHeaderPanel iApplyToHeader;
private UniTimeTable<FutureRoomInterface> iApplyTo;
private RoomsPageMode iMode = null;
public RoomEdit(RoomsPageMode mode) {
iMode = mode;
iHeader = new UniTimeHeaderPanel();
ClickHandler clickCreateOrUpdate = new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
if (!validate()) {
iHeader.setErrorMessage(MESSAGES.failedValidationCheckForm());
UniTimeNotifications.error(MESSAGES.failedValidationCheckForm());
} else {
RoomUpdateRpcRequest request = RoomUpdateRpcRequest.createSaveOrUpdateRequest(getRoom());
String future = generateAlsoUpdateMessage(false);
if (future != null) {
if (Window.confirm(getRoom().getUniqueId() == null ? MESSAGES.confirmCreateRoomInFutureSessions(future) : MESSAGES.confirmUpdateRoomInFutureSessions(future)))
fillFutureFlags(request, false);
else
return;
}
LoadingWidget.getInstance().show(getRoom().getUniqueId() == null ? MESSAGES.waitSavingRoom() : MESSAGES.waitUpdatingRoom());
RPC.execute(request, new AsyncCallback<RoomDetailInterface>() {
@Override
public void onFailure(Throwable caught) {
LoadingWidget.getInstance().hide();
String message = null;
RoomDetailInterface result = null;
if (caught instanceof RoomException) {
message = caught.getMessage();
result = ((RoomException)caught).getRoom();
} else if (getRoom().getUniqueId() == null) {
message = MESSAGES.errorFailedToSaveRoom(caught.getMessage());
} else {
message = MESSAGES.errorFailedToUpdateRoom(caught.getMessage());
}
iHeader.setErrorMessage(message);
UniTimeNotifications.error(message);
if (result != null)
hide(result, true, message);
}
@Override
public void onSuccess(RoomDetailInterface result) {
LoadingWidget.getInstance().hide();
hide(result, true, null);
}
});
}
}
};
iHeader.addButton("create", MESSAGES.buttonCreateRoom(), 100, clickCreateOrUpdate);
iHeader.addButton("update", MESSAGES.buttonUpdateRoom(), 100, clickCreateOrUpdate);
iHeader.addButton("delete", MESSAGES.buttonDeleteRoom(), 100, new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
RoomUpdateRpcRequest request = RoomUpdateRpcRequest.createDeleteRequest(getRoom().getSessionId(), getRoom().getUniqueId());
String future = generateAlsoUpdateMessage(true);
if (Window.confirm(future == null ? MESSAGES.confirmDeleteRoom() : MESSAGES.confirmDeleteRoomInFutureSessions(future))) {
if (future != null) fillFutureFlags(request, true);
} else {
return;
}
LoadingWidget.getInstance().show(MESSAGES.waitDeletingRoom());
RPC.execute(request, new AsyncCallback<RoomDetailInterface>() {
@Override
public void onFailure(Throwable caught) {
LoadingWidget.getInstance().hide();
String message = null;
RoomDetailInterface result = null;
if (caught instanceof RoomException) {
message = caught.getMessage();
result = ((RoomException)caught).getRoom();
} else {
message = MESSAGES.errorFailedToDeleteRoom(caught.getMessage());
}
iHeader.setErrorMessage(message);
UniTimeNotifications.error(message);
if (result != null)
hide(result, true, message);
}
@Override
public void onSuccess(RoomDetailInterface result) {
LoadingWidget.getInstance().hide();
hide(null, false, null);
}
});
}
});
iHeader.addButton("back", MESSAGES.buttonBack(), 75, new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
hide(null, true, null);
}
});
iForm = new SimpleForm(2);
iForm.addStyleName("unitime-RoomEdit");
iType = new UniTimeWidget<ListBox>(new ListBox()); iType.getWidget().setStyleName("unitime-TextBox");
iType.getWidget().addChangeHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent event) {
typeChanged();
iType.clearHint();
iHeader.clearMessage();
}
});
iBuilding = new UniTimeWidget<ListBox>(new ListBox()); iBuilding.getWidget().setStyleName("unitime-TextBox");
iBuilding.getWidget().addItem(MESSAGES.itemSelect(), "-1");
iBuilding.getWidget().addChangeHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent event) {
buildingChanged();
iBuilding.clearHint();
iHeader.clearMessage();
}
});
iName = new UniTimeWidget<TextBox>(new TextBox());
iName.getWidget().setStyleName("unitime-TextBox");
iName.getWidget().setMaxLength(20);
iName.getWidget().setWidth("150px");
iName.getWidget().addChangeHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent event) {
iName.clearHint();
iHeader.clearMessage();
}
});
iNameLabel = new Label(MESSAGES.propRoomName());
iDisplayName = new TextBox();
iDisplayName.setStyleName("unitime-TextBox");
iDisplayName.setMaxLength(100);
iDisplayName.setWidth("480px");
iExternalId = new TextBox();
iExternalId.setStyleName("unitime-TextBox");
iExternalId.setMaxLength(40);
iExternalId.setWidth("300px");
iCapacity = new UniTimeWidget<NumberBox>(new NumberBox());
iCapacity.getWidget().setDecimal(false);
iCapacity.getWidget().setNegative(false);
iCapacity.getWidget().setMaxLength(6);
iCapacity.getWidget().setWidth("80px");
iCapacity.getWidget().addChangeHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent event) {
iCapacity.clearHint();
iHeader.clearMessage();
}
});
iControllingDepartment = new UniTimeWidget<ListBox>(new ListBox());
iControllingDepartment.getWidget().setStyleName("unitime-TextBox");
iX =new NumberBox();
iX.setMaxLength(12);
iX.setWidth("80px");
iX.setDecimal(true);
iX.setNegative(true);
iX.addStyleName("number");
iY = new NumberBox();
iY.setMaxLength(12);
iY.setWidth("80px");
iY.setDecimal(true);
iY.setNegative(true);
iY.addStyleName("number");
iX.getElement().setId("coordX");
iY.getElement().setId("coordY");
iCoordinates = new UniTimeWidget<P>(new P("coordinates"));
iCoordinates.getWidget().add(iX);
P comma = new P("comma"); comma.setText(", ");
iCoordinates.getWidget().add(comma);
iCoordinates.getWidget().add(iY);
iCoordinatesFormat = new P("format");
iCoordinates.getWidget().add(iCoordinatesFormat);
iX.addValueChangeHandler(new ValueChangeHandler<String>() {
@Override
public void onValueChange(ValueChangeEvent<String> event) {
if (iProperties.isGoogleMap())
setMarker();
}
});
iY.addValueChangeHandler(new ValueChangeHandler<String>() {
@Override
public void onValueChange(ValueChangeEvent<String> event) {
if (iProperties.isGoogleMap())
setMarker();
}
});
iArea = new NumberBox();
iArea.setDecimal(true);
iArea.setNegative(false);
iArea.addStyleName("number");
iArea.setWidth("80px");
iArea.setMaxLength(12);
iAreaPanel = new UniTimeWidget<P>(new P("area"));
iAreaPanel.getWidget().add(iArea);
iAreaFormat = new P("format");
iAreaFormat.setText(CONSTANTS.roomAreaUnitsLong());
iAreaPanel.getWidget().add(iAreaFormat);
iDistanceCheck = new CheckBox();
iDistanceCheck.addValueChangeHandler(new ValueChangeHandler<Boolean>() {
@Override
public void onValueChange(ValueChangeEvent<Boolean> event) {
distanceCheckChanged();
}
});
iRoomCheck = new CheckBox();
iRoomCheck.addValueChangeHandler(new ValueChangeHandler<Boolean>() {
@Override
public void onValueChange(ValueChangeEvent<Boolean> event) {
roomCheckChanged();
}
});
iExaminationRoomsPanel = new P("exams"); iExaminationRoomsPanel.setWidth("100%");
iExamCapacity = new UniTimeWidget<NumberBox>(new NumberBox());
iExamCapacity.getWidget().setDecimal(false);
iExamCapacity.getWidget().setNegative(false);
iExamCapacity.getWidget().setMaxLength(6);
iExamCapacity.getWidget().setWidth("80px");
iExamCapacity.getWidget().addChangeHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent event) {
iExamCapacity.clearHint();
iHeader.clearMessage();
}
});
iEventDepartment = new ListBox();
iEventDepartment.setStyleName("unitime-TextBox");
iEventDepartment.addChangeHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent event) {
iEventAvailabilityHeader.setVisible(!"-1".equals(iEventDepartment.getValue(iEventDepartment.getSelectedIndex())));
iEventAvailability.setVisible(!"-1".equals(iEventDepartment.getValue(iEventDepartment.getSelectedIndex())));
}
});
iEventStatus = new ListBox();
iEventStatus.setStyleName("unitime-TextBox");
iEventStatus.addItem(MESSAGES.itemDefault(), "-1");
for (int i = 0; i < CONSTANTS.eventStatusName().length; i++)
iEventStatus.addItem(CONSTANTS.eventStatusName()[i], String.valueOf(i));
iNote = new UniTimeWidget<TextArea>(new TextArea());
iNote.getWidget().setStyleName("unitime-TextArea");
iNote.getWidget().setVisibleLines(5);
iNote.getWidget().setCharacterWidth(70);
iBreakTime = new NumberBox();
iBreakTime.setDecimal(false);
iBreakTime.setNegative(false);
iBreakTime.addStyleName("number");
iBreakTime.setWidth("80px");
iBreakTime.setMaxLength(12);
iBreakTimePanel = new P("breaktime");
iBreakTimePanel.add(iBreakTime);
P f = new P("note");
f.setText(MESSAGES.useDefaultBreakTimeWhenEmpty());
iBreakTimePanel.add(f);
iRoomSharingHeader = new UniTimeHeaderPanel(MESSAGES.headerRoomSharing());
iRoomSharing = new RoomSharingWidget(true, true);
iRoomSharing.addValueChangeHandler(new ValueChangeHandler<RoomInterface.RoomSharingModel>() {
@Override
public void onValueChange(ValueChangeEvent<RoomSharingModel> event) {
iRoomSharingHeader.clearMessage();
}
});
iControllingDepartment.getWidget().addChangeHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent event) {
iControllingDepartment.clearHint();
if (iRoom.getDepartment(iLastSelectedDepartmentId) == null)
iRoomSharing.removeOption(iLastSelectedDepartmentId);
iLastSelectedDepartmentId = Long.valueOf(iControllingDepartment.getWidget().getValue(iControllingDepartment.getWidget().getSelectedIndex()));
if (iLastSelectedDepartmentId > 0)
iRoomSharing.addOption(iLastSelectedDepartmentId);
}
});
iPeriodPreferencesHeader = new UniTimeHeaderPanel(MESSAGES.headerExaminationPeriodPreferences());
iEventAvailabilityHeader = new UniTimeHeaderPanel(MESSAGES.headerEventAvailability());
iEventAvailability = new RoomSharingWidget(true);
iPicturesHeader = new UniTimeHeaderPanel(MESSAGES.headerRoomPictures());
iPictures = new UniTimeTable<RoomPictureInterface>();
iPictures.setStyleName("unitime-RoomPictures");
List<UniTimeTableHeader> header = new ArrayList<UniTimeTableHeader>();
header.add(new UniTimeTableHeader(MESSAGES.colPicture()));
header.add(new UniTimeTableHeader(MESSAGES.colName()));
header.add(new UniTimeTableHeader(MESSAGES.colContentType()));
header.add(new UniTimeTableHeader(MESSAGES.colPictureType()));
header.add(new UniTimeTableHeader(" "));
iPictures.addRow(null, header);
iFileUpload = new UniTimeFileUpload();
iFileUpload.addSubmitCompleteHandler(new SubmitCompleteHandler() {
@Override
public void onSubmitComplete(SubmitCompleteEvent event) {
RPC.execute(RoomPictureRequest.upload(iRoom.getSessionId(), iRoom.getUniqueId()), new AsyncCallback<RoomPictureResponse>() {
@Override
public void onFailure(Throwable caught) {
iHeader.setErrorMessage(MESSAGES.failedToUploadRoomPicture(caught.getMessage()));
}
@Override
public void onSuccess(RoomPictureResponse result) {
if (result.hasPictures()) {
for (final RoomPictureInterface picture: result.getPictures()) {
for (int row = 1; row < iPictures.getRowCount(); row ++)
if (picture.getName().equals(iPictures.getData(row).getName())) {
iPictures.removeRow(row);
break;
}
iPictures.addRow(picture, line(picture));
}
iFileUpload.reset();
}
}
});
}
});
iApplyToHeader = new UniTimeHeaderPanel(MESSAGES.headerRoomApplyToFutureRooms());
iApplyToHeader.setTitleStyleName("update-options");
iApplyTo = new UniTimeTable<FutureRoomInterface>();
iApplyTo.setStyleName("unitime-RoomApplyTo");
List<UniTimeTableHeader> ah = new ArrayList<UniTimeTableHeader>();
ah.add(new UniTimeTableHeader(" "));
ah.add(new UniTimeTableHeader(MESSAGES.colName()));
ah.add(new UniTimeTableHeader(MESSAGES.colSession()));
for (FutureOperation op: FutureOperation.values()) {
ah.add(new UniTimeTableHeader(getFutureOperationLabel(op)));
}
iApplyTo.addRow(null, ah);
iFooter = iHeader.clonePanel();
initWidget(iForm);
}
public void setProperties(RoomPropertiesInterface properties) {
iProperties = properties;
iForm.setColSpan(iProperties.isGoogleMap() ? 3 : 2);
iBuilding.getWidget().clear();
for (BuildingInterface building: iProperties.getBuildings())
iBuilding.getWidget().addItem(building.getAbbreviation() + " - " + building.getName(), building.getId().toString());
iCoordinatesFormat.setText(iProperties.getEllipsoid());
iExaminationRooms.clear();
iExaminationRoomsPanel.clear();
for (final ExamTypeInterface type: iProperties.getExamTypes()) {
final CheckBox ch = new CheckBox(type.getLabel());
ch.addStyleName("exam");
iExaminationRooms.put(type.getId(), ch);
iExaminationRoomsPanel.add(ch);
ch.setValue(false);
ch.addValueChangeHandler(new ValueChangeHandler<Boolean>() {
@Override
public void onValueChange(ValueChangeEvent<Boolean> event) {
Integer row = iPeriodPreferencesRow.get(type.getId());
if (row != null)
iForm.getRowFormatter().setVisible(row, event.getValue());
boolean prefVisible = false;
for (ExamTypeInterface t: iProperties.getExamTypes()) {
if (iExaminationRooms.get(t.getId()).getValue()) { prefVisible = true; break; }
}
if (iPeriodPreferencesHeaderRow > 0)
iForm.getRowFormatter().setVisible(iPeriodPreferencesHeaderRow, prefVisible);
if (!event.getValue()) {
iExamCapacity.clearHint();
iHeader.clearMessage();
}
}
});
}
if (iProperties.isGoogleMap() && iGoogleMap == null) {
iGoogleMap = new AbsolutePanel();
iGoogleMap.setStyleName("map");
iGoogleMapControl = new AbsolutePanel(); iGoogleMapControl.setStyleName("control");
final TextBox searchBox = new TextBox();
searchBox.setStyleName("unitime-TextBox"); searchBox.addStyleName("searchBox");
searchBox.getElement().setId("mapSearchBox");
searchBox.setTabIndex(-1);
iGoogleMapControl.add(searchBox);
Button button = new Button(MESSAGES.buttonGeocode(), new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
geocodeAddress();
}
});
button.setTabIndex(-1);
searchBox.addKeyPressHandler(new KeyPressHandler() {
@Override
public void onKeyPress(KeyPressEvent event) {
switch (event.getNativeEvent().getKeyCode()) {
case KeyCodes.KEY_ENTER:
event.preventDefault();
geocodeAddress();
return;
}
}
});
button.addStyleName("geocode");
ToolBox.setWhiteSpace(button.getElement().getStyle(), "nowrap");
Character accessKey = UniTimeHeaderPanel.guessAccessKey(MESSAGES.buttonGeocode());
if (accessKey != null)
button.setAccessKey(accessKey);
iGoogleMapControl.add(button);
iGoogleMap.add(iGoogleMapControl);
addGoogleMap(iGoogleMap.getElement(), iGoogleMapControl.getElement());
}
iGroups.clear();
iGroupPanel.clear();
iGlobalGroupsPanel = null;
if (!iProperties.getGroups().isEmpty()) {
P groups = new P("groups");
for (GroupInterface group: iProperties.getGroups()) {
CheckBox ch = new CheckBox(group.getLabel());
ch.addStyleName("group");
iGroups.put(group.getId(), ch);
if (group.getDepartment() != null) {
P d = iGroupPanel.get(group.getDepartment().getId());
if (d == null) {
d = new P("groups");
d.setWidth("100%");
iGroupPanel.put(group.getDepartment().getId(), d);
}
d.add(ch);
} else {
groups.add(ch);
}
}
if (groups.getWidgetCount() > 0) {
iGlobalGroupsPanel = groups;
}
}
iFeatures.clear();
if (!iProperties.getFeatures().isEmpty()) {
for (FeatureInterface feature: iProperties.getFeatures()) {
CheckBox ch = new CheckBox(feature.getTitle());
ch.addStyleName("feature");
iFeatures.put(feature.getId(), ch);
}
}
iPeriodPreferences.clear();
for (ExamTypeInterface type: iProperties.getExamTypes()) {
PeriodPreferencesWidget pref = new PeriodPreferencesWidget(true);
iPeriodPreferences.put(type.getId(), pref);
}
}
public void setRoom(RoomDetailInterface room) {
iRoom = room;
if (iRoom == null) {
iRoom = new RoomDetailInterface();
iRoom.setSessionId(iProperties.getAcademicSessionId());
iRoom.setSessionName(iProperties.getAcademicSessionName());
iHeader.setEnabled("create", true);
iHeader.setEnabled("update", false);
iHeader.setEnabled("delete", false);
} else {
iHeader.setEnabled("create", false);
iHeader.setEnabled("update", true);
iHeader.setEnabled("delete", iRoom.isCanDelete());
}
iLastControllingDept = iRoom.getControlDepartment();
iLastEventDept = iRoom.getEventDepartment();
iForm.clear();
iHeader.clearMessage();
iForm.addHeaderRow(iHeader);
int firstRow = iForm.getRowCount();
if (iMode.hasSessionSelection()) {
iForm.addRow(MESSAGES.propAcademicSession(), new Label(iRoom.hasSessionName() ? iRoom.getSessionName() : iProperties.getAcademicSessionName()), 1);
}
if (iRoom.getRoomType() == null || iRoom.isCanChangeType()) {
iType.clearHint();
iType.getWidget().clear();
if (iRoom.getRoomType() == null) {
iType.getWidget().addItem(MESSAGES.itemSelect(), "-1");
for (RoomTypeInterface type: iProperties.getRoomTypes()) {
if (type.isRoom() && iProperties.isCanAddRoom())
iType.getWidget().addItem(type.getLabel(), type.getId().toString());
else if (!type.isRoom() && iProperties.isCanAddNonUniversity())
iType.getWidget().addItem(type.getLabel(), type.getId().toString());
}
iType.getWidget().setSelectedIndex(0);
} else {
for (RoomTypeInterface type: iProperties.getRoomTypes()) {
if (type.isRoom() && iRoom.getBuilding() != null)
iType.getWidget().addItem(type.getLabel(), type.getId().toString());
else if (!type.isRoom() && iRoom.getBuilding() == null)
iType.getWidget().addItem(type.getLabel(), type.getId().toString());
}
for (int i = 0; i < iType.getWidget().getItemCount(); i++) {
if (iType.getWidget().getValue(i).equals(iRoom.getRoomType().getId().toString())) {
iType.getWidget().setSelectedIndex(i); break;
}
}
}
iForm.addRow(MESSAGES.propRoomType(), iType, 1);
} else {
iForm.addRow(MESSAGES.propRoomType(), new Label(iRoom.getRoomType().getLabel(), false), 1);
}
if (iRoom.getUniqueId() != null && iRoom.getBuilding() == null) {
iBuildingRow = -1;
} else if (iRoom.getUniqueId() == null || iRoom.isCanChangeRoomProperties()) {
iBuilding.clearHint();
if (iRoom.getBuilding() == null) {
iBuilding.getWidget().setSelectedIndex(0);
} else {
iBuilding.getWidget().setSelectedIndex(1 + iProperties.getBuildings().indexOf(iRoom.getBuilding()));
}
iBuildingRow = iForm.addRow(MESSAGES.propBuilding(), iBuilding, 1);
} else {
iBuildingRow = iForm.addRow(MESSAGES.propBuilding(), new Label(iRoom.getBuilding().getAbbreviation() + " - " + iRoom.getBuilding().getName()), 1);
}
if (iRoom.getUniqueId() == null || iRoom.isCanChangeRoomProperties()) {
iName.clearHint();
iName.getWidget().setText(iRoom.getName() == null ? "" : iRoom.getName());
iForm.addRow(iNameLabel, iName, 1);
} else {
iForm.addRow(iNameLabel, new Label(iRoom.getName()), 1);
}
if (iRoom.getRoomType() == null || iRoom.isCanChangeType()) {
typeChanged();
} else {
if (iBuildingRow >= 0)
iForm.getRowFormatter().setVisible(iBuildingRow, iRoom.getRoomType() != null && iRoom.getRoomType().isRoom());
iNameLabel.setText(iRoom.getRoomType() != null && iRoom.getRoomType().isRoom() ? MESSAGES.propRoomNumber() : MESSAGES.propRoomName());
}
if (iRoom.getUniqueId() == null || iRoom.isCanChangeRoomProperties()) {
iDisplayName.setText(iRoom.getDisplayName() == null ? "" : iRoom.getDisplayName());
iForm.addRow(MESSAGES.propDisplayName(), iDisplayName, 1);
} else if (iRoom.hasDisplayName()) {
iForm.addRow(MESSAGES.propDisplayName(), new Label(iRoom.getDisplayName()), 1);
}
if ((iRoom.getUniqueId() == null && iProperties.isCanChangeExternalId()) || iRoom.isCanChangeExternalId()) {
iExternalId.setText(iRoom.getExternalId() == null ? "" : iRoom.getExternalId());
iForm.addRow(MESSAGES.propExternalId(), iExternalId, 1);
} else if (iRoom.hasExternalId()) {
iForm.addRow(MESSAGES.propExternalId(), new Label(iRoom.getExternalId()), 1);
}
if (iRoom.getUniqueId() == null || iRoom.isCanChangeCapacity()) {
iCapacity.clearHint();
iCapacity.getWidget().setValue(iRoom.getCapacity());
iForm.addRow(MESSAGES.propCapacity(), iCapacity, 1);
} else if (iRoom.getCapacity() != null) {
iForm.addRow(MESSAGES.propCapacity(), new Label(iRoom.getCapacity().toString()), 1);
}
if ((iRoom.getUniqueId() == null && iProperties.isCanChangeControll()) || iRoom.isCanChangeControll()) {
iControllingDepartment.clearHint();
iControllingDepartment.getWidget().clear();
iControllingDepartment.getWidget().addItem(MESSAGES.itemNoControlDepartment(), "-1");
for (DepartmentInterface department: iProperties.getDepartments())
iControllingDepartment.getWidget().addItem(department.getExtAbbreviationOrCode() + " - " + department.getExtLabelWhenExist(), department.getId().toString());
if (iRoom.getControlDepartment() == null) {
iControllingDepartment.getWidget().setSelectedIndex(0);
} else {
int index = iProperties.getDepartments().indexOf(iRoom.getControlDepartment());
if (index >= 0) {
iControllingDepartment.getWidget().setSelectedIndex(1 + index);
} else {
iControllingDepartment.getWidget().addItem(iRoom.getControlDepartment().getExtAbbreviationOrCode() + " - " + iRoom.getControlDepartment().getExtLabelWhenExist(), iRoom.getControlDepartment().getId().toString());
iControllingDepartment.getWidget().setSelectedIndex(iControllingDepartment.getWidget().getItemCount() - 1);
}
}
if (iRoom.getUniqueId() == null && iControllingDepartment.getWidget().getItemCount() == 2)
iControllingDepartment.getWidget().setSelectedIndex(1);
iForm.addRow(MESSAGES.propControllingDepartment(), iControllingDepartment, 1);
/* } else if (iRoom.getUniqueId() == null) {
iControllingDepartment.getWidget().clear();
for (DepartmentInterface department: iProperties.getDepartments())
iControllingDepartment.getWidget().addItem(department.getExtAbbreviationOrCode() + " - " + department.getExtLabelWhenExist(), department.getId().toString());
//TODO: guess selected department from filter
iForm.addRow(MESSAGES.propDepartment(), iControllingDepartment, 1);*/
} else if (iRoom.getControlDepartment() != null && iProperties.isCanSeeCourses()) {
iForm.addRow(MESSAGES.propControllingDepartment(), new Label(RoomDetail.toString(iRoom.getControlDepartment())), 1);
}
if (iRoom.getUniqueId() == null || iRoom.isCanChangeRoomProperties()) {
iX.setValue(iRoom.getX());
iY.setValue(iRoom.getY());
iForm.addRow(MESSAGES.propCoordinates(), iCoordinates, 1);
iArea.setValue(iRoom.getArea());
iForm.addRow(MESSAGES.propRoomArea(), iAreaPanel, 1);
if (iProperties.isCanSeeCourses()) {
iDistanceCheck.setValue(!iRoom.isIgnoreTooFar());
distanceCheckChanged();
iForm.addRow(MESSAGES.propDistanceCheck(), iDistanceCheck, 1);
}
iRoomCheck.setValue(!iRoom.isIgnoreRoomCheck());
roomCheckChanged();
iForm.addRow(MESSAGES.propRoomCheck(), iRoomCheck, 1);
if (iGoogleMapControl != null) iGoogleMapControl.setVisible(true);
} else {
if (iRoom.hasCoordinates())
if (iProperties != null && iProperties.hasEllipsoid())
iForm.addRow(MESSAGES.propCoordinates(), new HTML(MESSAGES.coordinatesWithEllipsoid(iRoom.getX(), iRoom.getY(), iProperties.getEllipsoid())), 1);
else
iForm.addRow(MESSAGES.propCoordinates(), new HTML(MESSAGES.coordinates(iRoom.getX(), iRoom.getY())), 1);
if (iRoom.getArea() != null)
iForm.addRow(MESSAGES.propRoomArea(), new HTML(MESSAGES.roomArea(iRoom.getArea()) + " " + CONSTANTS.roomAreaUnitsShort()), 1);
if (iProperties.isCanSeeCourses()) {
iForm.addRow(MESSAGES.propDistanceCheck(), new Check(!room.isIgnoreTooFar(), MESSAGES.infoDistanceCheckOn(), MESSAGES.infoDistanceCheckOff()), 1);
iForm.addRow(MESSAGES.propRoomCheck(), new Check(!room.isIgnoreRoomCheck(), MESSAGES.infoRoomCheckOn(), MESSAGES.infoRoomCheckOff()), 1);
} else if (iProperties.isCanSeeEvents()) {
iForm.addRow(MESSAGES.propRoomCheck(), new Check(!room.isIgnoreRoomCheck(), MESSAGES.infoRoomCheckOn(), MESSAGES.infoRoomCheckOff()), 1);
}
if (iGoogleMapControl != null) iGoogleMapControl.setVisible(false);
}
if ((iRoom.getUniqueId() == null && iProperties.isCanChangeExamStatus()) || iRoom.isCanChangeExamStatus()) {
for (Map.Entry<Long, CheckBox> e: iExaminationRooms.entrySet())
e.getValue().setValue(false);
if (iRoom.hasExamTypes()) {
for (ExamTypeInterface type: iRoom.getExamTypes())
iExaminationRooms.get(type.getId()).setValue(true);
}
iForm.addRow(MESSAGES.propExamRooms(), iExaminationRoomsPanel, 1);
iExamCapacity.getWidget().setValue(iRoom.getExamCapacity());
iForm.addRow(MESSAGES.propExamCapacity(), iExamCapacity, 1);
} else if (iProperties.isCanSeeExams() && (iRoom.getExamCapacity() != null || iRoom.hasExamTypes())) {
iForm.addRow(MESSAGES.propExamCapacity(), new RoomDetail.ExamSeatingCapacityLabel(iRoom), 1);
}
if ((iRoom.getUniqueId() == null && iProperties.isCanChangeEventProperties()) || iRoom.isCanChangeEventProperties()) {
iEventDepartment.clear();
if ((iRoom.getUniqueId() == null || iRoom.getEventDepartment() != null) && ((iRoom.getUniqueId() == null && iProperties.isCanChangeControll()) || iRoom.isCanChangeControll()))
iEventDepartment.addItem(MESSAGES.itemNoEventDepartment(), "-1");
for (DepartmentInterface department: iProperties.getDepartments())
if (department.isEvent())
iEventDepartment.addItem(department.getDeptCode() + " - " + department.getLabel(), department.getId().toString());
if (iRoom.getEventDepartment() == null) {
iEventDepartment.setSelectedIndex(0);
} else {
iEventDepartment.setSelectedIndex(0);
for (int i = 1; i < iEventDepartment.getItemCount(); i++) {
if (iEventDepartment.getValue(i).equals(iRoom.getEventDepartment().getId().toString())) {
iEventDepartment.setSelectedIndex(i); break;
}
}
if (iRoom.getEventDepartment() != null && "-1".equals(iEventDepartment.getValue(iEventDepartment.getSelectedIndex()))) {
iEventDepartment.addItem(iRoom.getEventDepartment().getDeptCode() + " - " + iRoom.getEventDepartment().getLabel(), iRoom.getEventDepartment().getId().toString());
iEventDepartment.setSelectedIndex(iEventDepartment.getItemCount() + - 1);
}
}
iForm.addRow(MESSAGES.propEventDepartment(), iEventDepartment, 1);
iEventStatus.setSelectedIndex(iRoom.getEventStatus() == null ? 0 : iRoom.getEventStatus() + 1);
iForm.addRow(MESSAGES.propEventStatus(), iEventStatus, 1);
iNote.getWidget().setText(iRoom.getEventNote() == null ? "" : iRoom.getEventNote());
iForm.addRow(MESSAGES.propEventNote(), iNote, 1);
iBreakTime.setValue(iRoom.getBreakTime());
iForm.addRow(MESSAGES.propBreakTime(), iBreakTimePanel, 1);
} else if (iProperties.isCanSeeEvents()) {
if (iRoom.getEventDepartment() != null)
iForm.addRow(MESSAGES.propEventDepartment(), new Label(RoomDetail.toString(iRoom.getEventDepartment(), true)), 1);
if (iRoom.getEventStatus() != null || iRoom.getDefaultEventStatus() != null) {
Label status = new Label(CONSTANTS.eventStatusName()[iRoom.getEventStatus() == null ? iRoom.getDefaultEventStatus() : iRoom.getEventStatus()]);
if (iRoom.getEventStatus() == null) status.addStyleName("default");
iForm.addRow(MESSAGES.propEventStatus(), status, 1);
}
if (iRoom.hasEventNote() || iRoom.hasDefaultEventNote()) {
HTML note = new HTML(iRoom.hasEventNote() ? iRoom.getEventNote() : iRoom.getDefaultEventNote());
if (!iRoom.hasEventNote()) note.addStyleName("default");
iForm.addRow(MESSAGES.propEventNote(), note, 1);
}
if (iRoom.getBreakTime() != null || iRoom.getDefaultBreakTime() != null) {
Label bt = new Label((iRoom.getBreakTime() == null ? iRoom.getDefaultBreakTime() : iRoom.getBreakTime()).toString());
if (iRoom.getBreakTime() == null) bt.addStyleName("default");
iForm.addRow(MESSAGES.propBreakTime(), bt, 1);
}
}
if (iProperties.isGoogleMap()) {
iForm.setWidget(firstRow, 2, iGoogleMap);
iForm.getFlexCellFormatter().setRowSpan(firstRow, 2, iForm.getRowCount() - firstRow - 1);
}
if (((iRoom.getUniqueId() == null && iProperties.isCanChangeGroups()) || iRoom.isCanChangeGroups()) && !iProperties.getGroups().isEmpty()) {
iForm.addHeaderRow(MESSAGES.headerRoomGroups());
for (Map.Entry<Long, CheckBox> e: iGroups.entrySet())
e.getValue().setValue(iRoom.hasGroup(e.getKey()));
if (iGlobalGroupsPanel != null) {
iForm.addRow(MESSAGES.propGlobalGroups(), iGlobalGroupsPanel);
} else {
List<GroupInterface> globalGroups = iRoom.getGlobalGroups();
if (!globalGroups.isEmpty())
iForm.addRow(MESSAGES.propGlobalGroups(), new RoomDetail.GroupsCell(globalGroups), 1);
}
for (DepartmentInterface dept: iProperties.getDepartments()) {
P d = iGroupPanel.get(dept.getId());
if (d != null)
iForm.addRow(dept.getExtLabelWhenExist() + ":", d);
}
} else if (iRoom.hasGroups()) {
iForm.addHeaderRow(MESSAGES.headerRoomGroups());
List<GroupInterface> globalGroups = iRoom.getGlobalGroups();
if (!globalGroups.isEmpty())
iForm.addRow(MESSAGES.propGlobalGroups(), new RoomDetail.GroupsCell(globalGroups));
List<GroupInterface> departmentalGroups = iRoom.getDepartmentalGroups(null);
if (!departmentalGroups.isEmpty())
iForm.addRow(MESSAGES.propDepartmenalGroups(), new RoomDetail.GroupsCell(departmentalGroups));
}
if (((iRoom.getUniqueId() == null && iProperties.isCanChangeFeatures()) || iRoom.isCanChangeFeatures()) && !iProperties.getFeatures().isEmpty()) {
iForm.addHeaderRow(MESSAGES.headerRoomFeatures());
for (Map.Entry<Long, CheckBox> e: iFeatures.entrySet())
e.getValue().setValue(iRoom.hasFeature(e.getKey()));
P features = new P("features");
Map<Long, P> fp = new HashMap<Long, P>();
for (FeatureInterface feature: iProperties.getFeatures()) {
CheckBox ch = iFeatures.get(feature.getId());
if (feature.getType() != null) {
P d = fp.get(feature.getType().getId());
if (d == null) {
d = new P("features");
d.setWidth("100%");
fp.put(feature.getType().getId(), d);
}
d.add(ch);
} else {
features.add(ch);
}
}
for (FeatureInterface feature: iRoom.getFeatures()) {
if (!iFeatures.containsKey(feature.getId()) && feature.getDepartment() == null) {
P f = new P("feature"); f.setText(feature.getTitle());
if (feature.getType() != null) {
P d = fp.get(feature.getType().getId());
if (d == null) {
d = new P("features");
d.setWidth("100%");
fp.put(feature.getType().getId(), d);
}
d.add(f);
} else {
features.add(f);
}
}
}
if (features.getWidgetCount() > 0)
iForm.addRow(MESSAGES.propFeatures(), features);
for (FeatureTypeInterface type: iProperties.getFeatureTypes()) {
P d = fp.get(type.getId());
if (d != null)
iForm.addRow(type.getLabel() + ":", d);
}
} else if (iRoom.hasFeatures()) {
iForm.addHeaderRow(MESSAGES.headerRoomFeatures());
List<FeatureInterface> features = iRoom.getFeatures((Long)null);
if (!features.isEmpty())
iForm.addRow(MESSAGES.propFeatures(), new RoomDetail.FeaturesCell(features));
for (FeatureTypeInterface type: iProperties.getFeatureTypes()) {
List<FeatureInterface> featuresOfType = iRoom.getFeatures(type);
if (!featuresOfType.isEmpty())
iForm.addRow(type.getLabel() + ":", new RoomDetail.FeaturesCell(featuresOfType));
}
}
if (iRoom.hasRoomSharingModel()) {
iRoomSharingHeader.clearMessage();
iRoomSharing.setEditable(iProperties.isCanEditDepartments() || (iRoom.getUniqueId() == null && iProperties.isCanChangeAvailability()) || iRoom.isCanChangeAvailability());
iRoomSharing.setModel(iRoom.getRoomSharingModel());
iRoomSharing.setVisible(true);
if (iRoom.getUniqueId() == null) {
iLastSelectedDepartmentId = Long.valueOf(iControllingDepartment.getWidget().getValue(iControllingDepartment.getWidget().getSelectedIndex()));
if (iLastSelectedDepartmentId > 0)
iRoomSharing.addOption(iLastSelectedDepartmentId);
}
iForm.addHeaderRow(iRoomSharingHeader);
iForm.addRow(iRoomSharing);
} else if (iProperties.isCanEditDepartments() || (iRoom.getUniqueId() == null && iProperties.isCanChangeAvailability()) || iRoom.isCanChangeAvailability()) {
iForm.addHeaderRow(iRoomSharingHeader);
iForm.addRow(iRoomSharing);
iRoomSharingHeader.showLoading();
iRoomSharing.setVisible(false);
RPC.execute(RoomInterface.RoomSharingRequest.load(iRoom.getSessionId(), iRoom.getUniqueId(), false, true), new AsyncCallback<RoomSharingModel>() {
@Override
public void onFailure(Throwable caught) {
iRoomSharingHeader.setErrorMessage(MESSAGES.failedToLoadRoomAvailability(caught.getMessage()));
}
@Override
public void onSuccess(RoomSharingModel result) {
iRoomSharingHeader.clearMessage();
iRoomSharing.setEditable(iProperties.isCanEditDepartments() || (iRoom.getUniqueId() == null && iProperties.isCanChangeAvailability()) || iRoom.isCanChangeAvailability());
iRoomSharing.setModel(result);
iRoomSharing.setVisible(true);
if (iRoom.getUniqueId() == null) {
iLastSelectedDepartmentId = Long.valueOf(iControllingDepartment.getWidget().getValue(iControllingDepartment.getWidget().getSelectedIndex()));
if (iLastSelectedDepartmentId > 0)
iRoomSharing.addOption(iLastSelectedDepartmentId);
}
}
});
}
if (iProperties.isCanEditRoomExams() || (iProperties.isCanSeeExams() && iRoom.isCanSeePeriodPreferences() && iRoom.hasExamTypes())) {
iPeriodPreferencesHeaderRow = iForm.addHeaderRow(iPeriodPreferencesHeader);
iForm.getRowFormatter().setVisible(iPeriodPreferencesHeaderRow, false);
for (ExamTypeInterface type: iProperties.getExamTypes()) {
PeriodPreferencesWidget pref = iPeriodPreferences.get(type.getId());
int row = iForm.addRow(MESSAGES.propExaminationPreferences(type.getLabel()), pref);
iPeriodPreferencesRow.put(type.getId(), row);
iForm.getRowFormatter().setVisible(iPeriodPreferencesRow.get(type.getId()), false);
}
iPeriodPreferencesHeader.clearMessage();
for (final ExamTypeInterface type: iProperties.getExamTypes()) {
final PeriodPreferencesWidget pref = iPeriodPreferences.get(type.getId());
if (iRoom.hasPeriodPreferenceModel(type.getId())) {
pref.setEditable(iProperties.isCanEditRoomExams());
pref.setModel(iRoom.getPeriodPreferenceModel(type.getId()));
iForm.getRowFormatter().setVisible(iPeriodPreferencesRow.get(type.getId()), iExaminationRooms.get(type.getId()).getValue());
if (iExaminationRooms.get(type.getId()).getValue())
iForm.getRowFormatter().setVisible(iPeriodPreferencesHeaderRow, true);
} else if ((iRoom.getUniqueId() == null && iProperties.isCanChangeExamStatus()) || iRoom.isCanChangeExamStatus()) {
iPeriodPreferencesHeader.showLoading();
iForm.getRowFormatter().setVisible(iPeriodPreferencesRow.get(type.getId()), false);
RPC.execute(RoomInterface.PeriodPreferenceRequest.load(iRoom.getSessionId(), iRoom.getUniqueId(), type.getId()), new AsyncCallback<PeriodPreferenceModel>() {
@Override
public void onFailure(Throwable caught) {
iPeriodPreferencesHeader.setErrorMessage(MESSAGES.failedToLoadPeriodPreferences(caught.getMessage()));
}
@Override
public void onSuccess(PeriodPreferenceModel result) {
iPeriodPreferencesHeader.clearMessage();
pref.setEditable(iProperties.isCanEditRoomExams());
pref.setModel(result);
iForm.getRowFormatter().setVisible(iPeriodPreferencesRow.get(type.getId()), iExaminationRooms.get(type.getId()).getValue());
}
});
} else {
iForm.getRowFormatter().setVisible(iPeriodPreferencesRow.get(type.getId()), false);
}
}
} else {
iPeriodPreferencesHeaderRow = -1;
iPeriodPreferencesRow.clear();
}
if (((iRoom.getUniqueId() == null && iProperties.isCanChangeEventAvailability()) || iRoom.isCanChangeEventAvailability()) ||
(iProperties.isCanSeeEvents() && iRoom.isCanSeeEventAvailability())) {
iForm.addHeaderRow(iEventAvailabilityHeader);
iForm.addRow(iEventAvailability);
iEventAvailabilityHeader.setVisible(!"-1".equals(iEventDepartment.getValue(iEventDepartment.getSelectedIndex())));
if (iRoom.hasEventAvailabilityModel()) {
iEventAvailabilityHeader.clearMessage();
iEventAvailability.setEditable((iRoom.getUniqueId() == null && iProperties.isCanChangeEventAvailability()) || iRoom.isCanChangeEventAvailability());
iEventAvailability.setModel(iRoom.getEventAvailabilityModel());
iEventAvailability.setVisible(!"-1".equals(iEventDepartment.getValue(iEventDepartment.getSelectedIndex())));
} else {
iEventAvailabilityHeader.showLoading();
iEventAvailability.setVisible(false);
RPC.execute(RoomInterface.RoomSharingRequest.load(iRoom.getSessionId(), iRoom.getUniqueId(), true), new AsyncCallback<RoomSharingModel>() {
@Override
public void onFailure(Throwable caught) {
iEventAvailabilityHeader.setErrorMessage(MESSAGES.failedToLoadRoomAvailability(caught.getMessage()));
}
@Override
public void onSuccess(RoomSharingModel result) {
iEventAvailabilityHeader.clearMessage();
iEventAvailability.setEditable((iRoom.getUniqueId() == null && iProperties.isCanChangeEventAvailability()) || iRoom.isCanChangeEventAvailability());
iEventAvailability.setModel(result);
iEventAvailability.setVisible(!"-1".equals(iEventDepartment.getValue(iEventDepartment.getSelectedIndex())));
}
});
}
}
if (iRoom.hasPictures() || (iRoom.getUniqueId() == null && iProperties.isCanChangePicture()) || iRoom.isCanChangePicture()) {
iForm.addHeaderRow(iPicturesHeader);
if ((iRoom.getUniqueId() == null && iProperties.isCanChangePicture()) || iRoom.isCanChangePicture())
iForm.addRow(MESSAGES.propNewPicture(), iFileUpload);
iForm.addRow(iPictures);
iPictures.clearTable(1);
if (iRoom.hasPictures()) {
for (final RoomPictureInterface picture: iRoom.getPictures())
iPictures.addRow(picture, line(picture));
}
}
iForm.addBottomRow(iFooter);
if (iRoom.getUniqueId() == null && iProperties.hasFutureSessions()) {
int row = iForm.addHeaderRow(iApplyToHeader);
iForm.getRowFormatter().addStyleName(row, "space-above");
iApplyTo.clearTable(1);
long id = 0;
for (AcademicSessionInterface session: iProperties.getFutureSessions()) {
List<Widget> line = new ArrayList<Widget>();
CheckBox select = new CheckBox();
line.add(select);
line.add(new Label());
line.add(new Label(session.getLabel()));
Integer flags = RoomCookie.getInstance().getFutureFlags(session.getId());
select.setValue(flags != null);
for (FutureOperation op: FutureOperation.values()) {
CheckBox ch = new CheckBox();
ch.setValue(canFutureOperation(iRoom, op) && ((flags == null && op.getDefaultSelectionNewRoom()) || (flags != null && op.in(flags))));
if (op == FutureOperation.ROOM_PROPERTIES) {
ch.setValue(true);
ch.setEnabled(false);
}
line.add(ch);
}
FutureRoomInterface fr = new FutureRoomInterface();
fr.setSession(session);
fr.setId(--id);
iApplyTo.addRow(fr, line);
}
for (FutureOperation op: FutureOperation.values()) {
iApplyTo.setColumnVisible(3 + op.ordinal(), canFutureOperation(iRoom, op));
}
iApplyTo.setColumnVisible(1, false);
iForm.addRow(iApplyTo);
} else if (iRoom.hasFutureRooms()) {
int row = iForm.addHeaderRow(iApplyToHeader);
iForm.getRowFormatter().addStyleName(row, "space-above");
iApplyTo.clearTable(1);
for (FutureRoomInterface fr: iRoom.getFutureRooms()) {
List<Widget> line = new ArrayList<Widget>();
CheckBox select = new CheckBox();
line.add(select);
line.add(new FutureRoomNameCell(fr));
line.add(new Label(fr.getSession().getLabel()));
Integer flags = RoomCookie.getInstance().getFutureFlags(fr.getSession().getId());
select.setValue(flags != null);
for (FutureOperation op: FutureOperation.values()) {
CheckBox ch = new CheckBox();
ch.setValue(canFutureOperation(iRoom, op) && ((flags == null && op.getDefaultSelection()) || (flags != null && op.in(flags))));
line.add(ch);
}
iApplyTo.addRow(fr, line);
}
for (FutureOperation op: FutureOperation.values()) {
iApplyTo.setColumnVisible(3 + op.ordinal(), canFutureOperation(iRoom, op));
}
iApplyTo.setColumnVisible(1, true);
iForm.addRow(iApplyTo);
}
}
public RoomDetailInterface getRoom() { return iRoom; }
protected void buildingChanged() {
BuildingInterface building = iProperties.getBuilding(Long.valueOf(iBuilding.getWidget().getValue(iBuilding.getWidget().getSelectedIndex())));
if (building != null) {
iX.setValue(building.getX());
iY.setValue(building.getY());
}
if (iProperties.isGoogleMap())
setMarker();
}
protected void typeChanged() {
RoomTypeInterface type = iProperties.getRoomType(Long.valueOf(iType.getWidget().getValue(iType.getWidget().getSelectedIndex())));
if (iBuildingRow >= 0)
iForm.getRowFormatter().setVisible(iBuildingRow, type != null && type.isRoom());
iNameLabel.setText(type != null && type.isRoom() ? MESSAGES.propRoomNumber() : MESSAGES.propRoomName());
}
private int iLastScrollTop, iLastScrollLeft;
public void show() {
UniTimePageLabel.getInstance().setPageName(iRoom.getUniqueId() == null ? MESSAGES.pageAddRoom() : MESSAGES.pageEditRoom());
setVisible(true);
iLastScrollLeft = Window.getScrollLeft();
iLastScrollTop = Window.getScrollTop();
onShow();
Window.scrollTo(0, 0);
if (iGoogleMap != null && !iGoogleMapInitialized) {
iGoogleMapInitialized = true;
ScriptInjector.fromUrl("https://maps.google.com/maps/api/js?sensor=false&callback=setupGoogleMap").setWindow(ScriptInjector.TOP_WINDOW).setCallback(
new Callback<Void, Exception>() {
@Override
public void onSuccess(Void result) {
}
@Override
public void onFailure(Exception e) {
UniTimeNotifications.error(e.getMessage(), e);
iGoogleMap = null;
iGoogleMapControl = null;
}
}).inject();
} else if (iGoogleMap != null) {
setMarker();
}
}
private List<Widget> line(final RoomPictureInterface picture) {
List<Widget> line = new ArrayList<Widget>();
Image image = null;
if (picture.getPictureType() == null || picture.getPictureType().isImage()) {
image = new Image(GWT.getHostPageBaseURL() + "picture?id=" + picture.getUniqueId());
image.addStyleName("image");
} else {
image = new Image(RESOURCES.download());
}
final ImageLink link = new ImageLink(image, GWT.getHostPageBaseURL() + "picture?id=" + picture.getUniqueId());
if (picture.getPictureType() != null && !picture.getPictureType().isImage())
link.setText(MESSAGES.roomPictureLink());
link.setTitle(picture.getName() + (picture.getPictureType() == null ? "" : " (" + picture.getPictureType().getLabel() + ")"));
line.add(link);
line.add(new Label(picture.getName()));
line.add(new Label(picture.getType()));
if ((iRoom.getUniqueId() == null && iProperties.isCanChangePicture()) || iRoom.isCanChangePicture()) {
final ListBox type = new ListBox(); type.setStyleName("unitime-TextBox");
if (picture.getPictureType() == null) {
type.addItem(MESSAGES.itemSelect(), "-1");
for (AttachmentTypeInterface t: iProperties.getPictureTypes()) {
type.addItem(t.getLabel(), t.getId().toString());
}
type.addChangeHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent event) {
Long id = Long.valueOf(type.getValue(type.getSelectedIndex()));
picture.setPictureType(iProperties.getPictureType(id));
if (picture.getPictureType() == null || picture.getPictureType().isImage()) {
link.setImage(new Image(GWT.getHostPageBaseURL() + "picture?id=" + picture.getUniqueId()));
link.getImage().addStyleName("image");
link.setText("");
} else {
link.setImage(new Image(RESOURCES.download()));
link.setText(MESSAGES.roomPictureLink());
}
link.setTitle(picture.getName() + (picture.getPictureType() == null ? "" : " (" + picture.getPictureType().getLabel() + ")"));
}
});
} else {
final AttachmentTypeInterface last = picture.getPictureType();
for (AttachmentTypeInterface t: iProperties.getPictureTypes()) {
type.addItem(t.getLabel(), t.getId().toString());
}
boolean found = false;
for (int i = 0; i < type.getItemCount(); i++) {
if (type.getValue(i).equals(picture.getPictureType().getId().toString())) {
type.setSelectedIndex(i); found = true; break;
}
}
if (!found) {
type.addItem(picture.getPictureType().getLabel(), picture.getPictureType().getId().toString());
type.setSelectedIndex(type.getItemCount() - 1);
}
type.addChangeHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent event) {
Long id = Long.valueOf(type.getValue(type.getSelectedIndex()));
if (last.getId().equals(id))
picture.setPictureType(last);
else
picture.setPictureType(iProperties.getPictureType(id));
if (picture.getPictureType() == null || picture.getPictureType().isImage()) {
link.setImage(new Image(GWT.getHostPageBaseURL() + "picture?id=" + picture.getUniqueId()));
link.getImage().addStyleName("image");
link.setText("");
} else {
link.setImage(new Image(RESOURCES.download()));
link.setText(MESSAGES.roomPictureLink());
}
link.setTitle(picture.getName() + (picture.getPictureType() == null ? "" : " (" + picture.getPictureType().getLabel() + ")"));
}
});
}
line.add(type);
} else {
line.add(new Label(picture.getPictureType() == null ? "" : picture.getPictureType().getLabel()));
}
if ((iRoom.getUniqueId() == null && iProperties.isCanChangePicture()) || iRoom.isCanChangePicture()) {
Image remove = new Image(RESOURCES.delete());
remove.setTitle(MESSAGES.titleDeleteRow());
remove.addStyleName("remove");
remove.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
for (int row = 1; row < iPictures.getRowCount(); row ++)
if (picture.getUniqueId().equals(iPictures.getData(row).getUniqueId())) {
iPictures.removeRow(row);
break;
}
iHeader.setEnabled("update", true);
event.stopPropagation();
}
});
line.add(remove);
}
return line;
}
public boolean validate() {
boolean result = true;
if (iRoom.getUniqueId() == null || iRoom.isCanChangeType()) {
Long typeId = Long.valueOf(iType.getWidget().getValue(iType.getWidget().getSelectedIndex()));
if (typeId < 0) {
iType.setErrorHint(MESSAGES.errorRoomTypeMustBeSelected());
result = false;
}
for (RoomTypeInterface type: iProperties.getRoomTypes()) {
if (type.getId().equals(typeId))
iRoom.setRoomType(type);
}
if (iRoom.getRoomType() == null) {
iType.setErrorHint(MESSAGES.errorRoomTypeMustBeSelected());
result = false;
}
}
if (iRoom.getUniqueId() == null || iRoom.isCanChangeRoomProperties()) {
if (iRoom.getRoomType() != null && iRoom.getRoomType().isRoom()) {
Long buildingId = Long.valueOf(iBuilding.getWidget().getValue(iBuilding.getWidget().getSelectedIndex()));
if (buildingId < 0) {
iBuilding.setErrorHint(MESSAGES.errorBuildingMustBeSelected(iRoom.getRoomType().getLabel()));
result = false;
} else {
for (BuildingInterface building: iProperties.getBuildings()) {
if (building.getId().equals(buildingId))
iRoom.setBuilding(building);
}
if (iRoom.getBuilding() == null) {
iBuilding.setErrorHint(MESSAGES.errorBuildingMustBeSelected(iRoom.getRoomType().getLabel()));
result = false;
}
}
}
iRoom.setName(iName.getWidget().getText());
if (iRoom.getName().isEmpty()) {
if (iRoom.getRoomType() != null && iRoom.getRoomType().isRoom())
iName.setErrorHint(MESSAGES.errorRoomNumberIsEmpty());
else
iName.setErrorHint(MESSAGES.errorLocationNameIsEmpty());
result = false;
}
iRoom.setDisplayName(iDisplayName.getText());
iRoom.setX(iX.toDouble());
iRoom.setY(iY.toDouble());
iRoom.setArea(iArea.toDouble());
if (iProperties.isCanSeeCourses())
iRoom.setIgnoreTooFar(!iDistanceCheck.getValue());
iRoom.setIgnoreRoomCheck(!iRoomCheck.getValue());
}
if ((iRoom.getUniqueId() == null && iProperties.isCanChangeExternalId()) || iRoom.isCanChangeExternalId()) {
iRoom.setExternalId(iExternalId.getText());
}
if (iRoom.getUniqueId() == null || iRoom.isCanChangeCapacity()) {
iRoom.setCapacity(iCapacity.getWidget().toInteger());
if (iRoom.getCapacity() == null) {
iCapacity.setErrorHint(MESSAGES.errorRoomCapacityIsEmpty());
result = false;
}
}
if ((iRoom.getUniqueId() == null && iProperties.isCanChangeControll()) || iRoom.isCanChangeControll()) {
Long deptId = Long.valueOf(iControllingDepartment.getWidget().getValue(iControllingDepartment.getWidget().getSelectedIndex()));
if (deptId < 0) {
iRoom.setControlDepartment(null);
} else if (iLastControllingDept != null && deptId.equals(iLastControllingDept.getId())) {
iRoom.setControlDepartment(iLastControllingDept);
} else {
for (DepartmentInterface dept: iProperties.getDepartments()) {
if (deptId.equals(dept.getId()))
iRoom.setControlDepartment(dept);
}
}
if (iRoom.getControlDepartment() != null && iRoomSharing.getModel() != null) {
boolean hasDepartment = false;
if (iRoomSharing.getModel() != null) {
for (RoomSharingOption opt: iRoomSharing.getModel().getOptions()) {
if (iRoom.getControlDepartment().getId().equals(opt.getId())) { hasDepartment = true; break; }
}
}
if (!hasDepartment)
iControllingDepartment.setErrorHint(MESSAGES.errorControllingDepartmentNotAmongRoomSharing());
}
}
if (iProperties.isCanEditRoomExams()) {
iRoom.getExamTypes().clear();
for (ExamTypeInterface type: iProperties.getExamTypes()) {
if (iExaminationRooms.get(type.getId()).getValue()) {
iRoom.getExamTypes().add(type);
iRoom.setPeriodPreferenceModel(iPeriodPreferences.get(type.getId()).getModel());
}
}
}
if ((iRoom.getUniqueId() == null && iProperties.isCanChangeExamStatus()) || iRoom.isCanChangeExamStatus()) {
iRoom.setExamCapacity(iExamCapacity.getWidget().toInteger());
if (iRoom.hasExamTypes() && iRoom.getExamCapacity() == null) {
iExamCapacity.setErrorHint(MESSAGES.errorRoomExamCapacityIsEmpty());
result = false;
}
}
if ((iRoom.getUniqueId() == null && iProperties.isCanChangeEventProperties()) || iRoom.isCanChangeEventProperties()) {
Long deptId = Long.valueOf(iEventDepartment.getValue(iEventDepartment.getSelectedIndex()));
if (deptId < 0) {
iRoom.setEventDepartment(null);
} else if (iLastEventDept != null && deptId.equals(iLastEventDept.getId())) {
iRoom.setEventDepartment(iLastEventDept);
} else {
for (DepartmentInterface dept: iProperties.getDepartments()) {
if (deptId.equals(dept.getId()))
iRoom.setEventDepartment(dept);
}
}
if (iEventStatus.getSelectedIndex() == 0)
iRoom.setEventStatus(null);
else
iRoom.setEventStatus(iEventStatus.getSelectedIndex() - 1);
iRoom.setEventNote(iNote.getWidget().getText().isEmpty() ? null : iNote.getWidget().getText());
if (iNote.getWidget().getText().length() > 2048) {
iNote.setErrorHint(MESSAGES.errorEventNoteTooLong());
result = false;
}
iRoom.setBreakTime(iBreakTime.toInteger());
}
if ((iRoom.getUniqueId() == null && iProperties.isCanChangeGroups()) || iRoom.isCanChangeGroups()) {
for (GroupInterface group: iProperties.getGroups()) {
if (iGroups.get(group.getId()).getValue()) {
if (!iRoom.hasGroup(group.getId()))
iRoom.addGroup(group);
} else {
if (iRoom.hasGroup(group.getId()))
iRoom.removeGroup(group);
}
}
}
if ((iRoom.getUniqueId() == null && iProperties.isCanChangeFeatures()) || iRoom.isCanChangeFeatures()) {
for (FeatureInterface feature: iProperties.getFeatures()) {
if (iFeatures.get(feature.getId()).getValue()) {
if (!iRoom.hasFeature(feature.getId()))
iRoom.addFeature(feature);
} else {
if (iRoom.hasFeature(feature.getId()))
iRoom.removeFeature(feature);
}
}
}
if (iProperties.isCanEditDepartments() || (iRoom.getUniqueId() == null && iProperties.isCanChangeAvailability()) || iRoom.isCanChangeAvailability()) {
iRoom.setRoomSharingModel(iRoomSharing.getModel());
}
if ((iRoom.getUniqueId() == null && iProperties.isCanChangeEventAvailability()) || iRoom.isCanChangeEventAvailability()) {
iRoom.setEventAvailabilityModel(iEventAvailability.getModel());
}
if ((iRoom.getUniqueId() == null && iProperties.isCanChangePicture()) || iRoom.isCanChangePicture()) {
iRoom.getPictures().clear();
iRoom.getPictures().addAll(iPictures.getData());
}
if (iProperties.isCanEditDepartments() || (iRoom.getUniqueId() == null && iProperties.isCanChangeAvailability()) || iRoom.isCanChangeAvailability()) {
boolean hasDepartment = (iRoom.getEventDepartment() != null);
if (!hasDepartment && iRoomSharing.getModel() != null) {
for (RoomSharingOption opt: iRoomSharing.getModel().getOptions()) {
if (opt.getId() > 0) { hasDepartment = true; break; }
}
}
if (!hasDepartment) {
iRoomSharingHeader.setErrorMessage(MESSAGES.errorRoomHasNoDepartment());
result = false;
} else
iRoomSharingHeader.clearMessage();
}
return result;
}
public boolean isGoogleMapEditable() {
return iGoogleMapControl != null && iGoogleMapControl.isVisible();
}
public void hide(RoomDetailInterface room, boolean canShowDetail, String message) {
setVisible(false);
onHide(room, canShowDetail, message);
Window.scrollTo(iLastScrollLeft, iLastScrollTop);
}
protected void onHide(RoomDetailInterface detail, boolean canShowDetail, String message) {
}
protected void onShow() {
}
protected native void addGoogleMap(Element canvas, Element control) /*-{
$wnd.geoceodeMarker = function geoceodeMarker() {
var searchBox = $doc.getElementById('mapSearchBox');
$wnd.geocoder.geocode({'location': $wnd.marker.getPosition()}, function(results, status) {
if (status == $wnd.google.maps.GeocoderStatus.OK) {
if (results[0]) {
$wnd.marker.setTitle(results[0].formatted_address);
searchBox.value = results[0].formatted_address;
} else {
$wnd.marker.setTitle(null);
searchBox.value = "";
}
} else {
$wnd.marker.setTitle(null);
searchBox.value = "";
}
});
}
$wnd.that = this
$wnd.setupGoogleMap = function setupGoogleMap() {
var latlng = new $wnd.google.maps.LatLng(50, -58);
var myOptions = {
zoom: 2,
center: latlng,
mapTypeId: $wnd.google.maps.MapTypeId.ROADMAP
};
$wnd.geocoder = new $wnd.google.maps.Geocoder();
$wnd.map = new $wnd.google.maps.Map(canvas, myOptions);
$wnd.marker = new $wnd.google.maps.Marker({
position: latlng,
map: $wnd.map,
draggable: true,
visible: false
});
$wnd.map.controls[$wnd.google.maps.ControlPosition.BOTTOM_LEFT].push(control);
var t = null;
$wnd.google.maps.event.addListener($wnd.marker, 'position_changed', function() {
$doc.getElementById("coordX").value = '' + $wnd.marker.getPosition().lat().toFixed(6);
$doc.getElementById("coordY").value = '' + $wnd.marker.getPosition().lng().toFixed(6);
if (t != null) clearTimeout(t);
t = setTimeout($wnd.geoceodeMarker, 500);
});
$wnd.google.maps.event.addListener($wnd.map, 'rightclick', function(event) {
if ($wnd.marker.getDraggable()) {
$wnd.marker.setPosition(event.latLng);
$wnd.marker.setVisible(true);
}
});
$wnd.that.@org.unitime.timetable.gwt.client.rooms.RoomEdit::setMarker()();
};
}-*/;
protected native void setMarker() /*-{
try {
var x = $doc.getElementById("coordX").value;
var y = $doc.getElementById("coordY").value;
if (x && y) {
var pos = new $wnd.google.maps.LatLng(x, y);
$wnd.marker.setPosition(pos);
$wnd.marker.setVisible(true);
if ($wnd.marker.getMap().getZoom() <= 10) $wnd.marker.getMap().setZoom(16);
$wnd.marker.getMap().panTo(pos);
} else {
$wnd.marker.setVisible(false);
}
$wnd.marker.setDraggable(this.@org.unitime.timetable.gwt.client.rooms.RoomEdit::isGoogleMapEditable()());
} catch (error) {}
}-*/;
protected native void geocodeAddress() /*-{
var address = $doc.getElementById("mapSearchBox").value;
$wnd.geocoder.geocode({ 'address': address }, function(results, status) {
if (status == $wnd.google. maps.GeocoderStatus.OK) {
if (results[0]) {
$wnd.marker.setPosition(results[0].geometry.location);
$wnd.marker.setTitle(results[0].formatted_address);
$wnd.marker.setVisible(true);
if ($wnd.map.getZoom() <= 10) $wnd.map.setZoom(16);
$wnd.map.panTo(results[0].geometry.location);
} else {
$wnd.marker.setVisible(false);
}
} else {
$wnd.marker.setVisible(false);
}
});
}-*/;
protected String getFutureOperationLabel(FutureOperation op) {
switch (op) {
case ROOM_PROPERTIES:
return MESSAGES.colChangeRoomProperties();
case EXAM_PROPERTIES:
return MESSAGES.colChangeExamProperties();
case EVENT_PROPERTIES:
return MESSAGES.colChangeEventProperties();
case GROUPS:
return MESSAGES.colChangeRoomGroups();
case FEATURES:
return MESSAGES.colChangeRoomFeatures();
case ROOM_SHARING:
return MESSAGES.colChangeRoomSharing();
case EXAM_PREFS:
return MESSAGES.colChangeRoomPeriodPreferences();
case EVENT_AVAILABILITY:
return MESSAGES.colChangeRoomEventAvailability();
case PICTURES:
return MESSAGES.colChangeRoomPictures();
}
return op.name();
}
protected boolean canFutureOperation(RoomDetailInterface room, FutureOperation op) {
switch (op) {
case ROOM_PROPERTIES:
return iRoom.getRoomType() == null || iRoom.isCanChangeType() || iRoom.isCanChangeRoomProperties() || iRoom.isCanChangeExternalId() || iRoom.isCanChangeCapacity() || iRoom.isCanChangeControll();
case EXAM_PROPERTIES:
return (iRoom.getRoomType() == null && iProperties.isCanChangeExamStatus()) || iRoom.isCanChangeExamStatus();
case EVENT_PROPERTIES:
return (iRoom.getUniqueId() == null && iProperties.isCanChangeEventProperties()) || iRoom.isCanChangeEventProperties();
case GROUPS:
return ((iRoom.getUniqueId() == null && iProperties.isCanChangeGroups()) || iRoom.isCanChangeGroups()) && !iProperties.getGroups().isEmpty();
case FEATURES:
return ((iRoom.getUniqueId() == null && iProperties.isCanChangeFeatures()) || iRoom.isCanChangeFeatures()) && !iProperties.getFeatures().isEmpty();
case ROOM_SHARING:
return iProperties.isCanEditDepartments() || (iRoom.getUniqueId() == null && iProperties.isCanChangeAvailability()) || iRoom.isCanChangeAvailability();
case EXAM_PREFS:
return iProperties.isCanEditRoomExams();
case EVENT_AVAILABILITY:
return (iRoom.getUniqueId() == null && iProperties.isCanChangeEventAvailability()) || iRoom.isCanChangeEventAvailability();
case PICTURES:
return (iRoom.getUniqueId() == null && iProperties.isCanChangePicture()) || iRoom.isCanChangePicture();
default:
return false;
}
}
protected void fillFutureFlags(RoomUpdateRpcRequest request, boolean includeWhenNoFlags) {
request.clearFutureFlags();
if (iRoom.getUniqueId() == null && iProperties.hasFutureSessions()) {
for (int i = 1; i < iApplyTo.getRowCount(); i++) {
CheckBox ch = (CheckBox)iApplyTo.getWidget(i, 0);
if (ch.getValue()) {
int flags = 0;
for (FutureOperation op: FutureOperation.values()) {
CheckBox x = (CheckBox)iApplyTo.getWidget(i, 3 + op.ordinal());
if (x.getValue())
flags = op.set(flags);
}
if (flags == 0 && !includeWhenNoFlags) continue;
request.setFutureFlag(-iApplyTo.getData(1).getSession().getId(), flags);
RoomCookie.getInstance().setFutureFlags(iApplyTo.getData(1).getSession().getId(), flags);
} else {
RoomCookie.getInstance().setFutureFlags(iApplyTo.getData(1).getSession().getId(), null);
}
}
} else if (iRoom.hasFutureRooms()) {
for (int i = 1; i < iApplyTo.getRowCount(); i++) {
CheckBox ch = (CheckBox)iApplyTo.getWidget(i, 0);
if (ch.getValue()) {
int flags = 0;
for (FutureOperation op: FutureOperation.values()) {
CheckBox x = (CheckBox)iApplyTo.getWidget(i, 3 + op.ordinal());
if (x.getValue())
flags = op.set(flags);
}
if (flags == 0 && !includeWhenNoFlags) continue;
request.setFutureFlag(iApplyTo.getData(1).getId(), flags);
RoomCookie.getInstance().setFutureFlags(iApplyTo.getData(1).getSession().getId(), flags);
} else {
RoomCookie.getInstance().setFutureFlags(iApplyTo.getData(1).getSession().getId(), null);
}
}
}
}
protected String generateAlsoUpdateMessage(boolean includeWhenNoFlags) {
if ((iRoom.getUniqueId() == null && iProperties.hasFutureSessions()) || iRoom.hasFutureRooms()) {
List<String> ret = new ArrayList<String>();
for (int i = 1; i < iApplyTo.getRowCount(); i++) {
CheckBox ch = (CheckBox)iApplyTo.getWidget(i, 0);
if (ch.getValue()) {
int flags = 0;
for (FutureOperation op: FutureOperation.values()) {
CheckBox x = (CheckBox)iApplyTo.getWidget(i, 3 + op.ordinal());
if (x.getValue())
flags = op.set(flags);
}
if (flags == 0 && !includeWhenNoFlags) continue;
ret.add(iApplyTo.getData(1).getSession().getLabel());
}
}
if (!ret.isEmpty())
return ToolBox.toString(ret);
}
return null;
}
class FutureRoomNameCell extends Label {
FutureRoomNameCell(final FutureRoomInterface room) {
super(room.hasDisplayName() ? MESSAGES.label(room.getLabel(), room.getDisplayName()) : room.getLabel());
addMouseOverHandler(new MouseOverHandler() {
@Override
public void onMouseOver(MouseOverEvent event) {
RoomHint.showHint(FutureRoomNameCell.this.getElement(), room.getId(), null, null, true);
}
});
addMouseOutHandler(new MouseOutHandler() {
@Override
public void onMouseOut(MouseOutEvent event) {
RoomHint.hideHint();
}
});
}
}
protected void roomCheckChanged() {
iRoomCheck.setHTML(iRoomCheck.getValue() ? MESSAGES.infoRoomCheckOn() : MESSAGES.infoRoomCheckOff());
if (iRoomCheck.getValue()) {
iRoomCheck.addStyleName("check-enabled");
iRoomCheck.removeStyleName("check-disabled");
} else {
iRoomCheck.addStyleName("check-disabled");
iRoomCheck.removeStyleName("check-enabled");
}
}
protected void distanceCheckChanged() {
iDistanceCheck.setHTML(iDistanceCheck.getValue() ? MESSAGES.infoDistanceCheckOn() : MESSAGES.infoDistanceCheckOff());
if (iDistanceCheck.getValue()) {
iDistanceCheck.addStyleName("check-enabled");
iDistanceCheck.removeStyleName("check-disabled");
} else {
iDistanceCheck.addStyleName("check-disabled");
iDistanceCheck.removeStyleName("check-enabled");
}
}
}
| |
/*
* Copyright 2010 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.optaplanner.core.config.localsearch;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamImplicit;
import org.optaplanner.core.config.heuristic.policy.HeuristicConfigPolicy;
import org.optaplanner.core.config.heuristic.selector.common.SelectionCacheType;
import org.optaplanner.core.config.heuristic.selector.common.SelectionOrder;
import org.optaplanner.core.config.heuristic.selector.move.MoveSelectorConfig;
import org.optaplanner.core.config.heuristic.selector.move.composite.CartesianProductMoveSelectorConfig;
import org.optaplanner.core.config.heuristic.selector.move.composite.UnionMoveSelectorConfig;
import org.optaplanner.core.config.heuristic.selector.move.generic.ChangeMoveSelectorConfig;
import org.optaplanner.core.config.heuristic.selector.move.generic.SwapMoveSelectorConfig;
import org.optaplanner.core.config.localsearch.decider.acceptor.AcceptorConfig;
import org.optaplanner.core.config.localsearch.decider.acceptor.AcceptorType;
import org.optaplanner.core.config.localsearch.decider.forager.LocalSearchForagerConfig;
import org.optaplanner.core.config.localsearch.decider.forager.LocalSearchPickEarlyType;
import org.optaplanner.core.config.phase.PhaseConfig;
import org.optaplanner.core.config.solver.EnvironmentMode;
import org.optaplanner.core.config.util.ConfigUtils;
import org.optaplanner.core.impl.heuristic.selector.move.MoveSelector;
import org.optaplanner.core.impl.localsearch.DefaultLocalSearchPhase;
import org.optaplanner.core.impl.localsearch.LocalSearchPhase;
import org.optaplanner.core.impl.localsearch.decider.LocalSearchDecider;
import org.optaplanner.core.impl.localsearch.decider.acceptor.Acceptor;
import org.optaplanner.core.impl.localsearch.decider.forager.LocalSearchForager;
import org.optaplanner.core.impl.solver.recaller.BestSolutionRecaller;
import org.optaplanner.core.impl.solver.termination.Termination;
import static org.apache.commons.lang3.ObjectUtils.*;
@XStreamAlias("localSearch")
public class LocalSearchPhaseConfig extends PhaseConfig<LocalSearchPhaseConfig> {
// Warning: all fields are null (and not defaulted) because they can be inherited
// and also because the input config file should match the output config file
protected LocalSearchType localSearchType = null;
// TODO This is a List due to XStream limitations. With JAXB it could be just a MoveSelectorConfig instead.
@XStreamImplicit()
private List<MoveSelectorConfig> moveSelectorConfigList = null;
@XStreamAlias("acceptor")
private AcceptorConfig acceptorConfig = null;
@XStreamAlias("forager")
private LocalSearchForagerConfig foragerConfig = null;
// ************************************************************************
// Constructors and simple getters/setters
// ************************************************************************
public LocalSearchType getLocalSearchType() {
return localSearchType;
}
public void setLocalSearchType(LocalSearchType localSearchType) {
this.localSearchType = localSearchType;
}
public MoveSelectorConfig getMoveSelectorConfig() {
return moveSelectorConfigList == null ? null : moveSelectorConfigList.get(0);
}
public void setMoveSelectorConfig(MoveSelectorConfig moveSelectorConfig) {
this.moveSelectorConfigList = moveSelectorConfig == null ? null : Collections.singletonList(moveSelectorConfig);
}
public AcceptorConfig getAcceptorConfig() {
return acceptorConfig;
}
public void setAcceptorConfig(AcceptorConfig acceptorConfig) {
this.acceptorConfig = acceptorConfig;
}
public LocalSearchForagerConfig getForagerConfig() {
return foragerConfig;
}
public void setForagerConfig(LocalSearchForagerConfig foragerConfig) {
this.foragerConfig = foragerConfig;
}
// ************************************************************************
// Builder methods
// ************************************************************************
@Override
public LocalSearchPhase buildPhase(int phaseIndex, HeuristicConfigPolicy solverConfigPolicy,
BestSolutionRecaller bestSolutionRecaller, Termination solverTermination) {
HeuristicConfigPolicy phaseConfigPolicy = solverConfigPolicy.createPhaseConfigPolicy();
DefaultLocalSearchPhase phase = new DefaultLocalSearchPhase(
phaseIndex, solverConfigPolicy.getLogIndentation(), bestSolutionRecaller,
buildPhaseTermination(phaseConfigPolicy, solverTermination));
phase.setDecider(buildDecider(phaseConfigPolicy,
phase.getTermination()));
EnvironmentMode environmentMode = phaseConfigPolicy.getEnvironmentMode();
if (environmentMode.isNonIntrusiveFullAsserted()) {
phase.setAssertStepScoreFromScratch(true);
}
if (environmentMode.isIntrusiveFastAsserted()) {
phase.setAssertExpectedStepScore(true);
phase.setAssertShadowVariablesAreNotStaleAfterStep(true);
}
return phase;
}
private LocalSearchDecider buildDecider(HeuristicConfigPolicy configPolicy, Termination termination) {
MoveSelector moveSelector = buildMoveSelector(configPolicy);
Acceptor acceptor = buildAcceptor(configPolicy);
LocalSearchForager forager = buildForager(configPolicy);
LocalSearchDecider decider = new LocalSearchDecider(configPolicy.getLogIndentation(),
termination, moveSelector, acceptor, forager);
if (moveSelector.isNeverEnding() && !forager.supportsNeverEndingMoveSelector()) {
throw new IllegalStateException("The moveSelector (" + moveSelector
+ ") has neverEnding (" + moveSelector.isNeverEnding()
+ "), but the forager (" + forager
+ ") does not support it.\n"
+ "Maybe configure the <forager> with an <acceptedCountLimit>.");
}
EnvironmentMode environmentMode = configPolicy.getEnvironmentMode();
if (environmentMode.isNonIntrusiveFullAsserted()) {
decider.setAssertMoveScoreFromScratch(true);
}
if (environmentMode.isIntrusiveFastAsserted()) {
decider.setAssertExpectedUndoMoveScore(true);
}
return decider;
}
protected Acceptor buildAcceptor(HeuristicConfigPolicy configPolicy) {
AcceptorConfig acceptorConfig_;
if (acceptorConfig != null) {
if (localSearchType != null) {
throw new IllegalArgumentException("The localSearchType (" + localSearchType
+ ") must not be configured if the acceptorConfig (" + acceptorConfig
+ ") is explicitly configured.");
}
acceptorConfig_ = acceptorConfig;
} else {
LocalSearchType localSearchType_ = defaultIfNull(localSearchType, LocalSearchType.LATE_ACCEPTANCE);
acceptorConfig_ = new AcceptorConfig();
switch (localSearchType_) {
case HILL_CLIMBING:
case VARIABLE_NEIGHBORHOOD_DESCENT:
acceptorConfig_.setAcceptorTypeList(Collections.singletonList(AcceptorType.HILL_CLIMBING));
break;
case TABU_SEARCH:
acceptorConfig_.setAcceptorTypeList(Collections.singletonList(AcceptorType.ENTITY_TABU));
break;
case SIMULATED_ANNEALING:
acceptorConfig_.setAcceptorTypeList(Collections.singletonList(AcceptorType.SIMULATED_ANNEALING));
break;
case LATE_ACCEPTANCE:
acceptorConfig_.setAcceptorTypeList(Collections.singletonList(AcceptorType.LATE_ACCEPTANCE));
break;
default:
throw new IllegalStateException("The localSearchType (" + localSearchType_
+ ") is not implemented.");
}
}
return acceptorConfig_.buildAcceptor(configPolicy);
}
protected LocalSearchForager buildForager(HeuristicConfigPolicy configPolicy) {
LocalSearchForagerConfig foragerConfig_;
if (foragerConfig != null) {
if (localSearchType != null) {
throw new IllegalArgumentException("The localSearchType (" + localSearchType
+ ") must not be configured if the foragerConfig (" + foragerConfig
+ ") is explicitly configured.");
}
foragerConfig_ = foragerConfig;
} else {
LocalSearchType localSearchType_ = defaultIfNull(localSearchType, LocalSearchType.LATE_ACCEPTANCE);
foragerConfig_ = new LocalSearchForagerConfig();
switch (localSearchType_) {
case HILL_CLIMBING:
foragerConfig_.setAcceptedCountLimit(1);
break;
case TABU_SEARCH:
// Slow stepping algorithm
foragerConfig_.setAcceptedCountLimit(1000);
break;
case SIMULATED_ANNEALING:
case LATE_ACCEPTANCE:
// Fast stepping algorithm
foragerConfig_.setAcceptedCountLimit(1);
break;
case VARIABLE_NEIGHBORHOOD_DESCENT:
foragerConfig_.setPickEarlyType(LocalSearchPickEarlyType.FIRST_LAST_STEP_SCORE_IMPROVING);
break;
default:
throw new IllegalStateException("The localSearchType (" + localSearchType_
+ ") is not implemented.");
}
}
return foragerConfig_.buildForager(configPolicy);
}
protected MoveSelector buildMoveSelector(HeuristicConfigPolicy configPolicy) {
MoveSelector moveSelector;
SelectionCacheType defaultCacheType = SelectionCacheType.JUST_IN_TIME;
SelectionOrder defaultSelectionOrder;
if (localSearchType == LocalSearchType.VARIABLE_NEIGHBORHOOD_DESCENT) {
defaultSelectionOrder = SelectionOrder.ORIGINAL;
} else {
defaultSelectionOrder = SelectionOrder.RANDOM;
}
if (ConfigUtils.isEmptyCollection(moveSelectorConfigList)) {
// Default to changeMoveSelector and swapMoveSelector
UnionMoveSelectorConfig unionMoveSelectorConfig = new UnionMoveSelectorConfig();
unionMoveSelectorConfig.setMoveSelectorConfigList(Arrays.<MoveSelectorConfig>asList(
new ChangeMoveSelectorConfig(), new SwapMoveSelectorConfig()));
moveSelector = unionMoveSelectorConfig.buildMoveSelector(configPolicy,
defaultCacheType, defaultSelectionOrder);
} else if (moveSelectorConfigList.size() == 1) {
moveSelector = moveSelectorConfigList.get(0).buildMoveSelector(
configPolicy, defaultCacheType, defaultSelectionOrder);
} else {
// TODO moveSelectorConfigList is only a List because of XStream limitations.
throw new IllegalArgumentException("The moveSelectorConfigList (" + moveSelectorConfigList
+ ") must be a singleton or empty. Use a single " + UnionMoveSelectorConfig.class.getSimpleName()
+ " or " + CartesianProductMoveSelectorConfig.class.getSimpleName()
+ " element to nest multiple MoveSelectors.");
}
return moveSelector;
}
@Override
public void inherit(LocalSearchPhaseConfig inheritedConfig) {
super.inherit(inheritedConfig);
localSearchType = ConfigUtils.inheritOverwritableProperty(localSearchType,
inheritedConfig.getLocalSearchType());
setMoveSelectorConfig(ConfigUtils.inheritOverwritableProperty(
getMoveSelectorConfig(), inheritedConfig.getMoveSelectorConfig()));
acceptorConfig = ConfigUtils.inheritConfig(acceptorConfig, inheritedConfig.getAcceptorConfig());
foragerConfig = ConfigUtils.inheritConfig(foragerConfig, inheritedConfig.getForagerConfig());
}
}
| |
/**
* JBoss, Home of Professional Open Source.
* Copyright 2014 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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.pnc.rest.provider;
import com.google.common.base.Preconditions;
import org.jboss.pnc.model.BuildConfiguration;
import org.jboss.pnc.model.BuildConfigurationAudited;
import org.jboss.pnc.model.BuildRecord;
import org.jboss.pnc.model.IdRev;
import org.jboss.pnc.model.ProductVersion;
import org.jboss.pnc.rest.restmodel.BuildConfigurationAuditedRest;
import org.jboss.pnc.rest.restmodel.BuildConfigurationRest;
import org.jboss.pnc.rest.restmodel.BuildRecordRest;
import org.jboss.pnc.rest.restmodel.ProductVersionRest;
import org.jboss.pnc.spi.datastore.repositories.BuildConfigurationAuditedRepository;
import org.jboss.pnc.spi.datastore.repositories.BuildConfigurationRepository;
import org.jboss.pnc.spi.datastore.repositories.BuildRecordRepository;
import org.jboss.pnc.spi.datastore.repositories.PageInfoProducer;
import org.jboss.pnc.spi.datastore.repositories.ProductVersionRepository;
import org.jboss.pnc.spi.datastore.repositories.SortInfoProducer;
import org.jboss.pnc.spi.datastore.repositories.api.PageInfo;
import org.jboss.pnc.spi.datastore.repositories.api.Predicate;
import org.jboss.pnc.spi.datastore.repositories.api.RSQLPredicateProducer;
import org.jboss.pnc.spi.datastore.repositories.api.SortInfo;
import org.jboss.pnc.spi.datastore.repositories.api.SortInfo.SortingDirection;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.ws.rs.core.Response;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import static org.jboss.pnc.rest.utils.StreamHelper.nullableStreamOf;
import static org.jboss.pnc.spi.datastore.predicates.BuildConfigurationPredicates.*;
import static org.jboss.pnc.spi.datastore.predicates.BuildRecordPredicates.withBuildConfigurationId;
@Stateless
public class BuildConfigurationProvider {
private BuildConfigurationRepository buildConfigurationRepository;
private BuildConfigurationAuditedRepository buildConfigurationAuditedRepository;
private BuildRecordRepository buildRecordRepository;
private ProductVersionRepository productVersionRepository;
private RSQLPredicateProducer rsqlPredicateProducer;
private SortInfoProducer sortInfoProducer;
private PageInfoProducer pageInfoProducer;
@Inject
public BuildConfigurationProvider(BuildConfigurationRepository buildConfigurationRepository,
BuildConfigurationAuditedRepository buildConfigurationAuditedRepository,
BuildRecordRepository buildRecordRepository,
ProductVersionRepository productVersionRepository,
RSQLPredicateProducer rsqlPredicateProducer,
SortInfoProducer sortInfoProducer, PageInfoProducer pageInfoProducer) {
this.buildConfigurationRepository = buildConfigurationRepository;
this.buildConfigurationAuditedRepository = buildConfigurationAuditedRepository;
this.buildRecordRepository = buildRecordRepository;
this.rsqlPredicateProducer = rsqlPredicateProducer;
this.sortInfoProducer = sortInfoProducer;
this.pageInfoProducer = pageInfoProducer;
this.productVersionRepository = productVersionRepository;
}
// needed for EJB/CDI
public BuildConfigurationProvider() {
}
public Function<? super BuildConfiguration, ? extends BuildConfigurationRest> toRestModel() {
return projectConfiguration -> new BuildConfigurationRest(projectConfiguration);
}
public List<BuildConfigurationRest> getAll(int pageIndex, int pageSize, String sortingRsql, String query) {
Predicate<BuildConfiguration> rsqlPredicate = rsqlPredicateProducer.getPredicate(BuildConfiguration.class, query);
PageInfo pageInfo = pageInfoProducer.getPageInfo(pageIndex, pageSize);
SortInfo sortInfo = sortInfoProducer.getSortInfo(sortingRsql);
return nullableStreamOf(buildConfigurationRepository.queryWithPredicates(pageInfo, sortInfo, rsqlPredicate))
.map(toRestModel())
.collect(Collectors.toList());
}
public List<BuildConfigurationRest> getAllForProject(Integer pageIndex, Integer pageSize, String sortingRsql, String query,
Integer projectId) {
Predicate<BuildConfiguration> rsqlPredicate = rsqlPredicateProducer.getPredicate(BuildConfiguration.class, query);
PageInfo pageInfo = pageInfoProducer.getPageInfo(pageIndex, pageSize);
SortInfo sortInfo = sortInfoProducer.getSortInfo(sortingRsql);
return nullableStreamOf(buildConfigurationRepository.queryWithPredicates(pageInfo, sortInfo, rsqlPredicate,
withProjectId(projectId)))
.map(toRestModel())
.collect(Collectors.toList());
}
public List<BuildConfigurationRest> getAllForProduct(int pageIndex, int pageSize, String sortingRsql, String query,
Integer productId) {
Predicate<BuildConfiguration> rsqlPredicate = rsqlPredicateProducer.getPredicate(BuildConfiguration.class, query);
PageInfo pageInfo = pageInfoProducer.getPageInfo(pageIndex, pageSize);
SortInfo sortInfo = sortInfoProducer.getSortInfo(sortingRsql);
return nullableStreamOf(buildConfigurationRepository.queryWithPredicates(pageInfo, sortInfo, rsqlPredicate,
withProductId(productId)))
.map(toRestModel())
.collect(Collectors.toList());
}
public List<BuildConfigurationRest> getAllForProductAndProductVersion(int pageIndex, int pageSize,
String sortingRsql, String query, Integer productId, Integer versionId) {
Predicate<BuildConfiguration> rsqlPredicate = rsqlPredicateProducer.getPredicate(BuildConfiguration.class, query);
PageInfo pageInfo = pageInfoProducer.getPageInfo(pageIndex, pageSize);
SortInfo sortInfo = sortInfoProducer.getSortInfo(sortingRsql);
return nullableStreamOf(buildConfigurationRepository.queryWithPredicates(pageInfo, sortInfo, rsqlPredicate,
withProductVersionId(versionId), withProductId(productId)))
.map(toRestModel())
.collect(Collectors.toList());
}
public BuildConfigurationRest getSpecific(Integer id) {
BuildConfiguration buildConfiguration = buildConfigurationRepository.queryById(id);
if (buildConfiguration == null) {
return null;
}
return new BuildConfigurationRest(buildConfiguration);
}
public Integer store(BuildConfigurationRest buildConfigurationRest) throws ConflictedEntryException {
Preconditions.checkArgument(buildConfigurationRest.getId() == null, "Id must be null");
validateBeforeSaving(buildConfigurationRest);
BuildConfiguration buildConfiguration = buildConfigurationRest.toBuildConfiguration(null);
buildConfiguration = buildConfigurationRepository.save(buildConfiguration);
return buildConfiguration.getId();
}
public Integer update(Integer id, BuildConfigurationRest buildConfigurationRest) throws ConflictedEntryException {
validateBeforeSaving(buildConfigurationRest);
Preconditions.checkArgument(id != null, "Id must not be null");
buildConfigurationRest.setId(id);
BuildConfiguration buildConfiguration = buildConfigurationRepository.queryById(id);
Preconditions.checkArgument(buildConfiguration != null, "Couldn't find buildConfiguration with id "
+ buildConfigurationRest.getId());
buildConfiguration = buildConfigurationRepository.save(buildConfigurationRest.toBuildConfiguration(buildConfiguration));
return buildConfiguration.getId();
}
private void validateBeforeSaving(BuildConfigurationRest buildConfigurationRest) throws ConflictedEntryException, IllegalArgumentException {
Preconditions.checkArgument(buildConfigurationRest.getName() != null, "Name must not be null");
Preconditions.checkArgument(buildConfigurationRest.getProjectId() != null, "Project Id must not be null");
if(buildConfigurationRepository
.count(withProjectId(buildConfigurationRest.getProjectId()), withName(buildConfigurationRest.getName())) > 0) {
throw new ConflictedEntryException("Configuration with the same name already exists within project", BuildConfiguration.class, buildConfigurationRest.getProjectId());
}
}
public Integer clone(Integer buildConfigurationId) {
BuildConfiguration buildConfiguration = buildConfigurationRepository.queryById(buildConfigurationId);
Preconditions.checkArgument(buildConfiguration != null, "Couldn't find buildConfiguration with id "
+ buildConfigurationId);
BuildConfiguration clonedBuildConfiguration = buildConfiguration.clone();
clonedBuildConfiguration = buildConfigurationRepository.save(clonedBuildConfiguration);
return clonedBuildConfiguration.getId();
}
public void delete(Integer configurationId) {
buildConfigurationRepository.delete(configurationId);
}
public Response addDependency(Integer configId, Integer dependencyId) {
BuildConfiguration buildConfig = buildConfigurationRepository.queryById(configId);
BuildConfiguration dependency = buildConfigurationRepository.queryById(dependencyId);
// Check that the dependency isn't pointing back to the same config
if (configId.equals(dependencyId)) {
return Response.status(Response.Status.BAD_REQUEST).entity("A build configuration cannot depend on itself").build();
}
// Check that the new dependency will not create a cycle
if (dependency.getAllDependencies().contains(buildConfig)) {
String errorMessage = "Cannot add dependency from : " + configId + " to: " + dependencyId + " because it would introduce a cyclic dependency";
return Response.status(Response.Status.BAD_REQUEST).entity(errorMessage).build();
}
buildConfig.addDependency(dependency);
buildConfigurationRepository.save(buildConfig);
return Response.ok().build();
}
public void removeDependency(Integer configId, Integer dependencyId) {
BuildConfiguration buildConfig = buildConfigurationRepository.queryById(configId);
BuildConfiguration dependency = buildConfigurationRepository.queryById(dependencyId);
buildConfig.removeDependency(dependency);
buildConfigurationRepository.save(buildConfig);
}
public Set<BuildConfigurationRest> getDependencies(Integer configId) {
BuildConfiguration buildConfig = buildConfigurationRepository.queryById(configId);
Set<BuildConfiguration> buildConfigurations = buildConfig.getDependencies();
return nullableStreamOf(buildConfigurations)
.map(toRestModel())
.collect(Collectors.toSet());
}
public Set<BuildConfigurationRest> getAllDependencies(Integer configId) {
BuildConfiguration buildConfig = buildConfigurationRepository.queryById(configId);
Set<BuildConfiguration> buildConfigurations = buildConfig.getAllDependencies();
return nullableStreamOf(buildConfigurations)
.map(toRestModel())
.collect(Collectors.toSet());
}
public void addProductVersion(Integer configId, Integer productVersionId) {
BuildConfiguration buildConfig = buildConfigurationRepository.queryById(configId);
ProductVersion productVersion = productVersionRepository.queryById(productVersionId);
buildConfig.addProductVersion(productVersion);
buildConfigurationRepository.save(buildConfig);
}
public void removeProductVersion(Integer configId, Integer productVersionId) {
BuildConfiguration buildConfig = buildConfigurationRepository.queryById(configId);
ProductVersion productVersion = productVersionRepository.queryById(productVersionId);
buildConfig.removeProductVersion(productVersion);
buildConfigurationRepository.save(buildConfig);
}
public List<ProductVersionRest> getProductVersions(Integer configId) {
BuildConfiguration buildConfig = buildConfigurationRepository.queryById(configId);
Set<ProductVersion> productVersions = buildConfig.getProductVersions();
return nullableStreamOf(productVersions)
.map(productVersionToRestModel())
.collect(Collectors.toList());
}
public List<BuildConfigurationAuditedRest> getRevisions(Integer id) {
List<BuildConfigurationAudited> auditedBuildConfigs = buildConfigurationAuditedRepository.findAllByIdOrderByRevDesc(id);
return nullableStreamOf(auditedBuildConfigs)
.map(buildConfigurationAuditedToRestModel())
.collect(Collectors.toList());
}
public BuildConfigurationAuditedRest getRevision(Integer id, Integer rev) {
IdRev idRev = new IdRev(id, rev);
BuildConfigurationAudited auditedBuildConfig = buildConfigurationAuditedRepository.queryById(idRev);
if (auditedBuildConfig == null) {
return null;
}
return new BuildConfigurationAuditedRest (auditedBuildConfig);
}
public Response getLatestBuildRecord(Integer configId) {
BuildConfiguration buildConfiguration = buildConfigurationRepository.queryById(configId);
if (buildConfiguration == null) {
return Response.status(Response.Status.NOT_FOUND).entity("No build configuration exists with id: " + configId).build();
}
PageInfo pageInfo = this.pageInfoProducer.getPageInfo(0, 1);
SortInfo sortInfo = this.sortInfoProducer.getSortInfo(SortingDirection.DESC, "endTime");
List<BuildRecord> buildRecords = buildRecordRepository.queryWithPredicates(pageInfo, sortInfo, withBuildConfigurationId(configId));
if (buildRecords.isEmpty()) {
return Response.status(Response.Status.NO_CONTENT).entity("No build records found for configuration id: " + configId).build();
}
BuildRecordRest latestBuildRecord = new BuildRecordRest(buildRecords.get(0));
return Response.ok(latestBuildRecord).build();
}
public Response getBuildRecords(int pageIndex, int pageSize, String sortingRsql, String query, Integer configurationId) {
BuildConfiguration buildConfiguration = buildConfigurationRepository.queryById(configurationId);
if (buildConfiguration == null) {
return Response.status(Response.Status.NOT_FOUND).entity("No build configuration exists with id: " + configurationId).build();
}
Predicate<BuildRecord> rsqlPredicate = rsqlPredicateProducer.getPredicate(BuildRecord.class, query);
PageInfo pageInfo = pageInfoProducer.getPageInfo(pageIndex, pageSize);
SortInfo sortInfo = sortInfoProducer.getSortInfo(sortingRsql);
List<BuildRecordRest> buildRecords = nullableStreamOf(buildRecordRepository.queryWithPredicates(pageInfo, sortInfo, rsqlPredicate, withBuildConfigurationId(configurationId)))
.map(buildRecordToRestModel())
.collect(Collectors.toList());
return Response.ok(buildRecords).build();
}
private Function<ProductVersion, ProductVersionRest> productVersionToRestModel() {
return productVersion -> new ProductVersionRest(productVersion);
}
private Function<BuildRecord, BuildRecordRest> buildRecordToRestModel() {
return buildRecord -> new BuildRecordRest(buildRecord);
}
private Function<BuildConfigurationAudited, BuildConfigurationAuditedRest> buildConfigurationAuditedToRestModel() {
return BuildConfigurationAudited -> new BuildConfigurationAuditedRest(BuildConfigurationAudited);
}
}
| |
/**
* 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.wildfly.camel.test.reactor;
import java.util.Arrays;
import java.util.Collections;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import javax.naming.Context;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.component.reactive.streams.api.CamelReactiveStreams;
import org.apache.camel.component.reactive.streams.api.CamelReactiveStreamsService;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.impl.DefaultExchange;
import org.apache.camel.util.ExchangeHelper;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.reactivestreams.Publisher;
import org.wildfly.extension.camel.CamelAware;
import org.wildfly.extension.camel.WildFlyCamelContext;
import reactor.core.Disposable;
import reactor.core.publisher.Flux;
@CamelAware
@RunWith(Arquillian.class)
public class ReactorIntegrationTest {
static final AtomicBoolean boundAlready = new AtomicBoolean();
@Deployment
public static JavaArchive createDeployment() {
return ShrinkWrap.create(JavaArchive.class, "camel-reactor-tests.jar");
}
public static class SampleBean {
public String hello(String name) {
return "Hello " + name;
}
}
@Test
public void testFromStreamDirect() throws Exception {
CamelContext camelctx = new DefaultCamelContext();
camelctx.addRoutes(new RouteBuilder() {
public void configure() {
from("direct:reactive")
.to("reactive-streams:numbers");
}
});
camelctx.start();
try {
AtomicInteger value = new AtomicInteger(0);
CamelReactiveStreamsService crs = CamelReactiveStreams.get(camelctx);
Flux.from(crs.fromStream("numbers", Integer.class))
.doOnNext(res -> Assert.assertEquals(value.incrementAndGet(), res.intValue()))
.subscribe();
ProducerTemplate template = camelctx.createProducerTemplate();
template.sendBody("direct:reactive", 1);
template.sendBody("direct:reactive", 2);
template.sendBody("direct:reactive", 3);
Assert.assertEquals(3, value.get());
} finally {
camelctx.stop();
}
}
@Test
public void testFromStreamTimer() throws Exception {
CamelContext camelctx = new DefaultCamelContext();
camelctx.addRoutes(new RouteBuilder() {
@Override
public void configure() throws Exception {
from("timer:tick?period=5&repeatCount=30")
.setBody().header(Exchange.TIMER_COUNTER)
.to("reactive-streams:tick");
}
});
final int num = 30;
final CountDownLatch latch = new CountDownLatch(num);
final AtomicInteger value = new AtomicInteger(0);
CamelReactiveStreamsService crs = CamelReactiveStreams.get(camelctx);
Flux.from(crs.fromStream("tick", Integer.class))
.doOnNext(res -> Assert.assertEquals(value.incrementAndGet(), res.intValue()))
.doOnNext(n -> latch.countDown())
.subscribe();
camelctx.start();
try {
latch.await(5, TimeUnit.SECONDS);
Assert.assertEquals(num, value.get());
} finally {
camelctx.stop();
}
}
@Test
public void testFromStreamMultipleSubscriptionsWithDirect() throws Exception {
CamelContext camelctx = new DefaultCamelContext();
camelctx.addRoutes(new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:reactive")
.to("reactive-streams:direct");
}
});
camelctx.start();
try {
CamelReactiveStreamsService crs = CamelReactiveStreams.get(camelctx);
CountDownLatch latch1 = new CountDownLatch(2);
Flux.from(crs.fromStream("direct", Integer.class))
.doOnNext(res -> latch1.countDown())
.subscribe();
CountDownLatch latch2 = new CountDownLatch(2);
Flux.from(crs.fromStream("direct", Integer.class))
.doOnNext(res -> latch2.countDown())
.subscribe();
ProducerTemplate template = camelctx.createProducerTemplate();
template.sendBody("direct:reactive", 1);
template.sendBody("direct:reactive", 2);
Assert.assertTrue(latch1.await(5, TimeUnit.SECONDS));
Assert.assertTrue(latch2.await(5, TimeUnit.SECONDS));
} finally {
camelctx.stop();
}
}
@Test
public void testMultipleSubscriptionsWithTimer() throws Exception {
CamelContext camelctx = new DefaultCamelContext();
camelctx.addRoutes(new RouteBuilder() {
@Override
public void configure() throws Exception {
from("timer:tick?period=50")
.setBody().header(Exchange.TIMER_COUNTER)
.to("reactive-streams:tick");
}
});
CountDownLatch latch1 = new CountDownLatch(5);
CamelReactiveStreamsService crs = CamelReactiveStreams.get(camelctx);
Disposable disp1 = Flux.from(crs.fromStream("tick", Integer.class)).subscribe(res -> latch1.countDown());
camelctx.start();
try {
// Add another subscription
CountDownLatch latch2 = new CountDownLatch(5);
Disposable disp2 = Flux.from(crs.fromStream("tick", Integer.class)).subscribe(res -> latch2.countDown());
Assert.assertTrue(latch1.await(5, TimeUnit.SECONDS));
Assert.assertTrue(latch2.await(5, TimeUnit.SECONDS));
// Un subscribe both
disp1.dispose();
disp2.dispose();
// No active subscriptions, warnings expected
Thread.sleep(60);
// Add another subscription
CountDownLatch latch3 = new CountDownLatch(5);
Disposable disp3 = Flux.from(crs.fromStream("tick", Integer.class)).subscribe(res -> latch3.countDown());
Assert.assertTrue(latch3.await(5, TimeUnit.SECONDS));
disp3.dispose();
} finally {
camelctx.stop();
}
}
@Test
public void testFrom() throws Exception {
CamelContext camelctx = new DefaultCamelContext();
camelctx.start();
try {
CamelReactiveStreamsService crs = CamelReactiveStreams.get(camelctx);
Publisher<Exchange> timer = crs.from("timer:reactive?period=250&repeatCount=3");
AtomicInteger value = new AtomicInteger(0);
CountDownLatch latch = new CountDownLatch(3);
Flux.from(timer)
.map(exchange -> ExchangeHelper.getHeaderOrProperty(exchange, Exchange.TIMER_COUNTER, Integer.class))
.doOnNext(res -> Assert.assertEquals(value.incrementAndGet(), res.intValue()))
.doOnNext(res -> latch.countDown())
.subscribe();
Assert.assertTrue(latch.await(2, TimeUnit.SECONDS));
} finally {
camelctx.stop();
}
}
@Test
public void testFromPublisher() throws Exception {
CamelContext camelctx = new DefaultCamelContext();
camelctx.addRoutes(new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:source")
.to("direct:stream")
.setBody()
.simple("after stream: ${body}");
}
});
camelctx.start();
try {
CamelReactiveStreamsService crs = CamelReactiveStreams.get(camelctx);
crs.process("direct:stream",
publisher ->
Flux.from(publisher)
.map(e -> {
int i = e.getIn().getBody(Integer.class);
e.getOut().setBody(-i);
return e;
}
)
);
ProducerTemplate template = camelctx.createProducerTemplate();
for (int i = 1; i <= 3; i++) {
Assert.assertEquals(
"after stream: " + (-i),
template.requestBody("direct:source", i, String.class)
);
}
} finally {
camelctx.stop();
}
}
@Test
public void testFromPublisherWithConversion() throws Exception {
CamelContext camelctx = new DefaultCamelContext();
camelctx.addRoutes(new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:source")
.to("direct:stream")
.setBody()
.simple("after stream: ${body}");
}
});
camelctx.start();
try {
CamelReactiveStreamsService crs = CamelReactiveStreams.get(camelctx);
crs.process("direct:stream",
Integer.class,
publisher ->
Flux.from(publisher).map(Math::negateExact)
);
ProducerTemplate template = camelctx.createProducerTemplate();
for (int i = 1; i <= 3; i++) {
Assert.assertEquals(
"after stream: " + (-i),
template.requestBody("direct:source", i, String.class)
);
}
} finally {
camelctx.stop();
}
}
// ************************************************
// toStream/to
// ************************************************
@Test
public void testToStream() throws Exception {
CamelContext camelctx = new DefaultCamelContext();
camelctx.addRoutes(new RouteBuilder() {
public void configure() {
from("reactive-streams:reactive")
.setBody().constant("123");
}
});
camelctx.start();
try {
CamelReactiveStreamsService crs = CamelReactiveStreams.get(camelctx);
Publisher<Exchange> publisher = crs.toStream("reactive", new DefaultExchange(camelctx));
Exchange res = Flux.from(publisher).blockFirst();
Assert.assertNotNull(res);
String content = res.getIn().getBody(String.class);
Assert.assertNotNull(content);
Assert.assertEquals("123", content);
} finally {
camelctx.stop();
}
}
@Test
public void testTo() throws Exception {
CamelContext camelctx = createWildFlyCamelContext();
camelctx.start();
try {
CamelReactiveStreamsService crs = CamelReactiveStreams.get(camelctx);
Set<String> values = Collections.synchronizedSet(new TreeSet<>());
CountDownLatch latch = new CountDownLatch(3);
Flux.just(1, 2, 3)
.flatMap(e -> crs.to("bean:hello", e, String.class))
.doOnNext(res -> values.add(res))
.doOnNext(res -> latch.countDown())
.subscribe();
Assert.assertTrue(latch.await(2, TimeUnit.SECONDS));
Assert.assertEquals(new TreeSet<>(Arrays.asList("Hello 1", "Hello 2", "Hello 3")), values);
} finally {
camelctx.stop();
}
}
@Test
public void testToWithExchange() throws Exception {
CamelContext camelctx = createWildFlyCamelContext();
camelctx.start();
try {
CamelReactiveStreamsService crs = CamelReactiveStreams.get(camelctx);
Set<String> values = Collections.synchronizedSet(new TreeSet<>());
CountDownLatch latch = new CountDownLatch(3);
Flux.just(1, 2, 3)
.flatMap(e -> crs.to("bean:hello", e))
.map(e -> e.getOut())
.map(e -> e.getBody(String.class))
.doOnNext(res -> values.add(res))
.doOnNext(res -> latch.countDown())
.subscribe();
Assert.assertTrue(latch.await(2, TimeUnit.SECONDS));
Assert.assertEquals(new TreeSet<>(Arrays.asList("Hello 1", "Hello 2", "Hello 3")), values);
} finally {
camelctx.stop();
}
}
@Test
public void testToFunction() throws Exception {
CamelContext camelctx = createWildFlyCamelContext();
camelctx.start();
try {
CamelReactiveStreamsService crs = CamelReactiveStreams.get(camelctx);
/* A TreeSet will order the messages alphabetically regardless of the insertion order
* This is important because in the Flux returned by Flux.flatMap(Function<? super T, ? extends
* Publisher<? extends R>>) the emissions may interleave */
Set<String> values = Collections.synchronizedSet(new TreeSet<>());
CountDownLatch latch = new CountDownLatch(3);
Function<Object, Publisher<String>> fun = crs.to("bean:hello", String.class);
Flux.just(1, 2, 3)
.flatMap(fun)
.doOnNext(res -> values.add(res))
.doOnNext(res -> latch.countDown())
.subscribe();
Assert.assertTrue(latch.await(2, TimeUnit.SECONDS));
Assert.assertEquals(new TreeSet<>(Arrays.asList("Hello 1", "Hello 2", "Hello 3")), values);
} finally {
camelctx.stop();
}
}
@Test
public void testToFunctionWithExchange() throws Exception {
CamelContext camelctx = createWildFlyCamelContext();
camelctx.start();
try {
CamelReactiveStreamsService crs = CamelReactiveStreams.get(camelctx);
Set<String> values = Collections.synchronizedSet(new TreeSet<>());
CountDownLatch latch = new CountDownLatch(3);
Function<Object, Publisher<Exchange>> fun = crs.to("bean:hello");
Flux.just(1, 2, 3)
.flatMap(fun)
.map(e -> e.getOut())
.map(e -> e.getBody(String.class))
.doOnNext(res -> values.add(res))
.doOnNext(res -> latch.countDown())
.subscribe();
Assert.assertTrue(latch.await(2, TimeUnit.SECONDS));
Assert.assertEquals(new TreeSet<>(Arrays.asList("Hello 1", "Hello 2", "Hello 3")), values);
} finally {
camelctx.stop();
}
}
@Test
public void testSubscriber() throws Exception {
CamelContext camelctx = new DefaultCamelContext();
camelctx.addRoutes(new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:reactor")
.to("mock:result");
}
});
camelctx.start();
try {
CamelReactiveStreamsService crs = CamelReactiveStreams.get(camelctx);
Flux.just(1, 2, 3)
.subscribe(crs.subscriber("direct:reactor", Integer.class));
MockEndpoint mock = camelctx.getEndpoint("mock:result", MockEndpoint.class);
mock.expectedMessageCount(3);
mock.assertIsSatisfied();
int idx = 1;
for (Exchange ex : mock.getExchanges()) {
Assert.assertEquals(new Integer(idx++), ex.getIn().getBody(Integer.class));
}
} finally {
camelctx.stop();
}
}
@Test(expected = IllegalStateException.class)
public void testOnlyOneCamelProducerPerPublisher() throws Exception {
CamelContext camelctx = new DefaultCamelContext();
camelctx.addRoutes(new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:one")
.to("reactive-streams:stream");
from("direct:two")
.to("reactive-streams:stream");
}
});
camelctx.start();
}
private CamelContext createWildFlyCamelContext() throws Exception {
WildFlyCamelContext camelctx = new WildFlyCamelContext();
if (boundAlready.compareAndSet(false, true)) {
Context jndictx = camelctx.getNamingContext();
jndictx.bind("hello", new SampleBean());
}
return camelctx;
}
}
| |
/**
* 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.falcon.oozie.process;
import org.apache.falcon.FalconException;
import org.apache.falcon.cluster.util.EmbeddedCluster;
import org.apache.falcon.entity.ClusterHelper;
import org.apache.falcon.entity.EntityUtil;
import org.apache.falcon.entity.store.ConfigurationStore;
import org.apache.falcon.entity.v0.Entity;
import org.apache.falcon.entity.v0.EntityType;
import org.apache.falcon.entity.v0.cluster.Cluster;
import org.apache.falcon.entity.v0.cluster.Interfacetype;
import org.apache.falcon.entity.v0.feed.Feed;
import org.apache.falcon.entity.v0.process.Process;
import org.apache.falcon.oozie.bundle.BUNDLEAPP;
import org.apache.falcon.oozie.coordinator.CONFIGURATION;
import org.apache.falcon.oozie.coordinator.COORDINATORAPP;
import org.apache.falcon.oozie.workflow.ACTION;
import org.apache.falcon.oozie.workflow.WORKFLOWAPP;
import org.apache.falcon.util.StartupProperties;
import org.apache.falcon.workflow.WorkflowExecutionArgs;
import org.apache.falcon.workflow.WorkflowExecutionContext;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.testng.Assert;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
/**
* Base for falcon unit tests involving configuration store.
*/
public class AbstractTestBase {
protected Entity storeEntity(EntityType type, String name, String resource, String writeEndpoint) throws Exception {
Unmarshaller unmarshaller = type.getUnmarshaller();
ConfigurationStore store = ConfigurationStore.get();
switch (type) {
case CLUSTER:
Cluster cluster = (Cluster) unmarshaller.unmarshal(this.getClass().getResource(resource));
if (name != null){
store.remove(type, name);
cluster.setName(name);
}
store.publish(type, cluster);
if (writeEndpoint != null) {
ClusterHelper.getInterface(cluster, Interfacetype.WRITE).setEndpoint(writeEndpoint);
FileSystem fs = new Path(writeEndpoint).getFileSystem(EmbeddedCluster.newConfiguration());
fs.create(
new Path(ClusterHelper.getLocation(cluster, "working"), "libext/FEED/retention/ext.jar")).close();
fs.create(
new Path(ClusterHelper.getLocation(cluster, "working"), "libext/FEED/replication/ext.jar")).close();
}
return cluster;
case FEED:
Feed feed = (Feed) unmarshaller.unmarshal(this.getClass().getResource(resource));
if (name != null) {
store.remove(type, name);
feed.setName(name);
}
store.publish(type, feed);
return feed;
case PROCESS:
Process process = (Process) unmarshaller.unmarshal(this.getClass().getResource(resource));
if (name != null) {
store.remove(type, name);
process.setName(name);
}
store.publish(type, process);
return process;
default:
}
throw new IllegalArgumentException("Unhandled type: " + type);
}
protected COORDINATORAPP getCoordinator(FileSystem fs, Path path) throws Exception {
String coordStr = readFile(fs, path);
Unmarshaller unmarshaller = JAXBContext.newInstance(COORDINATORAPP.class).createUnmarshaller();
SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
Schema schema = schemaFactory.newSchema(this.getClass().getResource("/oozie-coordinator-0.3.xsd"));
unmarshaller.setSchema(schema);
JAXBElement<COORDINATORAPP> jaxbBundle = unmarshaller.unmarshal(
new StreamSource(new ByteArrayInputStream(coordStr.trim().getBytes())), COORDINATORAPP.class);
return jaxbBundle.getValue();
}
protected BUNDLEAPP getBundle(FileSystem fs, Path path) throws Exception {
String bundleStr = readFile(fs, new Path(path, "bundle.xml"));
Unmarshaller unmarshaller = JAXBContext.newInstance(BUNDLEAPP.class).createUnmarshaller();
SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
Schema schema = schemaFactory.newSchema(this.getClass().getResource("/oozie-bundle-0.1.xsd"));
unmarshaller.setSchema(schema);
JAXBElement<BUNDLEAPP> jaxbBundle = unmarshaller.unmarshal(
new StreamSource(new ByteArrayInputStream(bundleStr.trim().getBytes())), BUNDLEAPP.class);
return jaxbBundle.getValue();
}
protected String readFile(FileSystem fs, Path path) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(fs.open(path)));
String line;
StringBuilder contents = new StringBuilder();
while ((line = reader.readLine()) != null) {
contents.append(line);
}
return contents.toString();
}
protected void cleanupStore() throws FalconException {
ConfigurationStore store = ConfigurationStore.get();
for (EntityType type : EntityType.values()) {
Collection<String> entities = store.getEntities(type);
for (String entity : entities) {
store.remove(type, entity);
}
}
}
protected void assertLibExtensions(FileSystem fs, COORDINATORAPP coord, EntityType type,
String lifecycle) throws Exception {
WORKFLOWAPP wf = getWorkflowapp(fs, coord);
List<Object> actions = wf.getDecisionOrForkOrJoin();
String lifeCyclePath = lifecycle == null ? "" : "/" + lifecycle;
for (Object obj : actions) {
if (!(obj instanceof ACTION)) {
continue;
}
ACTION action = (ACTION) obj;
List<String> files = null;
if (action.getJava() != null) {
files = action.getJava().getFile();
} else if (action.getPig() != null) {
files = action.getPig().getFile();
} else if (action.getMapReduce() != null) {
files = action.getMapReduce().getFile();
}
if (files != null) {
Assert.assertTrue(files.get(files.size() - 1).endsWith(
"/projects/falcon/working/libext/" + type.name() + lifeCyclePath + "/ext.jar"));
}
}
}
@SuppressWarnings("unchecked")
protected WORKFLOWAPP getWorkflowapp(FileSystem fs, COORDINATORAPP coord) throws JAXBException, IOException {
String wfPath = coord.getAction().getWorkflow().getAppPath().replace("${nameNode}", "");
return getWorkflowapp(fs, new Path(wfPath, "workflow.xml"));
}
@SuppressWarnings("unchecked")
protected WORKFLOWAPP getWorkflowapp(FileSystem fs, Path path) throws JAXBException, IOException {
JAXBContext jaxbContext = JAXBContext.newInstance(WORKFLOWAPP.class);
return ((JAXBElement<WORKFLOWAPP>) jaxbContext.createUnmarshaller().unmarshal(fs.open(path))).getValue();
}
protected ACTION getAction(WORKFLOWAPP wf, String name) {
for (Object action : wf.getDecisionOrForkOrJoin()) {
if (action instanceof ACTION && ((ACTION) action).getName().equals(name)) {
return (ACTION) action;
}
}
throw new IllegalArgumentException("Invalid action name " + name);
}
protected void assertAction(WORKFLOWAPP wf, String name, boolean assertRetry) {
ACTION action = getAction(wf, name);
Assert.assertNotNull(action);
if (assertRetry) {
Assert.assertEquals(action.getRetryMax(), "3");
Assert.assertEquals(action.getRetryInterval(), "1");
}
}
protected HashMap<String, String> getCoordProperties(COORDINATORAPP coord) {
HashMap<String, String> props = new HashMap<String, String>();
for (CONFIGURATION.Property prop : coord.getAction().getWorkflow().getConfiguration().getProperty()) {
props.put(prop.getName(), prop.getValue());
}
return props;
}
protected void verifyEntityProperties(Entity entity, Cluster cluster, Cluster srcCluster,
WorkflowExecutionContext.EntityOperations operation,
HashMap<String, String> props) throws Exception {
Assert.assertEquals(props.get(WorkflowExecutionArgs.ENTITY_NAME.getName()),
entity.getName());
Assert.assertEquals(props.get(WorkflowExecutionArgs.ENTITY_TYPE.getName()),
entity.getEntityType().name());
if (WorkflowExecutionContext.EntityOperations.REPLICATE == operation) {
Assert.assertEquals(props.get(WorkflowExecutionArgs.CLUSTER_NAME.getName()),
cluster.getName() + WorkflowExecutionContext.CLUSTER_NAME_SEPARATOR + srcCluster.getName());
} else {
Assert.assertEquals(props.get(WorkflowExecutionArgs.CLUSTER_NAME.getName()), cluster.getName());
}
Assert.assertEquals(props.get(WorkflowExecutionArgs.LOG_DIR.getName()), getLogPath(cluster, entity));
Assert.assertEquals(props.get("falconDataOperation"), operation.name());
}
protected void verifyEntityProperties(Entity entity, Cluster cluster,
WorkflowExecutionContext.EntityOperations operation,
HashMap<String, String> props) throws Exception {
verifyEntityProperties(entity, cluster, null, operation, props);
}
private String getLogPath(Cluster cluster, Entity entity) {
Path logPath = EntityUtil.getLogPath(cluster, entity);
return (logPath.toUri().getScheme() == null ? "${nameNode}" : "") + logPath;
}
protected void verifyBrokerProperties(Cluster cluster, HashMap<String, String> props) {
Assert.assertEquals(props.get(WorkflowExecutionArgs.USER_BRKR_URL.getName()),
ClusterHelper.getMessageBrokerUrl(cluster));
Assert.assertEquals(props.get(WorkflowExecutionArgs.USER_BRKR_IMPL_CLASS.getName()),
ClusterHelper.getMessageBrokerImplClass(cluster));
String falconBrokerUrl = StartupProperties.get().getProperty(
"broker.url", "tcp://localhost:61616?daemon=true");
Assert.assertEquals(props.get(WorkflowExecutionArgs.BRKR_URL.getName()), falconBrokerUrl);
String falconBrokerImplClass = StartupProperties.get().getProperty(
"broker.impl.class", ClusterHelper.DEFAULT_BROKER_IMPL_CLASS);
Assert.assertEquals(props.get(WorkflowExecutionArgs.BRKR_IMPL_CLASS.getName()),
falconBrokerImplClass);
String jmsMessageTTL = StartupProperties.get().getProperty("broker.ttlInMins",
String.valueOf(3 * 24 * 60L));
Assert.assertEquals(props.get(WorkflowExecutionArgs.BRKR_TTL.getName()), jmsMessageTTL);
}
}
| |
/**
* Copyright (c) 2006-2009, Redv.com
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Redv.com nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/**
* Created on 2006-10-29 13:43:33
*/
package cn.net.openid.jos.web.controller;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.ModelAndView;
import cn.net.openid.jos.domain.Attribute;
import cn.net.openid.jos.domain.Persona;
import cn.net.openid.jos.domain.User;
import cn.net.openid.jos.service.TimeZoneOffsetFormat;
import cn.net.openid.jos.web.AbstractJosSimpleFormController;
import cn.net.openid.jos.web.filter.UserAgentLocalesFilter;
/**
* The controller to add/modify a persona.
*
* @author Sutra Zhou
*/
public class PersonaController extends AbstractJosSimpleFormController {
/**
* The logger.
*/
private static final Log LOG = LogFactory.getLog(PersonaController.class);
/**
* The formatter for offset.
*/
private TimeZoneOffsetFormat offsetFormat = new TimeZoneOffsetFormat();
/**
* The locale resolver.
*/
private LocaleResolver localeResolver;
/**
* @param localeResolver
* the localeResolver to set
*/
public void setLocaleResolver(final LocaleResolver localeResolver) {
this.localeResolver = localeResolver;
}
/**
* {@inheritDoc}
*/
@Override
protected Object formBackingObject(final HttpServletRequest request)
throws Exception {
User user = getUser(request);
String id = request.getParameter("id");
Persona persona;
if (StringUtils.isEmpty(id)) {
persona = new Persona(user);
} else {
persona = getJosService().getPersona(user, id);
if (persona == null) {
persona = new Persona(user);
}
}
return persona;
}
/**
* {@inheritDoc}
*/
@Override
protected void initBinder(final HttpServletRequest request,
final ServletRequestDataBinder binder) throws Exception {
super.initBinder(request, binder);
/*
* binder.registerCustomEditor(Date.class, "dob", new CustomDateEditor(
* new SimpleDateFormat("yyyy-MM-dd"), true));
*/
}
/**
* {@inheritDoc}
*/
@Override
protected void onBindAndValidate(final HttpServletRequest request,
final Object command, final BindException errors) throws Exception {
Persona persona = (Persona) command;
persona.clearAttributes();
addAttributes(persona, request);
if (LOG.isDebugEnabled()) {
LOG.debug("isSessionForm: " + isSessionForm());
LOG.debug("persona dob: " + persona.getDob());
LOG.debug("---- attibutes ----");
LOG.debug("attribute count: " + persona.getAttributes().size());
for (Iterator<Attribute> iterator = persona.getAttributes()
.iterator(); iterator.hasNext();) {
Attribute attribute = iterator.next();
LOG.debug(String.format("%1$s(%2$s)=%3$s",
attribute.getAlias(), attribute.getType(), attribute
.getValues()));
}
}
super.onBindAndValidate(request, command, errors);
}
/**
* {@inheritDoc}
*/
@SuppressWarnings("unchecked")
@Override
protected Map referenceData(final HttpServletRequest request)
throws Exception {
Map data = super.referenceData(request);
if (data == null) {
data = new HashMap<Object, Object>();
}
final Locale locale = this.localeResolver.resolveLocale(request);
// Locale
String c, l;
final Map<String, String> relatedCountries =
new LinkedHashMap<String, String>();
final Map<String, String> relatedLanguages =
new LinkedHashMap<String, String>();
c = locale.getCountry();
l = locale.getLanguage();
if (!StringUtils.isEmpty(c)) {
relatedCountries.put(c, locale.getDisplayCountry(locale));
}
if (!StringUtils.isEmpty(l)) {
relatedLanguages.put(l, locale.getDisplayLanguage(locale));
}
final Collection<Locale> userAgentLocales = UserAgentLocalesFilter
.getUserAgentLocales(request);
final Set<String> userAgentCountries = new HashSet<String>();
final Set<String> userAgentLanguages = new HashSet<String>();
for (Locale theLocale : userAgentLocales) {
c = theLocale.getCountry();
l = theLocale.getLanguage();
if (!StringUtils.isEmpty(c) && !relatedCountries.containsKey(c)) {
relatedCountries.put(c, theLocale.getDisplayCountry(locale));
}
if (!StringUtils.isEmpty(l) && !relatedLanguages.containsKey(l)) {
relatedLanguages.put(l, theLocale.getDisplayLanguage(locale));
}
userAgentCountries.add(c);
userAgentLanguages.add(l);
}
final Map<String, String> countries =
new LinkedHashMap<String, String>();
final Map<String, String> languages =
new LinkedHashMap<String, String>();
Locale[] locales = Locale.getAvailableLocales();
String displayCountry, displayLanguage;
boolean related;
for (Locale theLocale : locales) {
c = theLocale.getCountry();
l = theLocale.getLanguage();
related = (userAgentCountries.contains(c) || userAgentLanguages
.contains(l));
if (!StringUtils.isEmpty(c)) {
displayCountry = theLocale.getDisplayCountry(locale);
if (related && !relatedCountries.containsKey(c)) {
relatedCountries.put(c, displayCountry);
}
if (!countries.containsKey(c)) {
countries.put(c, displayCountry);
}
}
if (!StringUtils.isEmpty(l)) {
displayLanguage = theLocale.getDisplayLanguage(locale);
if (related && !relatedLanguages.containsKey(l)) {
relatedLanguages.put(c, displayLanguage);
}
if (!languages.containsKey(l)) {
languages.put(l, displayLanguage);
}
}
}
data.put("relatedCountries", relatedCountries);
data.put("relatedLanguages", relatedLanguages);
Map m = new LinkedHashMap();
m.put(this.getMessageSourceAccessor().getMessage("persona.title.all"),
countries);
data.put("countries", m);
m = new LinkedHashMap();
m.put(this.getMessageSourceAccessor().getMessage("persona.title.all"),
languages);
data.put("languages", m);
// TimeZone
final Map<String, String> relatedTimeZones =
new LinkedHashMap<String, String>();
Integer userAgentOffset = org.apache.commons.lang.math.NumberUtils
.createInteger(request.getParameter("offset"));
int userAgentOffsetValue = userAgentOffset != null ? userAgentOffset
.intValue() : 0;
final Map<String, String> timeZones =
new LinkedHashMap<String, String>();
String[] timeZoneIds = TimeZone.getAvailableIDs();
String format = this.getMessageSourceAccessor().getMessage("timeZone");
for (String timeZoneId : timeZoneIds) {
TimeZone timeZone = TimeZone.getTimeZone(timeZoneId);
String id = timeZone.getID();
String shortName = timeZone.getDisplayName(false, TimeZone.SHORT,
locale);
String longName = timeZone.getDisplayName(false, TimeZone.LONG,
locale);
int offset = timeZone.getRawOffset();
String displayTimeZone = String.format(format, offsetFormat
.format(offset), shortName, longName, timeZone.getID());
if (userAgentOffset != null && userAgentOffsetValue == offset) {
relatedTimeZones.put(id, displayTimeZone);
}
timeZones.put(id, displayTimeZone);
}
data.put("relatedTimeZones", relatedTimeZones);
m = new LinkedHashMap();
m.put(this.getMessageSourceAccessor().getMessage("persona.title.all"),
timeZones);
data.put("timeZones", m);
return data;
}
/**
* {@inheritDoc}
*/
@Override
protected ModelAndView onSubmit(final HttpServletRequest request,
final HttpServletResponse response, final Object command,
final BindException errors) throws Exception {
Persona persona = (Persona) command;
if (StringUtils.isEmpty(persona.getId())) {
getJosService().insertPersona(getUser(request), persona);
} else {
getJosService().updatePersona(getUser(request), persona);
}
return super.onSubmit(request, response, command, errors);
}
/**
* Adds attributes from request to persona.
*
* @param persona
* the persona
* @param request
* the HTTP servlet request
*/
@SuppressWarnings("unchecked")
private static void addAttributes(final Persona persona,
final HttpServletRequest request) {
String key, id, alias, type;
String[] values;
for (Enumeration<String> names = request.getParameterNames(); names
.hasMoreElements();) {
String name = names.nextElement();
if (name.startsWith("attribute.alias.")) {
key = name.substring("attribute.alias.".length());
id = request.getParameter("attribute.id." + key);
alias = request.getParameter("attribute.alias." + key);
type = request.getParameter("attribute.type." + key);
values = request.getParameterValues("attribute.value." + key);
// Remove all empty strings.
int oldLen = 0;
int newLen = values.length;
do {
oldLen = newLen;
values = (String[]) ArrayUtils.removeElement(values,
StringUtils.EMPTY);
newLen = values.length;
} while (newLen != oldLen);
if (StringUtils.isNotEmpty(alias)
&& !ArrayUtils.isEmpty(values)) {
Attribute attribute = new Attribute(persona, alias, type,
values);
if (StringUtils.isNotEmpty(id)) {
attribute.setId(id);
}
persona.addAttribute(attribute);
if (LOG.isDebugEnabled()) {
LOG.debug(String.format(
"id: %1$s, alias: %2$s, values: %3$s.",
attribute.getId(), attribute.getAlias(),
attribute.getValues()));
}
}
}
}
}
}
| |
/*
* Copyright 2010 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.jsr94.rules.admin;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.util.Map;
import javax.rules.admin.LocalRuleExecutionSetProvider;
import javax.rules.admin.RuleExecutionSet;
import javax.rules.admin.RuleExecutionSetCreateException;
import org.drools.compiler.builder.impl.KnowledgeBuilderConfigurationImpl;
import org.drools.compiler.builder.impl.KnowledgeBuilderImpl;
import org.drools.compiler.compiler.DroolsParserException;
import org.drools.core.definitions.InternalKnowledgePackage;
import org.drools.decisiontable.InputType;
import org.drools.decisiontable.SpreadsheetCompiler;
import org.drools.jsr94.rules.Constants;
/**
* The Drools implementation of the <code>LocalRuleExecutionSetProvider</code>
* interface which defines <code>RuleExecutionSet</code> creation methods for
* defining <code>RuleExecutionSet</code>s from local (non-serializable)
* resources.
*
* @see LocalRuleExecutionSetProvider
*/
public class LocalRuleExecutionSetProviderImpl
implements
LocalRuleExecutionSetProvider {
/** Default constructor. */
public LocalRuleExecutionSetProviderImpl() {
super();
}
/**
* Creates a <code>RuleExecutionSet</code> implementation using a supplied
* input stream and additional Drools-specific properties. A Drools-specific
* rule execution set is read from the supplied InputStream. The method
* <code>createRuleExecutionSet</code> taking a Reader instance should be
* used if the source is a character stream and encoding conversion should
* be performed.
*
* @param ruleExecutionSetStream
* an input stream used to read the rule execution set.
* @param properties
* additional properties used to create the
* <code>RuleExecutionSet</code> implementation. May be
* <code>null</code>.
*
* @throws RuleExecutionSetCreateException
* on rule execution set creation error.
*
* @return The created <code>RuleExecutionSet</code>.
*/
public RuleExecutionSet createRuleExecutionSet(final InputStream ruleExecutionSetStream,
final Map properties) throws RuleExecutionSetCreateException {
if ( properties != null ) {
String source = ( String ) properties.get( Constants.RES_SOURCE );
if ( source == null ) {
// support legacy name
source = ( String ) properties.get( "source" );
}
if ( source != null && source.equals( Constants.RES_SOURCE_TYPE_DECISION_TABLE ) ) {
final SpreadsheetCompiler converter = new SpreadsheetCompiler();
final String drl = converter.compile( ruleExecutionSetStream,
InputType.XLS );
return createRuleExecutionSet( new StringReader( drl ), properties );
} else {
return createRuleExecutionSet( new InputStreamReader( ruleExecutionSetStream ), properties);
}
} else
return createRuleExecutionSet( new InputStreamReader( ruleExecutionSetStream ), properties);
}
/**
* Creates a <code>RuleExecutionSet</code> implementation using a supplied
* character stream Reader and additional Drools-specific properties. A
* Drools-specific rule execution set is read from the supplied Reader.
*
* @param ruleExecutionSetReader
* a Reader used to read the rule execution set.
* @param properties
* additional properties used to create the
* <code>RuleExecutionSet</code> implementation. May be
* <code>null</code>.
*
* @throws RuleExecutionSetCreateException
* on rule execution set creation error.
*
* @return The created <code>RuleExecutionSet</code>.
*/
public RuleExecutionSet createRuleExecutionSet(final Reader ruleExecutionSetReader,
final Map properties) throws RuleExecutionSetCreateException {
try {
KnowledgeBuilderConfigurationImpl config= null;
if ( properties != null ) {
config = (KnowledgeBuilderConfigurationImpl) properties.get( Constants.RES_PACKAGEBUILDER_CONFIG );
}
KnowledgeBuilderImpl builder = null;
if ( config != null ) {
builder = new KnowledgeBuilderImpl(config);
} else {
builder = new KnowledgeBuilderImpl();
}
Object dsrl = null;
String source = null;
if ( properties != null ) {
dsrl = properties.get( Constants.RES_DSL );
if ( dsrl == null ) {
// check for old legacy name ending
dsrl = properties.get( "dsl" );
}
source = ( String ) properties.get( Constants.RES_SOURCE );
if ( source == null ) {
// check for old legacy name ending
source = ( String ) properties.get( "source" );
}
}
if ( source == null ) {
source = "drl";
}
if ( dsrl == null ) {
if ( source.equals( Constants.RES_SOURCE_TYPE_XML ) || source.equals( "xml" ) ) {
builder.addPackageFromXml( ruleExecutionSetReader );
} else {
builder.addPackageFromDrl( ruleExecutionSetReader );
}
} else {
if ( source.equals( Constants.RES_SOURCE_TYPE_XML ) || source.equals( "xml" ) ) {
// xml cannot specify a dsl
builder.addPackageFromXml( ruleExecutionSetReader );
} else {
if ( dsrl instanceof Reader ) {
builder.addPackageFromDrl( ruleExecutionSetReader,
(Reader) dsrl );
} else {
builder.addPackageFromDrl( ruleExecutionSetReader,
new StringReader( (String) dsrl ) );
}
}
}
InternalKnowledgePackage pkg = builder.getPackage();
return createRuleExecutionSet( pkg,
properties );
} catch ( final IOException e ) {
throw new RuleExecutionSetCreateException( "cannot create rule execution set",
e );
} catch ( final DroolsParserException e ) {
throw new RuleExecutionSetCreateException( "cannot create rule execution set",
e );
}
}
/**
* Creates a <code>RuleExecutionSet</code> implementation from a
* Drools-specific AST representation and Drools-specific properties.
*
* @param ruleExecutionSetAst
* the vendor representation of a rule execution set
* @param properties
* additional properties used to create the
* <code>RuleExecutionSet</code> implementation. May be
* <code>null</code>.
*
* @throws RuleExecutionSetCreateException
* on rule execution set creation error.
*
* @return The created <code>RuleExecutionSet</code>.
*/
public RuleExecutionSet createRuleExecutionSet(final Object ruleExecutionSetAst,
final Map properties) throws RuleExecutionSetCreateException {
if ( ruleExecutionSetAst instanceof InternalKnowledgePackage ) {
InternalKnowledgePackage pkg = (InternalKnowledgePackage) ruleExecutionSetAst;
return this.createRuleExecutionSet( pkg,
properties );
}
throw new RuleExecutionSetCreateException( " Incoming AST object must be an org.kie.rule.Package. Was " + ruleExecutionSetAst.getClass() );
}
/**
* Creates a <code>RuleExecutionSet</code> implementation from a
* <code>RuleSet</code> and Drools-specific properties.
*
* @param pkg
* a Drools <code>org.kie.rule.Package</code> representation
* of a rule execution set.
* @param properties
* additional properties used to create the RuleExecutionSet
* implementation. May be <code>null</code>.
*
* @throws RuleExecutionSetCreateException
* on rule execution set creation error.
*
* @return The created <code>RuleExecutionSet</code>.
*/
private RuleExecutionSet createRuleExecutionSet(final InternalKnowledgePackage pkg,
final Map properties) throws RuleExecutionSetCreateException {
try {
return new RuleExecutionSetImpl( pkg,
properties );
} catch ( Exception e ) {
throw new RuleExecutionSetCreateException( "Failed to create RuleExecutionSet",
e );
}
}
}
| |
/*
* 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.druid.storage.s3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.AccessControlList;
import com.amazonaws.services.s3.model.AmazonS3Exception;
import com.amazonaws.services.s3.model.CanonicalGrantee;
import com.amazonaws.services.s3.model.CopyObjectRequest;
import com.amazonaws.services.s3.model.CopyObjectResult;
import com.amazonaws.services.s3.model.Grant;
import com.amazonaws.services.s3.model.ListObjectsV2Request;
import com.amazonaws.services.s3.model.ListObjectsV2Result;
import com.amazonaws.services.s3.model.Owner;
import com.amazonaws.services.s3.model.Permission;
import com.amazonaws.services.s3.model.PutObjectResult;
import com.amazonaws.services.s3.model.S3ObjectSummary;
import com.amazonaws.services.s3.model.StorageClass;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import org.apache.druid.java.util.common.Intervals;
import org.apache.druid.java.util.common.MapUtils;
import org.apache.druid.segment.loading.SegmentLoadingException;
import org.apache.druid.timeline.DataSegment;
import org.apache.druid.timeline.partition.NoneShardSpec;
import org.junit.Assert;
import org.junit.Test;
import java.io.File;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class S3DataSegmentMoverTest
{
private static final DataSegment SOURCE_SEGMENT = new DataSegment(
"test",
Intervals.of("2013-01-01/2013-01-02"),
"1",
ImmutableMap.of(
"key",
"baseKey/test/2013-01-01T00:00:00.000Z_2013-01-02T00:00:00.000Z/1/0/index.zip",
"bucket",
"main"
),
ImmutableList.of("dim1", "dim1"),
ImmutableList.of("metric1", "metric2"),
NoneShardSpec.instance(),
0,
1
);
@Test
public void testMove() throws Exception
{
MockAmazonS3Client mockS3Client = new MockAmazonS3Client();
S3DataSegmentMover mover = new S3DataSegmentMover(mockS3Client, new S3DataSegmentPusherConfig());
mockS3Client.putObject(
"main",
"baseKey/test/2013-01-01T00:00:00.000Z_2013-01-02T00:00:00.000Z/1/0/index.zip"
);
DataSegment movedSegment = mover.move(
SOURCE_SEGMENT,
ImmutableMap.of("baseKey", "targetBaseKey", "bucket", "archive")
);
Map<String, Object> targetLoadSpec = movedSegment.getLoadSpec();
Assert.assertEquals("targetBaseKey/test/2013-01-01T00:00:00.000Z_2013-01-02T00:00:00.000Z/1/0/index.zip", MapUtils.getString(targetLoadSpec, "key"));
Assert.assertEquals("archive", MapUtils.getString(targetLoadSpec, "bucket"));
Assert.assertTrue(mockS3Client.didMove());
}
@Test
public void testMoveNoop() throws Exception
{
MockAmazonS3Client mockS3Client = new MockAmazonS3Client();
S3DataSegmentMover mover = new S3DataSegmentMover(mockS3Client, new S3DataSegmentPusherConfig());
mockS3Client.putObject(
"archive",
"targetBaseKey/test/2013-01-01T00:00:00.000Z_2013-01-02T00:00:00.000Z/1/0/index.zip"
);
DataSegment movedSegment = mover.move(
SOURCE_SEGMENT,
ImmutableMap.of("baseKey", "targetBaseKey", "bucket", "archive")
);
Map<String, Object> targetLoadSpec = movedSegment.getLoadSpec();
Assert.assertEquals("targetBaseKey/test/2013-01-01T00:00:00.000Z_2013-01-02T00:00:00.000Z/1/0/index.zip", MapUtils.getString(targetLoadSpec, "key"));
Assert.assertEquals("archive", MapUtils.getString(targetLoadSpec, "bucket"));
Assert.assertFalse(mockS3Client.didMove());
}
@Test(expected = SegmentLoadingException.class)
public void testMoveException() throws Exception
{
MockAmazonS3Client mockS3Client = new MockAmazonS3Client();
S3DataSegmentMover mover = new S3DataSegmentMover(mockS3Client, new S3DataSegmentPusherConfig());
mover.move(
SOURCE_SEGMENT,
ImmutableMap.of("baseKey", "targetBaseKey", "bucket", "archive")
);
}
@Test
public void testIgnoresGoneButAlreadyMoved() throws Exception
{
MockAmazonS3Client mockS3Client = new MockAmazonS3Client();
S3DataSegmentMover mover = new S3DataSegmentMover(mockS3Client, new S3DataSegmentPusherConfig());
mover.move(new DataSegment(
"test",
Intervals.of("2013-01-01/2013-01-02"),
"1",
ImmutableMap.of(
"key",
"baseKey/test/2013-01-01T00:00:00.000Z_2013-01-02T00:00:00.000Z/1/0/index.zip",
"bucket",
"DOES NOT EXIST"
),
ImmutableList.of("dim1", "dim1"),
ImmutableList.of("metric1", "metric2"),
NoneShardSpec.instance(),
0,
1
), ImmutableMap.of("bucket", "DOES NOT EXIST", "baseKey", "baseKey"));
}
@Test(expected = SegmentLoadingException.class)
public void testFailsToMoveMissing() throws Exception
{
MockAmazonS3Client mockS3Client = new MockAmazonS3Client();
S3DataSegmentMover mover = new S3DataSegmentMover(mockS3Client, new S3DataSegmentPusherConfig());
mover.move(new DataSegment(
"test",
Intervals.of("2013-01-01/2013-01-02"),
"1",
ImmutableMap.of(
"key",
"baseKey/test/2013-01-01T00:00:00.000Z_2013-01-02T00:00:00.000Z/1/0/index.zip",
"bucket",
"DOES NOT EXIST"
),
ImmutableList.of("dim1", "dim1"),
ImmutableList.of("metric1", "metric2"),
NoneShardSpec.instance(),
0,
1
), ImmutableMap.of("bucket", "DOES NOT EXIST", "baseKey", "baseKey2"));
}
private static class MockAmazonS3Client extends ServerSideEncryptingAmazonS3
{
Map<String, Set<String>> storage = new HashMap<>();
boolean copied = false;
boolean deletedOld = false;
private MockAmazonS3Client()
{
super(new AmazonS3Client(), new NoopServerSideEncryption());
}
public boolean didMove()
{
return copied && deletedOld;
}
@Override
public AccessControlList getBucketAcl(String bucketName)
{
final AccessControlList acl = new AccessControlList();
acl.setOwner(new Owner("ownerId", "owner"));
acl.grantAllPermissions(new Grant(new CanonicalGrantee(acl.getOwner().getId()), Permission.FullControl));
return acl;
}
@Override
public boolean doesObjectExist(String bucketName, String objectKey)
{
Set<String> objects = storage.get(bucketName);
return (objects != null && objects.contains(objectKey));
}
@Override
public ListObjectsV2Result listObjectsV2(ListObjectsV2Request listObjectsV2Request)
{
final String bucketName = listObjectsV2Request.getBucketName();
final String objectKey = listObjectsV2Request.getPrefix();
if (doesObjectExist(bucketName, objectKey)) {
final S3ObjectSummary objectSummary = new S3ObjectSummary();
objectSummary.setBucketName(bucketName);
objectSummary.setKey(objectKey);
objectSummary.setStorageClass(StorageClass.Standard.name());
final ListObjectsV2Result result = new ListObjectsV2Result();
result.setBucketName(bucketName);
result.setPrefix(objectKey);
result.setKeyCount(1);
result.getObjectSummaries().add(objectSummary);
result.setTruncated(true);
return result;
} else {
return new ListObjectsV2Result();
}
}
@Override
public CopyObjectResult copyObject(CopyObjectRequest copyObjectRequest)
{
final String sourceBucketName = copyObjectRequest.getSourceBucketName();
final String sourceObjectKey = copyObjectRequest.getSourceKey();
final String destinationBucketName = copyObjectRequest.getDestinationBucketName();
final String destinationObjectKey = copyObjectRequest.getDestinationKey();
copied = true;
if (doesObjectExist(sourceBucketName, sourceObjectKey)) {
storage.computeIfAbsent(destinationBucketName, k -> new HashSet<>())
.add(destinationObjectKey);
return new CopyObjectResult();
} else {
final AmazonS3Exception exception = new AmazonS3Exception("S3DataSegmentMoverTest");
exception.setErrorCode("NoSuchKey");
exception.setStatusCode(404);
throw exception;
}
}
@Override
public void deleteObject(String bucket, String objectKey)
{
deletedOld = true;
storage.get(bucket).remove(objectKey);
}
public PutObjectResult putObject(String bucketName, String key)
{
return putObject(bucketName, key, (File) null);
}
@Override
public PutObjectResult putObject(String bucketName, String key, File file)
{
storage.putIfAbsent(bucketName, new HashSet<>());
storage.get(bucketName).add(key);
return new PutObjectResult();
}
}
}
| |
package org.pathvisio.biomartconnect.impl;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.InputStream;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JToggleButton;
import javax.swing.MutableComboBoxModel;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Highlighter;
import javax.swing.text.Highlighter.HighlightPainter;
import org.bridgedb.Xref;
import org.pathvisio.core.model.DataNodeType;
import org.pathvisio.desktop.PvDesktop;
import org.pathvisio.inforegistry.IInfoProvider;
import org.w3c.dom.Document;
/**
* This provider queries ensembl biomart to get coding sequence of
* the selected gene product and display it in the info panel. It also retrieves
* all the exons for the gene product. User is given an option to mark all the exons
*
* @author rsaxena
*
*/
public class SequenceViewerProvider implements IInfoProvider {
private PvDesktop desktop;
public SequenceViewerProvider(PvDesktop desktop){
this.desktop = desktop;
}
/**
* Implementing the required function of IInfoProvider interface.
* Gives the name to be shown in the inforegistry plugin.
*/
@Override
public String getName() {
return("Biomart Sequence Viewer");
}
/**
* Implementing the required function of IInfoProvider interface.
* Tells inforegistry that it works only for gene products.
*/
@Override
public Set<DataNodeType> getDatanodeTypes() {
Set<DataNodeType> s = new HashSet<DataNodeType>();
s.add(DataNodeType.GENEPRODUCT);
return s;
}
/**
* Implementing the required function of IInfoProvider interface.
* Queries ensembl biomart to find coding sequence of the selected data node.
*
* @param xref - to provide id and data source of the selected data node
* @return JComponent containing the coding sequence to be displayed
* in the info panel.
*/
@Override
public JComponent getInformation(Xref xref) {
//Makes sure organism for the selected gene product is know
if(desktop.getSwingEngine().getCurrentOrganism() == null)
return(new JLabel ("Organism not set for active pathway."));
//Queries Utils.mapId to find any corresponding ensembl gene id
Xref mapped = Utils.mapId(xref, desktop);
if(mapped.getId().equals("")){
return(new JLabel("<html>This identifier cannot be mapped to Ensembl.<br/>Check if the correct identifier mapping database is loaded.</html>"));
}
//Checks is the internet connection working before proceeding forward
if(BiomartQueryService.isInternetReachable()) {
//Holds attributes for the organism of the gene product selected
String organism = Utils.mapOrganism(desktop.getSwingEngine().getCurrentOrganism().toString());
if(organism != null) {
Collection<String> attrs = new HashSet<String>();
attrs.add("ensembl_gene_id");
attrs.add("ensembl_transcript_id");
//responsible for getting coding sequence
attrs.add("coding");
Collection<String> identifierFilters = new HashSet<String>();
identifierFilters.add(mapped.getId().toString());
//Querying Biomart
Document result = BiomartQueryService.createQuery(organism, attrs, identifierFilters,"FASTA");
//Creating input stream of the results obtained from the biomart
InputStream is = BiomartQueryService.getDataStream(result);
//Creating a new object of custom data structure(SequenceContainer)
final SequenceContainer sc = new SequenceContainer();
//parsing the coding sequence returned in fasta format
sc.fastaParser(is,mapped.getId().toString(),false);
/**
* Now preparing to query for exons
*/
attrs.remove("coding");
//responsible for getting exons
attrs.add("gene_exon");
result = BiomartQueryService.createQuery(organism, attrs, identifierFilters,"FASTA");
is = BiomartQueryService.getDataStream(result);
sc.fastaParser(is,mapped.getId().toString(),true);
//JCombobox to show all the transcript ids
final JComboBox transcriptIdList = new JComboBox();
MutableComboBoxModel model = (MutableComboBoxModel)transcriptIdList.getModel();
JPanel jp = new JPanel();
final JTextArea jta = new JTextArea();
jta.setLineWrap(true);
JScrollPane jsp = new JScrollPane(jta,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
jta.setEditable(false);
for(InfoPerTranscriptId obj: sc.transcriptIdList){
model.addElement(obj.getTranscriptId());
}
transcriptIdList.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
JComboBox temp_combo = (JComboBox)e.getSource();
String currentQuantity = (String)temp_combo.getSelectedItem();
jta.setText(sc.find(currentQuantity).getSequence());
}
});
//Button to mark all the exons
JToggleButton mark_exon = new JToggleButton("Mark Exons");
mark_exon.addActionListener(new ActionListener(){
String replacedStr = null;
public void actionPerformed(ActionEvent e){
if( ((JToggleButton)e.getSource()).isSelected()){
replacedStr = sc.find(transcriptIdList.getSelectedItem().toString()).getSequence();
jta.setText(replacedStr);
Highlighter highlighter = jta.getHighlighter();
HighlightPainter painter = new DefaultHighlighter.DefaultHighlightPainter(Color.PINK);
for(String temp_exon: sc.find(transcriptIdList.getSelectedItem().toString()).getExon()){
if(sc.find(transcriptIdList.getSelectedItem().toString()).getSequence().contains(temp_exon)){
int p0 = replacedStr.indexOf(temp_exon);
int p1 = p0 + temp_exon.length();
try {
//Highlighting the exon
highlighter.addHighlight(p0, p1, painter );
}
catch (BadLocationException e1) {
e1.printStackTrace();
}
}}}}});
jp.setLayout(new BorderLayout());
jp.add(transcriptIdList, BorderLayout.NORTH);
jp.add(jsp,BorderLayout.CENTER);
jp.add(mark_exon,BorderLayout.SOUTH);
return jp;
}
}
return null;
}
}
| |
/**
* Copyright (c) 2015 Aldebaran Robotics. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the COPYING file.
* Created by epinault and tcruz
*/
package com.aldebaran.qi.helper.proxies;
import com.aldebaran.qi.*;
import com.aldebaran.qi.helper.*;
import java.util.List;
import java.util.Map;
import java.util.List;
/**
* This module computes the direction of the look of a person from the orientation of his/her face. It is then possible to know if the person looks at the robot or not.
* @see <a href="http://doc.aldebaran.lan/doc/master/aldeb-doc/naoqi/peopleperception/algazeanalysis.html#algazeanalysis">NAOqi APIs for ALGazeAnalysis </a>
* NAOqi V2.4.x
*/
public class ALGazeAnalysis extends ALProxy {
private AsyncALGazeAnalysis asyncProxy;
public ALGazeAnalysis(Session session) throws Exception{
super(session);
asyncProxy = new AsyncALGazeAnalysis();
asyncProxy.setService(getService());
}
/**
* Get the async version of this proxy
*
* @return a AsyncALGazeAnalysis object
*/
public AsyncALGazeAnalysis async() {
return asyncProxy;
}
/**
* Sets the tolerance (between 0 and 1) for deciding whether or not a person is looking at the robot after face analysis. This tolerance is used only when face analysis is enabled.
*
* @param tolerance New value of the tolerance (between 0 and 1).
*/
public void setTolerance(Float tolerance) throws CallError, InterruptedException{
call("setTolerance", tolerance).get();
}
/**
* Changes the pause status of the extractor
*
* @param status New pause satus
*/
public void pause(Boolean status) throws CallError, InterruptedException{
call("pause", status).get();
}
/**
* Turns face analysis on or off.
*
* @param status True to turn it on, False to turn it off.
*/
public void setFaceAnalysisEnabled(Boolean status) throws CallError, InterruptedException{
call("setFaceAnalysisEnabled", status).get();
}
/**
* Gets the current status of face analysis.
*
* @return True if face analysis is enabled, False otherwise.
*/
public Boolean isFaceAnalysisEnabled() throws CallError, InterruptedException {
return (Boolean)call("isFaceAnalysisEnabled").get();
}
/**
* Gets the tolerance used to decide whether or not a person is looking at the robot after face analysis.
*
* @return Current value of the tolerance.
*/
public Float getTolerance() throws CallError, InterruptedException {
return (Float)call("getTolerance").get();
}
/**
* Gets extractor running status
*
* @return True if the extractor is currently processing images, False if not
*/
public Boolean isProcessing() throws CallError, InterruptedException {
return (Boolean)call("isProcessing").get();
}
/**
*
*
*/
public Boolean isStatsEnabled() throws CallError, InterruptedException {
return (Boolean)call("isStatsEnabled").get();
}
/**
*
*
*/
public void clearStats() throws CallError, InterruptedException{
call("clearStats").get();
}
/**
*
*
*/
public Boolean isTraceEnabled() throws CallError, InterruptedException {
return (Boolean)call("isTraceEnabled").get();
}
/**
* Exits and unregisters the module.
*
*/
public void exit() throws CallError, InterruptedException{
call("exit").get();
}
/**
* Returns the version of the module.
*
* @return A string containing the version of the module.
*/
public String version() throws CallError, InterruptedException {
return (String)call("version").get();
}
/**
* Just a ping. Always returns true
*
* @return returns true
*/
public Boolean ping() throws CallError, InterruptedException {
return (Boolean)call("ping").get();
}
/**
* Retrieves the module's method list.
*
* @return An array of method names.
*/
public List<String> getMethodList() throws CallError, InterruptedException {
return (List<String>)call("getMethodList").get();
}
/**
* Retrieves a method's description.
*
* @param methodName The name of the method.
* @return A structure containing the method's description.
*/
public Object getMethodHelp(String methodName) throws CallError, InterruptedException {
return (Object)call("getMethodHelp", methodName).get();
}
/**
* Retrieves the module's description.
*
* @return A structure describing the module.
*/
public Object getModuleHelp() throws CallError, InterruptedException {
return (Object)call("getModuleHelp").get();
}
/**
* Wait for the end of a long running method that was called using 'post'
*
* @param id The ID of the method that was returned when calling the method using 'post'
* @param timeoutPeriod The timeout period in ms. To wait indefinately, use a timeoutPeriod of zero.
* @return True if the timeout period terminated. False if the method returned.
*/
public Boolean wait(Integer id, Integer timeoutPeriod) throws CallError, InterruptedException {
return (Boolean)call("wait", id, timeoutPeriod).get();
}
/**
* Wait for the end of a long running method that was called using 'post', returns a cancelable future
*
* @param id The ID of the method that was returned when calling the method using 'post'
*/
public void wait(Integer id) throws CallError, InterruptedException{
call("wait", id).get();
}
/**
* Returns true if the method is currently running.
*
* @param id The ID of the method that was returned when calling the method using 'post'
* @return True if the method is currently running
*/
public Boolean isRunning(Integer id) throws CallError, InterruptedException {
return (Boolean)call("isRunning", id).get();
}
/**
* returns true if the method is currently running
*
* @param id the ID of the method to wait for
*/
public void stop(Integer id) throws CallError, InterruptedException{
call("stop", id).get();
}
/**
* Gets the name of the parent broker.
*
* @return The name of the parent broker.
*/
public String getBrokerName() throws CallError, InterruptedException {
return (String)call("getBrokerName").get();
}
/**
* Gets the method usage string. This summarises how to use the method.
*
* @param name The name of the method.
* @return A string that summarises the usage of the method.
*/
public String getUsage(String name) throws CallError, InterruptedException {
return (String)call("getUsage", name).get();
}
/**
* Subscribes to the extractor. This causes the extractor to start writing information to memory using the keys described by getOutputNames(). These can be accessed in memory using ALMemory.getData("keyName"). In many cases you can avoid calling subscribe on the extractor by just calling ALMemory.subscribeToEvent() supplying a callback method. This will automatically subscribe to the extractor for you.
*
* @param name Name of the module which subscribes.
* @param period Refresh period (in milliseconds) if relevant.
* @param precision Precision of the extractor if relevant.
*/
public void subscribe(String name, Integer period, Float precision) throws CallError, InterruptedException{
call("subscribe", name, period, precision).get();
}
/**
* Subscribes to the extractor. This causes the extractor to start writing information to memory using the keys described by getOutputNames(). These can be accessed in memory using ALMemory.getData("keyName"). In many cases you can avoid calling subscribe on the extractor by just calling ALMemory.subscribeToEvent() supplying a callback method. This will automatically subscribe to the extractor for you.
*
* @param name Name of the module which subscribes.
*/
public void subscribe(String name) throws CallError, InterruptedException{
call("subscribe", name).get();
}
/**
* Unsubscribes from the extractor.
*
* @param name Name of the module which had subscribed.
*/
public void unsubscribe(String name) throws CallError, InterruptedException{
call("unsubscribe", name).get();
}
/**
* Updates the period if relevant.
*
* @param name Name of the module which has subscribed.
* @param period Refresh period (in milliseconds).
*/
public void updatePeriod(String name, Integer period) throws CallError, InterruptedException{
call("updatePeriod", name, period).get();
}
/**
* Updates the precision if relevant.
*
* @param name Name of the module which has subscribed.
* @param precision Precision of the extractor.
*/
public void updatePrecision(String name, Float precision) throws CallError, InterruptedException{
call("updatePrecision", name, precision).get();
}
/**
* Gets the current period.
*
* @return Refresh period (in milliseconds).
*/
public Integer getCurrentPeriod() throws CallError, InterruptedException {
return (Integer)call("getCurrentPeriod").get();
}
/**
* Gets the current precision.
*
* @return Precision of the extractor.
*/
public Float getCurrentPrecision() throws CallError, InterruptedException {
return (Float)call("getCurrentPrecision").get();
}
/**
* Gets the period for a specific subscription.
*
* @param name Name of the module which has subscribed.
* @return Refresh period (in milliseconds).
*/
public Integer getMyPeriod(String name) throws CallError, InterruptedException {
return (Integer)call("getMyPeriod", name).get();
}
/**
* Gets the precision for a specific subscription.
*
* @param name name of the module which has subscribed
* @return precision of the extractor
*/
public Float getMyPrecision(String name) throws CallError, InterruptedException {
return (Float)call("getMyPrecision", name).get();
}
/**
* Gets the parameters given by the module.
*
* @return Array of names and parameters of all subscribers.
*/
public Object getSubscribersInfo() throws CallError, InterruptedException {
return (Object)call("getSubscribersInfo").get();
}
/**
* Get the list of values updated in ALMemory.
*
* @return Array of values updated by this extractor in ALMemory
*/
public List<String> getOutputNames() throws CallError, InterruptedException {
return (List<String>)call("getOutputNames").get();
}
/**
* Get the list of events updated in ALMemory.
*
* @return Array of events updated by this extractor in ALMemory
*/
public List<String> getEventList() throws CallError, InterruptedException {
return (List<String>)call("getEventList").get();
}
/**
* Get the list of events updated in ALMemory.
*
* @return Array of events updated by this extractor in ALMemory
*/
public List<String> getMemoryKeyList() throws CallError, InterruptedException {
return (List<String>)call("getMemoryKeyList").get();
}
/**
* Gets extractor pause status
*
* @return True if the extractor is paused, False if not
*/
public Boolean isPaused() throws CallError, InterruptedException {
return (Boolean)call("isPaused").get();
}
public class AsyncALGazeAnalysis extends ALProxy {
protected AsyncALGazeAnalysis(){
super();
}
/**
* Sets the tolerance (between 0 and 1) for deciding whether or not a person is looking at the robot after face analysis. This tolerance is used only when face analysis is enabled.
*
* @param tolerance New value of the tolerance (between 0 and 1).
* @return The Future
*/
public Future<Void> setTolerance(Float tolerance) throws CallError, InterruptedException{
return call("setTolerance", tolerance);
}
/**
* Changes the pause status of the extractor
*
* @param status New pause satus
* @return The Future
*/
public Future<Void> pause(Boolean status) throws CallError, InterruptedException{
return call("pause", status);
}
/**
* Turns face analysis on or off.
*
* @param status True to turn it on, False to turn it off.
* @return The Future
*/
public Future<Void> setFaceAnalysisEnabled(Boolean status) throws CallError, InterruptedException{
return call("setFaceAnalysisEnabled", status);
}
/**
* Gets the current status of face analysis.
*
* @return True if face analysis is enabled, False otherwise.
*/
public Future<Boolean> isFaceAnalysisEnabled() throws CallError, InterruptedException {
return call("isFaceAnalysisEnabled");
}
/**
* Gets the tolerance used to decide whether or not a person is looking at the robot after face analysis.
*
* @return Current value of the tolerance.
*/
public Future<Float> getTolerance() throws CallError, InterruptedException {
return call("getTolerance");
}
/**
* Gets extractor running status
*
* @return True if the extractor is currently processing images, False if not
*/
public Future<Boolean> isProcessing() throws CallError, InterruptedException {
return call("isProcessing");
}
/**
*
*
*/
public Future<Boolean> isStatsEnabled() throws CallError, InterruptedException {
return call("isStatsEnabled");
}
/**
*
*
* @return The Future
*/
public Future<Void> clearStats() throws CallError, InterruptedException{
return call("clearStats");
}
/**
*
*
*/
public Future<Boolean> isTraceEnabled() throws CallError, InterruptedException {
return call("isTraceEnabled");
}
/**
* Exits and unregisters the module.
*
* @return The Future
*/
public Future<Void> exit() throws CallError, InterruptedException{
return call("exit");
}
/**
* Returns the version of the module.
*
* @return A string containing the version of the module.
*/
public Future<String> version() throws CallError, InterruptedException {
return call("version");
}
/**
* Just a ping. Always returns true
*
* @return returns true
*/
public Future<Boolean> ping() throws CallError, InterruptedException {
return call("ping");
}
/**
* Retrieves the module's method list.
*
* @return An array of method names.
*/
public Future<List<String>> getMethodList() throws CallError, InterruptedException {
return call("getMethodList");
}
/**
* Retrieves a method's description.
*
* @param methodName The name of the method.
* @return A structure containing the method's description.
*/
public Future<Object> getMethodHelp(String methodName) throws CallError, InterruptedException {
return call("getMethodHelp", methodName);
}
/**
* Retrieves the module's description.
*
* @return A structure describing the module.
*/
public Future<Object> getModuleHelp() throws CallError, InterruptedException {
return call("getModuleHelp");
}
/**
* Wait for the end of a long running method that was called using 'post'
*
* @param id The ID of the method that was returned when calling the method using 'post'
* @param timeoutPeriod The timeout period in ms. To wait indefinately, use a timeoutPeriod of zero.
* @return True if the timeout period terminated. False if the method returned.
*/
public Future<Boolean> wait(Integer id, Integer timeoutPeriod) throws CallError, InterruptedException {
return call("wait", id, timeoutPeriod);
}
/**
* Wait for the end of a long running method that was called using 'post', returns a cancelable future
*
* @param id The ID of the method that was returned when calling the method using 'post'
* @return The Future
*/
public Future<Void> wait(Integer id) throws CallError, InterruptedException{
return call("wait", id);
}
/**
* Returns true if the method is currently running.
*
* @param id The ID of the method that was returned when calling the method using 'post'
* @return True if the method is currently running
*/
public Future<Boolean> isRunning(Integer id) throws CallError, InterruptedException {
return call("isRunning", id);
}
/**
* returns true if the method is currently running
*
* @param id the ID of the method to wait for
* @return The Future
*/
public Future<Void> stop(Integer id) throws CallError, InterruptedException{
return call("stop", id);
}
/**
* Gets the name of the parent broker.
*
* @return The name of the parent broker.
*/
public Future<String> getBrokerName() throws CallError, InterruptedException {
return call("getBrokerName");
}
/**
* Gets the method usage string. This summarises how to use the method.
*
* @param name The name of the method.
* @return A string that summarises the usage of the method.
*/
public Future<String> getUsage(String name) throws CallError, InterruptedException {
return call("getUsage", name);
}
/**
* Subscribes to the extractor. This causes the extractor to start writing information to memory using the keys described by getOutputNames(). These can be accessed in memory using ALMemory.getData("keyName"). In many cases you can avoid calling subscribe on the extractor by just calling ALMemory.subscribeToEvent() supplying a callback method. This will automatically subscribe to the extractor for you.
*
* @param name Name of the module which subscribes.
* @param period Refresh period (in milliseconds) if relevant.
* @param precision Precision of the extractor if relevant.
* @return The Future
*/
public Future<Void> subscribe(String name, Integer period, Float precision) throws CallError, InterruptedException{
return call("subscribe", name, period, precision);
}
/**
* Subscribes to the extractor. This causes the extractor to start writing information to memory using the keys described by getOutputNames(). These can be accessed in memory using ALMemory.getData("keyName"). In many cases you can avoid calling subscribe on the extractor by just calling ALMemory.subscribeToEvent() supplying a callback method. This will automatically subscribe to the extractor for you.
*
* @param name Name of the module which subscribes.
* @return The Future
*/
public Future<Void> subscribe(String name) throws CallError, InterruptedException{
return call("subscribe", name);
}
/**
* Unsubscribes from the extractor.
*
* @param name Name of the module which had subscribed.
* @return The Future
*/
public Future<Void> unsubscribe(String name) throws CallError, InterruptedException{
return call("unsubscribe", name);
}
/**
* Updates the period if relevant.
*
* @param name Name of the module which has subscribed.
* @param period Refresh period (in milliseconds).
* @return The Future
*/
public Future<Void> updatePeriod(String name, Integer period) throws CallError, InterruptedException{
return call("updatePeriod", name, period);
}
/**
* Updates the precision if relevant.
*
* @param name Name of the module which has subscribed.
* @param precision Precision of the extractor.
* @return The Future
*/
public Future<Void> updatePrecision(String name, Float precision) throws CallError, InterruptedException{
return call("updatePrecision", name, precision);
}
/**
* Gets the current period.
*
* @return Refresh period (in milliseconds).
*/
public Future<Integer> getCurrentPeriod() throws CallError, InterruptedException {
return call("getCurrentPeriod");
}
/**
* Gets the current precision.
*
* @return Precision of the extractor.
*/
public Future<Float> getCurrentPrecision() throws CallError, InterruptedException {
return call("getCurrentPrecision");
}
/**
* Gets the period for a specific subscription.
*
* @param name Name of the module which has subscribed.
* @return Refresh period (in milliseconds).
*/
public Future<Integer> getMyPeriod(String name) throws CallError, InterruptedException {
return call("getMyPeriod", name);
}
/**
* Gets the precision for a specific subscription.
*
* @param name name of the module which has subscribed
* @return precision of the extractor
*/
public Future<Float> getMyPrecision(String name) throws CallError, InterruptedException {
return call("getMyPrecision", name);
}
/**
* Gets the parameters given by the module.
*
* @return Array of names and parameters of all subscribers.
*/
public Future<Object> getSubscribersInfo() throws CallError, InterruptedException {
return call("getSubscribersInfo");
}
/**
* Get the list of values updated in ALMemory.
*
* @return Array of values updated by this extractor in ALMemory
*/
public Future<List<String>> getOutputNames() throws CallError, InterruptedException {
return call("getOutputNames");
}
/**
* Get the list of events updated in ALMemory.
*
* @return Array of events updated by this extractor in ALMemory
*/
public Future<List<String>> getEventList() throws CallError, InterruptedException {
return call("getEventList");
}
/**
* Get the list of events updated in ALMemory.
*
* @return Array of events updated by this extractor in ALMemory
*/
public Future<List<String>> getMemoryKeyList() throws CallError, InterruptedException {
return call("getMemoryKeyList");
}
/**
* Gets extractor pause status
*
* @return True if the extractor is paused, False if not
*/
public Future<Boolean> isPaused() throws CallError, InterruptedException {
return call("isPaused");
}
}
}
| |
package me.hao0.common.security;
class Base64 {
static private final int BASELENGTH = 128;
static private final int LOOKUPLENGTH = 64;
static private final int TWENTYFOURBITGROUP = 24;
static private final int EIGHTBIT = 8;
static private final int SIXTEENBIT = 16;
static private final int FOURBYTE = 4;
static private final int SIGN = -128;
static private final char PAD = '=';
static private final boolean fDebug = false;
static final private byte[] base64Alphabet = new byte[BASELENGTH];
static final private char[] lookUpBase64Alphabet = new char[LOOKUPLENGTH];
static {
for (int i = 0; i < BASELENGTH; ++i) {
base64Alphabet[i] = -1;
}
for (int i = 'Z'; i >= 'A'; i--) {
base64Alphabet[i] = (byte) (i - 'A');
}
for (int i = 'z'; i >= 'a'; i--) {
base64Alphabet[i] = (byte) (i - 'a' + 26);
}
for (int i = '9'; i >= '0'; i--) {
base64Alphabet[i] = (byte) (i - '0' + 52);
}
base64Alphabet['+'] = 62;
base64Alphabet['/'] = 63;
for (int i = 0; i <= 25; i++) {
lookUpBase64Alphabet[i] = (char) ('A' + i);
}
for (int i = 26, j = 0; i <= 51; i++, j++) {
lookUpBase64Alphabet[i] = (char) ('a' + j);
}
for (int i = 52, j = 0; i <= 61; i++, j++) {
lookUpBase64Alphabet[i] = (char) ('0' + j);
}
lookUpBase64Alphabet[62] = (char) '+';
lookUpBase64Alphabet[63] = (char) '/';
}
private static boolean isWhiteSpace(char octect) {
return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9);
}
private static boolean isPad(char octect) {
return (octect == PAD);
}
private static boolean isData(char octect) {
return (octect < BASELENGTH && base64Alphabet[octect] != -1);
}
/**
* Encodes hex octects into Base64
*
* @param binaryData Array containing binaryData
* @return Encoded Base64 array
*/
public static String encode(byte[] binaryData) {
if (binaryData == null) {
return null;
}
int lengthDataBits = binaryData.length * EIGHTBIT;
if (lengthDataBits == 0) {
return "";
}
int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP;
int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP;
int numberQuartet = fewerThan24bits != 0 ? numberTriplets + 1 : numberTriplets;
char encodedData[] = null;
encodedData = new char[numberQuartet * 4];
byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0;
int encodedIndex = 0;
int dataIndex = 0;
if (fDebug) {
System.out.println("number of triplets = " + numberTriplets);
}
for (int i = 0; i < numberTriplets; i++) {
b1 = binaryData[dataIndex++];
b2 = binaryData[dataIndex++];
b3 = binaryData[dataIndex++];
if (fDebug) {
System.out.println("b1= " + b1 + ", b2= " + b2 + ", b3= " + b3);
}
l = (byte) (b2 & 0x0f);
k = (byte) (b1 & 0x03);
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);
byte val3 = ((b3 & SIGN) == 0) ? (byte) (b3 >> 6) : (byte) ((b3) >> 6 ^ 0xfc);
if (fDebug) {
System.out.println("val2 = " + val2);
System.out.println("k4 = " + (k << 4));
System.out.println("vak = " + (val2 | (k << 4)));
}
encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];
encodedData[encodedIndex++] = lookUpBase64Alphabet[(l << 2) | val3];
encodedData[encodedIndex++] = lookUpBase64Alphabet[b3 & 0x3f];
}
// form integral number of 6-bit groups
if (fewerThan24bits == EIGHTBIT) {
b1 = binaryData[dataIndex];
k = (byte) (b1 & 0x03);
if (fDebug) {
System.out.println("b1=" + b1);
System.out.println("b1<<2 = " + (b1 >> 2));
}
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex++] = lookUpBase64Alphabet[k << 4];
encodedData[encodedIndex++] = PAD;
encodedData[encodedIndex++] = PAD;
} else if (fewerThan24bits == SIXTEENBIT) {
b1 = binaryData[dataIndex];
b2 = binaryData[dataIndex + 1];
l = (byte) (b2 & 0x0f);
k = (byte) (b1 & 0x03);
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);
encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];
encodedData[encodedIndex++] = lookUpBase64Alphabet[l << 2];
encodedData[encodedIndex++] = PAD;
}
return new String(encodedData);
}
/**
* Decodes Base64 data into octects
*
* @param encoded string containing Base64 data
* @return Array containind decoded data.
*/
public static byte[] decode(String encoded) {
if (encoded == null) {
return null;
}
char[] base64Data = encoded.toCharArray();
// remove white spaces
int len = removeWhiteSpace(base64Data);
if (len % FOURBYTE != 0) {
return null;//should be divisible by four
}
int numberQuadruple = (len / FOURBYTE);
if (numberQuadruple == 0) {
return new byte[0];
}
byte decodedData[] = null;
byte b1 = 0, b2 = 0, b3 = 0, b4 = 0;
char d1 = 0, d2 = 0, d3 = 0, d4 = 0;
int i = 0;
int encodedIndex = 0;
int dataIndex = 0;
decodedData = new byte[(numberQuadruple) * 3];
for (; i < numberQuadruple - 1; i++) {
if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++]))
|| !isData((d3 = base64Data[dataIndex++]))
|| !isData((d4 = base64Data[dataIndex++]))) {
return null;
}//if found "no data" just return null
b1 = base64Alphabet[d1];
b2 = base64Alphabet[d2];
b3 = base64Alphabet[d3];
b4 = base64Alphabet[d4];
decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);
}
if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++]))) {
return null;//if found "no data" just return null
}
b1 = base64Alphabet[d1];
b2 = base64Alphabet[d2];
d3 = base64Data[dataIndex++];
d4 = base64Data[dataIndex++];
if (!isData((d3)) || !isData((d4))) {//Check if they are PAD characters
if (isPad(d3) && isPad(d4)) {
if ((b2 & 0xf) != 0)//last 4 bits should be zero
{
return null;
}
byte[] tmp = new byte[i * 3 + 1];
System.arraycopy(decodedData, 0, tmp, 0, i * 3);
tmp[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
return tmp;
} else if (!isPad(d3) && isPad(d4)) {
b3 = base64Alphabet[d3];
if ((b3 & 0x3) != 0)//last 2 bits should be zero
{
return null;
}
byte[] tmp = new byte[i * 3 + 2];
System.arraycopy(decodedData, 0, tmp, 0, i * 3);
tmp[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
tmp[encodedIndex] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
return tmp;
} else {
return null;
}
} else { //No PAD e.g 3cQl
b3 = base64Alphabet[d3];
b4 = base64Alphabet[d4];
decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);
}
return decodedData;
}
/**
* remove WhiteSpace from MIME containing encoded Base64 data.
*
* @param data the byte array of base64 data (with WS)
* @return the new length
*/
private static int removeWhiteSpace(char[] data) {
if (data == null) {
return 0;
}
// count characters that's not whitespace
int newSize = 0;
int len = data.length;
for (int i = 0; i < len; i++) {
if (!isWhiteSpace(data[i])) {
data[newSize++] = data[i];
}
}
return newSize;
}
}
| |
/*
# Licensed Materials - Property of IBM
# Copyright IBM Corp. 2015
*/
package com.ibm.streamsx.topology.internal.core;
import static com.ibm.streamsx.topology.generator.operator.OpProperties.LANGUAGE_JAVA;
import static com.ibm.streamsx.topology.generator.operator.OpProperties.MODEL_FUNCTIONAL;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import com.ibm.streamsx.topology.TStream;
import com.ibm.streamsx.topology.TopologyElement;
import com.ibm.streamsx.topology.builder.BInputPort;
import com.ibm.streamsx.topology.builder.BOperatorInvocation;
import com.ibm.streamsx.topology.builder.BOutput;
import com.ibm.streamsx.topology.builder.BOutputPort;
import com.ibm.streamsx.topology.internal.functional.FunctionalOpProperties;
import com.ibm.streamsx.topology.internal.functional.ObjectSchemas;
import com.ibm.streamsx.topology.internal.logic.ObjectUtils;
import com.ibm.streamsx.topology.spi.runtime.TupleSerializer;
/**
* Maintains the core core for building a topology of Java streams.
*
*/
public class JavaFunctional {
/**
* Add an operator that executes a Java function (as an instance of a class)
* for its logic.
*/
/*
public static BOperatorInvocation addFunctionalOperator(TopologyElement te,
String kind, Serializable logic) {
verifySerializable(logic);
String logicString = ObjectUtils.serializeLogic(logic);
BOperatorInvocation bop = te.builder().addOperator("FRED", kind,
Collections.singletonMap(FUNCTIONAL_LOGIC_PARAM, logicString));
addDependency(te, bop, logic);
return bop;
}
*/
public static BOperatorInvocation addFunctionalOperator(TopologyElement te,
String name, String kind, Serializable logic) {
return addFunctionalOperator(te, name, kind, logic, null);
}
public static BOperatorInvocation addFunctionalOperator(TopologyElement te,
String name, String kind, Serializable logic,
Map<String,Object> params) {
if (params == null)
params = new HashMap<>();
verifySerializable(logic);
String logicString = ObjectUtils.serializeLogic(logic);
params.put(FunctionalOpProperties.FUNCTIONAL_LOGIC_PARAM, logicString);
BOperatorInvocation bop = te.builder().addOperator(name, kind, params);
bop.setModel(MODEL_FUNCTIONAL, LANGUAGE_JAVA);
addDependency(te, bop, logic);
return bop;
}
private static final Set<Class<?>> VIEWABLE_TYPES = new HashSet<>();
static {
VIEWABLE_TYPES.add(String.class);
}
/**
* Add an output port to an operator that uses a Java class as its object
* type.
*/
public static <T> TStream<T> addJavaOutput(TopologyElement te,
BOperatorInvocation bop, Type tupleType, boolean singlePort) {
return addJavaOutput(te, bop, tupleType, Optional.empty(), singlePort);
}
public static <T> TStream<T> addJavaOutput(TopologyElement te,
BOperatorInvocation bop, Type tupleType,
Optional<TupleSerializer> serializer, boolean singlePort) {
String mappingSchema = ObjectSchemas.getMappingSchema(tupleType);
BOutputPort bstream = bop.addOutput(mappingSchema,
singlePort ? Optional.of(bop.name()) : Optional.empty());
return getJavaTStream(te, bop, bstream, tupleType, serializer);
}
/**
* Create a Java stream on top of an output port.
* Multiple streams can be added to an output port.
*/
public static <T> TStream<T> getJavaTStream(TopologyElement te,
BOperatorInvocation bop, BOutputPort bstream, Type tupleType,
Optional<TupleSerializer> serializer) {
if (tupleType != null)
bstream.setNativeType(tupleType);
addDependency(te, bop, tupleType);
if (serializer.isPresent())
addDependency(te, bop, serializer.get());
// If the stream is just a Java object as a blob
// then don't allow them to be viewed.
if (!VIEWABLE_TYPES.contains(tupleType)) {
bop.addConfig("streamViewability", false);
}
return new StreamImpl<T>(te, bstream, tupleType, serializer);
}
/**
* Connect a Java functional operator to output from an output creating an
* input port if required. Ensures the operator has its dependencies on the
* tuple type added.
*/
public static BInputPort connectTo(TopologyElement te, BOutput output,
Type tupleType, BOperatorInvocation receivingBop,
BInputPort input) {
addDependency(te, receivingBop, tupleType);
return receivingBop.inputFrom(output, input);
}
/**
* Add a third-party dependency to all eligible operators
*/
public static void addJarDependency(TopologyElement te,
String location) {
te.topology().getDependencyResolver().addJarDependency(location);
}
/**
* Add a third-party dependency to all eligible operators.
*/
public static void addClassDependency(TopologyElement te,
Class<?> clazz) {
te.topology().getDependencyResolver().addClassDependency(clazz);
}
/**
* Add a dependency for the operator to a Java tuple type.
*/
public static void addDependency(TopologyElement te,
BOperatorInvocation bop, Type tupleType) {
if (tupleType instanceof Class) {
Class<?> tupleClass = (Class<?>) tupleType;
if ("com.ibm.streams.operator.Tuple".equals(tupleClass.getName()))
return;
te.topology().getDependencyResolver().addJarDependency(bop, tupleClass);
}
if (tupleType instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) tupleType;
addDependency(te, bop, pt.getRawType());
for (Type typeArg : pt.getActualTypeArguments())
addDependency(te, bop, typeArg);
}
}
/**
* Add a dependency for the operator to its functional logic.
*/
private static void addDependency(TopologyElement te,
BOperatorInvocation bop, Object function) {
te.topology().getDependencyResolver().addJarDependency(bop, function);
}
/**
* Copy dependencies from one operator to another.
*/
public static void copyDependencies(TopologyElement te,
BOperatorInvocation source,
BOperatorInvocation op) {
te.topology().getDependencyResolver().copyDependencies(source, op);
}
/**
* Simple check of the fields in the serializable logic
* to ensure that all non-transient field are serializable.
* @param logic
*/
private static void verifySerializable(Serializable logic) {
final Class<?> logicClass = logic.getClass();
for (Field f : logicClass.getDeclaredFields()) {
final int modifiers = f.getModifiers();
if (Modifier.isStatic(modifiers))
continue;
if (Modifier.isTransient(modifiers))
continue;
// We can't check for regular fields as the
// declaration might be valid as Object, but only
// contain serializable objects at runtime.
if (!f.isSynthetic())
continue;
Class<?> fieldClass = f.getType();
if (fieldClass.isPrimitive())
continue;
if (!Serializable.class.isAssignableFrom(fieldClass)) {
throw new IllegalArgumentException(
"Functional logic argument " + logic + " contains a non-serializable field:"
+ f.getName() + " ,"
+ "ensure anonymous classes are declared in a static context.");
}
}
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.drill.exec.store.easy.text.compliant;
/*******************************************************************************
* Copyright 2014 uniVocity Software Pty 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.
******************************************************************************/
import io.netty.buffer.DrillBuf;
import io.netty.util.internal.PlatformDependent;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import org.apache.drill.exec.memory.BoundsChecking;
import org.apache.hadoop.fs.ByteBufferReadable;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.Seekable;
import org.apache.hadoop.io.compress.CompressionInputStream;
import com.google.common.base.Preconditions;
import com.univocity.parsers.common.Format;
/**
* Class that fronts an InputStream to provide a byte consumption interface.
* Also manages only reading lines to and from each split.
*/
final class TextInput {
private static final byte NULL_BYTE = (byte) '\0';
private final byte lineSeparator1;
private final byte lineSeparator2;
private final byte normalizedLineSeparator;
private final TextParsingSettings settings;
private long lineCount;
private long charCount;
/**
* The starting position in the file.
*/
private final long startPos;
private final long endPos;
private int bufferMark;
private long streamMark;
private long streamPos;
private final Seekable seekable;
private final FSDataInputStream inputFS;
private final InputStream input;
private final DrillBuf buffer;
private final ByteBuffer underlyingBuffer;
private final long bStart;
private final long bStartMinus1;
private final boolean bufferReadable;
/**
* Whether there was a possible partial line separator on the previous
* read so we dropped it and it should be appended to next read.
*/
private boolean remByte = false;
/**
* The current position in the buffer.
*/
public int bufferPtr;
/**
* The quantity of valid data in the buffer.
*/
public int length = -1;
private boolean endFound = false;
/**
* Creates a new instance with the mandatory characters for handling newlines transparently.
* @param lineSeparator the sequence of characters that represent a newline, as defined in {@link Format#getLineSeparator()}
* @param normalizedLineSeparator the normalized newline character (as defined in {@link Format#getNormalizedNewline()}) that is used to replace any lineSeparator sequence found in the input.
*/
public TextInput(TextParsingSettings settings, InputStream input, DrillBuf readBuffer, long startPos, long endPos) {
byte[] lineSeparator = settings.getNewLineDelimiter();
byte normalizedLineSeparator = settings.getNormalizedNewLine();
Preconditions.checkArgument(lineSeparator != null && (lineSeparator.length == 1 || lineSeparator.length == 2), "Invalid line separator. Expected 1 to 2 characters");
Preconditions.checkArgument(input instanceof Seekable, "Text input only supports an InputStream that supports Seekable.");
boolean isCompressed = input instanceof CompressionInputStream ;
Preconditions.checkArgument(!isCompressed || startPos == 0, "Cannot use split on compressed stream.");
// splits aren't allowed with compressed data. The split length will be the compressed size which means we'll normally end prematurely.
if(isCompressed && endPos > 0){
endPos = Long.MAX_VALUE;
}
this.input = input;
this.seekable = (Seekable) input;
this.settings = settings;
if(input instanceof FSDataInputStream){
this.inputFS = (FSDataInputStream) input;
this.bufferReadable = inputFS.getWrappedStream() instanceof ByteBufferReadable;
}else{
this.inputFS = null;
this.bufferReadable = false;
}
this.startPos = startPos;
this.endPos = endPos;
this.lineSeparator1 = lineSeparator[0];
this.lineSeparator2 = lineSeparator.length == 2 ? lineSeparator[1] : NULL_BYTE;
this.normalizedLineSeparator = normalizedLineSeparator;
this.buffer = readBuffer;
this.bStart = buffer.memoryAddress();
this.bStartMinus1 = bStart -1;
this.underlyingBuffer = buffer.nioBuffer(0, buffer.capacity());
}
/**
* Test the input to position for read start. If the input is a non-zero split or
* splitFirstLine is enabled, input will move to appropriate complete line.
* @throws IOException
*/
final void start() throws IOException {
lineCount = 0;
if(startPos > 0){
seekable.seek(startPos);
}
updateBuffer();
if (length > 0) {
if(startPos > 0 || settings.isSkipFirstLine()){
// move to next full record.
skipLines(1);
}
}
}
/**
* Helper method to get the most recent characters consumed since the last record started.
* May get an incomplete string since we don't support stream rewind. Returns empty string for now.
* @return String of last few bytes.
* @throws IOException
*/
public String getStringSinceMarkForError() throws IOException {
return " ";
}
long getPos(){
return streamPos + bufferPtr;
}
public void mark(){
streamMark = streamPos;
bufferMark = bufferPtr;
}
/**
* read some more bytes from the stream. Uses the zero copy interface if available. Otherwise, does byte copy.
* @throws IOException
*/
private final void read() throws IOException {
if(bufferReadable){
if(remByte){
underlyingBuffer.put(lineSeparator1);
remByte = false;
}
length = inputFS.read(underlyingBuffer);
}else{
byte[] b = new byte[underlyingBuffer.capacity()];
if(remByte){
b[0] = lineSeparator1;
length = input.read(b, 1, b.length - 1);
remByte = false;
}else{
length = input.read(b);
}
underlyingBuffer.put(b);
}
}
/**
* Read more data into the buffer. Will also manage split end conditions.
* @throws IOException
*/
private final void updateBuffer() throws IOException {
streamPos = seekable.getPos();
underlyingBuffer.clear();
if(endFound){
length = -1;
return;
}
read();
// check our data read allowance.
if(streamPos + length >= this.endPos){
updateLengthBasedOnConstraint();
}
charCount += bufferPtr;
bufferPtr = 1;
buffer.writerIndex(underlyingBuffer.limit());
buffer.readerIndex(underlyingBuffer.position());
}
/**
* Checks to see if we can go over the end of our bytes constraint on the data. If so,
* adjusts so that we can only read to the last character of the first line that crosses
* the split boundary.
*/
private void updateLengthBasedOnConstraint(){
// we've run over our alotted data.
final byte lineSeparator1 = this.lineSeparator1;
final byte lineSeparator2 = this.lineSeparator2;
// find the next line separator:
final long max = bStart + length;
for(long m = this.bStart + (endPos - streamPos); m < max; m++){
if(PlatformDependent.getByte(m) == lineSeparator1){
// we found a potential line break.
if(lineSeparator2 == NULL_BYTE){
// we found a line separator and don't need to consult the next byte.
length = (int)(m - bStart) + 1; // make sure we include line separator otherwise query may fail (DRILL-4317)
endFound = true;
break;
}else{
// this is a two byte line separator.
long mPlus = m+1;
if(mPlus < max){
// we can check next byte and see if the second lineSeparator is correct.
if(lineSeparator2 == PlatformDependent.getByte(mPlus)){
length = (int)(mPlus - bStart);
endFound = true;
break;
}else{
// this was a partial line break.
continue;
}
}else{
// the last character of the read was a remnant byte. We'll hold off on dealing with this byte until the next read.
remByte = true;
length -= 1;
break;
}
}
}
}
}
/**
* Get next byte from stream. Also maintains the current line count. Will throw a StreamFinishedPseudoException
* when the stream has run out of bytes.
* @return next byte from stream.
* @throws IOException
*/
public final byte nextChar() throws IOException {
final byte lineSeparator1 = this.lineSeparator1;
final byte lineSeparator2 = this.lineSeparator2;
if (length == -1) {
throw StreamFinishedPseudoException.INSTANCE;
}
if (BoundsChecking.BOUNDS_CHECKING_ENABLED) {
buffer.checkBytes(bufferPtr - 1, bufferPtr);
}
byte byteChar = PlatformDependent.getByte(bStartMinus1 + bufferPtr);
if (bufferPtr >= length) {
if (length != -1) {
updateBuffer();
bufferPtr--;
} else {
throw StreamFinishedPseudoException.INSTANCE;
}
}
bufferPtr++;
// monitor for next line.
if (lineSeparator1 == byteChar && (lineSeparator2 == NULL_BYTE || lineSeparator2 == buffer.getByte(bufferPtr - 1))) {
lineCount++;
if (lineSeparator2 != NULL_BYTE) {
byteChar = normalizedLineSeparator;
if (bufferPtr >= length) {
if (length != -1) {
updateBuffer();
} else {
throw StreamFinishedPseudoException.INSTANCE;
}
}
}
}
return byteChar;
}
/**
* Number of lines read since the start of this split.
* @return
*/
public final long lineCount() {
return lineCount;
}
/**
* Skip forward the number of line delimiters. If you are in the middle of a line,
* a value of 1 will skip to the start of the next record.
* @param lines Number of lines to skip.
* @throws IOException
*/
public final void skipLines(int lines) throws IOException {
if (lines < 1) {
return;
}
long expectedLineCount = this.lineCount + lines;
try {
do {
nextChar();
} while (lineCount < expectedLineCount);
if (lineCount < lines) {
throw new IllegalArgumentException("Unable to skip " + lines + " lines from line " + (expectedLineCount - lines) + ". End of input reached");
}
} catch (EOFException ex) {
throw new IllegalArgumentException("Unable to skip " + lines + " lines from line " + (expectedLineCount - lines) + ". End of input reached");
}
}
public final long charCount() {
return charCount + bufferPtr;
}
public long getLineCount() {
return lineCount;
}
public void close() throws IOException{
input.close();
}
}
| |
package org.springframework.security.web.authentication.rememberme;
import static org.junit.Assert.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices;
import org.springframework.security.web.authentication.rememberme.CookieTheftException;
import org.springframework.security.web.authentication.rememberme.InvalidCookieException;
import org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationException;
import org.springframework.util.StringUtils;
/**
* @author Luke Taylor
*/
public class AbstractRememberMeServicesTests {
static User joe = new User("joe", "password", true, true,true,true, AuthorityUtils.createAuthorityList("ROLE_A"));
@Test(expected = InvalidCookieException.class)
public void nonBase64CookieShouldBeDetected() {
new MockRememberMeServices().decodeCookie("nonBase64CookieValue%");
}
@Test
public void cookieShouldBeCorrectlyEncodedAndDecoded() {
String[] cookie = new String[] {"http://name", "cookie", "tokens", "blah"};
MockRememberMeServices services = new MockRememberMeServices();
String encoded = services.encodeCookie(cookie);
// '=' aren't alowed in version 0 cookies.
assertFalse(encoded.endsWith("="));
String[] decoded = services.decodeCookie(encoded);
assertEquals(4, decoded.length);
assertEquals("http://name", decoded[0]);
assertEquals("cookie", decoded[1]);
assertEquals("tokens", decoded[2]);
assertEquals("blah", decoded[3]);
}
@Test
public void autoLoginShouldReturnNullIfNoLoginCookieIsPresented() {
MockRememberMeServices services = new MockRememberMeServices();
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
assertNull(services.autoLogin(request, response));
// shouldn't try to invalidate our cookie
assertNull(response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY));
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
// set non-login cookie
request.setCookies(new Cookie[] {new Cookie("mycookie", "cookie")});
assertNull(services.autoLogin(request, response));
assertNull(response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY));
}
@Test
public void successfulAutoLoginReturnsExpectedAuthentication() {
MockRememberMeServices services = new MockRememberMeServices();
services.setUserDetailsService(new MockUserDetailsService(joe, false));
assertNotNull(services.getUserDetailsService());
MockHttpServletRequest request = new MockHttpServletRequest();
request.setCookies(createLoginCookie("cookie:1:2"));
MockHttpServletResponse response = new MockHttpServletResponse();
Authentication result = services.autoLogin(request, response);
assertNotNull(result);
}
@Test
public void autoLoginShouldFailIfInvalidCookieExceptionIsRaised() {
MockRememberMeServices services = new MockRememberMeServices();
services.setUserDetailsService(new MockUserDetailsService(joe, true));
MockHttpServletRequest request = new MockHttpServletRequest();
// Wrong number of tokes
request.setCookies(createLoginCookie("cookie:1"));
MockHttpServletResponse response = new MockHttpServletResponse();
Authentication result = services.autoLogin(request, response);
assertNull(result);
assertCookieCancelled(response);
}
@Test
public void autoLoginShouldFailIfUserNotFound() {
MockRememberMeServices services = new MockRememberMeServices();
services.setUserDetailsService(new MockUserDetailsService(joe, true));
MockHttpServletRequest request = new MockHttpServletRequest();
request.setCookies(createLoginCookie("cookie:1:2"));
MockHttpServletResponse response = new MockHttpServletResponse();
Authentication result = services.autoLogin(request, response);
assertNull(result);
assertCookieCancelled(response);
}
@Test
public void autoLoginShouldFailIfUserAccountIsLocked() {
MockRememberMeServices services = new MockRememberMeServices();
User joeLocked = new User("joe", "password",false,true,true,true,joe.getAuthorities());
services.setUserDetailsService(new MockUserDetailsService(joeLocked, false));
MockHttpServletRequest request = new MockHttpServletRequest();
request.setCookies(createLoginCookie("cookie:1:2"));
MockHttpServletResponse response = new MockHttpServletResponse();
Authentication result = services.autoLogin(request, response);
assertNull(result);
assertCookieCancelled(response);
}
@Test
public void loginFailShouldCancelCookie() {
MockRememberMeServices services = new MockRememberMeServices();
services.setUserDetailsService(new MockUserDetailsService(joe, true));
MockHttpServletRequest request = new MockHttpServletRequest();
request.setContextPath("contextpath");
request.setCookies(createLoginCookie("cookie:1:2"));
MockHttpServletResponse response = new MockHttpServletResponse();
services.loginFail(request, response);
assertCookieCancelled(response);
}
@Test(expected = CookieTheftException.class)
public void cookieTheftExceptionShouldBeRethrown() {
MockRememberMeServices services = new MockRememberMeServices() {
protected UserDetails processAutoLoginCookie(String[] cookieTokens, HttpServletRequest request, HttpServletResponse response) {
throw new CookieTheftException("Pretending cookie was stolen");
}
};
services.setUserDetailsService(new MockUserDetailsService(joe, false));
MockHttpServletRequest request = new MockHttpServletRequest();
request.setCookies(createLoginCookie("cookie:1:2"));
MockHttpServletResponse response = new MockHttpServletResponse();
services.autoLogin(request, response);
}
@Test
public void loginSuccessCallsOnLoginSuccessCorrectly() {
MockRememberMeServices services = new MockRememberMeServices();
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
Authentication auth = new UsernamePasswordAuthenticationToken("joe","password");
// No parameter set
services = new MockRememberMeServices();
services.loginSuccess(request, response, auth);
assertFalse(services.loginSuccessCalled);
// Parameter set to true
services = new MockRememberMeServices();
request.setParameter(MockRememberMeServices.DEFAULT_PARAMETER, "true");
services.loginSuccess(request, response, auth);
assertTrue(services.loginSuccessCalled);
// Different parameter name, set to true
services = new MockRememberMeServices();
services.setParameter("my_parameter");
request.setParameter("my_parameter", "true");
services.loginSuccess(request, response, auth);
assertTrue(services.loginSuccessCalled);
// Parameter set to false
services = new MockRememberMeServices();
request.setParameter(MockRememberMeServices.DEFAULT_PARAMETER, "false");
services.loginSuccess(request, response, auth);
assertFalse(services.loginSuccessCalled);
// alwaysRemember set to true
services = new MockRememberMeServices();
services.setAlwaysRemember(true);
services.loginSuccess(request, response, auth);
assertTrue(services.loginSuccessCalled);
}
@Test
public void setCookieUsesCorrectNamePathAndValue() {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
request.setContextPath("contextpath");
MockRememberMeServices services = new MockRememberMeServices() {
protected String encodeCookie(String[] cookieTokens) {
return cookieTokens[0];
}
};
services.setCookieName("mycookiename");
services.setCookie(new String[] {"mycookie"}, 1000, request, response);
Cookie cookie = response.getCookie("mycookiename");
assertNotNull(cookie);
assertEquals("mycookie", cookie.getValue());
assertEquals("mycookiename", cookie.getName());
assertEquals("contextpath", cookie.getPath());
assertFalse(cookie.getSecure());
}
@Test
public void setCookieSetsSecureFlagIfConfigured() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
request.setContextPath("contextpath");
MockRememberMeServices services = new MockRememberMeServices() {
protected String encodeCookie(String[] cookieTokens) {
return cookieTokens[0];
}
};
services.setUseSecureCookie(true);
services.setCookie(new String[] {"mycookie"}, 1000, request, response);
Cookie cookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
assertTrue(cookie.getSecure());
}
private Cookie[] createLoginCookie(String cookieToken) {
MockRememberMeServices services = new MockRememberMeServices();
Cookie cookie = new Cookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY,
services.encodeCookie(StringUtils.delimitedListToStringArray(cookieToken, ":")));
return new Cookie[] {cookie};
}
private void assertCookieCancelled(MockHttpServletResponse response) {
Cookie returnedCookie = response.getCookie(AbstractRememberMeServices.SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY);
assertNotNull(returnedCookie);
assertEquals(0, returnedCookie.getMaxAge());
}
//~ Inner Classes ==================================================================================================
private class MockRememberMeServices extends AbstractRememberMeServices {
boolean loginSuccessCalled;
private MockRememberMeServices() {
setKey("key");
}
protected void onLoginSuccess(HttpServletRequest request, HttpServletResponse response, Authentication successfulAuthentication) {
loginSuccessCalled = true;
}
protected UserDetails processAutoLoginCookie(String[] cookieTokens, HttpServletRequest request, HttpServletResponse response) throws RememberMeAuthenticationException {
if(cookieTokens.length != 3) {
throw new InvalidCookieException("deliberate exception");
}
UserDetails user = getUserDetailsService().loadUserByUsername("joe");
return user;
}
}
public static class MockUserDetailsService implements UserDetailsService {
private UserDetails toReturn;
private boolean throwException;
public MockUserDetailsService(UserDetails toReturn, boolean throwException) {
this.toReturn = toReturn;
this.throwException = throwException;
}
public UserDetails loadUserByUsername(String username) {
if (throwException) {
throw new UsernameNotFoundException("as requested by mock");
}
return toReturn;
}
}
}
| |
/*
* Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
test %W% %E%
@bug 4874070
@summary Tests basic DnD functionality
@author Your Name: Alexey Utkin area=dnd
@run applet ImageDecoratedDnDInOut.html
*/
import java.applet.Applet;
import java.awt.*;
import java.awt.Robot;
import java.awt.event.InputEvent;
import java.awt.dnd.DragSource;
public class ImageDecoratedDnDInOut extends Applet {
//Declare things used in the test, like buttons and labels here
public void init() {
//Create instructions for the user here, as well as set up
// the environment -- set the layout manager, add buttons,
// etc.
this.setLayout(new BorderLayout());
String[] instructions =
{
"Automatic test.",
"A Frame, which contains a yellow button labeled \"Drag ME!\" and ",
"a red panel, will appear below. ",
"1. The button would be clicked and dragged to the red panel. ",
"2. When the mouse enters the red panel during the drag, the panel ",
"should turn yellow. On the systems that supports pictured drag, ",
"the image under the drag-cursor should appear (ancor is shifted ",
"from top-left corner of the picture inside the picture to 10pt in both dimensions ). ",
"In WIN32 systems the image under cursor would be visible ONLY over ",
"the drop targets with activated extended OLE D\'n\'D support (that are ",
"the desktop and IE ).",
"3. The mouse would be released.",
"The panel should turn red again and a yellow button labeled ",
"\"Drag ME!\" should appear inside the panel. "
};
Sysout.createDialogWithInstructions(instructions);
}//End init()
public void start() {
Frame f = new Frame("Use keyboard for DnD change");
Panel mainPanel;
Component dragSource, dropTarget;
f.setBounds(0, 400, 200, 200);
f.setLayout(new BorderLayout());
mainPanel = new Panel();
mainPanel.setLayout(new BorderLayout());
mainPanel.setBackground(Color.blue);
dropTarget = new DnDTarget(Color.red, Color.yellow);
dragSource = new DnDSource("Drag ME! (" + (DragSource.isDragImageSupported()?"with ":"without") + " image)" );
mainPanel.add(dragSource, "North");
mainPanel.add(dropTarget, "Center");
f.add(mainPanel, BorderLayout.CENTER);
f.setVisible(true);
try {
Point sourcePoint = dragSource.getLocationOnScreen();
Dimension d = dragSource.getSize();
sourcePoint.translate(d.width / 2, d.height / 2);
Robot robot = new Robot();
robot.mouseMove(sourcePoint.x, sourcePoint.y);
robot.mousePress(InputEvent.BUTTON1_MASK);
Thread.sleep(2000);
for(int i = 0; i <100; ++i) {
robot.mouseMove(
sourcePoint.x + d.width / 2 + 10,
sourcePoint.y + d.height);
Thread.sleep(100);
robot.mouseMove(sourcePoint.x, sourcePoint.y);
Thread.sleep(100);
robot.mouseMove(
sourcePoint.x,
sourcePoint.y + d.height);
Thread.sleep(100);
}
sourcePoint.y += d.height;
robot.mouseMove(sourcePoint.x, sourcePoint.y);
Thread.sleep(100);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
Thread.sleep(4000);
} catch( Exception e){
e.printStackTrace();
throw new RuntimeException("test failed: drop was not successful with exception " + e);
}
}// start()
}// class DnDAcceptanceTest
/**
* *************************************************
* Standard Test Machinery
* DO NOT modify anything below -- it's a standard
* chunk of code whose purpose is to make user
* interaction uniform, and thereby make it simpler
* to read and understand someone else's test.
* **************************************************
*/
class Sysout {
private static TestDialog dialog;
public static void createDialogWithInstructions(String[] instructions) {
dialog = new TestDialog(new Frame(), "Instructions");
dialog.printInstructions(instructions);
dialog.show();
println("Any messages for the tester will display here.");
}
public static void createDialog() {
dialog = new TestDialog(new Frame(), "Instructions");
String[] defInstr = {"Instructions will appear here. ", ""};
dialog.printInstructions(defInstr);
dialog.show();
println("Any messages for the tester will display here.");
}
public static void printInstructions(String[] instructions) {
dialog.printInstructions(instructions);
}
public static void println(String messageIn) {
dialog.displayMessage(messageIn);
}
}// Sysout class
class TestDialog extends Dialog {
TextArea instructionsText;
TextArea messageText;
int maxStringLength = 80;
//DO NOT call this directly, go through Sysout
public TestDialog(Frame frame, String name) {
super(frame, name);
int scrollBoth = TextArea.SCROLLBARS_BOTH;
instructionsText = new TextArea("", 15, maxStringLength, scrollBoth);
add("North", instructionsText);
messageText = new TextArea("", 5, maxStringLength, scrollBoth);
add("South", messageText);
pack();
show();
}// TestDialog()
//DO NOT call this directly, go through Sysout
public void printInstructions(String[] instructions) {
//Clear out any current instructions
instructionsText.setText("");
//Go down array of instruction strings
String printStr, remainingStr;
for (int i = 0; i < instructions.length; i++) {
//chop up each into pieces maxSringLength long
remainingStr = instructions[i];
while (remainingStr.length() > 0) {
//if longer than max then chop off first max chars to print
if (remainingStr.length() >= maxStringLength) {
//Try to chop on a word boundary
int posOfSpace = remainingStr.
lastIndexOf(' ', maxStringLength - 1);
if (posOfSpace <= 0) posOfSpace = maxStringLength - 1;
printStr = remainingStr.substring(0, posOfSpace + 1);
remainingStr = remainingStr.substring(posOfSpace + 1);
}
//else just print
else {
printStr = remainingStr;
remainingStr = "";
}
instructionsText.append(printStr + "\n");
}// while
}// for
}//printInstructions()
//DO NOT call this directly, go through Sysout
public void displayMessage(String messageIn) {
messageText.append(messageIn + "\n");
}
}// TestDialog class
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.nifi.processors.standard;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import org.apache.nifi.annotation.behavior.EventDriven;
import org.apache.nifi.annotation.behavior.InputRequirement;
import org.apache.nifi.annotation.behavior.InputRequirement.Requirement;
import org.apache.nifi.annotation.behavior.SupportsBatching;
import org.apache.nifi.annotation.behavior.WritesAttribute;
import org.apache.nifi.annotation.documentation.CapabilityDescription;
import org.apache.nifi.annotation.documentation.SeeAlso;
import org.apache.nifi.annotation.documentation.Tags;
import org.apache.nifi.components.AllowableValue;
import org.apache.nifi.components.PropertyDescriptor;
import org.apache.nifi.distributed.cache.client.Deserializer;
import org.apache.nifi.distributed.cache.client.DistributedMapCacheClient;
import org.apache.nifi.distributed.cache.client.Serializer;
import org.apache.nifi.distributed.cache.client.exception.DeserializationException;
import org.apache.nifi.distributed.cache.client.exception.SerializationException;
import org.apache.nifi.expression.AttributeExpression.ResultType;
import org.apache.nifi.expression.ExpressionLanguageScope;
import org.apache.nifi.flowfile.FlowFile;
import org.apache.nifi.logging.ComponentLog;
import org.apache.nifi.processor.AbstractProcessor;
import org.apache.nifi.processor.DataUnit;
import org.apache.nifi.processor.ProcessContext;
import org.apache.nifi.processor.ProcessSession;
import org.apache.nifi.processor.Relationship;
import org.apache.nifi.processor.exception.ProcessException;
import org.apache.nifi.processor.util.StandardValidators;
@EventDriven
@SupportsBatching
@Tags({"map", "cache", "put", "distributed"})
@InputRequirement(Requirement.INPUT_REQUIRED)
@CapabilityDescription("Gets the content of a FlowFile and puts it to a distributed map cache, using a cache key " +
"computed from FlowFile attributes. If the cache already contains the entry and the cache update strategy is " +
"'keep original' the entry is not replaced.'")
@WritesAttribute(attribute = "cached", description = "All FlowFiles will have an attribute 'cached'. The value of this " +
"attribute is true, is the FlowFile is cached, otherwise false.")
@SeeAlso(classNames = {"org.apache.nifi.distributed.cache.client.DistributedMapCacheClientService", "org.apache.nifi.distributed.cache.server.map.DistributedMapCacheServer",
"org.apache.nifi.processors.standard.FetchDistributedMapCache"})
public class PutDistributedMapCache extends AbstractProcessor {
public static final String CACHED_ATTRIBUTE_NAME = "cached";
// Identifies the distributed map cache client
public static final PropertyDescriptor DISTRIBUTED_CACHE_SERVICE = new PropertyDescriptor.Builder()
.name("Distributed Cache Service")
.description("The Controller Service that is used to cache flow files")
.required(true)
.identifiesControllerService(DistributedMapCacheClient.class)
.build();
// Selects the FlowFile attribute, whose value is used as cache key
public static final PropertyDescriptor CACHE_ENTRY_IDENTIFIER = new PropertyDescriptor.Builder()
.name("Cache Entry Identifier")
.description("A FlowFile attribute, or the results of an Attribute Expression Language statement, which will " +
"be evaluated against a FlowFile in order to determine the cache key")
.required(true)
.addValidator(StandardValidators.createAttributeExpressionLanguageValidator(ResultType.STRING, true))
.expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES)
.build();
public static final AllowableValue CACHE_UPDATE_REPLACE = new AllowableValue("replace", "Replace if present",
"Adds the specified entry to the cache, replacing any value that is currently set.");
public static final AllowableValue CACHE_UPDATE_KEEP_ORIGINAL = new AllowableValue("keeporiginal", "Keep original",
"Adds the specified entry to the cache, if the key does not exist.");
public static final PropertyDescriptor CACHE_UPDATE_STRATEGY = new PropertyDescriptor.Builder()
.name("Cache update strategy")
.description("Determines how the cache is updated if the cache already contains the entry")
.required(true)
.allowableValues(CACHE_UPDATE_REPLACE, CACHE_UPDATE_KEEP_ORIGINAL)
.defaultValue(CACHE_UPDATE_REPLACE.getValue())
.build();
public static final PropertyDescriptor CACHE_ENTRY_MAX_BYTES = new PropertyDescriptor.Builder()
.name("Max cache entry size")
.description("The maximum amount of data to put into cache")
.required(false)
.addValidator(StandardValidators.DATA_SIZE_VALIDATOR)
.defaultValue("1 MB")
.expressionLanguageSupported(ExpressionLanguageScope.NONE)
.build();
public static final Relationship REL_SUCCESS = new Relationship.Builder()
.name("success")
.description("Any FlowFile that is successfully inserted into cache will be routed to this relationship")
.build();
public static final Relationship REL_FAILURE = new Relationship.Builder()
.name("failure")
.description("Any FlowFile that cannot be inserted into the cache will be routed to this relationship")
.build();
private final Set<Relationship> relationships;
private final Serializer<String> keySerializer = new StringSerializer();
private final Serializer<byte[]> valueSerializer = new CacheValueSerializer();
private final Deserializer<byte[]> valueDeserializer = new CacheValueDeserializer();
public PutDistributedMapCache() {
final Set<Relationship> rels = new HashSet<>();
rels.add(REL_SUCCESS);
rels.add(REL_FAILURE);
relationships = Collections.unmodifiableSet(rels);
}
@Override
protected List<PropertyDescriptor> getSupportedPropertyDescriptors() {
final List<PropertyDescriptor> descriptors = new ArrayList<>();
descriptors.add(CACHE_ENTRY_IDENTIFIER);
descriptors.add(DISTRIBUTED_CACHE_SERVICE);
descriptors.add(CACHE_UPDATE_STRATEGY);
descriptors.add(CACHE_ENTRY_MAX_BYTES);
return descriptors;
}
@Override
public Set<Relationship> getRelationships() {
return relationships;
}
@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
FlowFile flowFile = session.get();
if (flowFile == null) {
return;
}
final ComponentLog logger = getLogger();
// cache key is computed from attribute 'CACHE_ENTRY_IDENTIFIER' with expression language support
final String cacheKey = context.getProperty(CACHE_ENTRY_IDENTIFIER).evaluateAttributeExpressions(flowFile).getValue();
// if the computed value is null, or empty, we transfer the flow file to failure relationship
if (StringUtils.isBlank(cacheKey)) {
logger.error("FlowFile {} has no attribute for given Cache Entry Identifier", new Object[] {flowFile});
flowFile = session.penalize(flowFile);
session.transfer(flowFile, REL_FAILURE);
return;
}
// the cache client used to interact with the distributed cache
final DistributedMapCacheClient cache = context.getProperty(DISTRIBUTED_CACHE_SERVICE).asControllerService(DistributedMapCacheClient.class);
try {
final long maxCacheEntrySize = context.getProperty(CACHE_ENTRY_MAX_BYTES).asDataSize(DataUnit.B).longValue();
long flowFileSize = flowFile.getSize();
// too big flow file
if (flowFileSize > maxCacheEntrySize) {
logger.warn("Flow file {} size {} exceeds the max cache entry size ({} B).", new Object[] {flowFile, flowFileSize, maxCacheEntrySize});
session.transfer(flowFile, REL_FAILURE);
return;
}
if (flowFileSize == 0) {
logger.warn("Flow file {} is empty, there is nothing to cache.", new Object[] {flowFile});
session.transfer(flowFile, REL_FAILURE);
return;
}
// get flow file content
final ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
session.exportTo(flowFile, byteStream);
byte[] cacheValue = byteStream.toByteArray();
final String updateStrategy = context.getProperty(CACHE_UPDATE_STRATEGY).getValue();
boolean cached = false;
if (updateStrategy.equals(CACHE_UPDATE_REPLACE.getValue())) {
cache.put(cacheKey, cacheValue, keySerializer, valueSerializer);
cached = true;
} else if (updateStrategy.equals(CACHE_UPDATE_KEEP_ORIGINAL.getValue())) {
final byte[] oldValue = cache.getAndPutIfAbsent(cacheKey, cacheValue, keySerializer, valueSerializer, valueDeserializer);
if (oldValue == null) {
cached = true;
}
}
// set 'cached' attribute
flowFile = session.putAttribute(flowFile, CACHED_ATTRIBUTE_NAME, String.valueOf(cached));
if (cached) {
session.transfer(flowFile, REL_SUCCESS);
} else {
session.transfer(flowFile, REL_FAILURE);
}
} catch (final IOException e) {
flowFile = session.penalize(flowFile);
session.transfer(flowFile, REL_FAILURE);
logger.error("Unable to communicate with cache when processing {} due to {}", new Object[] {flowFile, e});
}
}
public static class CacheValueSerializer implements Serializer<byte[]> {
@Override
public void serialize(final byte[] bytes, final OutputStream out) throws SerializationException, IOException {
out.write(bytes);
}
}
public static class CacheValueDeserializer implements Deserializer<byte[]> {
@Override
public byte[] deserialize(final byte[] input) throws DeserializationException, IOException {
if (input == null || input.length == 0) {
return null;
}
return input;
}
}
/**
* Simple string serializer, used for serializing the cache key
*/
public static class StringSerializer implements Serializer<String> {
@Override
public void serialize(final String value, final OutputStream out) throws SerializationException, IOException {
out.write(value.getBytes(StandardCharsets.UTF_8));
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.network.fluent.models;
import com.azure.core.annotation.Fluent;
import com.azure.core.management.SubResource;
import com.azure.core.util.logging.ClientLogger;
import com.azure.resourcemanager.network.models.IpTag;
import com.azure.resourcemanager.network.models.IpVersion;
import com.azure.resourcemanager.network.models.ProvisioningState;
import com.azure.resourcemanager.network.models.ReferencedPublicIpAddress;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
/** Public IP prefix properties. */
@Fluent
public final class PublicIpPrefixPropertiesFormatInner {
@JsonIgnore private final ClientLogger logger = new ClientLogger(PublicIpPrefixPropertiesFormatInner.class);
/*
* The public IP address version.
*/
@JsonProperty(value = "publicIPAddressVersion")
private IpVersion publicIpAddressVersion;
/*
* The list of tags associated with the public IP prefix.
*/
@JsonProperty(value = "ipTags")
private List<IpTag> ipTags;
/*
* The Length of the Public IP Prefix.
*/
@JsonProperty(value = "prefixLength")
private Integer prefixLength;
/*
* The allocated Prefix.
*/
@JsonProperty(value = "ipPrefix", access = JsonProperty.Access.WRITE_ONLY)
private String ipPrefix;
/*
* The list of all referenced PublicIPAddresses.
*/
@JsonProperty(value = "publicIPAddresses", access = JsonProperty.Access.WRITE_ONLY)
private List<ReferencedPublicIpAddress> publicIpAddresses;
/*
* The reference to load balancer frontend IP configuration associated with
* the public IP prefix.
*/
@JsonProperty(value = "loadBalancerFrontendIpConfiguration", access = JsonProperty.Access.WRITE_ONLY)
private SubResource loadBalancerFrontendIpConfiguration;
/*
* The customIpPrefix that this prefix is associated with.
*/
@JsonProperty(value = "customIPPrefix")
private SubResource customIpPrefix;
/*
* The resource GUID property of the public IP prefix resource.
*/
@JsonProperty(value = "resourceGuid", access = JsonProperty.Access.WRITE_ONLY)
private String resourceGuid;
/*
* The provisioning state of the public IP prefix resource.
*/
@JsonProperty(value = "provisioningState", access = JsonProperty.Access.WRITE_ONLY)
private ProvisioningState provisioningState;
/*
* NatGateway of Public IP Prefix.
*/
@JsonProperty(value = "natGateway")
private NatGatewayInner natGateway;
/**
* Get the publicIpAddressVersion property: The public IP address version.
*
* @return the publicIpAddressVersion value.
*/
public IpVersion publicIpAddressVersion() {
return this.publicIpAddressVersion;
}
/**
* Set the publicIpAddressVersion property: The public IP address version.
*
* @param publicIpAddressVersion the publicIpAddressVersion value to set.
* @return the PublicIpPrefixPropertiesFormatInner object itself.
*/
public PublicIpPrefixPropertiesFormatInner withPublicIpAddressVersion(IpVersion publicIpAddressVersion) {
this.publicIpAddressVersion = publicIpAddressVersion;
return this;
}
/**
* Get the ipTags property: The list of tags associated with the public IP prefix.
*
* @return the ipTags value.
*/
public List<IpTag> ipTags() {
return this.ipTags;
}
/**
* Set the ipTags property: The list of tags associated with the public IP prefix.
*
* @param ipTags the ipTags value to set.
* @return the PublicIpPrefixPropertiesFormatInner object itself.
*/
public PublicIpPrefixPropertiesFormatInner withIpTags(List<IpTag> ipTags) {
this.ipTags = ipTags;
return this;
}
/**
* Get the prefixLength property: The Length of the Public IP Prefix.
*
* @return the prefixLength value.
*/
public Integer prefixLength() {
return this.prefixLength;
}
/**
* Set the prefixLength property: The Length of the Public IP Prefix.
*
* @param prefixLength the prefixLength value to set.
* @return the PublicIpPrefixPropertiesFormatInner object itself.
*/
public PublicIpPrefixPropertiesFormatInner withPrefixLength(Integer prefixLength) {
this.prefixLength = prefixLength;
return this;
}
/**
* Get the ipPrefix property: The allocated Prefix.
*
* @return the ipPrefix value.
*/
public String ipPrefix() {
return this.ipPrefix;
}
/**
* Get the publicIpAddresses property: The list of all referenced PublicIPAddresses.
*
* @return the publicIpAddresses value.
*/
public List<ReferencedPublicIpAddress> publicIpAddresses() {
return this.publicIpAddresses;
}
/**
* Get the loadBalancerFrontendIpConfiguration property: The reference to load balancer frontend IP configuration
* associated with the public IP prefix.
*
* @return the loadBalancerFrontendIpConfiguration value.
*/
public SubResource loadBalancerFrontendIpConfiguration() {
return this.loadBalancerFrontendIpConfiguration;
}
/**
* Get the customIpPrefix property: The customIpPrefix that this prefix is associated with.
*
* @return the customIpPrefix value.
*/
public SubResource customIpPrefix() {
return this.customIpPrefix;
}
/**
* Set the customIpPrefix property: The customIpPrefix that this prefix is associated with.
*
* @param customIpPrefix the customIpPrefix value to set.
* @return the PublicIpPrefixPropertiesFormatInner object itself.
*/
public PublicIpPrefixPropertiesFormatInner withCustomIpPrefix(SubResource customIpPrefix) {
this.customIpPrefix = customIpPrefix;
return this;
}
/**
* Get the resourceGuid property: The resource GUID property of the public IP prefix resource.
*
* @return the resourceGuid value.
*/
public String resourceGuid() {
return this.resourceGuid;
}
/**
* Get the provisioningState property: The provisioning state of the public IP prefix resource.
*
* @return the provisioningState value.
*/
public ProvisioningState provisioningState() {
return this.provisioningState;
}
/**
* Get the natGateway property: NatGateway of Public IP Prefix.
*
* @return the natGateway value.
*/
public NatGatewayInner natGateway() {
return this.natGateway;
}
/**
* Set the natGateway property: NatGateway of Public IP Prefix.
*
* @param natGateway the natGateway value to set.
* @return the PublicIpPrefixPropertiesFormatInner object itself.
*/
public PublicIpPrefixPropertiesFormatInner withNatGateway(NatGatewayInner natGateway) {
this.natGateway = natGateway;
return this;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
if (ipTags() != null) {
ipTags().forEach(e -> e.validate());
}
if (publicIpAddresses() != null) {
publicIpAddresses().forEach(e -> e.validate());
}
if (natGateway() != null) {
natGateway().validate();
}
}
}
| |
package com.eolwral.osmonitor;
import java.util.HashMap;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import com.eolwral.osmonitor.ipc.IpcService;
import com.eolwral.osmonitor.ui.ConnectionFragment;
import com.eolwral.osmonitor.ui.MessageFragment;
import com.eolwral.osmonitor.ui.MiscFragment;
import com.eolwral.osmonitor.ui.ProcessFragment;
import com.eolwral.osmonitor.util.CoreUtil;
import com.eolwral.osmonitor.util.UserInterfaceUtil;
import com.eolwral.osmonitor.settings.Settings;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar.Tab;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.view.Menu;
@SuppressWarnings("deprecation")
public class OSMonitor extends OSMonitorActivity implements
ActionBar.TabListener, ViewPager.OnPageChangeListener {
private ViewPager mViewPager = null;
@Override
public void onStop() {
super.onStop();
if (mViewPager == null)
return;
((OSMonitorPagerAdapter) mViewPager.getAdapter()).getItem(
mViewPager.getCurrentItem()).setUserVisibleHint(false);
// end self
if (isFinishing()) {
IpcService.getInstance().disconnect();
android.os.Process.killProcess(android.os.Process.myPid());
}
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
// create view
super.onCreate(savedInstanceState);
IpcService.Initialize(this);
UserInterfaceUtil.Initialize(this);
// load layout
setContentView(R.layout.ui_main);
// prepare pager
mViewPager = (ViewPager) findViewById(R.id.mainpager);
mViewPager
.setAdapter(new OSMonitorPagerAdapter(getSupportFragmentManager()));
mViewPager.setOnPageChangeListener(this);
// keep all fragments
mViewPager.setOffscreenPageLimit(5);
// prepare action bar
final ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setElevation(0);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.addTab(actionBar.newTab().setText(R.string.ui_process_tab)
.setTabListener(this));
actionBar.addTab(actionBar.newTab().setText(R.string.ui_connection_tab)
.setTabListener(this));
actionBar.addTab(actionBar.newTab().setText(R.string.ui_misc_tab)
.setTabListener(this));
actionBar.addTab(actionBar.newTab().setText(R.string.ui_debug_tab)
.setTabListener(this));
mViewPager.setCurrentItem(0);
// start background service
final Settings setting = Settings.getInstance(this);
if ((setting.isEnableCPUMeter() || setting.isAddShortCut())
&& !CoreUtil.isServiceRunning(this))
startService(new Intent(this, OSMonitorService.class));
// prepare exit
LocalBroadcastManager.getInstance(this).registerReceiver(ExitReceiver,
new IntentFilter("Exit"));
}
private BroadcastReceiver ExitReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
IpcService.getInstance().forceExit();
context.stopService(new Intent(context, OSMonitorService.class));
finish();
}
};
@Override
protected void onDestroy() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(ExitReceiver);
super.onDestroy();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
// No call for super(). Bug on API Level > 11.
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
/* prepare option on action bar */
super.onCreateOptionsMenu(menu);
return true;
}
@Override
public void onRestart() {
super.onRestart();
if (mViewPager == null)
return;
Fragment mFragment = ((OSMonitorPagerAdapter) mViewPager.getAdapter())
.getItem(mViewPager.getCurrentItem());
if (mFragment != null) {
// catch exception when back from screen off
try {
mFragment.setUserVisibleHint(true);
} catch (Exception e) { }
}
}
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
mViewPager.setCurrentItem(tab.getPosition());
if (mViewPager.getCurrentItem() != tab.getPosition())
mViewPager.setCurrentItem(tab.getPosition());
// force display menu when selected
((OSMonitorPagerAdapter) mViewPager.getAdapter()).getItem(
mViewPager.getCurrentItem()).setMenuVisibility(true);
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// force to hidden when unselected
((OSMonitorPagerAdapter) mViewPager.getAdapter())
.getItem(tab.getPosition()).setMenuVisibility(false);
}
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
@Override
public void onPageScrollStateChanged(int arg0) {
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
@Override
public void onPageSelected(int arg0) {
getSupportActionBar().setSelectedNavigationItem(arg0);
}
/* Pager Adapter for OSMonitor */
public class OSMonitorPagerAdapter extends FragmentPagerAdapter {
@SuppressLint("UseSparseArrays")
HashMap<Integer, Fragment> mFragment = new HashMap<Integer, Fragment>();
public OSMonitorPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
if (mFragment.containsKey(position))
return mFragment.get(position);
switch (position) {
/* Process */
case 0:
mFragment.put(0, new ProcessFragment());
break;
/* Connection */
case 1:
mFragment.put(1, new ConnectionFragment());
break;
/* Misc */
case 2:
mFragment.put(2, new MiscFragment());
break;
/* Message */
case 3:
mFragment.put(3, new MessageFragment());
break;
/* Monitor */
case 4:
// under construction
break;
}
return mFragment.get(position);
}
@Override
public int getCount() {
return 4;
}
}
}
| |
package LogMaintainence;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import serverclient.MainStart;
public class ChatLogging implements Runnable
{
private JSONObject mainObject;
private File jsonFilePath;
private String fileName;
private int totalUsers;
private String userId;
private String userName;
private BlockingQueue<String> bq;
public ChatLogging(String userId, String userName, BlockingQueue<String> bq)
{
this.userId = userId;
this.userName = userName;
this.fileName = userId+".json";
this.bq = bq;
}
@SuppressWarnings("unchecked")
public void run()
{
String newPathString = MainStart.rootpath+File.separator+"chatlogs";
File newPath = new File(newPathString);
newPath.mkdirs();
jsonFilePath = new File(newPath,fileName);
if(!jsonFilePath.exists()) // if file doesn't exist
{
mainObject = new JSONObject();
mainObject.put("totalUsers", totalUsers);
mainObject.put("groupId", userId);
mainObject.put("groupName", userName);
mainObject.put("lineCount", 0l);
JSONArray groupUsers = new JSONArray();
groupUsers.add(userId);
//groupUsers.add("rajat");
//groupUsers.add("shasuck");
//groupUsers.add("baid");
mainObject.put("users", groupUsers);
JSONArray chatArray = new JSONArray();
JSONObject sessionObject = new JSONObject();
sessionObject.put("1", chatArray);
mainObject.put("session", sessionObject);
mainObject.put("lastUpdatedSession", 1l);
}
else //if file exists
{
JSONParser parser = new JSONParser();
Object obj = null;
try
{
obj = parser.parse(new FileReader(jsonFilePath));
}
catch (IOException | ParseException e2)
{
e2.printStackTrace();
}
mainObject = (JSONObject)obj;
}
boolean on = true;
while(on)
{
String qElement=null;
String detailsArray[] = null;
for(int i=0;i<15;i++)
{
try {
qElement = bq.poll(1000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
if( qElement!=null && !qElement.isEmpty())
{
if(!qElement.equals("CLOSE"))
{
detailsArray = qElement.split("\\|"); //details[0]=userId [1]=userName [2]=timeStamp [3]=messageText
if(detailsArray.length>4)
{
for(int j=4;j<detailsArray.length;j++) //Concatenating message with pipes into one place
detailsArray[3]+="|"+detailsArray[j];
}
logCreate(detailsArray[0], detailsArray[1], detailsArray[3], detailsArray[2]);
}
else
{
on=false;
break;
}
}
}
writeLogToFile();
}
bq=null;
MainStart.people.get(userId).setBlockinQNull();
}
@SuppressWarnings("unchecked")
public void logCreate(String userId, String userName, String userMessage, String timeStamp)
{
long lastSessionValue = (long)mainObject.get("lastUpdatedSession");
JSONObject sessionObject = (JSONObject) mainObject.get("session");
long lineCount = (long)mainObject.get("lineCount");
lineCount++;
boolean sessionchange = false;
if(lineCount%5 == 0)
{
lastSessionValue++;
sessionchange = true;
}
JSONObject messageObject = new JSONObject();
messageObject.put("timeStamp", timeStamp);
messageObject.put("userName", userName);
messageObject.put("messageText", userMessage);
messageObject.put("userId", userId);
JSONArray chatArray;
if(!sessionchange)
{
chatArray = (JSONArray) sessionObject.get(""+lastSessionValue);
}
else
chatArray = new JSONArray();
chatArray.add(messageObject);
sessionObject.put(""+lastSessionValue, chatArray);
mainObject.put("lineCount", lineCount);
mainObject.put("lastUpdatedSession", lastSessionValue);
}
public void writeLogToFile()
{
try
{
/* Write Code to write the main object to file */
jsonFilePath.createNewFile();
FileWriter jsonFileWriter = new FileWriter(jsonFilePath);
jsonFileWriter.write(mainObject.toJSONString());
jsonFileWriter.flush();
jsonFileWriter.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void clearLog(String userId)
{
File path = new File(System.getProperty("user.dir"));
File jsonFilePath = new File(path,""+userId+".json");
String fileName = userId+".json";
if(jsonFilePath.exists())
{
try
{
if(jsonFilePath.delete())
System.out.println("file "+fileName+" is deleted\n");
else
System.out.println("delete failed\n");
}
catch (Exception e)
{
e.printStackTrace();
}
}
else
{
System.out.println("file doesnt exist!\n");
}
}
}
| |
package au.net.thehardings.ims.mergereport.dispatch;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.mail.MessagingException;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.jmock.Mock;
import au.net.thehardings.ims.mergereport.AllTests;
import au.net.thehardings.ims.mergereport.model.Commit;
import au.net.thehardings.ims.mergereport.model.Repository;
/**
* The class <code>FreemarkerDispatcherTest</code>
*/
public class FreemarkerDispatcherTest extends AllTests {
FreemarkerDispatcher freemarkerDispatcher;
/**
* Test lifecycle method runs before each test case.
*
* @throws Exception if an error occurs during test
*/
protected void setUp() throws Exception {
super.setUp();
freemarkerDispatcher = new TestableFreemarkerDispatcher();
}
/**
* Test case for the <code>FreemarkerDispatcher()</code> method
* of class <code>FreemarkerDispatcher</code>
*
* @throws Exception if an error occurs during test
*/
public void testFreemarkerDispatcher() throws Exception {
assertNotNull("The Freemarker configuration must have a default.", freemarkerDispatcher.cfg);
}
/**
* Test case for the <code>process()</code> method
* of class <code>FreemarkerDispatcher</code>
*
* @throws Exception if an error occurs during test
*/
public void testProcess() throws Exception {
String templateName = "template.ftl";
Map<String, Object> context = new HashMap<String, Object>();
Mock cfgMock = mock(Configuration.class);
cfgMock.expects(once()).method("getStrictSyntaxMode").will(returnValue(true));
cfgMock.expects(once()).method("getWhitespaceStripping").will(returnValue(true));
cfgMock.expects(once()).method("getTagSyntax").will(returnValue(0));
MockableTemplate.cfg = (Configuration) cfgMock.proxy();
Mock templateMock = mock(MockableTemplate.class);
templateMock.expects(once()).method("process").with(eq(context), isA(StringWriter.class));
cfgMock.expects(once()).method("getTemplate").with(eq(templateName)).will(returnValue(templateMock.proxy()));
freemarkerDispatcher.cfg = (Configuration) cfgMock.proxy();
freemarkerDispatcher.process(context, templateName);
}
/**
* Test case for the <code>process()</code> method
* of class <code>FreemarkerDispatcher</code>
*
* @throws Exception if an error occurs during test
*/
public void testProcessException1() throws Exception {
String templateName = "template.ftl";
Map<String, Object> context = new HashMap<String, Object>();
Mock cfgMock = mock(Configuration.class);
cfgMock.expects(once()).method("getTemplate").withAnyArguments().will(throwException(new IOException("unit test")));
freemarkerDispatcher.cfg = (Configuration) cfgMock.proxy();
try {
freemarkerDispatcher.process(context, templateName);
fail("should have thrown exception");
} catch (RuntimeException e) {
assertEquals("The exception text was not as expected", "Couldn't get freemarker template named '" + templateName + "'.", e.getMessage());
}
}
/**
* Test case for the <code>process()</code> method
* of class <code>FreemarkerDispatcher</code>
*
* @throws Exception if an error occurs during test
*/
public void testProcessException2() throws Exception {
String templateName = "template.ftl";
Map<String, Object> context = new HashMap<String, Object>();
Mock cfgMock = mock(Configuration.class);
cfgMock.expects(once()).method("getStrictSyntaxMode").will(returnValue(true));
cfgMock.expects(once()).method("getWhitespaceStripping").will(returnValue(true));
cfgMock.expects(once()).method("getTagSyntax").will(returnValue(0));
MockableTemplate.cfg = (Configuration) cfgMock.proxy();
Mock templateMock = mock(MockableTemplate.class);
templateMock.expects(once()).method("process").withAnyArguments().will(throwException(new TemplateException("unit test", null)));
cfgMock.expects(once()).method("getTemplate").with(eq(templateName)).will(returnValue(templateMock.proxy()));
freemarkerDispatcher.cfg = (Configuration) cfgMock.proxy();
try {
freemarkerDispatcher.process(context, templateName);
fail("should have thrown exception");
} catch (RuntimeException e) {
assertEquals("The exception text was not as expected", "Exception while processing template named '" + templateName + "'.", e.getMessage());
}
}
/**
* Test case for the <code>getUserCommits()</code> method
* of class <code>FreemarkerDispatcher</code>
*
* @throws Exception if an error occurs during test
*/
public void testGetUserCommits() throws Exception {
List<String> comments = new ArrayList<String>();
comments.add("Test comment");
Repository repository = new Repository();
repository.setName("repository");
Commit commit = new Commit.Builder(repository, "branch", 400).username("user").date("20071010").comment(comments).build();
List<Commit> commits = new ArrayList<Commit>();
commits.add(commit);
Map<String, Map<String, List<Commit>>> userCommits = freemarkerDispatcher.getUserCommits(commits);
assertTrue("There should only be one user", userCommits.size() == 1);
assertNotNull("The user was not found", userCommits.get(commit.getUsername()));
assertTrue("There should only be one repository", userCommits.get(commit.getUsername()).size() == 1);
assertNotNull("The repository was not found", userCommits.get(commit.getUsername()).get(commit.getRepository().getName()));
assertTrue("There should only be one commit", userCommits.get(commit.getUsername()).get(commit.getRepository().getName()).size() == 1);
assertEquals("The commit was different", commit.getCommitId(), userCommits.get(commit.getUsername()).get(commit.getRepository().getName()).get(0).getCommitId());
}
/**
* Test case for the <code>getUserCommands()</code> method
* of class <code>FreemarkerDispatcher</code>
*
* @throws Exception if an error occurs during test
*/
public void testGetUserCommands1() throws Exception {
List<String> comments = new ArrayList<String>();
comments.add("Test comment");
Repository repository = new Repository();
repository.setName("repository");
repository.setUrl("url");
repository.setBranchName("branch");
Commit commit1 = new Commit.Builder(repository, "branch", 400).username("user").date("20071010").comment(comments).build();
Commit commit2 = new Commit.Builder(repository, "branch", 401).username("user").date("20071010").comment(comments).build();
List<Commit> commits = new ArrayList<Commit>();
commits.add(commit1);
commits.add(commit2);
Map<String, Map<String, String>> userCommands = freemarkerDispatcher.getUserCommands(commits);
assertTrue("There should only be one user", userCommands.size() == 1);
assertNotNull("The user was not found", userCommands.get(commit1.getUsername()));
assertTrue("There should only be one repository", userCommands.get(commit1.getUsername()).size() == 1);
assertEquals("The command was different", "svn merge -c " + commit1.getCommitId() + "," + commit2.getCommitId() + " " + commit1.getRepository().getBranchUrl(), userCommands.get(commit1.getUsername()).get(commit1.getRepository().getName()));
}
/**
* Test case for the <code>getUserCommands()</code> method
* of class <code>FreemarkerDispatcher</code>
*
* @throws Exception if an error occurs during test
*/
public void testGetUserCommands2() throws Exception {
List<String> comments = new ArrayList<String>();
comments.add("Test comment");
Repository repository = new Repository();
repository.setName("repository");
repository.setUrl("url");
repository.setBranchName("branch");
Commit commit1 = new Commit.Builder(repository, "branch", 400).username("zzsysuser").date("20071010").comment(comments).build();
Commit commit2 = new Commit.Builder(repository, "branch", 401).username("zzsysuser").date("20071010").comment(comments).build();
List<Commit> commits = new ArrayList<Commit>();
commits.add(commit1);
commits.add(commit2);
Map<String, Map<String, String>> userCommands = freemarkerDispatcher.getUserCommands(commits);
assertTrue("There should only be one system user", userCommands.size() == 1);
assertNotNull("The system user was not found", userCommands.get(commit1.getUsername()));
assertTrue("There should only be one repository", userCommands.get(commit1.getUsername()).size() == 1);
assertEquals("The command was different", "svn merge --record-only -c " + commit1.getCommitId() + "," + commit2.getCommitId() + " " + commit1.getRepository().getBranchUrl(), userCommands.get(commit1.getUsername()).get(commit1.getRepository().getName()));
}
public class TestableFreemarkerDispatcher extends FreemarkerDispatcher {
public void dispatch(List<Commit> outstanding) throws MessagingException {
//do nothing here;
}
}
public static class MockableTemplate extends Template {
static Configuration cfg;
public MockableTemplate() throws IOException {
super("template.ftl", new StringReader(""), cfg);
}
}
}
| |
/**
*
* Copyright 2011 (C) 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 com.toolazydogs.maiden.agent.asm;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.Attribute;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.commons.LocalVariablesSorter;
import org.objectweb.asm.tree.MethodNode;
/**
* Use this class to insert code at the beginning and end of a method.
* <p/>
* An instance of {@link MethodVisitor} that wraps a method's code with a
* <code>try/finally</code> pair. It calls registered listeners, which
* implement {@link BeginEndMethodListener}, before the try block to allow
* listeners to insert code to be executed before the method's original
* code. When the <code>finally</code> segment is being generated the
* listeners are again called to insert code to be executed before the thread
* of control leaves the method.
* <p/>
* Listeners are also notified when a line number is encountered.
*/
public class BeginEndMethodVisitor implements MethodVisitor, Opcodes
{
private final static String CLASS_NAME = BeginEndMethodVisitor.class.getName();
private final static Logger LOGGER = Logger.getLogger(CLASS_NAME);
private final List<BeginEndMethodListener> listeners = new ArrayList<BeginEndMethodListener>();
private transient List<BeginEndMethodListener> reversed = null;
private final LocalVariablesSorter lvs;
private final MethodNode methodNode;
private final MethodVisitor visitor;
private State state = State.CLEARED;
private final Label l7 = new Label();
private Label start;
private boolean sawCode = false;
public BeginEndMethodVisitor(MethodVisitor visitor, int access, String name, String desc, String signature, String[] exceptions)
{
assert visitor != null;
assert name != null;
assert desc != null;
if (LOGGER.isLoggable(Level.CONFIG))
{
LOGGER.config("visitor: " + visitor);
LOGGER.config("access: " + access);
LOGGER.config("name: " + name);
LOGGER.config("desc: " + desc);
LOGGER.config("signature: " + signature);
for (String exception : exceptions) LOGGER.config("exception: " + exception);
}
this.visitor = visitor;
// this MethodNode instance is used to fill in hte gaps of frames and maxes
methodNode = new MethodNode(access, name, desc, signature, exceptions);
// We use this instance to keep track of local variables that may need to be created.
lvs = new LocalVariablesSorter(access, desc, methodNode);
}
public List<BeginEndMethodListener> getListeners()
{
reversed = null;
return listeners;
}
protected List<BeginEndMethodListener> getReversed()
{
if (reversed == null)
{
reversed = new ArrayList<BeginEndMethodListener>(listeners);
Collections.reverse(reversed);
}
return reversed;
}
public AnnotationVisitor visitAnnotationDefault() { return lvs.visitAnnotationDefault(); }
public AnnotationVisitor visitAnnotation(String desc, boolean visible) { return lvs.visitAnnotation(desc, visible); }
public AnnotationVisitor visitParameterAnnotation(int parameter, String desc, boolean visible) { return lvs.visitParameterAnnotation(parameter, desc, visible); }
public void visitAttribute(Attribute attr) { lvs.visitAttribute(attr); }
public void visitCode()
{
LOGGER.entering(CLASS_NAME, "visitCode");
lvs.visitCode();
for (BeginEndMethodListener listener : listeners) listener.begin(lvs);
state = State.NEED_START_LABEL;
LOGGER.exiting(CLASS_NAME, "visitCode");
}
public void visitFrame(int type, int nLocal, Object[] local, int nStack, Object[] stack)
{
}
public void visitInsn(int opcode)
{
LOGGER.entering(CLASS_NAME, "visitInsn", opcode);
flush();
switch (opcode)
{
case IRETURN:
case LRETURN:
case FRETURN:
case DRETURN:
case ARETURN:
case RETURN:
if (sawCode)
{
Label end = new Label();
lvs.visitLabel(end);
lvs.visitTryCatchBlock(start, end, l7, null);
}
for (BeginEndMethodListener listener : getReversed()) listener.end(lvs);
break;
default:
sawCode = true;
}
lvs.visitInsn(opcode);
LOGGER.exiting(CLASS_NAME, "visitInsn");
}
public void visitIntInsn(int opcode, int operand)
{
LOGGER.entering(CLASS_NAME, "visitIntInsn", new Object[]{opcode, operand});
flush();
sawCode = true;
lvs.visitIntInsn(opcode, operand);
LOGGER.exiting(CLASS_NAME, "visitIntInsn");
}
public void visitVarInsn(int opcode, int var)
{
LOGGER.entering(CLASS_NAME, "visitVarInsn", new Object[]{opcode, var});
flush();
sawCode = true;
lvs.visitVarInsn(opcode, var);
LOGGER.exiting(CLASS_NAME, "visitVarInsn");
}
public void visitTypeInsn(int opcode, String type)
{
LOGGER.entering(CLASS_NAME, "visitTypeInsn", new Object[]{opcode, type});
flush();
sawCode = true;
lvs.visitTypeInsn(opcode, type);
LOGGER.exiting(CLASS_NAME, "visitTypeInsn");
}
public void visitFieldInsn(int opcode, String owner, String name, String desc)
{
LOGGER.entering(CLASS_NAME, "visitFieldInsn", new Object[]{opcode, owner, name, desc});
flush();
sawCode = true;
lvs.visitFieldInsn(opcode, owner, name, desc);
LOGGER.exiting(CLASS_NAME, "visitFieldInsn");
}
public void visitMethodInsn(int opcode, String owner, String name, String desc)
{
LOGGER.entering(CLASS_NAME, "visitMethodInsn", new Object[]{opcode, owner, name, desc});
flush();
sawCode = true;
lvs.visitMethodInsn(opcode, owner, name, desc);
LOGGER.exiting(CLASS_NAME, "visitMethodInsn");
}
public void visitJumpInsn(int opcode, Label label)
{
LOGGER.entering(CLASS_NAME, "visitJumpInsn", new Object[]{opcode, label});
flush();
sawCode = true;
lvs.visitJumpInsn(opcode, label);
LOGGER.exiting(CLASS_NAME, "visitJumpInsn");
}
public void visitLabel(Label label)
{
LOGGER.entering(CLASS_NAME, "visitLabel", label);
flush();
lvs.visitLabel(label);
LOGGER.exiting(CLASS_NAME, "visitLabel");
}
public void visitLdcInsn(Object cst)
{
LOGGER.entering(CLASS_NAME, "visitLdcInsn", cst);
flush();
sawCode = true;
lvs.visitLdcInsn(cst);
LOGGER.exiting(CLASS_NAME, "visitLdcInsn");
}
public void visitIincInsn(int var, int increment)
{
LOGGER.entering(CLASS_NAME, "visitIincInsn", new Object[]{var, increment});
flush();
sawCode = true;
lvs.visitIincInsn(var, increment);
LOGGER.exiting(CLASS_NAME, "visitIincInsn");
}
public void visitTableSwitchInsn(int min, int max, Label dflt, Label[] labels)
{
LOGGER.entering(CLASS_NAME, "visitTableSwitchInsn", new Object[]{min, max, dflt, labels});
flush();
sawCode = true;
lvs.visitTableSwitchInsn(min, max, dflt, labels);
LOGGER.exiting(CLASS_NAME, "visitTableSwitchInsn");
}
public void visitLookupSwitchInsn(Label dflt, int[] keys, Label[] labels)
{
LOGGER.entering(CLASS_NAME, "visitLookupSwitchInsn", new Object[]{dflt, keys, labels});
flush();
sawCode = true;
lvs.visitLookupSwitchInsn(dflt, keys, labels);
LOGGER.exiting(CLASS_NAME, "visitLookupSwitchInsn");
}
public void visitMultiANewArrayInsn(String desc, int dims)
{
LOGGER.entering(CLASS_NAME, "visitMultiANewArrayInsn", new Object[]{desc, dims});
flush();
sawCode = true;
lvs.visitMultiANewArrayInsn(desc, dims);
LOGGER.exiting(CLASS_NAME, "visitMultiANewArrayInsn");
}
public void visitTryCatchBlock(Label start, Label end, Label handler, String type)
{
LOGGER.entering(CLASS_NAME, "visitTryCatchBlock", new Object[]{start, end, handler, type});
flush();
lvs.visitTryCatchBlock(start, end, handler, type);
LOGGER.exiting(CLASS_NAME, "visitTryCatchBlock");
}
public void visitLocalVariable(String name, String desc, String signature, Label start, Label end, int index)
{
LOGGER.entering(CLASS_NAME, "visitLocalVariable", new Object[]{name, desc, signature, start, end, index});
flush();
lvs.visitLocalVariable(name, desc, signature, start, end, index);
LOGGER.exiting(CLASS_NAME, "visitLocalVariable");
}
public void visitLineNumber(int line, Label start)
{
LOGGER.entering(CLASS_NAME, "visitLineNumber", new Object[]{line, start});
flush();
for (BeginEndMethodListener listener : listeners) listener.line(line);
lvs.visitLineNumber(line, start);
LOGGER.exiting(CLASS_NAME, "visitLineNumber");
}
public void visitMaxs(int maxStack, int maxLocals)
{
LOGGER.entering(CLASS_NAME, "visitMaxs", new Object[]{maxStack, maxLocals});
flush();
LOGGER.exiting(CLASS_NAME, "visitMaxs");
}
public void visitEnd()
{
LOGGER.entering(CLASS_NAME, "visitEnd");
flush();
if (sawCode)
{
LOGGER.finest("Saw code");
final Label l13 = new Label();
final int local = lvs.newLocal(Type.getType(Throwable.class));
lvs.visitTryCatchBlock(l7, l13, l7, null);
lvs.visitLabel(l7);
lvs.visitVarInsn(ASTORE, local);
lvs.visitLabel(l13);
for (BeginEndMethodListener listener : getReversed()) listener.end(lvs);
lvs.visitVarInsn(ALOAD, local);
lvs.visitInsn(ATHROW);
}
lvs.visitEnd();
methodNode.accept(visitor);
LOGGER.exiting(CLASS_NAME, "visitEnd");
}
/**
* Delay flushing out first label for our try/finally block until the first
* bit of code is encountered.
*/
private void flush()
{
LOGGER.entering(CLASS_NAME, "flush");
if (state == State.NEED_START_LABEL)
{
LOGGER.finest("Need start label");
start = new Label();
lvs.visitLabel(start);
state = State.CLEARED;
}
LOGGER.exiting(CLASS_NAME, "flush");
}
private static enum State
{
NEED_START_LABEL, CLEARED
}
}
| |
package com.github.czyzby.lml.parser.impl.tag;
import java.io.IOException;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.utils.GdxRuntimeException;
import com.badlogic.gdx.utils.ObjectMap;
import com.badlogic.gdx.utils.ObjectMap.Entry;
import com.github.czyzby.kiwi.util.common.Exceptions;
import com.github.czyzby.kiwi.util.common.Strings;
import com.github.czyzby.kiwi.util.gdx.collection.GdxMaps;
import com.github.czyzby.lml.parser.LmlParser;
import com.github.czyzby.lml.parser.impl.attribute.table.cell.AbstractCellLmlAttribute;
import com.github.czyzby.lml.parser.impl.tag.macro.AbstractConditionalLmlMacroTag;
import com.github.czyzby.lml.parser.impl.tag.macro.TableCellLmlMacroTag;
import com.github.czyzby.lml.parser.tag.LmlActorBuilder;
import com.github.czyzby.lml.parser.tag.LmlAttribute;
import com.github.czyzby.lml.parser.tag.LmlTag;
import com.github.czyzby.lml.parser.tag.LmlTagProvider;
import com.github.czyzby.lml.util.Lml;
/** Allows to create DTD schema files for LML templates.
*
* @author MJ */
public class Dtd {
protected static final String XML_ELEMENT_REGEX = "[\\w:.-]+";
private boolean displayLogs = true;
private boolean appendComments = true;
/** @param parser contains parsing data. Used to create mock-up actors. The skin MUST be fully loaded and contain
* all used actors' styles for the generator to work properly.
* @return DTD schema file containing all possible tags and their attributes. Any problems with the generation will
* be logged. This is a relatively heavy operation and should be done only during development.
* @see #getDtdSchema(LmlParser, Appendable) */
public static String getSchema(final LmlParser parser) {
final StringBuilder builder = new StringBuilder();
try {
new Dtd().getDtdSchema(parser, builder);
} catch (final IOException exception) {
throw new GdxRuntimeException("Unexpected: unable to append.", exception);
}
return builder.toString();
}
/** Saves DTD schema file containing all possible tags and their attributes. Any problems with the generation will
* be logged. This is a relatively heavy operation and should be done only during development.
*
* @param parser contains parsing data. Used to create mock-up actors. The skin MUST be fully loaded and contain all
* used actors' styles for the generator to work properly.
* @param appendable a reference to the file.
* @see #getDtdSchema(LmlParser, Appendable)
* @see #saveMinifiedSchema(LmlParser, Appendable) */
public static void saveSchema(final LmlParser parser, final Appendable appendable) {
try {
new Dtd().getDtdSchema(parser, appendable);
} catch (final IOException exception) {
throw new GdxRuntimeException("Unable to append to file.", exception);
}
}
/** Saves DTD schema file containing all possible tags and their attributes. Any problems with the generation will
* be logged. This is a relatively heavy operation and should be done only during development. Comments will not be
* appended, which will reduce the size of DTD file.
*
* @param parser contains parsing data. Used to create mock-up actors. The skin MUST be fully loaded and contain all
* used actors' styles for the generator to work properly.
* @param appendable a reference to the file.
* @see #getDtdSchema(LmlParser, Appendable)
* @see #saveSchema(LmlParser, Appendable) */
public static void saveMinifiedSchema(final LmlParser parser, final Appendable appendable) {
try {
new Dtd().setAppendComments(false).getDtdSchema(parser, appendable);
} catch (final IOException exception) {
throw new GdxRuntimeException("Unable to append to file.", exception);
}
}
/** @param displayLogs defaults to true. If set to false, parsing messages will not be shown in the console.
* @return this, for chaining. */
public Dtd setDisplayLogs(final boolean displayLogs) {
this.displayLogs = displayLogs;
return this;
}
/** @param appendComments defaults to true. If false, corresponding Java classes will not be added as comments to
* the DTD file.
* @return this, for chaining. */
public Dtd setAppendComments(final boolean appendComments) {
this.appendComments = appendComments;
return this;
}
/** @param message will be displayed in the console. */
protected void log(final String message) {
if (displayLogs) {
Gdx.app.log(Lml.LOGGER_TAG, message);
}
}
/** Creates DTD schema file containing all possible tags and their attributes. Any problems with the generation will
* be logged. This is a relatively heavy operation and should be done only during development.
*
* @param parser contains parsing data. Used to create mock-up actors. The skin MUST be fully loaded and contain all
* used actors' styles for the generator to work properly.
* @param builder values will be appended to this object.
* @throws IOException when unable to append. */
public void getDtdSchema(final LmlParser parser, final Appendable builder) throws IOException {
appendActorTags(builder, parser);
appendActorAttributes(parser, builder);
appendMacroTags(builder, parser);
appendMacroAttributes(parser, builder);
}
protected void appendDtdElement(final Appendable builder, final String comment, final String name)
throws IOException {
appendDtdElement(builder, comment, Strings.EMPTY_STRING, name);
}
protected void appendDtdElement(final Appendable builder, final String comment, final String prefix,
final String name) throws IOException {
appendDtdElement(builder, comment, prefix, name, "ANY");
}
protected void appendDtdElement(final Appendable builder, final String comment, final String prefix,
final String name, final String type) throws IOException {
if (!name.matches(XML_ELEMENT_REGEX)) {
log("Warning: '" + name + "' tag might contain invalid XML characters.");
}
if (appendComments) {
builder.append("<!-- ").append(comment).append(" -->\n");
}
builder.append("<!ELEMENT ").append(prefix).append(name).append(' ').append(type).append(">\n");
}
protected void appendDtdAttributes(final Appendable builder, final String tagName,
final ObjectMap<String, Object> attributes) throws IOException {
if (appendComments) {
for (final Entry<String, Object> attribute : attributes) {
if (!attribute.key.matches(XML_ELEMENT_REGEX)) {
log("Warning: '" + attribute + "' attribute might contain invalid XML characters.");
}
builder.append("<!-- ").append(attribute.value.getClass().getSimpleName()).append(" -->\n");
builder.append("<!ATTLIST ").append(tagName).append(' ').append(attribute.key)
.append(" CDATA #IMPLIED>\n");
}
return;
}
builder.append("<!ATTLIST ").append(tagName);
for (final Entry<String, Object> attribute : attributes) {
if (!attribute.key.matches(XML_ELEMENT_REGEX)) {
log("Warning: '" + attribute + "' attribute might contain invalid XML characters.");
}
builder.append("\n\t").append(attribute.key).append(" CDATA #IMPLIED");
}
builder.append(">\n");
}
protected void appendActorTags(final Appendable builder, final LmlParser parser) throws IOException {
if (appendComments) {
builder.append("<!-- Actor tags: -->\n");
}
final ObjectMap<String, LmlTagProvider> actorTags = parser.getSyntax().getTags();
for (final Entry<String, LmlTagProvider> actorTag : actorTags) {
appendDtdElement(builder, getTagClassName(actorTag.value), actorTag.key);
}
}
protected String getTagClassName(final LmlTagProvider provider) {
final String providerClass = provider.getClass().getSimpleName();
return providerClass.endsWith("Provider")
? providerClass.substring(0, providerClass.length() - "Provider".length()) : providerClass;
}
@SuppressWarnings("unchecked")
protected void appendActorAttributes(final LmlParser parser, final Appendable builder) throws IOException {
if (appendComments) {
builder.append("<!-- Actor tags' attributes: -->\n");
}
final ObjectMap<String, LmlTagProvider> actorTags = parser.getSyntax().getTags();
for (final Entry<String, LmlTagProvider> actorTag : actorTags) {
final ObjectMap<String, Object> attributes = GdxMaps.newObjectMap();
try {
final LmlTag tag = actorTag.value.create(parser, null, new StringBuilder(actorTag.key));
if (tag.getActor() == null) {
appendNonActorTagAttributes(tag, attributes, parser);
} else {
appendActorTagAttributes(tag, attributes, parser);
}
} catch (final Exception exception) {
Exceptions.ignore(exception);
log("Warning: unable to create an instance of actor mapped to '" + actorTag.key
+ "' tag name with provider: " + actorTag.value
+ ". Attributes list will not be complete. Is the provider properly implemented? Is a default style provided for the selected actor?");
attributes.putAll(
(ObjectMap<String, Object>) (Object) parser.getSyntax().getAttributesForActor(new Actor()));
attributes.putAll((ObjectMap<String, Object>) (Object) parser.getSyntax()
.getAttributesForBuilder(new LmlActorBuilder()));
}
appendDtdAttributes(builder, actorTag.key, attributes);
}
}
@SuppressWarnings("unchecked")
protected void appendNonActorTagAttributes(final LmlTag tag, final ObjectMap<String, Object> attributes,
final LmlParser parser) {
final Object managedObject = tag.getManagedObject();
if (managedObject != null) {
attributes.putAll(
(ObjectMap<String, Object>) (Object) parser.getSyntax().getAttributesForActor(managedObject));
}
}
@SuppressWarnings("unchecked")
protected void appendActorTagAttributes(final LmlTag tag, final ObjectMap<String, Object> attributes,
final LmlParser parser) {
LmlActorBuilder actorBuilder;
final boolean usesAbstractBase = tag instanceof AbstractActorLmlTag;
if (usesAbstractBase) {
actorBuilder = ((AbstractActorLmlTag) tag).getNewInstanceOfBuilder();
} else {
actorBuilder = new LmlActorBuilder();
}
// Appending attributes of component actors:
if (!Lml.DISABLE_COMPONENT_ACTORS_ATTRIBUTE_PARSING && usesAbstractBase
&& ((AbstractActorLmlTag) tag).hasComponentActors()) {
for (final Actor component : ((AbstractActorLmlTag) tag).getComponentActors(tag.getActor())) {
attributes.putAll(
(ObjectMap<String, Object>) (Object) parser.getSyntax().getAttributesForActor(component));
}
}
// Appending managed objects attributes:
if (tag.getManagedObject() != tag.getActor()) {
appendNonActorTagAttributes(tag, attributes, parser);
}
// Appending building attributes:
attributes
.putAll((ObjectMap<String, Object>) (Object) parser.getSyntax().getAttributesForBuilder(actorBuilder));
// Appending regular attributes:
attributes
.putAll((ObjectMap<String, Object>) (Object) parser.getSyntax().getAttributesForActor(tag.getActor()));
}
protected void appendMacroTags(final Appendable builder, final LmlParser parser) throws IOException {
if (appendComments) {
builder.append("<!-- Macro tags: -->\n");
}
final String macroMarker = String.valueOf(parser.getSyntax().getMacroMarker());
if (!macroMarker.matches(XML_ELEMENT_REGEX)) {
log("Error: current macro marker (" + macroMarker
+ ") is an invalid XML character. Override getMacroMarker in your current LmlSyntax implementation and provide a correct character to create valid DTD file.");
}
final ObjectMap<String, LmlTagProvider> macroTags = parser.getSyntax().getMacroTags();
for (final Entry<String, LmlTagProvider> macroTag : macroTags) {
appendDtdElement(builder, getTagClassName(macroTag.value), macroMarker, macroTag.key);
// If the tag is conditional, it should provide an extra name:else tag:
try {
final LmlTag tag = macroTag.value.create(parser, null, new StringBuilder(macroTag.key));
if (tag instanceof AbstractConditionalLmlMacroTag) {
appendDtdElement(builder, "'Else' helper tag of: " + macroTag.key, macroMarker,
macroTag.key + AbstractConditionalLmlMacroTag.ELSE_SUFFIX, "EMPTY");
}
} catch (final Exception expected) {
// Tag might need a parent or additional attributes and cannot be checked. It's OK.
Exceptions.ignore(expected);
log("Unable to create a macro tag instance using: " + macroTag.value.getClass().getSimpleName());
}
}
}
protected void appendMacroAttributes(final LmlParser parser, final Appendable builder) throws IOException {
if (appendComments) {
builder.append("<!-- Expected macro tags' attributes: -->\n");
}
final String macroMarker = String.valueOf(parser.getSyntax().getMacroMarker());
final ObjectMap<String, LmlTagProvider> macroTags = parser.getSyntax().getMacroTags();
for (final Entry<String, LmlTagProvider> macroTag : macroTags) {
try {
final LmlTag tag = macroTag.value.create(parser, null, new StringBuilder(macroTag.key));
if (tag instanceof TableCellLmlMacroTag) {
// Special case: listing all cell attributes:
appendTableDefaultsMacro(parser, builder, macroMarker, macroTag, tag);
} else if (tag instanceof AbstractMacroLmlTag) {
final String[] attributeNames = ((AbstractMacroLmlTag) tag).getExpectedAttributes();
if (attributeNames == null || attributeNames.length == 0) {
continue;
}
final ObjectMap<String, Object> attributes = GdxMaps.newObjectMap();
for (final String attributeName : attributeNames) {
attributes.put(attributeName, tag);
}
appendDtdAttributes(builder, macroMarker + macroTag.key, attributes);
}
} catch (final Exception expected) {
// Tag might need a parent or additional attributes and cannot be checked. It's OK.
Exceptions.ignore(expected);
}
}
}
private void appendTableDefaultsMacro(final LmlParser parser, final Appendable builder, final String macroMarker,
final Entry<String, LmlTagProvider> macroTag, final LmlTag tag) throws IOException {
final Actor mockUp = new Actor();
final ObjectMap<String, Object> attributes = GdxMaps.newObjectMap();
for (final Entry<String, LmlAttribute<?>> attribute : parser.getSyntax().getAttributesForActor(mockUp)) {
if (attribute.value instanceof AbstractCellLmlAttribute) {
attributes.put(attribute.key, attribute.value);
}
}
final String[] attributeNames = ((AbstractMacroLmlTag) tag).getExpectedAttributes();
if (attributeNames != null && attributeNames.length > 0) {
for (final String attribute : attributeNames) {
attributes.put(attribute, tag);
}
}
appendDtdAttributes(builder, macroMarker + macroTag.key, attributes);
}
}
| |
package io.bleepr.floor.bleepriofloormanagement.activity;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import net.danlew.android.joda.JodaTimeAndroid;
import java.util.ArrayList;
import java.util.List;
import io.bleepr.floor.bleepriofloormanagement.R;
import io.bleepr.floor.bleepriofloormanagement.service.BleeprBackendQueryService;
import static android.Manifest.permission.READ_CONTACTS;
/**
* A login screen that offers login via email/password.
*/
public class LoginActivity extends AppCompatActivity implements LoaderCallbacks<Cursor> {
/**
* Id to identity READ_CONTACTS permission request.
*/
private static final int REQUEST_READ_CONTACTS = 0;
/**
* A dummy authentication store containing known user names and passwords.
* TODO: remove after connecting to a real authentication system.
*/
private static final String[] DUMMY_CREDENTIALS = new String[]{
"foo@example.com:hello", "bar@example.com:world",
"book@peden.pizza:ketchup"
};
/**
* Keep track of the login task to ensure we can cancel it if requested.
*/
private UserLoginTask mAuthTask = null;
// UI references.
private AutoCompleteTextView mEmailView;
private EditText mPasswordView;
private View mProgressView;
private View mLoginFormView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
JodaTimeAndroid.init(this);
setContentView(R.layout.activity_login);
// Set up the login form.
mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
populateAutoComplete();
mPasswordView = (EditText) findViewById(R.id.password);
mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
if (id == R.id.login || id == EditorInfo.IME_NULL) {
attemptLogin();
return true;
}
return false;
}
});
Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
mEmailSignInButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
attemptLogin();
}
});
mLoginFormView = findViewById(R.id.login_form);
mProgressView = findViewById(R.id.login_progress);
}
private void populateAutoComplete() {
if (!mayRequestContacts()) {
return;
}
getLoaderManager().initLoader(0, null, this);
}
private boolean mayRequestContacts() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return true;
}
if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
return true;
}
if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
Snackbar.make(mEmailView, R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE)
.setAction(android.R.string.ok, new View.OnClickListener() {
@Override
@TargetApi(Build.VERSION_CODES.M)
public void onClick(View v) {
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
}
});
} else {
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
}
return false;
}
/**
* Callback received when a permissions request has been completed.
*/
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
if (requestCode == REQUEST_READ_CONTACTS) {
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
populateAutoComplete();
}
}
}
/**
* Attempts to sign in or register the account specified by the login form.
* If there are form errors (invalid email, missing fields, etc.), the
* errors are presented and no actual login attempt is made.
*/
private void attemptLogin() {
if (mAuthTask != null) {
return;
}
// Reset errors.
mEmailView.setError(null);
mPasswordView.setError(null);
// Store values at the time of the login attempt.
String email = mEmailView.getText().toString();
String password = mPasswordView.getText().toString();
boolean cancel = false;
View focusView = null;
// Check for a valid password, if the user entered one.
if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
mPasswordView.setError(getString(R.string.error_invalid_password));
focusView = mPasswordView;
cancel = true;
}
// Check for a valid email address.
if (TextUtils.isEmpty(email)) {
mEmailView.setError(getString(R.string.error_field_required));
focusView = mEmailView;
cancel = true;
} else if (!isEmailValid(email)) {
mEmailView.setError(getString(R.string.error_invalid_email));
focusView = mEmailView;
cancel = true;
}
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
} else {
// Show a progress spinner, and kick off a background task to
// perform the user login attempt.
showProgress(true);
mAuthTask = new UserLoginTask(this, email, password);
mAuthTask.execute((Void) null);
}
}
private boolean isEmailValid(String email) {
//TODO: Replace this with your own logic
return email.contains("@");
}
private boolean isPasswordValid(String password) {
//TODO: Replace this with your own logic
return password.length() > 4;
}
/**
* Shows the progress UI and hides the login form.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private void showProgress(final boolean show) {
// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
// for very easy animations. If available, use these APIs to fade-in
// the progress spinner.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
mLoginFormView.animate().setDuration(shortAnimTime).alpha(
show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
});
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mProgressView.animate().setDuration(shortAnimTime).alpha(
show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
}
});
} else {
// The ViewPropertyAnimator APIs are not available, so simply show
// and hide the relevant UI components.
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
@Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
return new CursorLoader(this,
// Retrieve data rows for the device user's 'profile' contact.
Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI,
ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION,
// Select only email addresses.
ContactsContract.Contacts.Data.MIMETYPE +
" = ?", new String[]{ContactsContract.CommonDataKinds.Email
.CONTENT_ITEM_TYPE},
// Show primary email addresses first. Note that there won't be
// a primary email address if the user hasn't specified one.
ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
}
@Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
List<String> emails = new ArrayList<>();
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
emails.add(cursor.getString(ProfileQuery.ADDRESS));
cursor.moveToNext();
}
addEmailsToAutoComplete(emails);
}
@Override
public void onLoaderReset(Loader<Cursor> cursorLoader) {
}
private interface ProfileQuery {
String[] PROJECTION = {
ContactsContract.CommonDataKinds.Email.ADDRESS,
ContactsContract.CommonDataKinds.Email.IS_PRIMARY,
};
int ADDRESS = 0;
int IS_PRIMARY = 1;
}
private void addEmailsToAutoComplete(List<String> emailAddressCollection) {
//Create adapter to tell the AutoCompleteTextView what to show in its dropdown list.
ArrayAdapter<String> adapter =
new ArrayAdapter<>(LoginActivity.this,
android.R.layout.simple_dropdown_item_1line, emailAddressCollection);
mEmailView.setAdapter(adapter);
}
/**
* Represents an asynchronous login/registration task used to authenticate
* the user.
*/
public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
private final String mEmail;
private final String mPassword;
private Activity mActivity;
UserLoginTask(Activity activity, String email, String password) {
mActivity = activity;
mEmail = email;
mPassword = password;
}
@Override
protected Boolean doInBackground(Void... params) {
// TODO: attempt authentication against a network service.
try {
// Simulate network access.
Thread.sleep(2000);
} catch (InterruptedException e) {
return false;
}
for (String credential : DUMMY_CREDENTIALS) {
String[] pieces = credential.split(":");
if (pieces[0].equals(mEmail)) {
// Account exists, return true if the password matches.
return pieces[1].equals(mPassword);
}
}
// TODO: register the new account here.
return true;
}
@Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
showProgress(false);
if (success) {
BleeprBackendQueryService.startRefresh(getApplicationContext(), null);
mActivity.startActivity(new Intent(mActivity, PostLoginMenuActivity.class));
} else {
mPasswordView.setError(getString(R.string.error_incorrect_password));
mPasswordView.requestFocus();
}
}
@Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}
}
| |
/**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 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.opensource.org/licenses/ECL-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
package org.sakaiproject.tool.assessment.ui.bean.author;
import java.io.Serializable;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.faces.model.SelectItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sakaiproject.component.cover.ServerConfigurationService;
import org.sakaiproject.tool.assessment.data.ifc.assessment.AssessmentIfc;
import org.sakaiproject.tool.assessment.data.ifc.assessment.SectionDataIfc;
import org.sakaiproject.tool.assessment.data.ifc.shared.TypeIfc;
import org.sakaiproject.tool.assessment.facade.AssessmentFacade;
import org.sakaiproject.tool.assessment.facade.PublishedAssessmentFacade;
import org.sakaiproject.tool.assessment.facade.PublishedSectionFacade;
import org.sakaiproject.tool.assessment.services.assessment.AssessmentService;
import org.sakaiproject.tool.assessment.services.assessment.PublishedAssessmentService;
import org.sakaiproject.tool.assessment.services.shared.TypeService;
import org.sakaiproject.tool.assessment.ui.bean.delivery.ItemContentsBean;
import org.sakaiproject.tool.assessment.ui.bean.delivery.SectionContentsBean;
import org.sakaiproject.tool.assessment.ui.listener.util.ContextUtil;
/**
* @author rshastri
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*
* Used to be org.navigoproject.ui.web.asi.author.assessment.AssessmentActionForm.java
*/
public class AssessmentBean implements Serializable {
private static Logger log = LoggerFactory.getLogger(AssessmentBean.class);
/** Use serialVersionUID for interoperability. */
private final static long serialVersionUID = -630950053380808339L;
private AssessmentIfc assessment;
private String assessmentId;
private String title;
// ArrayList of SectionContentsBean
private List<SectionContentsBean> sections = new ArrayList<SectionContentsBean>(); // this contains list of SectionFacde
private ArrayList<SelectItem> sectionList = new ArrayList<SelectItem>(); // this contains list of javax.faces.model.SelectItem
private ArrayList otherSectionList = new ArrayList(); // contains SectionItem of section except the current section
private ArrayList partNumbers = new ArrayList();
private int questionSize=0;
private double totalScore=0;
private String newQuestionTypeId;
private String firstSectionId;
private boolean hasRandomDrawPart;
private boolean showPrintLink;
private boolean hasGradingData = false;
private boolean hasSubmission = false;
private Boolean showPrintAssessment = null;
/*
* Creates a new AssessmentBean object.
*/
public AssessmentBean() {
}
public AssessmentIfc getAssessment() {
return assessment;
}
public void setAssessment(AssessmentIfc assessment) {
try {
this.assessment = assessment;
if (assessment instanceof AssessmentFacade) {
this.assessmentId = assessment.getAssessmentId().toString();
}
else if (assessment instanceof PublishedAssessmentFacade) {
this.assessmentId = ((PublishedAssessmentFacade) assessment).getPublishedAssessmentId().toString();
}
this.title = assessment.getTitle();
// work out the question side & total point
this.sections = new ArrayList<SectionContentsBean>();
List<? extends SectionDataIfc> sectionArray = assessment.getSectionArraySorted();
for (int i=0; i<sectionArray.size(); i++){
SectionDataIfc section = sectionArray.get(i);
SectionContentsBean sectionBean = new SectionContentsBean(section);
this.sections.add(sectionBean);
}
setPartNumbers();
setQuestionSizeAndTotalScore();
setSectionList(sectionArray);
}
catch (Exception ex) {
ex.printStackTrace();
}
}
// properties from Assessment
public String getAssessmentId() {
return this.assessmentId;
}
public void setAssessmentId(String assessmentId) {
this.assessmentId = assessmentId;
}
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
public List<SectionContentsBean> getSections() {
return sections;
}
public void setSections(ArrayList sections) {
this.sections = sections;
}
public ArrayList getPartNumbers() {
return partNumbers;
}
public void setPartNumbers() {
this.partNumbers = new ArrayList();
for (int i=1; i<=this.sections.size(); i++){
this.partNumbers.add(new SelectItem(i+""));
}
}
public int getQuestionSize() {
return this.questionSize;
}
public void setQuestionSizeAndTotalScore() {
this.questionSize = 0;
this.totalScore = 0;
int randomPartCount = 0;
AuthorBean author = (AuthorBean) ContextUtil.lookupBean("author");
for(int i=0;i<this.sections.size();i++){
SectionContentsBean sectionBean = (SectionContentsBean) sections.get(i);
ArrayList items = sectionBean.getItemContents();
int itemsInThisSection =0;
if (sectionBean.getSectionAuthorType().equals(SectionDataIfc.RANDOM_DRAW_FROM_QUESTIONPOOL)) {
// for random draw parts, add
randomPartCount++ ;
itemsInThisSection = sectionBean.getNumberToBeDrawn().intValue();
}
else {
itemsInThisSection = items.size();
}
this.questionSize += itemsInThisSection;
for (int j=0; j<itemsInThisSection; j++){
ItemContentsBean item = (ItemContentsBean)items.get(j);
if (item.getItemData().getScore()!=null){
this.totalScore += item.getItemData().getScore().doubleValue();
}
}
}
if (randomPartCount >0) {
setHasRandomDrawPart(true);
}
else {
setHasRandomDrawPart(false);
}
}
public int updateRandomPoolQuestions(String sectionId){
for(int i=0;i<this.sections.size();i++){
SectionContentsBean sectionBean = (SectionContentsBean) sections.get(i);
if(sectionBean.getSectionId().equals(sectionId)){
AssessmentService assessmentService = new AssessmentService();
int success = assessmentService.updateRandomPoolQuestions(assessmentService.getSection(sectionId));
if(success == AssessmentService.UPDATE_SUCCESS){
//need to update section since it has changed
sections.set(i, new SectionContentsBean(assessmentService.getSection(sectionBean.getSectionId())));
}else{
return success;
}
}
}
return AssessmentService.UPDATE_SUCCESS;
}
public double getTotalScore() {
return this.totalScore;
}
public void setTotalScore(double totalScore) {
this.totalScore = totalScore;
}
public String getNewQuestionTypeId() {
return this.newQuestionTypeId;
}
public void setNewQuestionTypeId(String newQuestionTypeId) {
this.newQuestionTypeId = newQuestionTypeId;
}
public SelectItem[] getItemTypes(){
// return list of TypeD
TypeService service = new TypeService();
List list = service.getFacadeItemTypes();
SelectItem[] itemTypes = new SelectItem[list.size()];
for (int i=0; i<list.size();i++){
TypeIfc t = (TypeIfc) list.get(i);
itemTypes[i] = new SelectItem(
t.getTypeId().toString(), t.getKeyword());
}
return itemTypes;
}
/**
* This set a list of SelectItem (sectionId, title) for selection box
* @param list
*/
public void setSectionList(List<? extends SectionDataIfc> list){
//this.assessmentTemplateIter = new AssessmentTemplateIteratorFacade(list);
this.sectionList = new ArrayList<SelectItem>();
try{
for (int i=0; i<list.size();i++){
SectionDataIfc f = list.get(i);
// sorry, cannot do f.getAssessmentTemplateId() 'cos such call requires
// "data" which we do not have in this case. The template list parsed
// to this method contains merely assesmentBaseId (in this case is the templateId)
// & title (see constructor AssessmentTemplateFacade(id, title))
this.sectionList.add(new SelectItem(
f.getSectionId().toString(), f.getTitle()));
if (i==0){
this.firstSectionId = f.getSectionId().toString();
}
}
}
catch(Exception e){
log.warn(e.getMessage());
}
}
public ArrayList<SelectItem> getSectionList(){
return sectionList;
}
public String getFirstSectionId()
{
return firstSectionId;
}
/**
* @param string the title
*/
public void setFirstSectionId(String firstSectionId)
{
this.firstSectionId = firstSectionId;
}
public ArrayList getOtherSectionList(){
return otherSectionList;
}
public void setOtherSectionList(ArrayList list){
this.otherSectionList = list; // list contains javax.faces.model.SelectItem
}
public boolean getHasRandomDrawPart() {
return this.hasRandomDrawPart;
}
public void setHasRandomDrawPart(boolean param) {
this.hasRandomDrawPart= param;
}
public boolean getShowPrintLink() {
return this.showPrintLink;
}
public void setShowPrintLink(boolean showPrintLink) {
this.showPrintLink= showPrintLink;
}
public boolean getHasGradingData() {
return this.hasGradingData;
}
public void setHasGradingData(boolean hasGradingData) {
this.hasGradingData = hasGradingData;
}
public boolean getHasSubmission() {
return this.hasSubmission;
}
public void setHasSubmission(boolean hasSubmission) {
this.hasSubmission = hasSubmission;
}
public boolean getShowPrintAssessment() {
//Should this override the setter?
if (showPrintAssessment == null) {
String printAssessment = ServerConfigurationService.getString("samigo.printAssessment", "true");
return Boolean.parseBoolean(printAssessment);
}
return showPrintAssessment;
}
public void setShowPrintAssessment(Boolean showPrintAssessment) {
this.showPrintAssessment= showPrintAssessment;
}
public boolean getExportable2MarkupText() {
AssessmentService assessmentService = new AssessmentService();
boolean result = false;
if (assessmentId != null) {
AssessmentFacade assessment = assessmentService.getAssessment(assessmentId);
result = assessmentService.isExportable(assessment);
}
return result;
}
}
| |
/*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 2002-2010 Oracle. All rights reserved.
*
* $Id: ClosedDbEviction.java,v 1.7 2010/01/04 15:51:12 cwl Exp $
*/
import java.io.File;
import java.util.Random;
import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseConfig;
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentConfig;
import com.sleepycat.je.EnvironmentStats;
import com.sleepycat.je.LockMode;
import com.sleepycat.je.OperationStatus;
import com.sleepycat.je.StatsConfig;
/**
* Applications with a large number of databases, randomly open and close
* databases at any time when needed. The mapping tree nodes (roots) in closed
* databases won't be evicted from cache immediately. As the applications run
* over time, this could cause a lot of waste in cache or even bad performance
* and OutOfMemoryError if cache overflows.
*
* We want to simulate such a scenario to test the efficiency of eviction of
* closed databases for SR 13415, to make sure that the eviction would not
* cause corruption or concurrency bugs:
* + Ensure that concurrency bugs don't occur when multiple threads are trying
* to close, evict and open a single database.
* + Another potential problem is that the database doesn't open correctly
* after being closed and evicted;
* + Cache budgeting is not done correctly during eviction or re-loading of
* the database after eviction.
*
*/
public class ClosedDbEviction {
private static int nDataAccessDbs = 1;
private static int nRegularDbs = 100000;
private static int nDbRecords = 100;
private static int nInitThreads = 8;
private static int nContentionThreads = 4;
private static int nDbsPerSet = 5;
private static int nKeepOpenedDbs = 100;
private static int nOps[] = new int[nContentionThreads];
private static long nTxnPerRecovery = 1000000l;
private static long nTotalTxns = 100000000l;
private static boolean verbose = false;
private static boolean init = false;
private static boolean contention = false;
private static boolean evict = false;
private static boolean recovery = false;
private static boolean runDataAccessThread = true;
private static String homeDir = "./tmp";
private static Environment env = null;
private static Database dataAccessDb = null;
private static Database metadataDb = null;
private static Database[] openDbList = new Database[nKeepOpenedDbs];
private static Random random = new Random();
private static Runtime rt = Runtime.getRuntime();
public static void main(String[] args) {
try {
ClosedDbEviction eviction = new ClosedDbEviction();
eviction.start(args);
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
/* Output command-line input arguments to log. */
private void printArgs(String[] args) {
System.out.print("\nCommand line arguments:");
for (String arg : args) {
System.out.print(' ');
System.out.print(arg);
}
System.out.println();
}
void start(String[] args) {
try {
if (args.length == 0) {
throw new IllegalArgumentException();
}
/* Parse command-line input arguments. */
for (int i = 0; i < args.length; i++) {
String arg = args[i];
String arg2 = (i < args.length - 1) ? args[i + 1] : null;
if (arg.equals("-v")) {
verbose = true;
} else if (arg.equals("-h")) {
if (arg2 == null) {
throw new IllegalArgumentException(arg);
}
homeDir = args[++i];
} else if (arg.equals("-init")) {
if (arg2 == null) {
throw new IllegalArgumentException(arg);
}
try {
nRegularDbs = Integer.parseInt(args[++i]);
} catch (NumberFormatException e) {
throw new IllegalArgumentException(arg2);
}
init = true;
} else if (arg.equals("-contention")) {
if (arg2 == null) {
throw new IllegalArgumentException(arg);
}
try {
nTotalTxns = Long.parseLong(args[++i]);
} catch (NumberFormatException e) {
throw new IllegalArgumentException(arg2);
}
contention = true;
} else if (arg.equals("-evict")) {
if (arg2 == null) {
throw new IllegalArgumentException(arg);
}
try {
nTotalTxns = Long.parseLong(args[++i]);
} catch (NumberFormatException e) {
throw new IllegalArgumentException(arg2);
}
evict = true;
} else if (arg.equals("-recovery")) {
if (arg2 == null) {
throw new IllegalArgumentException(arg);
}
try {
nTxnPerRecovery = Long.parseLong(args[++i]);
} catch (NumberFormatException e) {
throw new IllegalArgumentException(arg2);
}
recovery = true;
} else {
throw new IllegalArgumentException(arg);
}
}
/* Correctness self-check: nTotalTxns >= nTxnPerRecovery. */
if (nTotalTxns < nTxnPerRecovery) {
System.err.println
("ERROR: <nTotalTxns> argument should be larger than " +
nTxnPerRecovery + "!");
System.exit(1);
}
printArgs(args);
} catch (IllegalArgumentException e) {
System.out.println
("Usage: ClosedDbEviction [-v] -h <envHome> -init <nDbs>\n" +
"Usage: ClosedDbEviction [-v] -h <envHome> " +
"[-contention <nTotalTxns> | -evict <nTotalTxns>] " +
"[-recovery <nTxnsPerRecovery>]");
e.printStackTrace();
System.exit(1);
}
try {
if (init) {
doInit();
} else if (contention) {
doContention();
} else if (evict) {
doEvict();
} else {
System.err.println("No such argument.");
System.exit(1);
}
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
/**
* Initialize nRegularDBs, one dataAccessDb and one metadataDB.
*/
private void doInit() {
class InitThread extends Thread {
public int id;
private Environment env = null;
private Database db = null;
/**
* Constructor used for initializing databases.
*/
InitThread(int id, Environment env) {
this.id = id;
this.env = env;
}
public void run() {
try {
DatabaseConfig dbConfig = new DatabaseConfig();
dbConfig.setAllowCreate(true);
DatabaseEntry key = new DatabaseEntry();
DatabaseEntry data = new DatabaseEntry();
for (int i = 0;
i <= ((nRegularDbs + nDataAccessDbs) / nInitThreads);
i++) {
int dbId = id + (i * nInitThreads);
int totalRecords = nDbRecords;
boolean isDataAccessDb = false;
String dbName = "db" + dbId;
if (dbId <= (nRegularDbs / 10)) {
dbConfig.setDeferredWrite(true);
} else if (dbId >= nRegularDbs) {
if (dbId < (nRegularDbs + nDataAccessDbs)) {
isDataAccessDb = true;
dbName = "dataAccessDb";
totalRecords = 10 * nDbRecords;
} else {
break;
}
}
/* Open the database. */
db = env.openDatabase(null, dbName, dbConfig);
/* Insert totalRecords into database. */
for (int j = 0; j < totalRecords; j++) {
key.setData(Integer.toString(j).getBytes("UTF-8"));
makeData(data, j, isDataAccessDb);
OperationStatus status = db.put(null, key, data);
if (status != OperationStatus.SUCCESS) {
System.err.println
("ERROR: failed to insert the #" + j +
" key/data pair into " +
db.getDatabaseName());
System.exit(1);
}
}
db.close();
}
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
/**
* Generate the data. nDataAccessDbs should have a bigger size of
* data entry; regularDbs only make data entry equal to
* (index + "th-dataEntry").
*/
private void makeData(DatabaseEntry data,
int index,
boolean isDataAccessDb) throws Exception {
assert (data != null) : "makeData: Null data pointer";
if (isDataAccessDb) {
byte[] bytes = new byte[1024];
for (int i = 0; i < bytes.length; i++) {
bytes[i] = (byte) i;
}
data.setData(bytes);
} else {
data.setData((Integer.toString(index) + "th-dataEntry").
getBytes("UTF-8"));
}
}
}
/*
* Initialize "nRegularDbs" regular Dbs, one dataAccessDb and one
* metaDataDb according to these rules:
* - The "nRegularDBs" databases, with the dbIds range from
* 0 to (nRegularDBs - 1). Each of them would have "nDbRecords".
* - 10% of all "nRegularDBs" are deferredWrite databases.
* - 90% of all "nRegularDBs" are regular databases.
* - The dataAccessDb has "10 * nDbRecords" key/data pairs.
* - The metaDataDb is to save "nRegularDbs" info for contention test.
*/
try {
openEnv(128 * 1024 * 1024);
saveMetadata();
InitThread[] threads = new InitThread[nInitThreads];
long startTime = System.currentTimeMillis();
for (int i = 0; i < threads.length; i++) {
InitThread t = new InitThread(i, env);
t.start();
threads[i] = t;
}
for (int i = 0; i < threads.length; i++) {
threads[i].join();
}
long endTime = System.currentTimeMillis();
if (verbose) {
float elapsedSeconds = (endTime - startTime) / 1000f;
float throughput = (nRegularDbs * nDbRecords) / elapsedSeconds;
System.out.println
("\nInitialization Statistics Report" +
"\n Run starts at: " + (new java.util.Date(startTime)) +
", finishes at: " + (new java.util.Date(endTime)) +
"\n Initialized " + nRegularDbs + " databases, " +
"each contains " + nDbRecords + " records." +
"\n Elapsed seconds: " + elapsedSeconds +
", throughput: " + throughput + " ops/sec.");
}
closeEnv();
} catch (DatabaseException de) {
de.printStackTrace();
System.exit(1);
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
/**
* Simulate some contentions to make sure that the eviction would not
* cause corruption or concurrency bugs.
*/
private void doContention() {
class ContentionThread extends Thread {
public int id;
private float dataCheckPossibility = .01f;
private long txns;
private boolean done = false;
private Database currentDb = null;
private Database lastOpenedDb = null;
/**
* Constructor used for initializing databases.
*/
ContentionThread(int id, long txns) {
this.id = id;
this.txns = txns;
}
public void run() {
try {
/* Start dataAccessThread here. */
startDataAccessor();
/*
* All contention threads try to open "nDbsPerSet" DBs
* from the same set concurrently.
*/
while (!done) {
int dbId = random.nextInt(nDbsPerSet);
currentDb = env.openDatabase(null, "db" + dbId, null);
if (lastOpenedDb != null) {
lastOpenedDb.close();
}
lastOpenedDb = currentDb;
if (random.nextFloat() <= dataCheckPossibility) {
verifyData();
}
nOps[id]++;
if (nOps[id] > txns) {
if (lastOpenedDb != null) {
lastOpenedDb.close();
}
done = true;
}
}
/* Stop dataAccessThread here. */
stopDataAccessor();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
private void startDataAccessor() {
runDataAccessThread = true;
}
private void stopDataAccessor() {
runDataAccessThread = false;
}
/**
* Do the corruption check: just check that the data
* that is present looks correct.
*/
private void verifyData() throws Exception {
long dbCount = currentDb.count();
if (dbCount != nDbRecords) {
System.err.println
("WARNING: total records in " +
currentDb.getDatabaseName() + ": " + dbCount +
" doesn't meet the expected value: " + nDbRecords);
System.exit(1);
} else {
DatabaseEntry key = new DatabaseEntry();
DatabaseEntry data = new DatabaseEntry();
for (int i = 0; i < nDbRecords; i++) {
key.setData(Integer.toString(i).getBytes("UTF-8"));
OperationStatus status =
currentDb.get(null, key, data, LockMode.DEFAULT);
if (status != OperationStatus.SUCCESS) {
System.err.println
("ERROR: failed to retrieve the #" +
i + " key/data pair from " +
currentDb.getDatabaseName());
System.exit(1);
} else if (!(new String(data.getData(), "UTF-8")).
equals((Integer.toString(i) +
"th-dataEntry"))) {
System.err.println
("ERROR: current key/data pair: " + i +
"/" + (new String(data.getData(), "UTF-8")) +
" doesn't match the expected: " +
i + "/" + i +"th-dataEntry in " +
currentDb.getDatabaseName());
System.exit(1);
}
}
}
}
}
class DataAccessThread extends Thread {
public void run() {
try {
while (runDataAccessThread) {
/* Access records to fill up cache. */
DatabaseEntry key = new DatabaseEntry();
key.setData(Integer.
toString(random.nextInt(10 * nDbRecords)).
getBytes("UTF-8"));
DatabaseEntry data = new DatabaseEntry();
OperationStatus status =
dataAccessDb.get(null, key, data,
LockMode.DEFAULT);
if (status != OperationStatus.SUCCESS) {
System.err.println
("ERROR: failed to retrieve the #" +
new String(key.getData(), "UTF-8") +
" key/data pair from dataAccessDb.");
System.exit(1);
}
}
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
/*
* Simulate some contentions according to following rules:
* - Several threads try to open/close a set of databases repeatedly.
* - The other thread will continually access records from dataAccessDb
* to fill up cache.
*/
try {
long startTime = System.currentTimeMillis();
long txns = nTotalTxns;
if (recovery) {
txns = nTxnPerRecovery;
}
for (int loop = 0; loop < nTotalTxns / txns; loop++) {
/* Clear nOps[] before each run starts. */
for (int i = 0; i < nContentionThreads; i++) {
nOps[i] = 0;
}
openEnv(1024 * 1024);
readMetadata();
DataAccessThread dat = new DataAccessThread();
ContentionThread[] threads =
new ContentionThread[nContentionThreads];
for (int i = 0; i < threads.length; i++) {
ContentionThread t =
new ContentionThread(i, txns);
t.start();
threads[i] = t;
}
dat.start();
for (int i = 0; i < threads.length; i++) {
threads[i].join();
}
dat.join();
if (!checkStats(txns)) {
System.err.println
("doContention: stats check failed.");
System.exit(1);
}
closeEnv();
}
long endTime = System.currentTimeMillis();
float elapsedSecs = (endTime - startTime) / 1000f;
float throughput = nTotalTxns / elapsedSecs;
if (verbose) {
System.out.println
("\nContention Test Statistics Report" +
"\n Starts at: " + (new java.util.Date(startTime)) +
", Finishes at: " + (new java.util.Date(endTime)) +
"\n Total operations: " + nTotalTxns +
", Elapsed seconds: " + elapsedSecs +
", Throughput: " + throughput + " ops/sec.");
}
} catch (DatabaseException de) {
de.printStackTrace();
System.exit(1);
} catch (Throwable e) {
e.printStackTrace();
System.exit(1);
}
}
private void doEvict() {
final int offset = random.nextInt(nRegularDbs - nKeepOpenedDbs);
class EvictThread extends Thread {
public int id;
private float dataAccessPossibility = .01f;
private long txns = 0;
private Database currentDb = null;
private Database lastOpenedDb = null;
/**
* Constructor.
*/
public EvictThread(int id, long txns) {
this.id = id;
this.txns = txns;
}
public void run() {
try {
int dbId;
boolean done = false;
while (!done) {
dbId = random.nextInt(nRegularDbs);
if ((0 <= (dbId - offset)) &&
((dbId - offset) < nKeepOpenedDbs)) {
/*
* Randomly select nKeepOpenedDbs databases opened
* in a time. The dbId ranges from <offset> to
* <offset + nKeepOpenedDbs - 1>.
*/
if (openDbList[dbId - offset] == null) {
openDbList[dbId - offset] =
env.openDatabase(null, "db" + dbId, null);
}
} else {
/* Each thread select randomly from all DBs. */
currentDb =
env.openDatabase(null, "db" + dbId, null);
if (random.nextFloat() < dataAccessPossibility) {
DatabaseEntry key = new DatabaseEntry();
DatabaseEntry data = new DatabaseEntry();
key.setData(Integer.toString
(random.nextInt(nDbRecords)).
getBytes("UTF-8"));
currentDb.get(null, key, data,
LockMode.DEFAULT);
}
if (lastOpenedDb != null) {
lastOpenedDb.close();
}
lastOpenedDb = currentDb;
}
nOps[id]++;
if (nOps[id] > txns) {
if (lastOpenedDb != null) {
lastOpenedDb.close();
}
/* Close nKeepOpenedDbs before exit. */
for (int i = 0; i < nKeepOpenedDbs; i++) {
currentDb = openDbList[i];
if (currentDb != null) {
currentDb.close();
openDbList[i] = null;
}
}
done = true;
}
}
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
/*
* Simulate some contentions according to following rules:
* - Several threads try to open/close a set of databases repeatedly.
* - The other thread will continually access records from dataAccessDb
* to fill up cache.
*/
try {
long startTime = System.currentTimeMillis();
long txns = nTotalTxns;
if (recovery) {
txns = nTxnPerRecovery;
}
for (int loop = 0; loop < nTotalTxns / txns; loop++) {
/* Clear nOps[] before each run starts. */
for (int i = 0; i < nContentionThreads; i++) {
nOps[i] = 0;
}
openEnv(512 * 1024);
readMetadata();
EvictThread[] threads = new EvictThread[nContentionThreads];
for (int i = 0; i < threads.length; i++) {
EvictThread t = new EvictThread(i, txns);
t.start();
threads[i] = t;
}
for (int i = 0; i < threads.length; i++) {
threads[i].join();
}
if (!checkStats(txns)) {
System.err.println("doEvict: stats check failed.");
System.exit(1);
}
closeEnv();
}
long endTime = System.currentTimeMillis();
if (verbose) {
float elapsedSeconds = (endTime - startTime) / 1000f;
float throughput = nTotalTxns / elapsedSeconds;
System.out.println
("\nEviction Test Statistics Report" +
"\n Run starts at: " + (new java.util.Date(startTime)) +
", finishes at: " + (new java.util.Date(endTime)) +
"\n Total operations: " + nTotalTxns +
", Elapsed seconds: " + elapsedSeconds +
", Throughput: " + throughput + " ops/sec.");
}
} catch (DatabaseException de) {
de.printStackTrace();
System.exit(1);
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
/**
* Open an Environment.
*/
private void openEnv(long cacheSize) throws DatabaseException {
EnvironmentConfig envConfig = new EnvironmentConfig();
envConfig.setAllowCreate(true);
envConfig.setCacheSize(cacheSize);
env = new Environment(new File(homeDir), envConfig);
if (contention) {
dataAccessDb = env.openDatabase(null, "dataAccessDb", null);
}
}
/**
* Check to see if stats looks correct.
*/
private boolean checkStats(long txns) throws DatabaseException {
/* Get EnvironmentStats numbers. */
StatsConfig statsConfig = new StatsConfig();
statsConfig.setFast(true);
statsConfig.setClear(true);
EnvironmentStats stats = env.getStats(statsConfig);
long evictedINs = stats.getNNodesExplicitlyEvicted();
long evictedRoots = stats.getNRootNodesEvicted();
long dataBytes = stats.getDataBytes();
/* Check the eviction of INs and ROOTs actually happens. */
boolean nodesCheck = (evictedINs > 0);
boolean rootsCheck = (evictedRoots > 0);
if (verbose) {
System.out.printf
("\n\tEviction Statistics(calc txns: %d)%n" +
" Data Pass/Fail%n" +
" ---------- ---------%n" +
"EvictedINs: %10d %9S%n" +
"EvictedRoots:%10d %9S%n" +
"DataBytes: %10d%n" +
"jvm.maxMem: %10d%n" +
"jvm.freeMem: %10d%n" +
"jvm.totlMem: %10d%n",
txns, evictedINs, (nodesCheck ? "PASS" : "FAIL"),
evictedRoots, (rootsCheck ? "PASS" : "FAIL"),
dataBytes, rt.maxMemory(), rt.freeMemory(), rt.totalMemory());
System.out.println
("The test criteria: EvictedINs > 0, EvictedRoots > 0.");
}
return nodesCheck && rootsCheck;
}
/**
* Close the Databases and Environment.
*/
private void closeEnv() throws DatabaseException {
if (dataAccessDb != null) {
dataAccessDb.close();
}
if (env != null) {
env.close();
}
}
/**
* Store meta-data information into metadataDb.
*/
private void saveMetadata() throws Exception {
/* Store meta-data information into one additional database. */
DatabaseConfig dbConfig = new DatabaseConfig();
dbConfig.setAllowCreate(true);
metadataDb = env.openDatabase(null, "metadataDb", dbConfig);
OperationStatus status =
metadataDb.put(null,
new DatabaseEntry("nRegularDbs".getBytes("UTF-8")),
new DatabaseEntry(Integer.
toString(nRegularDbs).
getBytes("UTF-8")));
if (status != OperationStatus.SUCCESS) {
System.err.println
("Not able to save info into the metadata database.");
System.exit(1);
}
metadataDb.close();
}
/**
* Retrieve meta-data information from metadataDb.
*/
private void readMetadata() throws Exception {
/* Retrieve meta-data information from metadataDB. */
metadataDb = env.openDatabase(null, "metadataDb", null);
DatabaseEntry key = new DatabaseEntry("nRegularDbs".getBytes("UTF-8"));
DatabaseEntry data = new DatabaseEntry();
OperationStatus status =
metadataDb.get(null, key, data, LockMode.DEFAULT);
if (status != OperationStatus.SUCCESS) {
System.err.println
("Couldn't retrieve info from the metadata database.");
System.exit(1);
}
nRegularDbs = Integer.parseInt(new String (data.getData(), "UTF-8"));
metadataDb.close();
}
}
| |
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.vcs.impl;
import com.intellij.lifecycle.PeriodicalTasksCloser;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.components.ProjectComponent;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.editor.event.EditorFactoryAdapter;
import com.intellij.openapi.editor.event.EditorFactoryEvent;
import com.intellij.openapi.editor.event.EditorFactoryListener;
import com.intellij.openapi.editor.ex.DocumentBulkUpdateListener;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.impl.DirectoryIndex;
import com.intellij.openapi.startup.StartupManager;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.FileStatus;
import com.intellij.openapi.vcs.FileStatusListener;
import com.intellij.openapi.vcs.FileStatusManager;
import com.intellij.openapi.vcs.VcsApplicationSettings;
import com.intellij.openapi.vcs.ex.LineStatusTracker;
import com.intellij.openapi.vcs.history.VcsRevisionNumber;
import com.intellij.openapi.vfs.*;
import com.intellij.testFramework.LightVirtualFile;
import com.intellij.util.concurrency.QueueProcessorRemovePartner;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.HashMap;
import com.intellij.util.messages.MessageBusConnection;
import org.jetbrains.annotations.*;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
public class LineStatusTrackerManager implements ProjectComponent, LineStatusTrackerManagerI {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.vcs.impl.LineStatusTrackerManager");
@NotNull private final Object myLock = new Object();
@NotNull private final Project myProject;
@NotNull private final VcsBaseContentProvider myStatusProvider;
@NotNull private final Application myApplication;
@NotNull private final Disposable myDisposable;
@NotNull private final Map<Document, TrackerData> myLineStatusTrackers = new HashMap<>();
@NotNull private final QueueProcessorRemovePartner<Document, BaseRevisionLoader> myPartner;
private long myLoadCounter = 0;
public static LineStatusTrackerManagerI getInstance(final Project project) {
return PeriodicalTasksCloser.getInstance().safeGetComponent(project, LineStatusTrackerManagerI.class);
}
public LineStatusTrackerManager(@NotNull final Project project,
@NotNull final VcsBaseContentProvider statusProvider,
@NotNull final Application application,
@SuppressWarnings("UnusedParameters") DirectoryIndex makeSureIndexIsInitializedFirst) {
myProject = project;
myStatusProvider = statusProvider;
myApplication = application;
myPartner = new QueueProcessorRemovePartner<>(myProject, baseRevisionLoader -> baseRevisionLoader.run());
MessageBusConnection busConnection = project.getMessageBus().connect();
busConnection.subscribe(DocumentBulkUpdateListener.TOPIC, new DocumentBulkUpdateListener.Adapter() {
@Override
public void updateStarted(@NotNull final Document doc) {
final LineStatusTracker tracker = getLineStatusTracker(doc);
if (tracker != null) tracker.startBulkUpdate();
}
@Override
public void updateFinished(@NotNull final Document doc) {
final LineStatusTracker tracker = getLineStatusTracker(doc);
if (tracker != null) tracker.finishBulkUpdate();
}
});
busConnection.subscribe(LineStatusTrackerSettingListener.TOPIC, new LineStatusTrackerSettingListener() {
@Override
public void settingsUpdated() {
synchronized (myLock) {
LineStatusTracker.Mode mode = getMode();
for (TrackerData data : myLineStatusTrackers.values()) {
data.tracker.setMode(mode);
}
}
}
});
myDisposable = new Disposable() {
@Override
public void dispose() {
synchronized (myLock) {
for (final TrackerData data : myLineStatusTrackers.values()) {
data.tracker.release();
}
myLineStatusTrackers.clear();
myPartner.clear();
}
}
};
Disposer.register(myProject, myDisposable);
}
@Override
public void projectOpened() {
StartupManager.getInstance(myProject).registerPreStartupActivity(() -> {
final MyFileStatusListener fileStatusListener = new MyFileStatusListener();
final EditorFactoryListener editorFactoryListener = new MyEditorFactoryListener();
final MyVirtualFileListener virtualFileListener = new MyVirtualFileListener();
final FileStatusManager fsManager = FileStatusManager.getInstance(myProject);
fsManager.addFileStatusListener(fileStatusListener, myDisposable);
final EditorFactory editorFactory = EditorFactory.getInstance();
editorFactory.addEditorFactoryListener(editorFactoryListener, myDisposable);
final VirtualFileManager virtualFileManager = VirtualFileManager.getInstance();
virtualFileManager.addVirtualFileListener(virtualFileListener, myDisposable);
});
}
@Override
public void projectClosed() {
}
@Override
@NonNls
@NotNull
public String getComponentName() {
return "LineStatusTrackerManager";
}
public boolean isDisabled() {
return !myProject.isOpen() || myProject.isDisposed();
}
@Override
@Nullable
public LineStatusTracker getLineStatusTracker(final Document document) {
synchronized (myLock) {
if (isDisabled()) return null;
TrackerData data = myLineStatusTrackers.get(document);
return data != null ? data.tracker : null;
}
}
private boolean isTrackedEditor(@NotNull Editor editor) {
return editor.getProject() == null || editor.getProject() == myProject;
}
@NotNull
private List<Editor> getAllTrackedEditors(@NotNull Document document) {
return Arrays.asList(EditorFactory.getInstance().getEditors(document, myProject));
}
@NotNull
private List<Editor> getAllTrackedEditors() {
return ContainerUtil.filter(EditorFactory.getInstance().getAllEditors(), this::isTrackedEditor);
}
@CalledInAwt
private void onEditorCreated(@NotNull Editor editor) {
if (isTrackedEditor(editor)) {
installTracker(editor.getDocument());
}
}
@CalledInAwt
private void onEditorRemoved(@NotNull Editor editor) {
if (isTrackedEditor(editor)) {
List<Editor> editors = getAllTrackedEditors(editor.getDocument());
if (editors.size() == 0 ||
editors.size() == 1 && editor == editors.get(0)) {
doReleaseTracker(editor.getDocument());
}
}
}
@CalledInAwt
private void onEverythingChanged() {
synchronized (myLock) {
if (isDisabled()) return;
log("onEverythingChanged", null);
List<LineStatusTracker> trackers = ContainerUtil.map(myLineStatusTrackers.values(), data -> data.tracker);
for (LineStatusTracker tracker : trackers) {
resetTracker(tracker.getDocument(), tracker.getVirtualFile(), tracker);
}
for (Editor editor : getAllTrackedEditors()) {
installTracker(editor.getDocument());
}
}
}
@CalledInAwt
private void onFileChanged(@NotNull VirtualFile virtualFile) {
final Document document = FileDocumentManager.getInstance().getCachedDocument(virtualFile);
if (document == null) return;
synchronized (myLock) {
if (isDisabled()) return;
log("onFileChanged", virtualFile);
resetTracker(document, virtualFile, getLineStatusTracker(document));
}
}
private void installTracker(@NotNull Document document) {
VirtualFile file = FileDocumentManager.getInstance().getFile(document);
log("installTracker", file);
if (shouldBeInstalled(file)) {
doInstallTracker(file, document);
}
}
private void resetTracker(@NotNull Document document, @NotNull VirtualFile virtualFile, @Nullable LineStatusTracker tracker) {
boolean isOpened = !getAllTrackedEditors(document).isEmpty();
final boolean shouldBeInstalled = isOpened && shouldBeInstalled(virtualFile);
log("resetTracker: shouldBeInstalled - " + shouldBeInstalled + ", tracker - " + (tracker == null ? "null" : "found"), virtualFile);
if (tracker != null && shouldBeInstalled) {
doRefreshTracker(tracker);
}
else if (tracker != null) {
doReleaseTracker(document);
}
else if (shouldBeInstalled) {
doInstallTracker(virtualFile, document);
}
}
@Contract("null -> false")
private boolean shouldBeInstalled(@Nullable final VirtualFile virtualFile) {
if (isDisabled()) return false;
if (virtualFile == null || virtualFile instanceof LightVirtualFile) return false;
final FileStatusManager statusManager = FileStatusManager.getInstance(myProject);
if (statusManager == null) return false;
if (!myStatusProvider.isSupported(virtualFile)) {
log("shouldBeInstalled failed: file not supported", virtualFile);
return false;
}
final FileStatus status = statusManager.getStatus(virtualFile);
if (status == FileStatus.NOT_CHANGED || status == FileStatus.ADDED || status == FileStatus.UNKNOWN || status == FileStatus.IGNORED) {
log("shouldBeInstalled skipped: status=" + status, virtualFile);
return false;
}
return true;
}
private void doRefreshTracker(@NotNull LineStatusTracker tracker) {
synchronized (myLock) {
if (isDisabled()) return;
log("trackerRefreshed", tracker.getVirtualFile());
startAlarm(tracker.getDocument(), tracker.getVirtualFile());
}
}
private void doReleaseTracker(@NotNull Document document) {
synchronized (myLock) {
if (isDisabled()) return;
myPartner.remove(document);
final TrackerData data = myLineStatusTrackers.remove(document);
if (data != null) {
log("trackerReleased", data.tracker.getVirtualFile());
data.tracker.release();
}
}
}
private void doInstallTracker(@NotNull VirtualFile virtualFile, @NotNull Document document) {
synchronized (myLock) {
if (isDisabled()) return;
if (myLineStatusTrackers.containsKey(document)) return;
assert !myPartner.containsKey(document);
log("trackerInstalled", virtualFile);
final LineStatusTracker tracker = LineStatusTracker.createOn(virtualFile, document, myProject, getMode());
myLineStatusTrackers.put(document, new TrackerData(tracker));
startAlarm(document, virtualFile);
}
}
@NotNull
private static LineStatusTracker.Mode getMode() {
VcsApplicationSettings vcsApplicationSettings = VcsApplicationSettings.getInstance();
if (!vcsApplicationSettings.SHOW_LST_GUTTER_MARKERS) return LineStatusTracker.Mode.SILENT;
return vcsApplicationSettings.SHOW_WHITESPACES_IN_LST ? LineStatusTracker.Mode.SMART : LineStatusTracker.Mode.DEFAULT;
}
private void startAlarm(@NotNull final Document document, @NotNull final VirtualFile virtualFile) {
synchronized (myLock) {
myPartner.add(document, new BaseRevisionLoader(document, virtualFile));
}
}
private class BaseRevisionLoader implements Runnable {
@NotNull private final VirtualFile myVirtualFile;
@NotNull private final Document myDocument;
private BaseRevisionLoader(@NotNull final Document document, @NotNull final VirtualFile virtualFile) {
myDocument = document;
myVirtualFile = virtualFile;
}
@Override
public void run() {
if (isDisabled()) return;
if (!myVirtualFile.isValid()) {
log("BaseRevisionLoader failed: virtual file not valid", myVirtualFile);
reportTrackerBaseLoadFailed();
return;
}
VcsBaseContentProvider.BaseContent baseContent = myStatusProvider.getBaseRevision(myVirtualFile);
if (baseContent == null) {
log("BaseRevisionLoader failed: null returned for base revision", myVirtualFile);
reportTrackerBaseLoadFailed();
return;
}
// loads are sequential (in single threaded QueueProcessor);
// so myLoadCounter can't take less value for greater base revision -> the only thing we want from it
final VcsRevisionNumber revisionNumber = baseContent.getRevisionNumber();
final Charset charset = myVirtualFile.getCharset();
final long loadCounter = myLoadCounter;
myLoadCounter++;
synchronized (myLock) {
final TrackerData data = myLineStatusTrackers.get(myDocument);
if (data == null) {
log("BaseRevisionLoader canceled: tracker already released", myVirtualFile);
return;
}
if (!data.shouldBeUpdated(revisionNumber, charset, loadCounter)) {
log("BaseRevisionLoader canceled: no need to update", myVirtualFile);
return;
}
}
String lastUpToDateContent = baseContent.loadContent();
if (lastUpToDateContent == null) {
log("BaseRevisionLoader failed: can't load up-to-date content", myVirtualFile);
reportTrackerBaseLoadFailed();
return;
}
final String converted = StringUtil.convertLineSeparators(lastUpToDateContent);
final Runnable runnable = () -> {
synchronized (myLock) {
final TrackerData data = myLineStatusTrackers.get(myDocument);
if (data == null) {
log("BaseRevisionLoader initializing: tracker already released", myVirtualFile);
return;
}
if (!data.shouldBeUpdated(revisionNumber, charset, loadCounter)) {
log("BaseRevisionLoader initializing: no need to update", myVirtualFile);
return;
}
log("BaseRevisionLoader initializing: success", myVirtualFile);
myLineStatusTrackers.put(myDocument, new TrackerData(data.tracker, revisionNumber, charset, loadCounter));
data.tracker.setBaseRevision(converted);
}
};
nonModalAliveInvokeLater(runnable);
}
private void nonModalAliveInvokeLater(@NotNull Runnable runnable) {
myApplication.invokeLater(runnable, ModalityState.NON_MODAL, ignore -> isDisabled());
}
private void reportTrackerBaseLoadFailed() {
synchronized (myLock) {
doReleaseTracker(myDocument);
}
}
}
private class MyFileStatusListener implements FileStatusListener {
@Override
public void fileStatusesChanged() {
onEverythingChanged();
}
@Override
public void fileStatusChanged(@NotNull VirtualFile virtualFile) {
onFileChanged(virtualFile);
}
}
private class MyEditorFactoryListener extends EditorFactoryAdapter {
@Override
public void editorCreated(@NotNull EditorFactoryEvent event) {
onEditorCreated(event.getEditor());
}
@Override
public void editorReleased(@NotNull EditorFactoryEvent event) {
onEditorRemoved(event.getEditor());
}
}
private class MyVirtualFileListener implements VirtualFileListener {
@Override
public void beforeContentsChange(@NotNull VirtualFileEvent event) {
if (event.isFromRefresh()) {
onFileChanged(event.getFile());
}
}
@Override
public void propertyChanged(@NotNull VirtualFilePropertyEvent event) {
if (VirtualFile.PROP_ENCODING.equals(event.getPropertyName())) {
onFileChanged(event.getFile());
}
}
}
private static class TrackerData {
@NotNull public final LineStatusTracker tracker;
@Nullable private final ContentInfo currentContent;
public TrackerData(@NotNull LineStatusTracker tracker) {
this.tracker = tracker;
currentContent = null;
}
public TrackerData(@NotNull LineStatusTracker tracker,
@NotNull VcsRevisionNumber revision,
@NotNull Charset charset,
long loadCounter) {
this.tracker = tracker;
currentContent = new ContentInfo(revision, charset, loadCounter);
}
public boolean shouldBeUpdated(@NotNull VcsRevisionNumber revision, @NotNull Charset charset, long loadCounter) {
if (currentContent == null) return true;
if (currentContent.revision.equals(revision) && !currentContent.revision.equals(VcsRevisionNumber.NULL)) {
return !currentContent.charset.equals(charset);
}
return currentContent.loadCounter < loadCounter;
}
}
private static class ContentInfo {
@NotNull public final VcsRevisionNumber revision;
@NotNull public final Charset charset;
public final long loadCounter;
public ContentInfo(@NotNull VcsRevisionNumber revision, @NotNull Charset charset, long loadCounter) {
this.revision = revision;
this.charset = charset;
this.loadCounter = loadCounter;
}
}
private static void log(@NotNull String message, @Nullable VirtualFile file) {
if (LOG.isDebugEnabled()) {
if (file != null) message += "; file: " + file.getPath();
LOG.debug(message);
}
}
}
| |
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.nanovg;
import javax.annotation.*;
import java.nio.*;
import org.lwjgl.system.*;
import static org.lwjgl.system.Checks.*;
import static org.lwjgl.system.MemoryUtil.*;
public class OUI {
static { LibNanoVG.initialize(); }
/**
* <h5>Enum values:</h5>
*
* <ul>
* <li>{@link #UI_USERMASK USERMASK} -
* these bits, starting at bit 24, can be safely assigned by the application, e.g. as item types, other event types, drop targets, etc.
*
* <p>They can be set and queried using {@link #uiSetFlags SetFlags} and {@link #uiGetFlags GetFlags}.</p>
* </li>
* <li>{@link #UI_ANY ANY} - a special mask passed to {@link #uiFindItem FindItem}</li>
* </ul>
*/
public static final int
UI_USERMASK = 0xFF000000,
UI_ANY = 0xFFFFFFFF;
/**
* Item states as returned by {@link #uiGetState GetState}. ({@code UIitemState})
*
* <h5>Enum values:</h5>
*
* <ul>
* <li>{@link #UI_COLD COLD} - the item is inactive</li>
* <li>{@link #UI_HOT HOT} - the item is inactive, but the cursor is hovering over this item</li>
* <li>{@link #UI_ACTIVE ACTIVE} - the item is toggled, activated, focused (depends on item kind)</li>
* <li>{@link #UI_FROZEN FROZEN} - the item is unresponsive</li>
* </ul>
*/
public static final int
UI_COLD = 0,
UI_HOT = 1,
UI_ACTIVE = 2,
UI_FROZEN = 3;
/**
* Container flags to pass to {@link #uiSetBox SetBox}. ({@code UIboxFlags})
*
* <h5>Enum values:</h5>
*
* <ul>
* <li>{@link #UI_ROW ROW} - left to right</li>
* <li>{@link #UI_COLUMN COLUMN} - top to bottom</li>
* <li>{@link #UI_LAYOUT LAYOUT} - free layout</li>
* <li>{@link #UI_FLEX FLEX} - flex model</li>
* <li>{@link #UI_NOWRAP NOWRAP} - single-line</li>
* <li>{@link #UI_WRAP WRAP} - multi-line, wrap left to right</li>
* <li>{@link #UI_START START} - justify-content (start, end, center, space-between) at start of row/column</li>
* <li>{@link #UI_MIDDLE MIDDLE} - at center of row/column</li>
* <li>{@link #UI_END END} - at end of row/column</li>
* <li>{@link #UI_JUSTIFY JUSTIFY} - insert spacing to stretch across whole row/column</li>
* </ul>
*/
public static final int
UI_ROW = 0x002,
UI_COLUMN = 0x003,
UI_LAYOUT = 0x000,
UI_FLEX = 0x002,
UI_NOWRAP = 0x000,
UI_WRAP = 0x004,
UI_START = 0x008,
UI_MIDDLE = 0x000,
UI_END = 0x010,
UI_JUSTIFY = 0x018;
/**
* Child layout flags to pass to {@link #uiSetLayout SetLayout}. ({@code UIlayoutFlags})
*
* <h5>Enum values:</h5>
*
* <ul>
* <li>{@link #UI_LEFT LEFT} - anchor to left item or left side of parent</li>
* <li>{@link #UI_TOP TOP} - anchor to top item or top side of parent</li>
* <li>{@link #UI_RIGHT RIGHT} - anchor to right item or right side of parent</li>
* <li>{@link #UI_DOWN DOWN} - anchor to bottom item or bottom side of parent</li>
* <li>{@link #UI_HFILL HFILL} - anchor to both left and right item or parent borders</li>
* <li>{@link #UI_VFILL VFILL} - anchor to both top and bottom item or parent borders</li>
* <li>{@link #UI_HCENTER HCENTER} - center horizontally, with left margin as offset</li>
* <li>{@link #UI_VCENTER VCENTER} - center vertically, with top margin as offset</li>
* <li>{@link #UI_CENTER CENTER} - center in both directions, with left/top margin as offset</li>
* <li>{@link #UI_FILL FILL} - anchor to all four directions</li>
* <li>{@link #UI_BREAK BREAK} -
* when wrapping, put this element on a new line.
*
* <p>Wrapping layout code auto-inserts {@code UI_BREAK} flags, drawing routines can read them with {@link #uiGetLayout GetLayout}.</p>
* </li>
* </ul>
*/
public static final int
UI_LEFT = 0x020,
UI_TOP = 0x040,
UI_RIGHT = 0x080,
UI_DOWN = 0x100,
UI_HFILL = 0x0a0,
UI_VFILL = 0x140,
UI_HCENTER = 0x000,
UI_VCENTER = 0x000,
UI_CENTER = 0x000,
UI_FILL = 0x1e0,
UI_BREAK = 0x200;
/**
* Event flags. ({@code UIevent})
*
* <h5>Enum values:</h5>
*
* <ul>
* <li>{@link #UI_BUTTON0_DOWN BUTTON0_DOWN} - on button 0 down</li>
* <li>{@link #UI_BUTTON0_UP BUTTON0_UP} - on button 0 up when this event has a handler, {@link #uiGetState GetState} will return {@link #UI_ACTIVE ACTIVE} as long as button 0 is down</li>
* <li>{@link #UI_BUTTON0_HOT_UP BUTTON0_HOT_UP} -
* on button 0 up while item is hovered when this event has a handler, {@link #uiGetState GetState} will return {@link #UI_ACTIVE ACTIVE} when the cursor is hovering the items
* rectangle; this is the behavior expected for buttons
* </li>
* <li>{@link #UI_BUTTON0_CAPTURE BUTTON0_CAPTURE} - item is being captured (button 0 constantly pressed); when this event has a handler, {@link #uiGetState GetState} will return {@link #UI_ACTIVE ACTIVE} as long as button 0 is down</li>
* <li>{@link #UI_BUTTON2_DOWN BUTTON2_DOWN} - on button 2 down (right mouse button, usually triggers context menu)</li>
* <li>{@link #UI_SCROLL SCROLL} - item has received a scrollwheel event the accumulated wheel offset can be queried with {@link #uiGetScroll GetScroll}</li>
* <li>{@link #UI_KEY_DOWN KEY_DOWN} - item is focused and has received a key-down event the respective key can be queried using {@link #uiGetKey GetKey} and {@link #uiGetModifier GetModifier}</li>
* <li>{@link #UI_KEY_UP KEY_UP} - item is focused and has received a key-up event the respective key can be queried using {@link #uiGetKey GetKey} and {@link #uiGetModifier GetModifier}</li>
* <li>{@link #UI_CHAR CHAR} - item is focused and has received a character event the respective character can be queried using {@link #uiGetKey GetKey}</li>
* </ul>
*/
public static final int
UI_BUTTON0_DOWN = 0x0400,
UI_BUTTON0_UP = 0x0800,
UI_BUTTON0_HOT_UP = 0x1000,
UI_BUTTON0_CAPTURE = 0x2000,
UI_BUTTON2_DOWN = 0x4000,
UI_SCROLL = 0x8000,
UI_KEY_DOWN = 0x10000,
UI_KEY_UP = 0x20000,
UI_CHAR = 0x40000;
protected OUI() {
throw new UnsupportedOperationException();
}
// --- [ uiCreateContext ] ---
/**
* Creates a new UI context; call {@link #uiMakeCurrent MakeCurrent} to make this context the current context.
*
* <p>The context is managed by the client and must be released using {@link #uiDestroyContext DestroyContext}.</p>
*
* @param item_capacity the maximum number of items that can be declared. 4096 is a good starting value.
* @param buffer_capacity the maximum total size of bytes that can be allocated using {@link #uiAllocHandle AllocHandle}; you may pass 0 if you don't need to allocate handles. {@code (1<<20)}
* is a good starting value.
*/
@NativeType("UIcontext *")
public static native long uiCreateContext(@NativeType("unsigned int") int item_capacity, @NativeType("unsigned int") int buffer_capacity);
// --- [ uiMakeCurrent ] ---
/** Selects an UI context as the current context; a context must always be selected before using any of the other UI functions. */
public static native void uiMakeCurrent(@NativeType("UIcontext *") long ctx);
// --- [ uiDestroyContext ] ---
/** Unsafe version of: {@link #uiDestroyContext DestroyContext} */
public static native void nuiDestroyContext(long ctx);
/** Releases the memory of an UI context created with {@link #uiCreateContext CreateContext}; if the context is the current context, the current context will be set to {@code NULL}. */
public static void uiDestroyContext(@NativeType("UIcontext *") long ctx) {
if (CHECKS) {
check(ctx);
}
nuiDestroyContext(ctx);
}
// --- [ uiGetContext ] ---
/** Returns the currently selected context or {@code NULL}. */
@NativeType("UIcontext *")
public static native long uiGetContext();
// --- [ uiSetCursor ] ---
/** Sets the current cursor position (usually belonging to a mouse) to the screen coordinates at {@code (x,y)}. */
public static native void uiSetCursor(int x, int y);
// --- [ uiGetCursor ] ---
/** Unsafe version of: {@link #uiGetCursor GetCursor} */
public static native void nuiGetCursor(long __result);
/** Returns the current cursor position in screen coordinates as set by {@link #uiSetCursor SetCursor}. */
@NativeType("UIvec2")
public static UIVec2 uiGetCursor(@NativeType("UIvec2") UIVec2 __result) {
nuiGetCursor(__result.address());
return __result;
}
// --- [ uiGetCursorDelta ] ---
/** Unsafe version of: {@link #uiGetCursorDelta GetCursorDelta} */
public static native void nuiGetCursorDelta(long __result);
/** Returns the offset of the cursor relative to the last call to {@link #uiProcess Process}. */
@NativeType("UIvec2")
public static UIVec2 uiGetCursorDelta(@NativeType("UIvec2") UIVec2 __result) {
nuiGetCursorDelta(__result.address());
return __result;
}
// --- [ uiGetCursorStart ] ---
/** Unsafe version of: {@link #uiGetCursorStart GetCursorStart} */
public static native void nuiGetCursorStart(long __result);
/** Returns the beginning point of a drag operation. */
@NativeType("UIvec2")
public static UIVec2 uiGetCursorStart(@NativeType("UIvec2") UIVec2 __result) {
nuiGetCursorStart(__result.address());
return __result;
}
// --- [ uiGetCursorStartDelta ] ---
/** Unsafe version of: {@link #uiGetCursorStartDelta GetCursorStartDelta} */
public static native void nuiGetCursorStartDelta(long __result);
/** Returns the offset of the cursor relative to the beginning point of a drag operation. */
@NativeType("UIvec2")
public static UIVec2 uiGetCursorStartDelta(@NativeType("UIvec2") UIVec2 __result) {
nuiGetCursorStartDelta(__result.address());
return __result;
}
// --- [ uiSetButton ] ---
/** Unsafe version of: {@link #uiSetButton SetButton} */
public static native void nuiSetButton(int button, int mod, int enabled);
/**
* Sets a mouse or gamepad button as pressed/released button is in the range {@code 0..63} and maps to an application defined input source.
*
* @param mod an application defined set of flags for modifier keys
* @param enabled is 1 for pressed, 0 for released
*/
public static void uiSetButton(@NativeType("unsigned int") int button, @NativeType("unsigned int") int mod, @NativeType("int") boolean enabled) {
nuiSetButton(button, mod, enabled ? 1 : 0);
}
// --- [ uiGetButton ] ---
/** Unsafe version of: {@link #uiGetButton GetButton} */
public static native int nuiGetButton(int button);
/**
* Returns the current state of an application dependent input button as set by {@link #uiSetButton SetButton}.
*
* @return 1 if the button has been set to pressed, 0 for released
*/
@NativeType("int")
public static boolean uiGetButton(@NativeType("unsigned int") int button) {
return nuiGetButton(button) != 0;
}
// --- [ uiGetClicks ] ---
/** Returns the number of chained clicks; 1 is a single click, 2 is a double click, etc. */
public static native int uiGetClicks();
// --- [ uiSetKey ] ---
/** Unsafe version of: {@link #uiSetKey SetKey} */
public static native void nuiSetKey(int key, int mod, int enabled);
/**
* Sets a key as down/up; the key can be any application defined {@code keycode}.
*
* <p>All key events are being buffered until the next call to {@link #uiProcess Process}.</p>
*
* @param mod an application defined set of flags for modifier keys
* @param enabled 1 for key down, 0 for key up
*/
public static void uiSetKey(@NativeType("unsigned int") int key, @NativeType("unsigned int") int mod, @NativeType("int") boolean enabled) {
nuiSetKey(key, mod, enabled ? 1 : 0);
}
// --- [ uiSetChar ] ---
/**
* Sends a single character for text input; the character is usually in the unicode range, but can be application defined.
*
* <p>All char events are being buffered until the next call to {@link #uiProcess Process}.</p>
*/
public static native void uiSetChar(@NativeType("unsigned int") int value);
// --- [ uiSetScroll ] ---
/**
* Accumulates scroll wheel offsets for the current frame.
*
* <p>All offsets are being accumulated until the next call to {@link #uiProcess Process}.</p>
*/
public static native void uiSetScroll(int x, int y);
// --- [ uiGetScroll ] ---
/** Unsafe version of: {@link #uiGetScroll GetScroll} */
public static native void nuiGetScroll(long __result);
/** Returns the currently accumulated scroll wheel offsets for this frame */
@NativeType("UIvec2")
public static UIVec2 uiGetScroll(@NativeType("UIvec2") UIVec2 __result) {
nuiGetScroll(__result.address());
return __result;
}
// --- [ uiBeginLayout ] ---
/**
* Clears the item buffer.
*
* <p>{@code uiBeginLayout()} should be called before the first UI declaration for this frame to avoid concatenation of the same UI multiple times. After the
* call, all previously declared item IDs are invalid, and all application dependent context data has been freed.</p>
*
* <p>{@code uiBeginLayout()} must be followed by {@link #uiEndLayout EndLayout}.</p>
*/
public static native void uiBeginLayout();
// --- [ uiEndLayout ] ---
/**
* Layout all added items starting from the root item 0.
*
* <p>After calling {@code uiEndLayout()}, no further modifications to the item tree should be done until the next call to {@link #uiBeginLayout BeginLayout}. It is safe to
* immediately draw the items after a call to {@code uiEndLayout()}.</p>
*
* <p>This is an {@code O(N)} operation for {@code N = number of declared items}.</p>
*/
public static native void uiEndLayout();
// --- [ uiUpdateHotItem ] ---
/** Updates the current hot item; this only needs to be called if items are kept for more than one frame and {@link #uiEndLayout EndLayout} is not called. */
public static native void uiUpdateHotItem();
// --- [ uiProcess ] ---
/**
* Updates the internal state according to the current cursor position and button states, and call all registered handlers.
*
* <p>No further modifications to the item tree should be done until the next call to {@link #uiBeginLayout BeginLayout}. Items should be drawn before a call to
* {@code uiProcess()}.</p>
*
* <p>This is an {@code O(N)} operation for {@code N = number of declared items}.</p>
*
* @param timestamp the time in milliseconds relative to the last call to {@code uiProcess()} and is used to estimate the threshold for double-clicks after calling
* {@code uiProcess()}.
*/
public static native void uiProcess(int timestamp);
// --- [ uiClearState ] ---
/**
* Resets the currently stored hot/active etc. handles.
*
* <p>This should be called when a re-declaration of the UI changes the item indices, to avoid state related glitches because item identities have changed.</p>
*/
public static native void uiClearState();
// --- [ uiItem ] ---
/** Creates a new UI item and return the new item's ID. */
public static native int uiItem();
// --- [ uiSetFrozen ] ---
/** Unsafe version of: {@link #uiSetFrozen SetFrozen} */
public static native void nuiSetFrozen(int item, int enable);
/**
* Sets an items state to frozen.
*
* <p>The UI will not recurse into frozen items when searching for hot or active items; subsequently, frozen items and their child items will not cause mouse
* event notifications. The frozen state is not applied recursively; {@link #uiGetState GetState} will report {@link #UI_COLD COLD} for child items. Upon encountering a frozen item, the
* drawing routine needs to handle rendering of child items appropriately.</p>
*/
public static void uiSetFrozen(int item, @NativeType("int") boolean enable) {
nuiSetFrozen(item, enable ? 1 : 0);
}
// --- [ uiSetHandle ] ---
/**
* Sets the application-dependent handle of an item.
*
* @param handle an application defined 64-bit handle. If {@code NULL}, the item will not be interactive.
*/
public static native void uiSetHandle(int item, @NativeType("void *") long handle);
// --- [ uiAllocHandle ] ---
/** Unsafe version of: {@link #uiAllocHandle AllocHandle} */
public static native long nuiAllocHandle(int item, int size);
/**
* Allocates space for application-dependent context data and assign it as the handle to the item.
*
* <p>The memory of the pointer is managed by the UI context and released upon the next call to {@link #uiBeginLayout BeginLayout}.</p>
*/
@Nullable
@NativeType("void *")
public static ByteBuffer uiAllocHandle(int item, @NativeType("unsigned int") int size) {
long __result = nuiAllocHandle(item, size);
return memByteBufferSafe(__result, size);
}
// --- [ uiSetHandler ] ---
/** Unsafe version of: {@link #uiSetHandler SetHandler} */
public static native void nuiSetHandler(long handler);
/**
* Sets the global handler callback for interactive items.
*
* <p>The handler will be called for each item whose event flags are set using {@link #uiSetEvents SetEvents}.</p>
*/
public static void uiSetHandler(@NativeType("UIhandler") UIHandlerI handler) {
nuiSetHandler(handler.address());
}
// --- [ uiSetEvents ] ---
/** @param flags designates for which events the handler should be called. One or more of:<br><table><tr><td>{@link #UI_BUTTON0_DOWN BUTTON0_DOWN}</td><td>{@link #UI_BUTTON0_UP BUTTON0_UP}</td><td>{@link #UI_BUTTON0_HOT_UP BUTTON0_HOT_UP}</td><td>{@link #UI_BUTTON0_CAPTURE BUTTON0_CAPTURE}</td><td>{@link #UI_BUTTON2_DOWN BUTTON2_DOWN}</td><td>{@link #UI_SCROLL SCROLL}</td><td>{@link #UI_KEY_DOWN KEY_DOWN}</td><td>{@link #UI_KEY_UP KEY_UP}</td></tr><tr><td>{@link #UI_CHAR CHAR}</td></tr></table> */
public static native void uiSetEvents(int item, @NativeType("unsigned int") int flags);
// --- [ uiSetFlags ] ---
/** @param flags a user-defined set of flags defined by {@link #UI_USERMASK USERMASK} */
public static native void uiSetFlags(int item, @NativeType("unsigned int") int flags);
// --- [ uiInsert ] ---
/**
* Assigns an item to a container.
*
* <p>An item ID of 0 refers to the root item. The function searches for the last item and calls {@link #uiAppend Append} on it, which is an {@code O(N)} operation for
* {@code N} siblings. It is usually more efficient to call {@code uiInser}t() for the first child, then chain additional siblings using
* {@code uiAppend()}.</p>
*
* @return the child item ID if the container has already added items
*/
public static native int uiInsert(int item, int child);
// --- [ uiAppend ] ---
/**
* Assigns an item to the same container as another item.
*
* @param sibling inserted after {@code item}
*/
public static native int uiAppend(int item, int sibling);
// --- [ uiInsertBack ] ---
/**
* Inserts child into container item like {@link #uiInsert Insert}, but prepend it to the first child item, effectively putting it in the background.
*
* <p>It is efficient to call {@code uiInsertBack()} repeatedly in cases where drawing or layout order doesn't matter.</p>
*/
public static native int uiInsertBack(int item, int child);
// --- [ uiInsertFront ] ---
/** Same as {@link #uiInsert Insert}. */
public static native int uiInsertFront(int item, int child);
// --- [ uiSetSize ] ---
/**
* Sets the size of the item.
*
* <p>A size of 0 indicates the dimension to be dynamic; if the size is set, the item can not expand beyond that size.</p>
*/
public static native void uiSetSize(int item, int w, int h);
// --- [ uiSetLayout ] ---
/**
* Sets the anchoring behavior of the item to one or multiple {@code UIlayoutFlags}.
*
* @param flags one or more of:<br><table><tr><td>{@link #UI_LEFT LEFT}</td><td>{@link #UI_TOP TOP}</td><td>{@link #UI_RIGHT RIGHT}</td><td>{@link #UI_DOWN DOWN}</td><td>{@link #UI_HFILL HFILL}</td><td>{@link #UI_VFILL VFILL}</td><td>{@link #UI_HCENTER HCENTER}</td><td>{@link #UI_VCENTER VCENTER}</td><td>{@link #UI_CENTER CENTER}</td><td>{@link #UI_FILL FILL}</td><td>{@link #UI_BREAK BREAK}</td></tr></table>
*/
public static native void uiSetLayout(int item, @NativeType("unsigned int") int flags);
// --- [ uiSetBox ] ---
/**
* Sets the box model behavior of the item to one or multiple {@code UIboxFlags}.
*
* @param flags one or more of:<br><table><tr><td>{@link #UI_ROW ROW}</td><td>{@link #UI_COLUMN COLUMN}</td><td>{@link #UI_LAYOUT LAYOUT}</td><td>{@link #UI_FLEX FLEX}</td><td>{@link #UI_NOWRAP NOWRAP}</td><td>{@link #UI_WRAP WRAP}</td><td>{@link #UI_START START}</td><td>{@link #UI_MIDDLE MIDDLE}</td><td>{@link #UI_END END}</td><td>{@link #UI_JUSTIFY JUSTIFY}</td></tr></table>
*/
public static native void uiSetBox(int item, @NativeType("unsigned int") int flags);
// --- [ uiSetMargins ] ---
/** Unsafe version of: {@link #uiSetMargins SetMargins} */
public static native void nuiSetMargins(int item, short l, short t, short r, short b);
/**
* Sets the left, top, right and bottom margins of an item.
*
* <p>When the item is anchored to the parent or another item, the margin controls the distance from the neighboring element.</p>
*/
public static void uiSetMargins(int item, @NativeType("short") int l, @NativeType("short") int t, @NativeType("short") int r, @NativeType("short") int b) {
nuiSetMargins(item, (short)l, (short)t, (short)r, (short)b);
}
// --- [ uiFocus ] ---
/**
* Sets item as recipient of all keyboard events.
*
* @param item if -1, no item will be focused
*/
public static native void uiFocus(int item);
// --- [ uiFirstChild ] ---
/**
* Returns the first child item of a container item.
*
* <p>If the item is not a container or does not contain any items, -1 is returned.</p>
*
* @param item if 0, the first child item of the root item will be returned
*/
public static native int uiFirstChild(int item);
// --- [ uiNextSibling ] ---
/**
* Returns an items next sibling in the list of the parent containers children.
*
* <p>If {@code item} is 0 or the item is the last child item, -1 will be returned.</p>
*/
public static native int uiNextSibling(int item);
// --- [ uiGetItemCount ] ---
/** Returns the total number of allocated items */
public static native int uiGetItemCount();
// --- [ uiGetAllocSize ] ---
/** Returns the total bytes that have been allocated by {@link #uiAllocHandle AllocHandle} */
@NativeType("unsigned int")
public static native int uiGetAllocSize();
// --- [ uiGetState ] ---
/**
* Returns the current state of the item.
*
* <p>This state is only valid after a call to {@link #uiProcess Process}. The returned value is one of {@link #UI_COLD COLD}, {@link #UI_HOT HOT}, {@link #UI_ACTIVE ACTIVE}, {@link #UI_FROZEN FROZEN}.</p>
*/
@NativeType("UIitemState")
public static native int uiGetState(int item);
// --- [ uiGetHandle ] ---
/** Returns the application-dependent handle of the item as passed to {@link #uiSetHandle SetHandle} or {@link #uiAllocHandle AllocHandle}. */
@NativeType("void *")
public static native long uiGetHandle(int item);
// --- [ uiGetHotItem ] ---
/** Returns the item that is currently under the cursor or -1 for none. */
public static native int uiGetHotItem();
// --- [ uiGetFocusedItem ] ---
/** Returns the item that is currently focused or -1 for none. */
public static native int uiGetFocusedItem();
// --- [ uiFindItem ] ---
/**
* Returns the topmost item containing absolute location {@code (x,y)}, starting with {@code item} as parent, using a set of flags and masks as filter.
*
* <p>If both {@code flags} and {@code mask} are {@link #UI_ANY ANY}, the first topmost item is returned. If {@code mask} is {@link #UI_ANY ANY}, the first topmost item matching
* <em>any</em> of flags is returned. otherwise the first item matching {@code (item.flags & flags) == mask} is returned. You may combine box, layout,
* event and user flags. Frozen items will always be ignored.</p>
*/
public static native int uiFindItem(int item, int x, int y, @NativeType("unsigned int") int flags, @NativeType("unsigned int") int mask);
// --- [ uiGetHandler ] ---
/** Unsafe version of: {@link #uiGetHandler GetHandler} */
public static native long nuiGetHandler();
/** Returns the handler callback as passed to {@link #uiSetHandler SetHandler} */
@Nullable
@NativeType("UIhandler")
public static UIHandler uiGetHandler() {
return UIHandler.createSafe(nuiGetHandler());
}
// --- [ uiGetEvents ] ---
/** Returns the event flags for an item as passed to {@link #uiSetEvents SetEvents} */
@NativeType("unsigned int")
public static native int uiGetEvents(int item);
// --- [ uiGetFlags ] ---
/** Returns the user-defined flags for an item as passed to {@link #uiSetFlags SetFlags} */
@NativeType("unsigned int")
public static native int uiGetFlags(int item);
// --- [ uiGetKey ] ---
/** When handling a {@code KEY_DOWN/KEY_UP} event: the key that triggered this event. */
@NativeType("unsigned int")
public static native int uiGetKey();
// --- [ uiGetModifier ] ---
/** When handling a keyboard or mouse event: the active modifier keys. */
@NativeType("unsigned int")
public static native int uiGetModifier();
// --- [ uiGetRect ] ---
/** Unsafe version of: {@link #uiGetRect GetRect} */
public static native void nuiGetRect(int item, long __result);
/**
* Returns the items layout rectangle in absolute coordinates.
*
* <p>If {@code uiGetRect()} is called before {@link #uiEndLayout EndLayout}, the values of the returned rectangle are undefined.</p>
*/
@NativeType("UIrect")
public static UIRect uiGetRect(int item, @NativeType("UIrect") UIRect __result) {
nuiGetRect(item, __result.address());
return __result;
}
// --- [ uiContains ] ---
/** Unsafe version of: {@link #uiContains Contains} */
public static native int nuiContains(int item, int x, int y);
/** Returns 1 if an items absolute rectangle contains a given coordinate, otherwise 0. */
@NativeType("int")
public static boolean uiContains(int item, int x, int y) {
return nuiContains(item, x, y) != 0;
}
// --- [ uiGetWidth ] ---
/** Returns the width of the item as set by {@link #uiSetSize SetSize}. */
public static native int uiGetWidth(int item);
// --- [ uiGetHeight ] ---
/** Return the height of the item as set by {@link #uiSetSize SetSize}. */
public static native int uiGetHeight(int item);
// --- [ uiGetLayout ] ---
/** Returns the anchoring behavior as set by {@link #uiSetLayout SetLayout}. */
@NativeType("unsigned int")
public static native int uiGetLayout(int item);
// --- [ uiGetBox ] ---
/** Returns the box model as set by {@link #uiSetBox SetBox}. */
@NativeType("unsigned int")
public static native int uiGetBox(int item);
// --- [ uiGetMarginLeft ] ---
/** Returns the left margin of the item as set with {@link #uiSetMargins SetMargins}. */
public static native short uiGetMarginLeft(int item);
// --- [ uiGetMarginTop ] ---
/** Returns the top margin of the item as set with {@link #uiSetMargins SetMargins}. */
public static native short uiGetMarginTop(int item);
// --- [ uiGetMarginRight ] ---
/** Returns the right margin of the item as set with {@link #uiSetMargins SetMargins}. */
public static native short uiGetMarginRight(int item);
// --- [ uiGetMarginDown ] ---
/** Returns the bottom margin of the item as set with {@link #uiSetMargins SetMargins}. */
public static native short uiGetMarginDown(int item);
// --- [ uiRecoverItem ] ---
/**
* When {@link #uiBeginLayout BeginLayout} is called, the most recently declared items are retained. When {@link #uiEndLayout EndLayout} completes, it matches the old item hierarchy to the new
* one and attempts to map old items to new items as well as possible. When passed an item Id from the previous frame, {@code uiRecoverItem()} returns the
* item's new assumed Id, or -1 if the item could not be mapped. It is valid to pass -1 as item.
*/
public static native int uiRecoverItem(int olditem);
// --- [ uiRemapItem ] ---
/**
* In cases where it is important to recover old state over changes in the view, and the built-in remapping fails, the UI declaration can manually remap
* old items to new IDs in cases where e.g. the previous item ID has been temporarily saved; {@code uiRemapItem()} would then be called after creating the
* new item using {@link #uiItem Item}.
*/
public static native void uiRemapItem(int olditem, int newitem);
// --- [ uiGetLastItemCount ] ---
/** Returns the number if items that have been allocated in the last frame. */
public static native int uiGetLastItemCount();
}
| |
/*
* Copyright 2017, Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.speech.spi.v1;
import com.google.api.core.BetaApi;
import com.google.api.gax.core.GoogleCredentialsProvider;
import com.google.api.gax.core.PropertiesProvider;
import com.google.api.gax.grpc.ChannelProvider;
import com.google.api.gax.grpc.ClientSettings;
import com.google.api.gax.grpc.ExecutorProvider;
import com.google.api.gax.grpc.InstantiatingChannelProvider;
import com.google.api.gax.grpc.InstantiatingExecutorProvider;
import com.google.api.gax.grpc.OperationCallSettings;
import com.google.api.gax.grpc.SimpleCallSettings;
import com.google.api.gax.grpc.StreamingCallSettings;
import com.google.api.gax.grpc.UnaryCallSettings;
import com.google.api.gax.retrying.RetrySettings;
import com.google.cloud.speech.v1.LongRunningRecognizeRequest;
import com.google.cloud.speech.v1.LongRunningRecognizeResponse;
import com.google.cloud.speech.v1.RecognizeRequest;
import com.google.cloud.speech.v1.RecognizeResponse;
import com.google.cloud.speech.v1.StreamingRecognizeRequest;
import com.google.cloud.speech.v1.StreamingRecognizeResponse;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.longrunning.Operation;
import io.grpc.Status;
import java.io.IOException;
import java.util.List;
import javax.annotation.Generated;
import org.threeten.bp.Duration;
// AUTO-GENERATED DOCUMENTATION AND CLASS
/**
* Settings class to configure an instance of {@link SpeechClient}.
*
* <p>The default instance has everything set to sensible defaults:
*
* <ul>
* <li>The default service address (speech.googleapis.com) and default port (443) are used.
* <li>Credentials are acquired automatically through Application Default Credentials.
* <li>Retries are configured for idempotent methods but not for non-idempotent methods.
* </ul>
*
* <p>The builder of this class is recursive, so contained classes are themselves builders. When
* build() is called, the tree of builders is called to create the complete settings object. For
* example, to set the total timeout of recognize to 30 seconds:
*
* <pre>
* <code>
* SpeechSettings.Builder speechSettingsBuilder =
* SpeechSettings.defaultBuilder();
* speechSettingsBuilder.recognizeSettings().getRetrySettingsBuilder()
* .setTotalTimeout(Duration.ofSeconds(30));
* SpeechSettings speechSettings = speechSettingsBuilder.build();
* </code>
* </pre>
*/
@Generated("by GAPIC v0.0.5")
@BetaApi
public class SpeechSettings extends ClientSettings {
/** The default scopes of the service. */
private static final ImmutableList<String> DEFAULT_SERVICE_SCOPES =
ImmutableList.<String>builder().add("https://www.googleapis.com/auth/cloud-platform").build();
private static final String DEFAULT_GAPIC_NAME = "gapic";
private static final String DEFAULT_GAPIC_VERSION = "";
private static final String PROPERTIES_FILE = "/com/google/cloud/speech/project.properties";
private static final String META_VERSION_KEY = "artifact.version";
private static String gapicVersion;
private static final io.grpc.MethodDescriptor<RecognizeRequest, RecognizeResponse>
METHOD_RECOGNIZE =
io.grpc.MethodDescriptor.create(
io.grpc.MethodDescriptor.MethodType.UNARY,
"google.cloud.speech.v1.Speech/Recognize",
io.grpc.protobuf.ProtoUtils.marshaller(RecognizeRequest.getDefaultInstance()),
io.grpc.protobuf.ProtoUtils.marshaller(RecognizeResponse.getDefaultInstance()));
private static final io.grpc.MethodDescriptor<LongRunningRecognizeRequest, Operation>
METHOD_LONG_RUNNING_RECOGNIZE =
io.grpc.MethodDescriptor.create(
io.grpc.MethodDescriptor.MethodType.UNARY,
"google.cloud.speech.v1.Speech/LongRunningRecognize",
io.grpc.protobuf.ProtoUtils.marshaller(
LongRunningRecognizeRequest.getDefaultInstance()),
io.grpc.protobuf.ProtoUtils.marshaller(Operation.getDefaultInstance()));
private static final io.grpc.MethodDescriptor<
StreamingRecognizeRequest, StreamingRecognizeResponse>
METHOD_STREAMING_RECOGNIZE =
io.grpc.MethodDescriptor.create(
io.grpc.MethodDescriptor.MethodType.BIDI_STREAMING,
"google.cloud.speech.v1.Speech/StreamingRecognize",
io.grpc.protobuf.ProtoUtils.marshaller(
StreamingRecognizeRequest.getDefaultInstance()),
io.grpc.protobuf.ProtoUtils.marshaller(
StreamingRecognizeResponse.getDefaultInstance()));
private final SimpleCallSettings<RecognizeRequest, RecognizeResponse> recognizeSettings;
private final OperationCallSettings<LongRunningRecognizeRequest, LongRunningRecognizeResponse>
longRunningRecognizeSettings;
private final StreamingCallSettings<StreamingRecognizeRequest, StreamingRecognizeResponse>
streamingRecognizeSettings;
/** Returns the object with the settings used for calls to recognize. */
public SimpleCallSettings<RecognizeRequest, RecognizeResponse> recognizeSettings() {
return recognizeSettings;
}
/** Returns the object with the settings used for calls to longRunningRecognize. */
public OperationCallSettings<LongRunningRecognizeRequest, LongRunningRecognizeResponse>
longRunningRecognizeSettings() {
return longRunningRecognizeSettings;
}
/** Returns the object with the settings used for calls to streamingRecognize. */
public StreamingCallSettings<StreamingRecognizeRequest, StreamingRecognizeResponse>
streamingRecognizeSettings() {
return streamingRecognizeSettings;
}
/** Returns a builder for the default ExecutorProvider for this service. */
public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() {
return InstantiatingExecutorProvider.newBuilder();
}
/** Returns the default service endpoint. */
public static String getDefaultEndpoint() {
return "speech.googleapis.com:443";
}
/** Returns the default service scopes. */
public static List<String> getDefaultServiceScopes() {
return DEFAULT_SERVICE_SCOPES;
}
/** Returns a builder for the default credentials for this service. */
public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() {
return GoogleCredentialsProvider.newBuilder().setScopesToApply(DEFAULT_SERVICE_SCOPES);
}
/** Returns a builder for the default ChannelProvider for this service. */
public static InstantiatingChannelProvider.Builder defaultChannelProviderBuilder() {
return InstantiatingChannelProvider.newBuilder()
.setEndpoint(getDefaultEndpoint())
.setGeneratorHeader(DEFAULT_GAPIC_NAME, getGapicVersion())
.setCredentialsProvider(defaultCredentialsProviderBuilder().build());
}
private static String getGapicVersion() {
if (gapicVersion == null) {
gapicVersion =
PropertiesProvider.loadProperty(SpeechSettings.class, PROPERTIES_FILE, META_VERSION_KEY);
gapicVersion = gapicVersion == null ? DEFAULT_GAPIC_VERSION : gapicVersion;
}
return gapicVersion;
}
/** Returns a builder for this class with recommended defaults. */
public static Builder defaultBuilder() {
return Builder.createDefault();
}
/** Returns a new builder for this class. */
public static Builder newBuilder() {
return new Builder();
}
/** Returns a builder containing all the values of this settings class. */
public Builder toBuilder() {
return new Builder(this);
}
private SpeechSettings(Builder settingsBuilder) throws IOException {
super(settingsBuilder.getExecutorProvider(), settingsBuilder.getChannelProvider());
recognizeSettings = settingsBuilder.recognizeSettings().build();
longRunningRecognizeSettings = settingsBuilder.longRunningRecognizeSettings().build();
streamingRecognizeSettings = settingsBuilder.streamingRecognizeSettings().build();
}
/** Builder for SpeechSettings. */
public static class Builder extends ClientSettings.Builder {
private final ImmutableList<UnaryCallSettings.Builder> unaryMethodSettingsBuilders;
private final SimpleCallSettings.Builder<RecognizeRequest, RecognizeResponse> recognizeSettings;
private final OperationCallSettings.Builder<
LongRunningRecognizeRequest, LongRunningRecognizeResponse>
longRunningRecognizeSettings;
private final StreamingCallSettings.Builder<
StreamingRecognizeRequest, StreamingRecognizeResponse>
streamingRecognizeSettings;
private static final ImmutableMap<String, ImmutableSet<Status.Code>> RETRYABLE_CODE_DEFINITIONS;
static {
ImmutableMap.Builder<String, ImmutableSet<Status.Code>> definitions = ImmutableMap.builder();
definitions.put(
"idempotent",
Sets.immutableEnumSet(
Lists.<Status.Code>newArrayList(
Status.Code.DEADLINE_EXCEEDED, Status.Code.UNAVAILABLE)));
definitions.put(
"non_idempotent",
Sets.immutableEnumSet(Lists.<Status.Code>newArrayList(Status.Code.UNAVAILABLE)));
RETRYABLE_CODE_DEFINITIONS = definitions.build();
}
private static final ImmutableMap<String, RetrySettings.Builder> RETRY_PARAM_DEFINITIONS;
static {
ImmutableMap.Builder<String, RetrySettings.Builder> definitions = ImmutableMap.builder();
RetrySettings.Builder settingsBuilder = null;
settingsBuilder =
RetrySettings.newBuilder()
.setInitialRetryDelay(Duration.ofMillis(100L))
.setRetryDelayMultiplier(1.3)
.setMaxRetryDelay(Duration.ofMillis(60000L))
.setInitialRpcTimeout(Duration.ofMillis(190000L))
.setRpcTimeoutMultiplier(1.0)
.setMaxRpcTimeout(Duration.ofMillis(190000L))
.setTotalTimeout(Duration.ofMillis(600000L));
definitions.put("default", settingsBuilder);
RETRY_PARAM_DEFINITIONS = definitions.build();
}
private Builder() {
super(defaultChannelProviderBuilder().build());
recognizeSettings = SimpleCallSettings.newBuilder(METHOD_RECOGNIZE);
longRunningRecognizeSettings =
OperationCallSettings.newBuilder(
METHOD_LONG_RUNNING_RECOGNIZE, LongRunningRecognizeResponse.class);
longRunningRecognizeSettings.setPollingInterval(Duration.ofMillis(20000));
streamingRecognizeSettings = StreamingCallSettings.newBuilder(METHOD_STREAMING_RECOGNIZE);
unaryMethodSettingsBuilders = ImmutableList.<UnaryCallSettings.Builder>of(recognizeSettings);
}
private static Builder createDefault() {
Builder builder = new Builder();
builder
.recognizeSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("idempotent"))
.setRetrySettingsBuilder(RETRY_PARAM_DEFINITIONS.get("default"));
builder
.longRunningRecognizeSettings()
.getInitialCallSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("non_idempotent"))
.setRetrySettingsBuilder(RETRY_PARAM_DEFINITIONS.get("default"));
return builder;
}
private Builder(SpeechSettings settings) {
super(settings);
recognizeSettings = settings.recognizeSettings.toBuilder();
longRunningRecognizeSettings = settings.longRunningRecognizeSettings.toBuilder();
streamingRecognizeSettings = settings.streamingRecognizeSettings.toBuilder();
unaryMethodSettingsBuilders = ImmutableList.<UnaryCallSettings.Builder>of(recognizeSettings);
}
@Override
public Builder setExecutorProvider(ExecutorProvider executorProvider) {
super.setExecutorProvider(executorProvider);
return this;
}
@Override
public Builder setChannelProvider(ChannelProvider channelProvider) {
super.setChannelProvider(channelProvider);
return this;
}
/**
* Applies the given settings to all of the unary API methods in this service. Only values that
* are non-null will be applied, so this method is not capable of un-setting any values.
*
* <p>Note: This method does not support applying settings to streaming methods.
*/
public Builder applyToAllUnaryMethods(UnaryCallSettings.Builder unaryCallSettings)
throws Exception {
super.applyToAllUnaryMethods(unaryMethodSettingsBuilders, unaryCallSettings);
return this;
}
/** Returns the builder for the settings used for calls to recognize. */
public SimpleCallSettings.Builder<RecognizeRequest, RecognizeResponse> recognizeSettings() {
return recognizeSettings;
}
/** Returns the builder for the settings used for calls to longRunningRecognize. */
public OperationCallSettings.Builder<LongRunningRecognizeRequest, LongRunningRecognizeResponse>
longRunningRecognizeSettings() {
return longRunningRecognizeSettings;
}
/** Returns the builder for the settings used for calls to streamingRecognize. */
public StreamingCallSettings.Builder<StreamingRecognizeRequest, StreamingRecognizeResponse>
streamingRecognizeSettings() {
return streamingRecognizeSettings;
}
@Override
public SpeechSettings build() throws IOException {
return new SpeechSettings(this);
}
}
}
| |
/*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.ivyde.internal.eclipse.cpcontainer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.ivy.core.module.descriptor.ModuleDescriptor;
import org.apache.ivyde.eclipse.IvyDEException;
import org.apache.ivyde.eclipse.cp.IvyClasspathContainer;
import org.apache.ivyde.eclipse.cp.IvyClasspathContainerConfiguration;
import org.apache.ivyde.eclipse.cp.IvyClasspathContainerHelper;
import org.apache.ivyde.eclipse.cp.SettingsSetup;
import org.apache.ivyde.internal.eclipse.IvyMarkerManager;
import org.apache.ivyde.internal.eclipse.IvyPlugin;
import org.apache.ivyde.internal.eclipse.ui.AdvancedSetupTab;
import org.apache.ivyde.internal.eclipse.ui.ClasspathSetupTab;
import org.apache.ivyde.internal.eclipse.ui.ConfTableViewer;
import org.apache.ivyde.internal.eclipse.ui.IvyFilePathText;
import org.apache.ivyde.internal.eclipse.ui.MappingSetupTab;
import org.apache.ivyde.internal.eclipse.ui.SettingsSetupTab;
import org.apache.ivyde.internal.eclipse.ui.ConfTableViewer.ConfTableListener;
import org.apache.ivyde.internal.eclipse.ui.IvyFilePathText.IvyXmlPathListener;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.jdt.core.IClasspathAttribute;
import org.eclipse.jdt.core.IClasspathContainer;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.wizards.IClasspathContainerPage;
import org.eclipse.jdt.ui.wizards.IClasspathContainerPageExtension;
import org.eclipse.jdt.ui.wizards.NewElementWizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
/**
* Editor of the classpath container configuration at the project level.
*/
public class IvydeContainerPage extends NewElementWizardPage implements IClasspathContainerPage,
IClasspathContainerPageExtension {
private IJavaProject project;
private IvyFilePathText ivyFilePathText;
private ConfTableViewer confTableViewer;
private IvyClasspathContainerConfiguration conf;
private IClasspathEntry entry;
private TabFolder tabs;
private boolean exported = false;
private String oldIvyFile = null;
private List<String> oldConfs = null;
private IvyClasspathContainerState state;
private SettingsSetupTab settingsSetupTab;
private ClasspathSetupTab classpathSetupTab;
private MappingSetupTab mappingSetupTab;
private AdvancedSetupTab advancedSetupTab;
/**
* Constructor
*/
public IvydeContainerPage() {
super("IvyDE Container");
}
public IJavaProject getProject() {
return project;
}
void checkCompleted() {
String error = null;
if (ivyFilePathText.getIvyFilePath().length() == 0) {
error = "Choose an Ivy file";
} else if (project != null) {
error = checkConf();
}
setErrorMessage(error);
setPageComplete(error == null);
}
/**
* Check that the chosen configuration doesn't already exist within the current project.
* <p>
* The uniqueness is for xmlivyPath + conf
* </p>
*
* @return String
*/
private String checkConf() {
String error = null;
String ivyFilePath = ivyFilePathText.getIvyFilePath();
List<String> selectedConfigurations = confTableViewer.getSelectedConfigurations();
List<IvyClasspathContainer> containers = IvyClasspathContainerHelper
.getContainers(project);
if (containers == null) {
return null;
}
for (IvyClasspathContainer container : containers) {
IvyClasspathContainerConfiguration cpc = container.getConf();
// first check that this is not the one we are editing
if (cpc.getIvyXmlPath().equals(oldIvyFile) && oldConfs != null
&& oldConfs.size() == cpc.getConfs().size()
&& oldConfs.containsAll(cpc.getConfs())) {
continue;
}
if (cpc.getIvyXmlPath().equals(ivyFilePath)) {
if (selectedConfigurations.isEmpty() || selectedConfigurations.contains("*")
|| cpc.getConfs().isEmpty() || cpc.getConfs().contains("*")) {
error = "A container already exists for the selected conf of "
+ "the module descriptor";
break;
} else {
List<String> list = new ArrayList<>(cpc.getConfs());
list.retainAll(selectedConfigurations);
if (!list.isEmpty()) {
error = "A container already exists for the selected conf of "
+ "the module descriptor";
break;
}
}
}
}
return error;
}
void checkIvyXmlPath() {
ModuleDescriptor md;
try {
md = state.getModuleDescriptor();
ivyFilePathText.setIvyXmlError(null);
} catch (IvyDEException e) {
md = null;
ivyFilePathText.setIvyXmlError(e);
}
confTableViewer.setModuleDescriptor(md);
checkCompleted();
}
public boolean finish() {
List<String> confs = confTableViewer.getSelectedConfigurations();
if (confs.isEmpty()) {
confs = Collections.singletonList("*");
}
conf.setConfs(confs);
if (settingsSetupTab.isProjectSpecific()) {
conf.setSettingsProjectSpecific(true);
conf.setIvySettingsSetup(settingsSetupTab.getSettingsEditor().getIvySettingsSetup());
} else {
conf.setSettingsProjectSpecific(false);
}
if (classpathSetupTab.isProjectSpecific()) {
conf.setClassthProjectSpecific(true);
conf.setClasspathSetup(classpathSetupTab.getClasspathSetupEditor().getClasspathSetup());
} else {
conf.setClassthProjectSpecific(false);
}
if (mappingSetupTab.isProjectSpecific()) {
conf.setMappingProjectSpecific(true);
conf.setMappingSetup(mappingSetupTab.getMappingSetupEditor().getMappingSetup());
} else {
conf.setMappingProjectSpecific(false);
}
if (advancedSetupTab.isProjectSpecific()) {
conf.setAdvancedProjectSpecific(true);
conf.setAdvancedSetup(advancedSetupTab.getAdvancedSetupEditor().getAdvancedSetup());
} else {
conf.setAdvancedProjectSpecific(false);
}
IPath path = IvyClasspathContainerConfAdapter.getPath(conf);
IClasspathAttribute[] atts = conf.getAttributes();
entry = JavaCore.newContainerEntry(path, null, atts, exported);
if (project != null) {
try {
IvyClasspathContainerImpl ivycp = new IvyClasspathContainerImpl(project, path,
new IClasspathEntry[0], atts);
JavaCore.setClasspathContainer(path, new IJavaProject[] {project},
new IClasspathContainer[] {ivycp}, null);
ivycp.launchResolve(false, null);
} catch (JavaModelException e) {
IvyPlugin.log(e);
}
}
if (conf.getJavaProject() != null && oldIvyFile != null
&& !oldIvyFile.equals(conf.getIvyXmlPath())) {
// changing the ivy.xml, remove old marker on the old file, if any
IvyMarkerManager ivyMarkerManager = IvyPlugin.getDefault().getIvyMarkerManager();
ivyMarkerManager.removeMarkers(conf.getJavaProject().getProject(), oldIvyFile);
}
return true;
}
public IClasspathEntry getSelection() {
return entry;
}
public void setSelection(IClasspathEntry entry) {
if (entry == null) {
conf = new IvyClasspathContainerConfiguration(project, "ivy.xml", true);
} else {
conf = new IvyClasspathContainerConfiguration(project, entry.getPath(), true,
entry.getExtraAttributes());
exported = entry.isExported();
}
state = new IvyClasspathContainerState(conf);
oldIvyFile = conf.getIvyXmlPath();
oldConfs = conf.getConfs();
}
public void setSelection(IFile ivyfile) {
conf = new IvyClasspathContainerConfiguration(project, ivyfile.getProjectRelativePath()
.toString(), true);
// if there is an ivysettings.xml file at the root of the project, configure the container
// to use it
if (project != null) {
IResource settings = project.getProject().findMember(new Path("ivysettings.xml"));
if (settings != null) {
conf.setSettingsProjectSpecific(true);
SettingsSetup setup = new SettingsSetup();
setup.setIvySettingsPath("ivysettings.xml");
conf.setIvySettingsSetup(setup);
}
}
state = new IvyClasspathContainerState(conf);
}
public void createControl(Composite parent) {
setTitle("IvyDE Managed Libraries");
setDescription("Choose Ivy file and its configurations.");
tabs = new TabFolder(parent, SWT.BORDER);
tabs.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, true));
TabItem mainTab = new TabItem(tabs, SWT.NONE);
mainTab.setText("Main");
mainTab.setControl(createMainTab(tabs));
IProject p = project == null ? null : project.getProject();
settingsSetupTab = new SettingsSetupTab(tabs, p) {
protected void settingsUpdated() {
try {
conf.setSettingsProjectSpecific(isProjectSpecific());
conf.setIvySettingsSetup(getSettingsEditor().getIvySettingsSetup());
state.setIvySettingsLastModified(-1);
state.getIvy();
getSettingsEditor().setSettingsError(null);
checkIvyXmlPath();
} catch (IvyDEException e) {
getSettingsEditor().setSettingsError(e);
}
}
};
classpathSetupTab = new ClasspathSetupTab(tabs, p);
mappingSetupTab = new MappingSetupTab(tabs, p);
advancedSetupTab = new AdvancedSetupTab(tabs, p);
tabs.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
ivyFilePathText.updateErrorMarker();
settingsSetupTab.getSettingsEditor().updateErrorMarker();
}
});
setControl(tabs);
loadFromConf();
checkCompleted();
tabs.setFocus();
}
private Control createMainTab(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout());
composite.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, true));
// CheckStyle:MagicNumber| OFF
Composite configComposite = new Composite(composite, SWT.NONE);
configComposite.setLayout(new GridLayout(2, false));
configComposite.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, true));
ivyFilePathText = new IvyFilePathText(configComposite, SWT.NONE, project == null ? null
: project.getProject());
ivyFilePathText.addListener(new IvyXmlPathListener() {
public void ivyXmlPathUpdated(String path) {
conf.setIvyXmlPath(path);
checkIvyXmlPath();
}
});
ivyFilePathText.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false, 2,
1));
// Label for ivy configurations field
Label confLabel = new Label(configComposite, SWT.NONE);
confLabel.setText("Configurations");
// table for configuration selection
confTableViewer = new ConfTableViewer(configComposite, SWT.NONE);
confTableViewer.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, true));
confTableViewer.addListener(new ConfTableListener() {
public void confTableUpdated(List<String> confs) {
checkCompleted();
}
});
// refresh
Button refreshConf = new Button(configComposite, SWT.NONE);
refreshConf.setLayoutData(new GridData(GridData.END, GridData.CENTER, true, false, 2, 1));
refreshConf.setText("Reload the list of configurations");
refreshConf.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent ev) {
ModuleDescriptor md;
try {
md = state.getModuleDescriptor();
} catch (IvyDEException e) {
md = null;
e.show(IStatus.ERROR, "Ivy configuration error",
"The configurations of the ivy.xml file could not be retrieved: ");
}
confTableViewer.setModuleDescriptor(md);
}
});
return composite;
}
private void loadFromConf() {
ivyFilePathText.init(conf.getIvyXmlPath());
settingsSetupTab.init(conf.isSettingsProjectSpecific(), conf.getIvySettingsSetup());
confTableViewer.init(conf.getConfs()); // *after* settingsSetupTab.init()!
classpathSetupTab.init(conf.isClassthProjectSpecific(), conf.getClasspathSetup());
mappingSetupTab.init(conf.isMappingProjectSpecific(), conf.getMappingSetup());
// project == null <==> container in a launch config: always resolve before launch
advancedSetupTab.init(conf.isAdvancedProjectSpecific(), conf.getAdvancedSetup(),
project == null);
settingsSetupTab.projectSpecificChanged();
classpathSetupTab.projectSpecificChanged();
mappingSetupTab.projectSpecificChanged();
advancedSetupTab.projectSpecificChanged();
}
public void initialize(IJavaProject p, IClasspathEntry[] currentEntries) {
this.project = p;
}
}
| |
/*
* 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.druid.query;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import org.apache.druid.guice.annotations.PublicApi;
import org.apache.druid.java.util.common.IAE;
import org.apache.druid.java.util.common.ISE;
import org.apache.druid.java.util.common.Numbers;
import org.apache.druid.java.util.common.StringUtils;
import org.apache.druid.segment.QueryableIndexStorageAdapter;
import java.util.concurrent.TimeUnit;
@PublicApi
public class QueryContexts
{
public static final String FINALIZE_KEY = "finalize";
public static final String PRIORITY_KEY = "priority";
public static final String LANE_KEY = "lane";
public static final String TIMEOUT_KEY = "timeout";
public static final String MAX_SCATTER_GATHER_BYTES_KEY = "maxScatterGatherBytes";
public static final String MAX_QUEUED_BYTES_KEY = "maxQueuedBytes";
public static final String DEFAULT_TIMEOUT_KEY = "defaultTimeout";
public static final String BROKER_PARALLEL_MERGE_KEY = "enableParallelMerge";
public static final String BROKER_PARALLEL_MERGE_INITIAL_YIELD_ROWS_KEY = "parallelMergeInitialYieldRows";
public static final String BROKER_PARALLEL_MERGE_SMALL_BATCH_ROWS_KEY = "parallelMergeSmallBatchRows";
public static final String BROKER_PARALLELISM = "parallelMergeParallelism";
public static final String VECTORIZE_KEY = "vectorize";
public static final String VECTORIZE_VIRTUAL_COLUMNS_KEY = "vectorizeVirtualColumns";
public static final String VECTOR_SIZE_KEY = "vectorSize";
public static final String MAX_SUBQUERY_ROWS_KEY = "maxSubqueryRows";
public static final String JOIN_FILTER_PUSH_DOWN_KEY = "enableJoinFilterPushDown";
public static final String JOIN_FILTER_REWRITE_ENABLE_KEY = "enableJoinFilterRewrite";
public static final String JOIN_FILTER_REWRITE_VALUE_COLUMN_FILTERS_ENABLE_KEY = "enableJoinFilterRewriteValueColumnFilters";
public static final String JOIN_FILTER_REWRITE_MAX_SIZE_KEY = "joinFilterRewriteMaxSize";
public static final String USE_FILTER_CNF_KEY = "useFilterCNF";
public static final String NUM_RETRIES_ON_MISSING_SEGMENTS_KEY = "numRetriesOnMissingSegments";
public static final String RETURN_PARTIAL_RESULTS_KEY = "returnPartialResults";
public static final String USE_CACHE_KEY = "useCache";
public static final String SECONDARY_PARTITION_PRUNING_KEY = "secondaryPartitionPruning";
public static final boolean DEFAULT_BY_SEGMENT = false;
public static final boolean DEFAULT_POPULATE_CACHE = true;
public static final boolean DEFAULT_USE_CACHE = true;
public static final boolean DEFAULT_POPULATE_RESULTLEVEL_CACHE = true;
public static final boolean DEFAULT_USE_RESULTLEVEL_CACHE = true;
public static final Vectorize DEFAULT_VECTORIZE = Vectorize.TRUE;
public static final Vectorize DEFAULT_VECTORIZE_VIRTUAL_COLUMN = Vectorize.FALSE;
public static final int DEFAULT_PRIORITY = 0;
public static final int DEFAULT_UNCOVERED_INTERVALS_LIMIT = 0;
public static final long DEFAULT_TIMEOUT_MILLIS = TimeUnit.MINUTES.toMillis(5);
public static final long NO_TIMEOUT = 0;
public static final boolean DEFAULT_ENABLE_PARALLEL_MERGE = true;
public static final boolean DEFAULT_ENABLE_JOIN_FILTER_PUSH_DOWN = true;
public static final boolean DEFAULT_ENABLE_JOIN_FILTER_REWRITE = true;
public static final boolean DEFAULT_ENABLE_JOIN_FILTER_REWRITE_VALUE_COLUMN_FILTERS = false;
public static final long DEFAULT_ENABLE_JOIN_FILTER_REWRITE_MAX_SIZE = 10000;
public static final boolean DEFAULT_USE_FILTER_CNF = false;
public static final boolean DEFAULT_SECONDARY_PARTITION_PRUNING = true;
@SuppressWarnings("unused") // Used by Jackson serialization
public enum Vectorize
{
FALSE {
@Override
public boolean shouldVectorize(final boolean canVectorize)
{
return false;
}
},
TRUE {
@Override
public boolean shouldVectorize(final boolean canVectorize)
{
return canVectorize;
}
},
FORCE {
@Override
public boolean shouldVectorize(final boolean canVectorize)
{
if (!canVectorize) {
throw new ISE("Cannot vectorize!");
}
return true;
}
};
public abstract boolean shouldVectorize(boolean canVectorize);
@JsonCreator
public static Vectorize fromString(String str)
{
return Vectorize.valueOf(StringUtils.toUpperCase(str));
}
@Override
@JsonValue
public String toString()
{
return StringUtils.toLowerCase(name()).replace('_', '-');
}
}
public static <T> boolean isBySegment(Query<T> query)
{
return isBySegment(query, DEFAULT_BY_SEGMENT);
}
public static <T> boolean isBySegment(Query<T> query, boolean defaultValue)
{
return parseBoolean(query, "bySegment", defaultValue);
}
public static <T> boolean isPopulateCache(Query<T> query)
{
return isPopulateCache(query, DEFAULT_POPULATE_CACHE);
}
public static <T> boolean isPopulateCache(Query<T> query, boolean defaultValue)
{
return parseBoolean(query, "populateCache", defaultValue);
}
public static <T> boolean isUseCache(Query<T> query)
{
return isUseCache(query, DEFAULT_USE_CACHE);
}
public static <T> boolean isUseCache(Query<T> query, boolean defaultValue)
{
return parseBoolean(query, USE_CACHE_KEY, defaultValue);
}
public static <T> boolean isPopulateResultLevelCache(Query<T> query)
{
return isPopulateResultLevelCache(query, DEFAULT_POPULATE_RESULTLEVEL_CACHE);
}
public static <T> boolean isPopulateResultLevelCache(Query<T> query, boolean defaultValue)
{
return parseBoolean(query, "populateResultLevelCache", defaultValue);
}
public static <T> boolean isUseResultLevelCache(Query<T> query)
{
return isUseResultLevelCache(query, DEFAULT_USE_RESULTLEVEL_CACHE);
}
public static <T> boolean isUseResultLevelCache(Query<T> query, boolean defaultValue)
{
return parseBoolean(query, "useResultLevelCache", defaultValue);
}
public static <T> boolean isFinalize(Query<T> query, boolean defaultValue)
{
return parseBoolean(query, FINALIZE_KEY, defaultValue);
}
public static <T> boolean isSerializeDateTimeAsLong(Query<T> query, boolean defaultValue)
{
return parseBoolean(query, "serializeDateTimeAsLong", defaultValue);
}
public static <T> boolean isSerializeDateTimeAsLongInner(Query<T> query, boolean defaultValue)
{
return parseBoolean(query, "serializeDateTimeAsLongInner", defaultValue);
}
public static <T> Vectorize getVectorize(Query<T> query)
{
return getVectorize(query, QueryContexts.DEFAULT_VECTORIZE);
}
public static <T> Vectorize getVectorize(Query<T> query, Vectorize defaultValue)
{
return parseEnum(query, VECTORIZE_KEY, Vectorize.class, defaultValue);
}
public static <T> Vectorize getVectorizeVirtualColumns(Query<T> query)
{
return getVectorizeVirtualColumns(query, QueryContexts.DEFAULT_VECTORIZE_VIRTUAL_COLUMN);
}
public static <T> Vectorize getVectorizeVirtualColumns(Query<T> query, Vectorize defaultValue)
{
return parseEnum(query, VECTORIZE_VIRTUAL_COLUMNS_KEY, Vectorize.class, defaultValue);
}
public static <T> int getVectorSize(Query<T> query)
{
return getVectorSize(query, QueryableIndexStorageAdapter.DEFAULT_VECTOR_SIZE);
}
public static <T> int getVectorSize(Query<T> query, int defaultSize)
{
return parseInt(query, VECTOR_SIZE_KEY, defaultSize);
}
public static <T> int getMaxSubqueryRows(Query<T> query, int defaultSize)
{
return parseInt(query, MAX_SUBQUERY_ROWS_KEY, defaultSize);
}
public static <T> int getUncoveredIntervalsLimit(Query<T> query)
{
return getUncoveredIntervalsLimit(query, DEFAULT_UNCOVERED_INTERVALS_LIMIT);
}
public static <T> int getUncoveredIntervalsLimit(Query<T> query, int defaultValue)
{
return parseInt(query, "uncoveredIntervalsLimit", defaultValue);
}
public static <T> int getPriority(Query<T> query)
{
return getPriority(query, DEFAULT_PRIORITY);
}
public static <T> int getPriority(Query<T> query, int defaultValue)
{
return parseInt(query, PRIORITY_KEY, defaultValue);
}
public static <T> String getLane(Query<T> query)
{
return (String) query.getContextValue(LANE_KEY);
}
public static <T> boolean getEnableParallelMerges(Query<T> query)
{
return parseBoolean(query, BROKER_PARALLEL_MERGE_KEY, DEFAULT_ENABLE_PARALLEL_MERGE);
}
public static <T> int getParallelMergeInitialYieldRows(Query<T> query, int defaultValue)
{
return parseInt(query, BROKER_PARALLEL_MERGE_INITIAL_YIELD_ROWS_KEY, defaultValue);
}
public static <T> int getParallelMergeSmallBatchRows(Query<T> query, int defaultValue)
{
return parseInt(query, BROKER_PARALLEL_MERGE_SMALL_BATCH_ROWS_KEY, defaultValue);
}
public static <T> int getParallelMergeParallelism(Query<T> query, int defaultValue)
{
return parseInt(query, BROKER_PARALLELISM, defaultValue);
}
public static <T> boolean getEnableJoinFilterRewriteValueColumnFilters(Query<T> query)
{
return parseBoolean(
query,
JOIN_FILTER_REWRITE_VALUE_COLUMN_FILTERS_ENABLE_KEY,
DEFAULT_ENABLE_JOIN_FILTER_REWRITE_VALUE_COLUMN_FILTERS
);
}
public static <T> long getJoinFilterRewriteMaxSize(Query<T> query)
{
return parseLong(query, JOIN_FILTER_REWRITE_MAX_SIZE_KEY, DEFAULT_ENABLE_JOIN_FILTER_REWRITE_MAX_SIZE);
}
public static <T> boolean getEnableJoinFilterPushDown(Query<T> query)
{
return parseBoolean(query, JOIN_FILTER_PUSH_DOWN_KEY, DEFAULT_ENABLE_JOIN_FILTER_PUSH_DOWN);
}
public static <T> boolean getEnableJoinFilterRewrite(Query<T> query)
{
return parseBoolean(query, JOIN_FILTER_REWRITE_ENABLE_KEY, DEFAULT_ENABLE_JOIN_FILTER_REWRITE);
}
public static <T> boolean isSecondaryPartitionPruningEnabled(Query<T> query)
{
return parseBoolean(query, SECONDARY_PARTITION_PRUNING_KEY, DEFAULT_SECONDARY_PARTITION_PRUNING);
}
public static <T> Query<T> withMaxScatterGatherBytes(Query<T> query, long maxScatterGatherBytesLimit)
{
Object obj = query.getContextValue(MAX_SCATTER_GATHER_BYTES_KEY);
if (obj == null) {
return query.withOverriddenContext(ImmutableMap.of(MAX_SCATTER_GATHER_BYTES_KEY, maxScatterGatherBytesLimit));
} else {
long curr = ((Number) obj).longValue();
if (curr > maxScatterGatherBytesLimit) {
throw new IAE(
"configured [%s = %s] is more than enforced limit of [%s].",
MAX_SCATTER_GATHER_BYTES_KEY,
curr,
maxScatterGatherBytesLimit
);
} else {
return query;
}
}
}
public static <T> Query<T> verifyMaxQueryTimeout(Query<T> query, long maxQueryTimeout)
{
long timeout = getTimeout(query);
if (timeout > maxQueryTimeout) {
throw new IAE(
"configured [%s = %s] is more than enforced limit of maxQueryTimeout [%s].",
TIMEOUT_KEY,
timeout,
maxQueryTimeout
);
} else {
return query;
}
}
public static <T> long getMaxQueuedBytes(Query<T> query, long defaultValue)
{
return parseLong(query, MAX_QUEUED_BYTES_KEY, defaultValue);
}
public static <T> long getMaxScatterGatherBytes(Query<T> query)
{
return parseLong(query, MAX_SCATTER_GATHER_BYTES_KEY, Long.MAX_VALUE);
}
public static <T> boolean hasTimeout(Query<T> query)
{
return getTimeout(query) != NO_TIMEOUT;
}
public static <T> long getTimeout(Query<T> query)
{
return getTimeout(query, getDefaultTimeout(query));
}
public static <T> long getTimeout(Query<T> query, long defaultTimeout)
{
final long timeout = parseLong(query, TIMEOUT_KEY, defaultTimeout);
Preconditions.checkState(timeout >= 0, "Timeout must be a non negative value, but was [%s]", timeout);
return timeout;
}
public static <T> Query<T> withTimeout(Query<T> query, long timeout)
{
return query.withOverriddenContext(ImmutableMap.of(TIMEOUT_KEY, timeout));
}
public static <T> Query<T> withDefaultTimeout(Query<T> query, long defaultTimeout)
{
return query.withOverriddenContext(ImmutableMap.of(QueryContexts.DEFAULT_TIMEOUT_KEY, defaultTimeout));
}
static <T> long getDefaultTimeout(Query<T> query)
{
final long defaultTimeout = parseLong(query, DEFAULT_TIMEOUT_KEY, DEFAULT_TIMEOUT_MILLIS);
Preconditions.checkState(defaultTimeout >= 0, "Timeout must be a non negative value, but was [%s]", defaultTimeout);
return defaultTimeout;
}
public static <T> int getNumRetriesOnMissingSegments(Query<T> query, int defaultValue)
{
return query.getContextValue(NUM_RETRIES_ON_MISSING_SEGMENTS_KEY, defaultValue);
}
public static <T> boolean allowReturnPartialResults(Query<T> query, boolean defaultValue)
{
return query.getContextBoolean(RETURN_PARTIAL_RESULTS_KEY, defaultValue);
}
static <T> long parseLong(Query<T> query, String key, long defaultValue)
{
final Object val = query.getContextValue(key);
return val == null ? defaultValue : Numbers.parseLong(val);
}
static <T> int parseInt(Query<T> query, String key, int defaultValue)
{
final Object val = query.getContextValue(key);
return val == null ? defaultValue : Numbers.parseInt(val);
}
static <T> boolean parseBoolean(Query<T> query, String key, boolean defaultValue)
{
final Object val = query.getContextValue(key);
return val == null ? defaultValue : Numbers.parseBoolean(val);
}
private QueryContexts()
{
}
static <T, E extends Enum<E>> E parseEnum(Query<T> query, String key, Class<E> clazz, E defaultValue)
{
Object val = query.getContextValue(key);
if (val == null) {
return defaultValue;
}
if (val instanceof String) {
return Enum.valueOf(clazz, StringUtils.toUpperCase((String) val));
} else if (val instanceof Boolean) {
return Enum.valueOf(clazz, StringUtils.toUpperCase(String.valueOf(val)));
} else {
throw new ISE("Unknown type [%s]. Cannot parse!", val.getClass());
}
}
}
| |
/*
* Copyright 2011-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.lambdaworks.redis.protocol;
import static com.lambdaworks.redis.protocol.LettuceCharsets.buffer;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.junit.Before;
import org.junit.Test;
import com.lambdaworks.redis.*;
import com.lambdaworks.redis.codec.RedisCodec;
import com.lambdaworks.redis.codec.Utf8StringCodec;
import com.lambdaworks.redis.output.CommandOutput;
import com.lambdaworks.redis.output.StatusOutput;
public class AsyncCommandInternalsTest {
protected RedisCodec<String, String> codec = new Utf8StringCodec();
protected Command<String, String, String> internal;
protected AsyncCommand<String, String, String> sut;
@Before
public final void createCommand() throws Exception {
CommandOutput<String, String, String> output = new StatusOutput<>(codec);
internal = new Command<>(CommandType.INFO, output, null);
sut = new AsyncCommand<>(internal);
}
@Test
public void isCancelled() throws Exception {
assertThat(sut.isCancelled()).isFalse();
assertThat(sut.cancel(true)).isTrue();
assertThat(sut.isCancelled()).isTrue();
assertThat(sut.cancel(true)).isTrue();
}
@Test
public void isDone() throws Exception {
assertThat(sut.isDone()).isFalse();
sut.complete();
assertThat(sut.isDone()).isTrue();
}
@Test
public void awaitAllCompleted() throws Exception {
sut.complete();
assertThat(LettuceFutures.awaitAll(5, TimeUnit.MILLISECONDS, sut)).isTrue();
}
@Test
public void awaitAll() throws Exception {
assertThat(LettuceFutures.awaitAll(-1, TimeUnit.NANOSECONDS, sut)).isFalse();
}
@Test(expected = RedisCommandTimeoutException.class)
public void awaitNotCompleted() throws Exception {
LettuceFutures.awaitOrCancel(sut, 0, TimeUnit.NANOSECONDS);
}
@Test(expected = RedisException.class)
public void awaitWithExecutionException() throws Exception {
sut.completeExceptionally(new RedisException("error"));
LettuceFutures.awaitOrCancel(sut, 1, TimeUnit.SECONDS);
}
@Test(expected = CancellationException.class)
public void awaitWithCancelledCommand() throws Exception {
sut.cancel();
LettuceFutures.awaitOrCancel(sut, 5, TimeUnit.SECONDS);
}
@Test(expected = RedisException.class)
public void awaitAllWithExecutionException() throws Exception {
sut.completeExceptionally(new RedisCommandExecutionException("error"));
assertThat(LettuceFutures.awaitAll(0, TimeUnit.SECONDS, sut));
}
@Test
public void getError() throws Exception {
sut.getOutput().setError("error");
assertThat(internal.getError()).isEqualTo("error");
}
@Test(expected = ExecutionException.class)
public void getErrorAsync() throws Exception {
sut.getOutput().setError("error");
sut.complete();
sut.get();
}
@Test(expected = ExecutionException.class)
public void completeExceptionally() throws Exception {
sut.completeExceptionally(new RuntimeException("test"));
assertThat(internal.getError()).isEqualTo("test");
sut.get();
}
@Test
public void asyncGet() throws Exception {
sut.getOutput().set(buffer("one"));
sut.complete();
assertThat(sut.get()).isEqualTo("one");
sut.getOutput().toString();
}
@Test
public void customKeyword() throws Exception {
sut = new AsyncCommand<>(
new Command<>(MyKeywords.DUMMY, new StatusOutput<>(codec), null));
assertThat(sut.toString()).contains(MyKeywords.DUMMY.name());
}
@Test
public void customKeywordWithArgs() throws Exception {
sut = new AsyncCommand<>(
new Command<String, String, String>(MyKeywords.DUMMY, null, new CommandArgs<>(codec)));
sut.getArgs().add(MyKeywords.DUMMY);
assertThat(sut.getArgs().toString()).contains(MyKeywords.DUMMY.name());
}
@Test
public void getWithTimeout() throws Exception {
sut.getOutput().set(buffer("one"));
sut.complete();
assertThat(sut.get(0, TimeUnit.MILLISECONDS)).isEqualTo("one");
}
@Test(expected = TimeoutException.class, timeout = 100)
public void getTimeout() throws Exception {
assertThat(sut.get(2, TimeUnit.MILLISECONDS)).isNull();
}
@Test(timeout = 100)
public void awaitTimeout() throws Exception {
assertThat(sut.await(2, TimeUnit.MILLISECONDS)).isFalse();
}
@Test(expected = InterruptedException.class, timeout = 100)
public void getInterrupted() throws Exception {
Thread.currentThread().interrupt();
sut.get();
}
@Test(expected = InterruptedException.class, timeout = 100)
public void getInterrupted2() throws Exception {
Thread.currentThread().interrupt();
sut.get(5, TimeUnit.MILLISECONDS);
}
@Test(expected = RedisCommandInterruptedException.class, timeout = 100)
public void awaitInterrupted2() throws Exception {
Thread.currentThread().interrupt();
sut.await(5, TimeUnit.MILLISECONDS);
}
@Test(expected = IllegalStateException.class)
public void outputSubclassOverride1() {
CommandOutput<String, String, String> output = new CommandOutput<String, String, String>(codec, null) {
@Override
public String get() throws RedisException {
return null;
}
};
output.set(null);
}
@Test(expected = IllegalStateException.class)
public void outputSubclassOverride2() {
CommandOutput<String, String, String> output = new CommandOutput<String, String, String>(codec, null) {
@Override
public String get() throws RedisException {
return null;
}
};
output.set(0);
}
@Test
public void sillyTestsForEmmaCoverage() throws Exception {
assertThat(CommandType.valueOf("APPEND")).isEqualTo(CommandType.APPEND);
assertThat(CommandKeyword.valueOf("AFTER")).isEqualTo(CommandKeyword.AFTER);
}
private enum MyKeywords implements ProtocolKeyword {
DUMMY;
@Override
public byte[] getBytes() {
return name().getBytes();
}
}
}
| |
/*
* 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.deltaspike.scheduler.impl;
import org.apache.deltaspike.cdise.api.ContextControl;
import org.apache.deltaspike.core.api.provider.BeanProvider;
import org.apache.deltaspike.core.api.provider.DependentProvider;
import org.apache.deltaspike.core.util.ClassUtils;
import org.apache.deltaspike.core.util.ExceptionUtils;
import org.apache.deltaspike.core.util.PropertyFileUtils;
import org.apache.deltaspike.core.util.ProxyUtils;
import org.apache.deltaspike.core.util.metadata.AnnotationInstanceProvider;
import org.apache.deltaspike.scheduler.api.Scheduled;
import org.apache.deltaspike.scheduler.spi.Scheduler;
import org.quartz.CronScheduleBuilder;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobKey;
import org.quartz.JobListener;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.Stack;
import java.util.logging.Level;
import java.util.logging.Logger;
//vetoed class (see SchedulerExtension)
public class QuartzScheduler implements Scheduler<Job>
{
private static final Logger LOG = Logger.getLogger(QuartzScheduler.class.getName());
private static final Scheduled DEFAULT_SCHEDULED_LITERAL = AnnotationInstanceProvider.of(Scheduled.class);
private static ThreadLocal<JobListenerContext> currentJobListenerContext = new ThreadLocal<JobListenerContext>();
protected org.quartz.Scheduler scheduler;
@Override
public void start()
{
if (this.scheduler != null)
{
throw new UnsupportedOperationException("the scheduler is started already");
}
SchedulerFactory schedulerFactory = null;
try
{
Properties properties = new Properties();
properties.put(StdSchedulerFactory.PROP_SCHED_JOB_FACTORY_CLASS, CdiAwareJobFactory.class.getName());
try
{
ResourceBundle config = loadCustomQuartzConfig();
Enumeration<String> keys = config.getKeys();
String key;
while (keys.hasMoreElements())
{
key = keys.nextElement();
properties.put(key, config.getString(key));
}
}
catch (Exception e1)
{
LOG.info("no custom quartz-config file found. falling back to the default config provided by quartz.");
InputStream inputStream = null;
try
{
inputStream = ClassUtils.getClassLoader(null).getResourceAsStream("org/quartz/quartz.properties");
properties.load(inputStream);
}
catch (Exception e2)
{
LOG.warning("failed to load quartz default-config");
schedulerFactory = new StdSchedulerFactory();
}
finally
{
if (inputStream != null)
{
inputStream.close();
}
}
}
if (schedulerFactory == null)
{
schedulerFactory = new StdSchedulerFactory(properties);
}
}
catch (Exception e)
{
LOG.log(Level.WARNING, "fallback to default scheduler-factory", e);
schedulerFactory = new StdSchedulerFactory();
}
try
{
this.scheduler = schedulerFactory.getScheduler();
if (SchedulerBaseConfig.LifecycleIntegration.START_SCOPES_PER_JOB)
{
this.scheduler.getListenerManager().addJobListener(new InjectionAwareJobListener());
}
if (!this.scheduler.isStarted())
{
this.scheduler.startDelayed(SchedulerBaseConfig.LifecycleIntegration.DELAYED_START_IN_SECONDS);
}
}
catch (SchedulerException e)
{
throw ExceptionUtils.throwAsRuntimeException(e);
}
}
protected ResourceBundle loadCustomQuartzConfig()
{
//don't use quartz.properties as default-value
String configFile = SchedulerBaseConfig.SCHEDULER_CONFIG_FILE;
return PropertyFileUtils.getResourceBundle(configFile);
}
@Override
public void stop()
{
try
{
if (this.scheduler != null && this.scheduler.isStarted())
{
this.scheduler.shutdown(SchedulerBaseConfig.LifecycleIntegration.FORCE_STOP);
this.scheduler = null;
}
}
catch (SchedulerException e)
{
throw ExceptionUtils.throwAsRuntimeException(e);
}
}
@Override
public void registerNewJob(Class<? extends Job> jobClass)
{
JobKey jobKey = createJobKey(jobClass);
try
{
Scheduled scheduled = jobClass.getAnnotation(Scheduled.class);
String description = scheduled.description();
if ("".equals(scheduled.description()))
{
description = jobClass.getName();
}
JobDetail jobDetail = this.scheduler.getJobDetail(jobKey);
Trigger trigger;
if (jobDetail == null)
{
jobDetail = JobBuilder.newJob(jobClass)
.withDescription(description)
.withIdentity(jobKey)
.build();
trigger = TriggerBuilder.newTrigger()
.withSchedule(CronScheduleBuilder.cronSchedule(scheduled.cronExpression()))
.build();
this.scheduler.scheduleJob(jobDetail, trigger);
}
else if (scheduled.overrideOnStartup())
{
List<? extends Trigger> existingTriggers = this.scheduler.getTriggersOfJob(jobKey);
if (existingTriggers == null || existingTriggers.isEmpty())
{
//TODO re-visit it
trigger = TriggerBuilder.newTrigger()
.withSchedule(CronScheduleBuilder.cronSchedule(scheduled.cronExpression()))
.build();
this.scheduler.scheduleJob(jobDetail, trigger);
return;
}
if (existingTriggers.size() > 1)
{
throw new IllegalStateException("multiple triggers found for " + jobKey + " ('" + jobDetail + "')" +
", but aren't supported by @" + Scheduled.class.getName() + "#overrideOnStartup");
}
trigger = existingTriggers.iterator().next();
trigger = TriggerBuilder.newTrigger()
.withIdentity(trigger.getKey())
.withSchedule(CronScheduleBuilder.cronSchedule(scheduled.cronExpression()))
.build();
this.scheduler.rescheduleJob(trigger.getKey(), trigger);
}
else
{
Logger.getLogger(QuartzScheduler.class.getName()).info(jobKey + " exists already and will be ignored.");
}
}
catch (SchedulerException e)
{
throw ExceptionUtils.throwAsRuntimeException(e);
}
}
@Override
public void startJobManually(Class<? extends Job> jobClass)
{
try
{
this.scheduler.triggerJob(createJobKey(jobClass));
}
catch (SchedulerException e)
{
throw ExceptionUtils.throwAsRuntimeException(e);
}
}
@Override
public void interruptJob(Class<? extends Job> jobClass)
{
try
{
this.scheduler.interrupt(createJobKey(jobClass));
}
catch (SchedulerException e)
{
throw ExceptionUtils.throwAsRuntimeException(e);
}
}
@Override
public boolean deleteJob(Class<? extends Job> jobClass)
{
try
{
return this.scheduler.deleteJob(createJobKey(jobClass));
}
catch (SchedulerException e)
{
throw ExceptionUtils.throwAsRuntimeException(e);
}
}
@Override
public void pauseJob(Class<? extends Job> jobClass)
{
try
{
this.scheduler.pauseJob(createJobKey(jobClass));
}
catch (SchedulerException e)
{
throw ExceptionUtils.throwAsRuntimeException(e);
}
}
@Override
public void resumeJob(Class<? extends Job> jobClass)
{
try
{
this.scheduler.resumeJob(createJobKey(jobClass));
}
catch (SchedulerException e)
{
throw ExceptionUtils.throwAsRuntimeException(e);
}
}
@Override
public boolean isExecutingJob(Class<? extends Job> jobClass)
{
try
{
JobKey jobKey = createJobKey(jobClass);
JobDetail jobDetail = this.scheduler.getJobDetail(jobKey);
if (jobDetail == null)
{
return false;
}
for (JobExecutionContext jobExecutionContext : this.scheduler.getCurrentlyExecutingJobs())
{
if (jobKey.equals(jobExecutionContext.getJobDetail().getKey()))
{
return true;
}
}
return false;
}
catch (SchedulerException e)
{
throw ExceptionUtils.throwAsRuntimeException(e);
}
}
private static JobKey createJobKey(Class<?> jobClass)
{
Scheduled scheduled = jobClass.getAnnotation(Scheduled.class);
if (scheduled == null)
{
throw new IllegalStateException("@" + Scheduled.class.getName() + " is missing on " + jobClass.getName());
}
String groupName = scheduled.group().getSimpleName();
String jobName = jobClass.getSimpleName();
if (!Scheduled.class.getSimpleName().equals(groupName))
{
return new JobKey(jobName, groupName);
}
return new JobKey(jobName);
}
private class InjectionAwareJobListener implements JobListener
{
@Override
public String getName()
{
return getClass().getName();
}
@Override
public void jobToBeExecuted(JobExecutionContext jobExecutionContext)
{
Class<?> jobClass = ProxyUtils.getUnproxiedClass(jobExecutionContext.getJobInstance().getClass());
Scheduled scheduled = jobClass.getAnnotation(Scheduled.class);
//can happen with manually registered job-instances (via #unwrap)
if (scheduled == null)
{
scheduled = DEFAULT_SCHEDULED_LITERAL;
}
JobListenerContext jobListenerContext = new JobListenerContext();
currentJobListenerContext.set(jobListenerContext);
jobListenerContext.startContexts(scheduled);
boolean jobInstanceIsBean;
try
{
jobInstanceIsBean =
Boolean.TRUE.equals(jobExecutionContext.getScheduler().getContext().get(jobClass.getName()));
}
catch (SchedulerException e)
{
jobInstanceIsBean = false;
}
if (!jobInstanceIsBean)
{
BeanProvider.injectFields(jobExecutionContext.getJobInstance());
}
}
@Override
public void jobExecutionVetoed(JobExecutionContext context)
{
stopStartedScopes();
}
@Override
public void jobWasExecuted(JobExecutionContext context, JobExecutionException jobException)
{
stopStartedScopes();
}
private void stopStartedScopes()
{
JobListenerContext jobListenerContext = currentJobListenerContext.get();
if (jobListenerContext != null)
{
jobListenerContext.stopStartedScopes();
currentJobListenerContext.set(null);
currentJobListenerContext.remove();
}
}
}
private class JobListenerContext
{
private Stack<Class<? extends Annotation>> scopes = new Stack<Class<? extends Annotation>>();
private DependentProvider<ContextControl> contextControl;
public void startContexts(Scheduled scheduled)
{
Collections.addAll(this.scopes, scheduled.startScopes());
if (!this.scopes.isEmpty())
{
this.contextControl = BeanProvider.getDependent(ContextControl.class);
for (Class<? extends Annotation> scopeAnnotation : this.scopes)
{
contextControl.get().startContext(scopeAnnotation);
}
}
}
private void stopStartedScopes()
{
while (!this.scopes.empty())
{
this.contextControl.get().stopContext(this.scopes.pop());
}
this.contextControl.destroy();
}
}
@Override
public <S> S unwrap(Class<? extends S> schedulerClass)
{
if (schedulerClass.isAssignableFrom(this.scheduler.getClass()))
{
return (S)this.scheduler;
}
throw new IllegalArgumentException(schedulerClass.getName() +
" isn't compatible with " + this.scheduler.getClass().getName());
}
}
| |
/*
* Copyright 2013-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.rules;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.facebook.buck.io.ProjectFilesystem;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.model.BuildTargetFactory;
import com.facebook.buck.model.BuildTargetPattern;
import com.facebook.buck.parser.NoSuchBuildTargetException;
import com.facebook.buck.testutil.FakeProjectFilesystem;
import com.google.common.base.Functions;
import com.google.common.base.Optional;
import com.google.common.base.Throwables;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.junit.Before;
import org.junit.Test;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.Set;
@SuppressWarnings("unused") // Many unused fields in sample DTO objects.
public class ConstructorArgMarshallerTest {
private Path basePath;
private ConstructorArgMarshaller marshaller;
private BuildRuleResolver ruleResolver;
private ProjectFilesystem filesystem;
@Before
public void setUpInspector() {
basePath = Paths.get("example", "path");
marshaller = new ConstructorArgMarshaller();
ruleResolver = new BuildRuleResolver();
filesystem = new FakeProjectFilesystem();
}
@Test
public void shouldNotPopulateAnEmptyArg() throws NoSuchBuildTargetException {
class Dto {
}
Dto dto = new Dto();
try {
marshaller.populate(
filesystem,
buildRuleFactoryParams(),
dto,
ImmutableSet.<BuildTarget>builder(),
ImmutableSet.<BuildTargetPattern>builder(),
ImmutableMap.<String, Object>of());
} catch (RuntimeException | ConstructorArgMarshalException e) {
fail("Did not expect an exception to be thrown:\n" + Throwables.getStackTraceAsString(e));
}
}
@Test
public void shouldPopulateAStringValue()
throws ConstructorArgMarshalException, NoSuchBuildTargetException {
class Dto {
public String name;
}
Dto dto = new Dto();
marshaller.populate(
filesystem,
buildRuleFactoryParams(),
dto,
ImmutableSet.<BuildTarget>builder(),
ImmutableSet.<BuildTargetPattern>builder(),
ImmutableMap.<String, Object>of("name", "cheese"));
assertEquals("cheese", dto.name);
}
@Test
public void shouldPopulateABooleanValue()
throws ConstructorArgMarshalException, NoSuchBuildTargetException {
class Dto {
public boolean value;
}
Dto dto = new Dto();
marshaller.populate(
filesystem,
buildRuleFactoryParams(),
dto,
ImmutableSet.<BuildTarget>builder(),
ImmutableSet.<BuildTargetPattern>builder(),
ImmutableMap.<String, Object>of("value", true));
assertTrue(dto.value);
}
@Test
public void shouldPopulateBuildTargetValues()
throws ConstructorArgMarshalException, NoSuchBuildTargetException {
class Dto {
public BuildTarget target;
public BuildTarget local;
}
Dto dto = new Dto();
marshaller.populate(
filesystem,
buildRuleFactoryParams(),
dto,
ImmutableSet.<BuildTarget>builder(),
ImmutableSet.<BuildTargetPattern>builder(),
ImmutableMap.<String, Object>of(
"target", "//cake:walk",
"local", ":fish"
));
assertEquals(BuildTargetFactory.newInstance("//cake:walk"), dto.target);
assertEquals(BuildTargetFactory.newInstance("//example/path:fish"), dto.local);
}
@Test
public void shouldPopulateANumericValue()
throws ConstructorArgMarshalException, NoSuchBuildTargetException {
class Dto {
public long number;
}
Dto dto = new Dto();
marshaller.populate(
filesystem,
buildRuleFactoryParams(),
dto,
ImmutableSet.<BuildTarget>builder(),
ImmutableSet.<BuildTargetPattern>builder(),
ImmutableMap.<String, Object>of("number", 42L));
assertEquals(42, dto.number);
}
@Test
public void shouldPopulateAPathValue()
throws ConstructorArgMarshalException, NoSuchBuildTargetException {
class Dto {
@Hint(name = "some_path")
public Path somePath;
}
Dto dto = new Dto();
marshaller.populate(
filesystem,
buildRuleFactoryParams(),
dto,
ImmutableSet.<BuildTarget>builder(),
ImmutableSet.<BuildTargetPattern>builder(),
ImmutableMap.<String, Object>of("somePath", "Fish.java"));
assertEquals(Paths.get("example/path", "Fish.java"), dto.somePath);
}
@Test
public void shouldPopulateSourcePaths()
throws ConstructorArgMarshalException, NoSuchBuildTargetException {
class Dto {
public SourcePath filePath;
public SourcePath targetPath;
}
ProjectFilesystem projectFilesystem = new FakeProjectFilesystem();
BuildTarget target = BuildTargetFactory.newInstance("//example/path:peas");
FakeBuildRule rule = new FakeBuildRule(
target,
new SourcePathResolver(new BuildRuleResolver()));
ruleResolver.addToIndex(rule);
Dto dto = new Dto();
marshaller.populate(
filesystem,
buildRuleFactoryParams(),
dto,
ImmutableSet.<BuildTarget>builder(),
ImmutableSet.<BuildTargetPattern>builder(),
ImmutableMap.<String, Object>of(
"filePath", "cheese.txt",
"targetPath", ":peas"
));
assertEquals(
new PathSourcePath(projectFilesystem, Paths.get("example/path/cheese.txt")),
dto.filePath);
assertEquals(
new BuildTargetSourcePath(rule.getBuildTarget()),
dto.targetPath);
}
@Test
public void shouldPopulateAnImmutableSortedSet()
throws ConstructorArgMarshalException, NoSuchBuildTargetException {
class Dto {
public ImmutableSortedSet<BuildTarget> deps;
}
BuildTarget t1 = BuildTargetFactory.newInstance("//please/go:here");
BuildTarget t2 = BuildTargetFactory.newInstance("//example/path:there");
Dto dto = new Dto();
// Note: the ordering is reversed from the natural ordering
marshaller.populate(
filesystem,
buildRuleFactoryParams(),
dto,
ImmutableSet.<BuildTarget>builder(),
ImmutableSet.<BuildTargetPattern>builder(),
ImmutableMap.<String, Object>of("deps", ImmutableList.of("//please/go:here", ":there")));
assertEquals(ImmutableSortedSet.of(t2, t1), dto.deps);
}
@Test
public void shouldPopulateSets()
throws ConstructorArgMarshalException, NoSuchBuildTargetException {
class Dto {
public Set<Path> paths;
}
Dto dto = new Dto();
marshaller.populate(
filesystem,
buildRuleFactoryParams(),
dto,
ImmutableSet.<BuildTarget>builder(),
ImmutableSet.<BuildTargetPattern>builder(),
ImmutableMap.<String, Object>of("paths", ImmutableList.of("one", "two")));
assertEquals(
ImmutableSet.of(Paths.get("example/path/one"), Paths.get("example/path/two")),
dto.paths);
}
@Test
public void shouldPopulateLists()
throws ConstructorArgMarshalException, NoSuchBuildTargetException {
class Dto {
public List<String> list;
}
Dto dto = new Dto();
marshaller.populate(
filesystem,
buildRuleFactoryParams(),
dto,
ImmutableSet.<BuildTarget>builder(),
ImmutableSet.<BuildTargetPattern>builder(),
ImmutableMap.<String, Object>of("list", ImmutableList.of("alpha", "beta")));
assertEquals(ImmutableList.of("alpha", "beta"), dto.list);
}
@Test
public void collectionsCanBeOptionalAndWillBeSetToAnOptionalEmptyCollectionIfMissing()
throws ConstructorArgMarshalException, NoSuchBuildTargetException {
class Dto {
public Optional<Set<BuildTarget>> targets;
}
Dto dto = new Dto();
Map<String, Object> args = Maps.newHashMap();
args.put("targets", Lists.newArrayList());
marshaller.populate(
filesystem,
buildRuleFactoryParams(),
dto,
ImmutableSet.<BuildTarget>builder(),
ImmutableSet.<BuildTargetPattern>builder(),
args);
assertEquals(Optional.of((Set<BuildTarget>) Sets.<BuildTarget>newHashSet()), dto.targets);
}
@Test
public void optionalCollectionsWithoutAValueWillBeSetToAnEmptyOptionalCollection()
throws ConstructorArgMarshalException, NoSuchBuildTargetException {
class Dto {
public Optional<Set<String>> strings;
}
Dto dto = new Dto();
Map<String, Object> args = Maps.newHashMap();
// Deliberately not populating args
marshaller.populate(
filesystem,
buildRuleFactoryParams(),
dto,
ImmutableSet.<BuildTarget>builder(),
ImmutableSet.<BuildTargetPattern>builder(),
args);
assertEquals(Optional.of((Set<String>) Sets.<String>newHashSet()), dto.strings);
}
@Test(expected = ConstructorArgMarshalException.class)
public void shouldBeAnErrorToAttemptToSetASingleValueToACollection()
throws ConstructorArgMarshalException, NoSuchBuildTargetException {
class Dto {
public String file;
}
Dto dto = new Dto();
marshaller.populate(
filesystem,
buildRuleFactoryParams(),
dto,
ImmutableSet.<BuildTarget>builder(),
ImmutableSet.<BuildTargetPattern>builder(),
ImmutableMap.<String, Object>of("file", ImmutableList.of("a", "b")));
}
@Test(expected = ConstructorArgMarshalException.class)
public void shouldBeAnErrorToAttemptToSetACollectionToASingleValue()
throws ConstructorArgMarshalException, NoSuchBuildTargetException {
class Dto {
public Set<String> strings;
}
Dto dto = new Dto();
marshaller.populate(
filesystem,
buildRuleFactoryParams(),
dto,
ImmutableSet.<BuildTarget>builder(),
ImmutableSet.<BuildTargetPattern>builder(),
ImmutableMap.<String, Object>of("strings", "isn't going to happen"));
}
@Test(expected = ConstructorArgMarshalException.class)
public void shouldBeAnErrorToSetTheWrongTypeOfValueInACollection()
throws ConstructorArgMarshalException, NoSuchBuildTargetException {
class Dto {
public Set<String> strings;
}
Dto dto = new Dto();
marshaller.populate(
filesystem,
buildRuleFactoryParams(),
dto,
ImmutableSet.<BuildTarget>builder(),
ImmutableSet.<BuildTargetPattern>builder(),
ImmutableMap.<String, Object>of("strings", ImmutableSet.of(true, false)));
}
@Test
public void shouldNormalizePaths()
throws ConstructorArgMarshalException, NoSuchBuildTargetException {
class Dto {
public Path path;
}
Dto dto = new Dto();
marshaller.populate(
filesystem,
buildRuleFactoryParams(),
dto,
ImmutableSet.<BuildTarget>builder(),
ImmutableSet.<BuildTargetPattern>builder(),
ImmutableMap.<String, Object>of("path", "./bar/././fish.txt"));
assertEquals(basePath.resolve("bar/fish.txt").normalize(), dto.path);
}
@Test(expected = RuntimeException.class)
public void lowerBoundGenericTypesCauseAnException()
throws ConstructorArgMarshalException, NoSuchBuildTargetException {
class Dto {
public List<? super BuildTarget> nope;
}
marshaller.populate(
filesystem,
buildRuleFactoryParams(),
new Dto(),
ImmutableSet.<BuildTarget>builder(),
ImmutableSet.<BuildTargetPattern>builder(),
ImmutableMap.<String, Object>of("nope", ImmutableList.of("//will/not:happen")));
}
public void shouldSetBuildTargetParameters()
throws ConstructorArgMarshalException, NoSuchBuildTargetException {
class Dto {
public BuildTarget single;
public BuildTarget sameBuildFileTarget;
public List<BuildTarget> targets;
}
Dto dto = new Dto();
marshaller.populate(
filesystem,
buildRuleFactoryParams(),
dto,
ImmutableSet.<BuildTarget>builder(),
ImmutableSet.<BuildTargetPattern>builder(),
ImmutableMap.<String, Object>of(
"single", "//com/example:cheese",
"sameBuildFileTarget", ":cake",
"targets", ImmutableList.of(":cake", "//com/example:cheese")
));
BuildTarget cheese = BuildTargetFactory.newInstance("//com/example:cheese");
BuildTarget cake = BuildTargetFactory.newInstance("//example/path:cake");
assertEquals(cheese, dto.single);
assertEquals(cake, dto.sameBuildFileTarget);
assertEquals(ImmutableList.of(cake, cheese), dto.targets);
}
@Test
public void upperBoundGenericTypesCauseValuesToBeSetToTheUpperBound()
throws ConstructorArgMarshalException, NoSuchBuildTargetException {
class Dto {
public List<? extends SourcePath> yup;
}
ProjectFilesystem projectFilesystem = new FakeProjectFilesystem();
SourcePathResolver pathResolver = new SourcePathResolver(new BuildRuleResolver());
BuildRule rule = new FakeBuildRule(
BuildTargetFactory.newInstance("//will:happen"), pathResolver);
ruleResolver.addToIndex(rule);
Dto dto = new Dto();
marshaller.populate(
filesystem,
buildRuleFactoryParams(),
dto,
ImmutableSet.<BuildTarget>builder(),
ImmutableSet.<BuildTargetPattern>builder(),
ImmutableMap.<String, Object>of(
"yup",
ImmutableList.of(rule.getBuildTarget().getFullyQualifiedName())));
BuildTargetSourcePath path = new BuildTargetSourcePath(rule.getBuildTarget());
assertEquals(ImmutableList.of(path), dto.yup);
}
@Test
public void specifyingZeroIsNotConsideredOptional()
throws ConstructorArgMarshalException, NoSuchBuildTargetException {
class Dto {
public Optional<Integer> number;
}
Dto dto = new Dto();
marshaller.populate(
filesystem,
buildRuleFactoryParams(),
dto,
ImmutableSet.<BuildTarget>builder(),
ImmutableSet.<BuildTargetPattern>builder(),
ImmutableMap.<String, Object>of("number", 0));
assertTrue(dto.number.isPresent());
assertEquals(Optional.of(0), dto.number);
}
@Test
public void canPopulateSimpleConstructorArgFromBuildFactoryParams()
throws ConstructorArgMarshalException, NoSuchBuildTargetException {
class Dto {
public String required;
public Optional<String> notRequired;
public int num;
// Turns out there no optional number params
//public Optional<Long> optionalLong;
public boolean needed;
public Optional<Boolean> notNeeded;
public SourcePath aSrcPath;
public Optional<SourcePath> notASrcPath;
public Path aPath;
public Optional<Path> notAPath;
}
ProjectFilesystem projectFilesystem = new FakeProjectFilesystem();
FakeBuildRule expectedRule = new FakeBuildRule(
BuildTargetFactory.newInstance("//example/path:path"),
new SourcePathResolver(new BuildRuleResolver()));
ruleResolver.addToIndex(expectedRule);
ImmutableMap<String, Object> args = ImmutableMap.<String, Object>builder()
.put("required", "cheese")
.put("notRequired", "cake")
// Long because that's what comes from python.
.put("num", 42L)
// Skipping optional Long.
.put("needed", true)
// Skipping optional boolean.
.put("aSrcPath", ":path")
.put("aPath", "./File.java")
.put("notAPath", "./NotFile.java")
.build();
Dto dto = new Dto();
marshaller.populate(
filesystem,
buildRuleFactoryParams(),
dto,
ImmutableSet.<BuildTarget>builder(),
ImmutableSet.<BuildTargetPattern>builder(),
args);
assertEquals("cheese", dto.required);
assertEquals("cake", dto.notRequired.get());
assertEquals(42, dto.num);
assertTrue(dto.needed);
assertEquals(Optional.<Boolean>absent(), dto.notNeeded);
BuildTargetSourcePath expected = new BuildTargetSourcePath(expectedRule.getBuildTarget());
assertEquals(expected, dto.aSrcPath);
assertEquals(Paths.get("example/path/NotFile.java"), dto.notAPath.get());
}
@Test
/**
* Since we populated the params from the python script, and the python script inserts default
* values instead of nulls it's never possible for someone to see "Optional.absent()", but that's
* what we want as authors of buildables. Handle that case.
*/
public void shouldPopulateDefaultValuesAsBeingAbsent()
throws ConstructorArgMarshalException, NoSuchBuildTargetException {
class Dto {
public Optional<String> noString;
public Optional<String> defaultString;
public Optional<SourcePath> noSourcePath;
public Optional<SourcePath> defaultSourcePath;
public int primitiveNum;
public Integer wrapperObjectNum;
public boolean primitiveBoolean;
public Boolean wrapperObjectBoolean;
}
// This is not an ImmutableMap so we can test null values.
Map<String, Object> args = Maps.newHashMap();
args.put("defaultString", null);
args.put("defaultSourcePath", null);
Dto dto = new Dto();
marshaller.populate(
filesystem,
buildRuleFactoryParams(),
dto,
ImmutableSet.<BuildTarget>builder(),
ImmutableSet.<BuildTargetPattern>builder(),
args);
assertEquals(Optional.<String>absent(), dto.noString);
assertEquals(Optional.<String>absent(), dto.defaultString);
assertEquals(Optional.<SourcePath>absent(), dto.noSourcePath);
assertEquals(Optional.<SourcePath>absent(), dto.defaultSourcePath);
assertEquals(0, dto.primitiveNum);
assertEquals(Integer.valueOf(0), dto.wrapperObjectNum);
}
@Test
public void shouldResolveCollectionOfSourcePaths()
throws ConstructorArgMarshalException, NoSuchBuildTargetException {
class Dto {
public ImmutableSortedSet<SourcePath> srcs;
}
BuildRuleResolver resolver = new BuildRuleResolver();
BuildTarget target = BuildTargetFactory.newInstance("//example/path:manifest");
BuildRule rule = new FakeBuildRule(target, new SourcePathResolver(resolver));
resolver.addToIndex(rule);
Dto dto = new Dto();
marshaller.populate(
filesystem,
buildRuleFactoryParams(),
dto,
ImmutableSet.<BuildTarget>builder(),
ImmutableSet.<BuildTargetPattern>builder(),
ImmutableMap.<String, Object>of(
"srcs",
ImmutableList.of("main.py", "lib/__init__.py", "lib/manifest.py")));
ImmutableSet<String> observedValues = FluentIterable.from(dto.srcs)
.transform(Functions.toStringFunction())
.toSet();
assertEquals(
ImmutableSet.of(
Paths.get("example/path/main.py").toString(),
Paths.get("example/path/lib/__init__.py").toString(),
Paths.get("example/path/lib/manifest.py").toString()),
observedValues);
}
public BuildRuleFactoryParams buildRuleFactoryParams() {
BuildTarget target = BuildTargetFactory.newInstance("//example/path:three");
return NonCheckingBuildRuleFactoryParams.createNonCheckingBuildRuleFactoryParams(target);
}
}
| |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.hc.core5.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.charset.StandardCharsets;
import org.junit.Assert;
import org.junit.Test;
/**
* Unit tests for {@link CharArrayBuffer}.
*
*/
public class TestCharArrayBuffer {
@Test
public void testConstructor() throws Exception {
final CharArrayBuffer buffer = new CharArrayBuffer(16);
Assert.assertEquals(16, buffer.capacity());
Assert.assertEquals(0, buffer.length());
Assert.assertNotNull(buffer.array());
Assert.assertEquals(16, buffer.array().length);
try {
new CharArrayBuffer(-1);
Assert.fail("IllegalArgumentException should have been thrown");
} catch (final IllegalArgumentException ex) {
// expected
}
}
@Test
public void testSimpleAppend() throws Exception {
final CharArrayBuffer buffer = new CharArrayBuffer(16);
Assert.assertEquals(16, buffer.capacity());
Assert.assertEquals(0, buffer.length());
final char[] b1 = buffer.toCharArray();
Assert.assertNotNull(b1);
Assert.assertEquals(0, b1.length);
Assert.assertTrue(buffer.isEmpty());
Assert.assertFalse(buffer.isFull());
final char[] tmp = new char[] { '1', '2', '3', '4'};
buffer.append(tmp, 0, tmp.length);
Assert.assertEquals(16, buffer.capacity());
Assert.assertEquals(4, buffer.length());
Assert.assertFalse(buffer.isEmpty());
Assert.assertFalse(buffer.isFull());
final char[] b2 = buffer.toCharArray();
Assert.assertNotNull(b2);
Assert.assertEquals(4, b2.length);
for (int i = 0; i < tmp.length; i++) {
Assert.assertEquals(tmp[i], b2[i]);
Assert.assertEquals(tmp[i], buffer.charAt(i));
}
Assert.assertEquals("1234", buffer.toString());
buffer.clear();
Assert.assertEquals(16, buffer.capacity());
Assert.assertEquals(0, buffer.length());
Assert.assertTrue(buffer.isEmpty());
Assert.assertFalse(buffer.isFull());
}
@Test
public void testExpandAppend() throws Exception {
final CharArrayBuffer buffer = new CharArrayBuffer(4);
Assert.assertEquals(4, buffer.capacity());
final char[] tmp = new char[] { '1', '2', '3', '4'};
buffer.append(tmp, 0, 2);
buffer.append(tmp, 0, 4);
buffer.append(tmp, 0, 0);
Assert.assertEquals(8, buffer.capacity());
Assert.assertEquals(6, buffer.length());
buffer.append(tmp, 0, 4);
Assert.assertEquals(16, buffer.capacity());
Assert.assertEquals(10, buffer.length());
Assert.assertEquals("1212341234", buffer.toString());
}
@Test
public void testAppendString() throws Exception {
final CharArrayBuffer buffer = new CharArrayBuffer(8);
buffer.append("stuff");
buffer.append(" and more stuff");
Assert.assertEquals("stuff and more stuff", buffer.toString());
}
@Test
public void testAppendNullString() throws Exception {
final CharArrayBuffer buffer = new CharArrayBuffer(8);
buffer.append((String)null);
Assert.assertEquals("null", buffer.toString());
}
@Test
public void testAppendCharArrayBuffer() throws Exception {
final CharArrayBuffer buffer1 = new CharArrayBuffer(8);
buffer1.append(" and more stuff");
final CharArrayBuffer buffer2 = new CharArrayBuffer(8);
buffer2.append("stuff");
buffer2.append(buffer1);
Assert.assertEquals("stuff and more stuff", buffer2.toString());
}
@Test
public void testAppendNullCharArrayBuffer() throws Exception {
final CharArrayBuffer buffer = new CharArrayBuffer(8);
buffer.append((CharArrayBuffer)null);
buffer.append((CharArrayBuffer)null, 0, 0);
Assert.assertEquals("", buffer.toString());
}
@Test
public void testAppendSingleChar() throws Exception {
final CharArrayBuffer buffer = new CharArrayBuffer(4);
buffer.append('1');
buffer.append('2');
buffer.append('3');
buffer.append('4');
buffer.append('5');
buffer.append('6');
Assert.assertEquals("123456", buffer.toString());
}
@Test
public void testInvalidCharArrayAppend() throws Exception {
final CharArrayBuffer buffer = new CharArrayBuffer(4);
buffer.append((char[])null, 0, 0);
final char[] tmp = new char[] { '1', '2', '3', '4'};
try {
buffer.append(tmp, -1, 0);
Assert.fail("IndexOutOfBoundsException should have been thrown");
} catch (final IndexOutOfBoundsException ex) {
// expected
}
try {
buffer.append(tmp, 0, -1);
Assert.fail("IndexOutOfBoundsException should have been thrown");
} catch (final IndexOutOfBoundsException ex) {
// expected
}
try {
buffer.append(tmp, 0, 8);
Assert.fail("IndexOutOfBoundsException should have been thrown");
} catch (final IndexOutOfBoundsException ex) {
// expected
}
try {
buffer.append(tmp, 10, Integer.MAX_VALUE);
Assert.fail("IndexOutOfBoundsException should have been thrown");
} catch (final IndexOutOfBoundsException ex) {
// expected
}
try {
buffer.append(tmp, 2, 4);
Assert.fail("IndexOutOfBoundsException should have been thrown");
} catch (final IndexOutOfBoundsException ex) {
// expected
}
}
@Test
public void testSetLength() throws Exception {
final CharArrayBuffer buffer = new CharArrayBuffer(4);
buffer.setLength(2);
Assert.assertEquals(2, buffer.length());
}
@Test
public void testSetInvalidLength() throws Exception {
final CharArrayBuffer buffer = new CharArrayBuffer(4);
try {
buffer.setLength(-2);
Assert.fail("IndexOutOfBoundsException should have been thrown");
} catch (final IndexOutOfBoundsException ex) {
// expected
}
try {
buffer.setLength(200);
Assert.fail("IndexOutOfBoundsException should have been thrown");
} catch (final IndexOutOfBoundsException ex) {
// expected
}
}
@Test
public void testEnsureCapacity() throws Exception {
final CharArrayBuffer buffer = new CharArrayBuffer(4);
buffer.ensureCapacity(2);
Assert.assertEquals(4, buffer.capacity());
buffer.ensureCapacity(8);
Assert.assertEquals(8, buffer.capacity());
}
@Test
public void testIndexOf() {
final CharArrayBuffer buffer = new CharArrayBuffer(16);
buffer.append("name: value");
Assert.assertEquals(4, buffer.indexOf(':'));
Assert.assertEquals(-1, buffer.indexOf(','));
Assert.assertEquals(4, buffer.indexOf(':', -1, 11));
Assert.assertEquals(4, buffer.indexOf(':', 0, 1000));
Assert.assertEquals(-1, buffer.indexOf(':', 2, 1));
}
@Test
public void testSubstring() {
final CharArrayBuffer buffer = new CharArrayBuffer(16);
buffer.append(" name: value ");
Assert.assertEquals(5, buffer.indexOf(':'));
Assert.assertEquals(" name", buffer.substring(0, 5));
Assert.assertEquals(" value ", buffer.substring(6, buffer.length()));
Assert.assertEquals("name", buffer.substringTrimmed(0, 5));
Assert.assertEquals("value", buffer.substringTrimmed(6, buffer.length()));
Assert.assertEquals("", buffer.substringTrimmed(13, buffer.length()));
}
@Test
public void testSubstringIndexOfOutBound() {
final CharArrayBuffer buffer = new CharArrayBuffer(16);
buffer.append("stuff");
try {
buffer.substring(-2, 10);
Assert.fail("IndexOutOfBoundsException should have been thrown");
} catch (final IndexOutOfBoundsException ex) {
// expected
}
try {
buffer.substringTrimmed(-2, 10);
Assert.fail("IndexOutOfBoundsException should have been thrown");
} catch (final IndexOutOfBoundsException ex) {
// expected
}
try {
buffer.substring(12, 10);
Assert.fail("IndexOutOfBoundsException should have been thrown");
} catch (final IndexOutOfBoundsException ex) {
// expected
}
try {
buffer.substringTrimmed(12, 10);
Assert.fail("IndexOutOfBoundsException should have been thrown");
} catch (final IndexOutOfBoundsException ex) {
// expected
}
try {
buffer.substring(2, 1);
Assert.fail("IndexOutOfBoundsException should have been thrown");
} catch (final IndexOutOfBoundsException ex) {
// expected
}
try {
buffer.substringTrimmed(2, 1);
Assert.fail("IndexOutOfBoundsException should have been thrown");
} catch (final IndexOutOfBoundsException ex) {
// expected
}
}
@Test
public void testAppendAsciiByteArray() throws Exception {
final String s1 = "stuff";
final String s2 = " and more stuff";
final byte[] b1 = s1.getBytes(StandardCharsets.US_ASCII);
final byte[] b2 = s2.getBytes(StandardCharsets.US_ASCII);
final CharArrayBuffer buffer = new CharArrayBuffer(8);
buffer.append(b1, 0, b1.length);
buffer.append(b2, 0, b2.length);
Assert.assertEquals("stuff and more stuff", buffer.toString());
}
@Test
public void testAppendISOByteArray() throws Exception {
final byte[] b = new byte[] {0x00, 0x20, 0x7F, -0x80, -0x01};
final CharArrayBuffer buffer = new CharArrayBuffer(8);
buffer.append(b, 0, b.length);
final char[] ch = buffer.toCharArray();
Assert.assertNotNull(ch);
Assert.assertEquals(5, ch.length);
Assert.assertEquals(0x00, ch[0]);
Assert.assertEquals(0x20, ch[1]);
Assert.assertEquals(0x7F, ch[2]);
Assert.assertEquals(0x80, ch[3]);
Assert.assertEquals(0xFF, ch[4]);
}
@Test
public void testAppendNullByteArray() throws Exception {
final CharArrayBuffer buffer = new CharArrayBuffer(8);
buffer.append((byte[])null, 0, 0);
Assert.assertEquals("", buffer.toString());
}
@Test
public void testAppendNullByteArrayBuffer() throws Exception {
final CharArrayBuffer buffer = new CharArrayBuffer(8);
buffer.append((ByteArrayBuffer)null, 0, 0);
Assert.assertEquals("", buffer.toString());
}
@Test
public void testInvalidAppendAsciiByteArray() throws Exception {
final CharArrayBuffer buffer = new CharArrayBuffer(4);
buffer.append((byte[])null, 0, 0);
final byte[] tmp = new byte[] { '1', '2', '3', '4'};
try {
buffer.append(tmp, -1, 0);
Assert.fail("IndexOutOfBoundsException should have been thrown");
} catch (final IndexOutOfBoundsException ex) {
// expected
}
try {
buffer.append(tmp, 0, -1);
Assert.fail("IndexOutOfBoundsException should have been thrown");
} catch (final IndexOutOfBoundsException ex) {
// expected
}
try {
buffer.append(tmp, 0, 8);
Assert.fail("IndexOutOfBoundsException should have been thrown");
} catch (final IndexOutOfBoundsException ex) {
// expected
}
try {
buffer.append(tmp, 10, Integer.MAX_VALUE);
Assert.fail("IndexOutOfBoundsException should have been thrown");
} catch (final IndexOutOfBoundsException ex) {
// expected
}
try {
buffer.append(tmp, 2, 4);
Assert.fail("IndexOutOfBoundsException should have been thrown");
} catch (final IndexOutOfBoundsException ex) {
// expected
}
}
@Test
public void testSerialization() throws Exception {
final CharArrayBuffer orig = new CharArrayBuffer(32);
orig.append('a');
orig.append('b');
orig.append('c');
final ByteArrayOutputStream outbuffer = new ByteArrayOutputStream();
try (final ObjectOutputStream outStream = new ObjectOutputStream(outbuffer)) {
outStream.writeObject(orig);
}
final byte[] raw = outbuffer.toByteArray();
final ByteArrayInputStream inBuffer = new ByteArrayInputStream(raw);
final ObjectInputStream inStream = new ObjectInputStream(inBuffer);
final CharArrayBuffer clone = (CharArrayBuffer) inStream.readObject();
Assert.assertEquals(orig.capacity(), clone.capacity());
Assert.assertEquals(orig.length(), clone.length());
final char[] data = clone.toCharArray();
Assert.assertNotNull(data);
Assert.assertEquals(3, data.length);
Assert.assertEquals('a', data[0]);
Assert.assertEquals('b', data[1]);
Assert.assertEquals('c', data[2]);
}
@Test
public void testSubSequenceIndexOfOutBound() {
final CharArrayBuffer buffer = new CharArrayBuffer(16);
buffer.append("stuff");
try {
buffer.subSequence(-2, 10);
Assert.fail("IndexOutOfBoundsException should have been thrown");
} catch (final IndexOutOfBoundsException ex) {
// expected
}
try {
buffer.subSequence(12, 10);
Assert.fail("IndexOutOfBoundsException should have been thrown");
} catch (final IndexOutOfBoundsException ex) {
// expected
}
try {
buffer.subSequence(2, 1);
Assert.fail("IndexOutOfBoundsException should have been thrown");
} catch (final IndexOutOfBoundsException ex) {
// expected
}
}
}
| |
/*
* Copyright 2014 mattitahvonenitmill.
*
* 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.vaadin.viritin.fields;
import com.vaadin.server.Resource;
import com.vaadin.ui.Component;
import com.vaadin.ui.Table;
import com.vaadin.util.ReflectTools;
import java.lang.reflect.Method;
import org.vaadin.viritin.ListContainer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import org.apache.commons.lang3.StringUtils;
import org.vaadin.viritin.LazyList;
import static org.vaadin.viritin.LazyList.DEFAULT_PAGE_SIZE;
import org.vaadin.viritin.SortableLazyList;
/**
* A better typed version of the Table component in Vaadin. Expects that users
* are always listing POJOs, which is most often the case in modern Java
* development. Uses ListContainer to bind data due to its superior performance
* compared to BeanItemContainer.
* <p>
* Note, that MTable don't support "multiselection mode". It is also very little
* tested in "editable mode".
* <p>
* If your "list" of entities is too large to load into memory, there are also
* constructors for typical "service layers". Then paged requests are used to
* fetch entities that are visible (or almost visible) in the UI. Behind the
* scenes LazyList is used to "wrap" your service into list.
*
* @param <T> the type of the POJO listed in this Table.
*/
public class MTable<T> extends Table {
private ListContainer<T> bic;
private String[] pendingProperties;
private String[] pendingHeaders;
private Collection sortableProperties;
public MTable() {
}
/**
* Constructs a Table with explicit bean type. Handy for example if your
* beans are JPA proxies or the table in empty when showing it initially.
*
* @param type the type of beans that are listed in this table
*/
public MTable(Class<T> type) {
bic = createContainer(type);
setContainerDataSource(bic);
}
public MTable(T... beans) {
this(new ArrayList<T>(Arrays.asList(beans)));
}
/**
* A shorthand to create MTable using LazyList. By default page size of
* LazyList.DEFAULT_PAGE_SIZE (30) is used.
*
* @param pageProvider the interface via entities are fetched
* @param countProvider the interface via the count of items is detected
*/
public MTable(LazyList.PagingProvider pageProvider,
LazyList.CountProvider countProvider) {
this(new LazyList(pageProvider, countProvider, DEFAULT_PAGE_SIZE));
}
/**
* A shorthand to create MTable using LazyList.
*
* @param pageProvider the interface via entities are fetched
* @param countProvider the interface via the count of items is detected
* @param pageSize the page size (aka maxResults) that is used in paging.
*/
public MTable(LazyList.PagingProvider pageProvider,
LazyList.CountProvider countProvider, int pageSize) {
this(new LazyList(pageProvider, countProvider, pageSize));
}
/**
* A shorthand to create MTable using SortableLazyList. By default page size
* of LazyList.DEFAULT_PAGE_SIZE (30) is used.
*
* @param pageProvider the interface via entities are fetched
* @param countProvider the interface via the count of items is detected
*/
public MTable(SortableLazyList.SortablePagingProvider pageProvider,
LazyList.CountProvider countProvider) {
this(new SortableLazyList(pageProvider, countProvider, DEFAULT_PAGE_SIZE));
}
/**
* A shorthand to create MTable using SortableLazyList.
*
* @param pageProvider the interface via entities are fetched
* @param countProvider the interface via the count of items is detected
* @param pageSize the page size (aka maxResults) that is used in paging.
*/
public MTable(SortableLazyList.SortablePagingProvider pageProvider,
LazyList.CountProvider countProvider, int pageSize) {
this(new SortableLazyList(pageProvider, countProvider, pageSize));
}
public MTable(Collection<T> beans) {
this();
if (beans != null) {
bic = createContainer(beans);
setContainerDataSource(bic);
}
}
protected ListContainer<T> createContainer(Class<T> type) {
return new ListContainer<T>(type);
}
protected ListContainer<T> createContainer(Collection<T> beans) {
return new ListContainer<T>(beans);
}
protected ListContainer<T> getContainer() {
return bic;
}
public MTable<T> withProperties(String... visibleProperties) {
if (isContainerInitialized()) {
bic.setContainerPropertyIds(visibleProperties);
setVisibleColumns((Object[]) visibleProperties);
} else {
pendingProperties = visibleProperties;
for (String string : visibleProperties) {
addContainerProperty(string, String.class, "");
}
}
for (String visibleProperty : visibleProperties) {
String[] parts = StringUtils.splitByCharacterTypeCamelCase(
visibleProperty);
parts[0] = StringUtils.capitalize(parts[0]);
for (int i = 1; i < parts.length; i++) {
parts[i] = parts[i].toLowerCase();
}
String saneCaption = StringUtils.join(parts, " ");
setColumnHeader(visibleProperty, saneCaption);
}
return this;
}
protected boolean isContainerInitialized() {
return bic != null;
}
public MTable<T> withColumnHeaders(String... columnNamesForVisibleProperties) {
if (isContainerInitialized()) {
setColumnHeaders(columnNamesForVisibleProperties);
} else {
pendingHeaders = columnNamesForVisibleProperties;
// Add headers to temporary indexed container, in case table is initially
// empty
for (String prop : columnNamesForVisibleProperties) {
addContainerProperty(prop, String.class, "");
}
}
return this;
}
/**
* Explicitly sets which properties are sortable in the UI.
*
* @param sortableProperties the collection of property identifiers/names
* that should be sortable
* @return the MTable instance
*/
public MTable<T> setSortableProperties(Collection sortableProperties) {
this.sortableProperties = sortableProperties;
return this;
}
/**
* Explicitly sets which properties are sortable in the UI.
*
* @param sortableProperties the collection of property identifiers/names
* that should be sortable
* @return the MTable instance
*/
public MTable<T> setSortableProperties(String... sortableProperties) {
this.sortableProperties = Arrays.asList(sortableProperties);
return this;
}
public Collection getSortableProperties() {
return sortableProperties;
}
@Override
public Collection<?> getSortableContainerPropertyIds() {
if (getSortableProperties() != null) {
return Collections.unmodifiableCollection(sortableProperties);
}
return super.getSortableContainerPropertyIds();
}
public void addMValueChangeListener(MValueChangeListener<T> listener) {
addListener(MValueChangeEvent.class, listener,
MValueChangeEventImpl.VALUE_CHANGE_METHOD);
// implicitly consider the table should be selectable
setSelectable(true);
// Needed as client side checks only for "real value change listener"
setImmediate(true);
}
public void removeMValueChangeListener(MValueChangeListener<T> listener) {
removeListener(MValueChangeEvent.class, listener,
MValueChangeEventImpl.VALUE_CHANGE_METHOD);
setSelectable(hasListeners(MValueChangeEvent.class));
}
@Override
protected void fireValueChange(boolean repaintIsNotNeeded) {
super.fireValueChange(repaintIsNotNeeded);
fireEvent(new MValueChangeEventImpl(this));
}
protected void ensureBeanItemContainer(Collection<T> beans) {
if (!isContainerInitialized()) {
bic = createContainer(beans);
if (pendingProperties != null) {
bic.setContainerPropertyIds(pendingProperties);
pendingProperties = null;
}
setContainerDataSource(bic);
if (pendingHeaders != null) {
setColumnHeaders(pendingHeaders);
pendingHeaders = null;
}
}
}
@Override
public T getValue() {
return (T) super.getValue();
}
@Override
@Deprecated
public void setMultiSelect(boolean multiSelect) {
super.setMultiSelect(multiSelect);
}
public MTable<T> addBeans(T... beans) {
addBeans(Arrays.asList(beans));
return this;
}
public MTable<T> addBeans(Collection<T> beans) {
if (!beans.isEmpty()) {
if (isContainerInitialized()) {
bic.addAll(beans);
} else {
ensureBeanItemContainer(beans);
}
}
return this;
}
public MTable<T> setBeans(T... beans) {
setBeans(new ArrayList<T>(Arrays.asList(beans)));
return this;
}
public MTable<T> setBeans(Collection<T> beans) {
if (!isContainerInitialized() && !beans.isEmpty()) {
ensureBeanItemContainer(beans);
} else if (isContainerInitialized()) {
bic.setCollection(beans);
}
return this;
}
public MTable<T> withFullWidth() {
setWidth(100, Unit.PERCENTAGE);
return this;
}
public MTable<T> withHeight(String height) {
setHeight(height);
return this;
}
public MTable<T> withFullHeight() {
return withHeight("100%");
}
public MTable<T> withWidth(String width) {
setWidth(width);
return this;
}
public MTable<T> withCaption(String caption) {
setCaption(caption);
return this;
}
public MTable<T> withStyleName(String styleName) {
setStyleName(styleName);
return this;
}
public MTable<T> withIcon(Resource icon) {
setIcon(icon);
return this;
}
public MTable<T> expand(String... propertiesToExpand) {
for (String property : propertiesToExpand) {
setColumnExpandRatio(property, 1);
}
return this;
}
public static interface SimpleColumnGenerator<T> {
public Object generate(T entity);
}
public MTable<T> withGeneratedColumn(String columnId,
final SimpleColumnGenerator<T> columnGenerator) {
addGeneratedColumn(columnId, new ColumnGenerator() {
@Override
public Object generateCell(Table source, Object itemId,
Object columnId) {
return columnGenerator.generate((T) itemId);
}
});
return this;
}
public static class SortEvent extends Component.Event {
private boolean preventContainerSort = false;
private final boolean sortAscending;
private final String sortProperty;
public SortEvent(Component source, boolean sortAscending,
String property) {
super(source);
this.sortAscending = sortAscending;
this.sortProperty = property;
}
public String getSortProperty() {
return sortProperty;
}
public boolean isSortAscending() {
return sortAscending;
}
/**
* By calling this method you can prevent the sort call to the container
* used by MTable. In this case you most most probably you want to
* manually sort the container instead.
*/
public void preventContainerSort() {
preventContainerSort = true;
}
public boolean isPreventContainerSort() {
return preventContainerSort;
}
private final static Method method = ReflectTools.findMethod(
SortListener.class, "onSort",
SortEvent.class);
}
/**
* A listener that can be used to track when user sorts table on a column.
*
* Via the event user can also prevent the "container sort" done by the
* Table and implement own sorting logic instead (e.g. get a sorted list of
* entities from the backend).
*
*/
public interface SortListener {
public void onSort(SortEvent event);
}
public MTable addSortListener(SortListener listener) {
addListener(SortEvent.class, listener, SortEvent.method);
return this;
}
public MTable removeSortListener(SortListener listener) {
removeListener(SortEvent.class, listener, SortEvent.method);
return this;
}
private boolean isSorting = false;
@Override
public void sort(Object[] propertyId, boolean[] ascending) throws UnsupportedOperationException {
if (isSorting) {
// hack to avoid recursion
return;
}
boolean refreshingPreviouslyEnabled = disableContentRefreshing();
boolean defaultTableSortingMethod = false;
try {
isSorting = true;
// create sort event and fire it, allow user to prevent default
// operation
final boolean sortAscending = ascending != null && ascending.length > 0 ? ascending[0] : true;
final String sortProperty = propertyId != null && propertyId.length > 0 ? propertyId[0].
toString() : null;
final SortEvent sortEvent = new SortEvent(this, sortAscending,
sortProperty);
fireEvent(sortEvent);
if (!sortEvent.isPreventContainerSort()) {
// if not prevented, do sorting
if (bic != null && bic.getItemIds() instanceof SortableLazyList) {
// Explicit support for SortableLazyList, set sort parameters
// it uses to backend services and clear internal buffers
SortableLazyList<T> sll = (SortableLazyList) bic.
getItemIds();
if (ascending == null || ascending.length == 0) {
sll.sort(true, null);
} else {
sll.sort(ascending[0], propertyId[0].toString());
}
resetPageBuffer();
} else {
super.sort(propertyId, ascending);
defaultTableSortingMethod = true;
}
}
if (!defaultTableSortingMethod) {
// Ensure the values used in UI are set as this method is public
// and can be called by both UI event and app logic
setSortAscending(sortAscending);
setSortContainerPropertyId(sortProperty);
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
isSorting = false;
if (refreshingPreviouslyEnabled) {
enableContentRefreshing(true);
}
}
}
/**
* Clears caches in case the Table is backed by a LazyList implementation.
* Also resets "pageBuffer" used by table. If you know you have changes in
* the listing, you can call this method to ensure the UI gets updated.
*/
public void resetLazyList() {
if (bic != null && bic.getItemIds() instanceof LazyList) {
((LazyList) bic.getItemIds()).reset();
}
resetPageBuffer();
}
}
| |
// Copyright (c) Microsoft Corporation.
// All rights reserved.
//
// This code is licensed under the MIT License.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package com.microsoft.aad.adal;
final class EventStrings {
private static final String EVENT_PREFIX = "Microsoft.ADAL.";
static final String EVENT_NAME = EVENT_PREFIX + "event_name";
// Event names
static final String API_EVENT = EVENT_PREFIX + "api_event";
static final String AUTHORITY_VALIDATION_EVENT = EVENT_PREFIX + "authority_validation";
static final String HTTP_EVENT = EVENT_PREFIX + "http_event";
static final String BROKER_EVENT = EVENT_PREFIX + "broker_event";
static final String UI_EVENT = EVENT_PREFIX + "ui_event";
static final String TOKEN_CACHE_LOOKUP = EVENT_PREFIX + "token_cache_lookup";
static final String TOKEN_CACHE_WRITE = EVENT_PREFIX + "token_cache_write";
static final String TOKEN_CACHE_DELETE = EVENT_PREFIX + "token_cache_delete";
static final String BROKER_REQUEST_SILENT = EVENT_PREFIX + "broker_request_silent";
static final String BROKER_REQUEST_INTERACTIVE = EVENT_PREFIX + "broker_request_interactive";
// Event Parameter names
static final String APPLICATION_NAME = EVENT_PREFIX + "application_name";
static final String APPLICATION_VERSION = EVENT_PREFIX + "application_version";
static final String CLIENT_ID = EVENT_PREFIX + "client_id";
static final String AUTHORITY_NAME = EVENT_PREFIX + "authority";
static final String AUTHORITY_TYPE = EVENT_PREFIX + "authority_type";
static final String API_DEPRECATED = EVENT_PREFIX + "is_deprecated"; // Android only
static final String AUTHORITY_VALIDATION = EVENT_PREFIX + "authority_validation_status";
static final String PROMPT_BEHAVIOR = EVENT_PREFIX + "prompt_behavior";
static final String EXTENDED_EXPIRES_ON_SETTING = EVENT_PREFIX + "extended_expires_on_setting";
static final String WAS_SUCCESSFUL = EVENT_PREFIX + "is_successful";
static final String API_ERROR_CODE = EVENT_PREFIX + "api_error_code";
static final String OAUTH_ERROR_CODE = EVENT_PREFIX + "oauth_error_code";
static final String IDP_NAME = EVENT_PREFIX + "idp";
static final String TENANT_ID = EVENT_PREFIX + "tenant_id";
static final String LOGIN_HINT = EVENT_PREFIX + "login_hint";
static final String USER_ID = EVENT_PREFIX + "user_id";
static final String CORRELATION_ID = EVENT_PREFIX + "correlation_id";
static final String DEVICE_ID = EVENT_PREFIX + "device_id";
static final String REQUEST_ID = EVENT_PREFIX + "request_id";
static final String START_TIME = EVENT_PREFIX + "start_time";
static final String STOP_TIME = EVENT_PREFIX + "stop_time";
static final String RESPONSE_TIME = EVENT_PREFIX + "response_time";
static final String REDIRECT_COUNT = EVENT_PREFIX + "redirect_count"; // Android only
static final String NTLM = EVENT_PREFIX + "ntlm";
static final String USER_CANCEL = EVENT_PREFIX + "user_cancel";
static final String BROKER_APP = EVENT_PREFIX + "broker_app";
static final String BROKER_VERSION = EVENT_PREFIX + "broker_version";
static final String BROKER_APP_USED = EVENT_PREFIX + "broker_app_used";
static final String TOKEN_TYPE = EVENT_PREFIX + "token_type";
static final String TOKEN_TYPE_IS_RT = EVENT_PREFIX + "is_rt";
static final String TOKEN_TYPE_IS_MRRT = EVENT_PREFIX + "is_mrrt";
static final String TOKEN_TYPE_IS_FRT = EVENT_PREFIX + "is_frt";
static final String TOKEN_TYPE_RT = EVENT_PREFIX + "rt"; // Android only
static final String TOKEN_TYPE_MRRT = EVENT_PREFIX + "mrrt"; // Android only
static final String TOKEN_TYPE_FRT = EVENT_PREFIX + "frt"; // Android only
static final String CACHE_EVENT_COUNT = EVENT_PREFIX + "cache_event_count";
static final String UI_EVENT_COUNT = EVENT_PREFIX + "ui_event_count";
static final String HTTP_EVENT_COUNT = EVENT_PREFIX + "http_event_count";
static final String HTTP_PATH = EVENT_PREFIX + "http_path";
static final String HTTP_USER_AGENT = EVENT_PREFIX + "user_agent";
static final String HTTP_METHOD = EVENT_PREFIX + "method";
static final String HTTP_METHOD_POST = EVENT_PREFIX + "post";
static final String HTTP_QUERY_PARAMETERS = EVENT_PREFIX + "query_params";
static final String HTTP_RESPONSE_CODE = EVENT_PREFIX + "response_code";
static final String HTTP_API_VERSION = EVENT_PREFIX + "api_version";
static final String REQUEST_ID_HEADER = EVENT_PREFIX + "x_ms_request_id";
static final String SERVER_ERROR_CODE = EVENT_PREFIX + "server_error_code";
static final String SERVER_SUBERROR_CODE = EVENT_PREFIX + "server_sub_error_code";
static final String TOKEN_AGE = EVENT_PREFIX + "rt_age";
static final String SPE_INFO = EVENT_PREFIX + "spe_info";
// Parameter values
static final String AUTHORITY_TYPE_ADFS = "adfs";
static final String AUTHORITY_TYPE_AAD = "aad";
static final String AUTHORITY_VALIDATION_SUCCESS = "yes";
static final String AUTHORITY_VALIDATION_FAILURE = "no";
static final String AUTHORITY_VALIDATION_NOT_DONE = "not_done";
// Broker account service related events
static final String BROKER_ACCOUNT_SERVICE_STARTS_BINDING = EVENT_PREFIX + "broker_account_service_starts_binding";
static final String BROKER_ACCOUNT_SERVICE_BINDING_SUCCEED = EVENT_PREFIX + "broker_account_service_binding_succeed";
static final String BROKER_ACCOUNT_SERVICE_CONNECTED = EVENT_PREFIX + "broker_account_service_connected";
// API ID
static final String API_ID = EVENT_PREFIX + "api_id";
static final String ACQUIRE_TOKEN_SILENT_SYNC = "1";
static final String ACQUIRE_TOKEN_SILENT = "2";
static final String ACQUIRE_TOKEN_SILENT_ASYNC = "3";
static final String ACQUIRE_TOKEN_WITH_REFRESH_TOKEN = "4";
static final String ACQUIRE_TOKEN_WITH_REFRESH_TOKEN_2 = "5";
static final String ACQUIRE_TOKEN_1 = "100";
static final String ACQUIRE_TOKEN_2 = "104";
static final String ACQUIRE_TOKEN_3 = "108";
static final String ACQUIRE_TOKEN_4 = "111";
static final String ACQUIRE_TOKEN_5 = "115";
static final String ACQUIRE_TOKEN_6 = "116";
static final String ACQUIRE_TOKEN_7 = "117";
static final String ACQUIRE_TOKEN_8 = "118";
static final String ACQUIRE_TOKEN_9 = "119";
static final String ACQUIRE_TOKEN_10 = "120";
// Private constructor to prevent initialization
private EventStrings() {
// Intentionally left blank
}
}
| |
/*
* Copyright 2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.bremersee.data.ldaptive;
import java.util.Collection;
import java.util.Collections;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Stream;
import javax.validation.constraints.NotNull;
import org.ldaptive.AddRequest;
import org.ldaptive.BindRequest;
import org.ldaptive.CompareRequest;
import org.ldaptive.ConnectionFactory;
import org.ldaptive.DeleteRequest;
import org.ldaptive.LdapEntry;
import org.ldaptive.ModifyDnRequest;
import org.ldaptive.ModifyRequest;
import org.ldaptive.SearchRequest;
import org.ldaptive.SearchResponse;
import org.ldaptive.extended.ExtendedRequest;
import org.ldaptive.extended.ExtendedResponse;
import org.ldaptive.extended.PasswordModifyRequest;
import org.ldaptive.extended.PasswordModifyResponseParser;
import org.springframework.lang.Nullable;
import org.springframework.validation.annotation.Validated;
/**
* The interface for ldap operations.
*
* @author Christian Bremer
*/
@Validated
public interface LdaptiveOperations {
/**
* Gets connection factory.
*
* @return the connection factory
*/
@NotNull
ConnectionFactory getConnectionFactory();
/**
* Executes add operation.
*
* @param addRequest the add request
*/
void add(@NotNull AddRequest addRequest);
/**
* Executes bind operation.
*
* @param request the request
* @return the boolean
*/
boolean bind(@NotNull BindRequest request);
/**
* Executes compare operation.
*
* @param request the request
* @return the boolean
*/
boolean compare(@NotNull CompareRequest request);
/**
* Executes delete operation.
*
* @param request the request
*/
void delete(@NotNull DeleteRequest request);
/**
* Executes an extended request.
*
* @param request the request
* @return the extended response
*/
@NotNull
ExtendedResponse executeExtension(@NotNull ExtendedRequest request);
/**
* Generate user password.
*
* @param dn the dn
* @return the generated user password
*/
default String generateUserPassword(@NotNull String dn) {
ExtendedResponse response = executeExtension(new PasswordModifyRequest(dn));
return PasswordModifyResponseParser.parse(response);
}
/**
* Executes modify operation.
*
* @param request the request
*/
void modify(@NotNull ModifyRequest request);
/**
* Executes modify dn operation.
*
* @param request the request
*/
void modifyDn(@NotNull ModifyDnRequest request);
/**
* Modifies user password.
*
* @param dn the dn
* @param oldPass the old pass
* @param newPass the new pass
*/
default void modifyUserPassword(@NotNull String dn, @Nullable String oldPass, @Nullable String newPass) {
executeExtension(new PasswordModifyRequest(dn, oldPass, newPass));
}
/**
* Executes search operation.
*
* @param request the request
* @return the search response
*/
@NotNull
SearchResponse search(@NotNull SearchRequest request);
/**
* Find one.
*
* @param request the request
* @return the optional ldap entry
*/
default Optional<LdapEntry> findOne(@NotNull SearchRequest request) {
return Optional.ofNullable(search(request))
.map(SearchResponse::getEntry);
}
/**
* Find one.
*
* @param <T> the type parameter
* @param request the request
* @param entryMapper the entry mapper
* @return the optional domain object
*/
default <T> Optional<T> findOne(
@NotNull SearchRequest request,
@NotNull LdaptiveEntryMapper<T> entryMapper) {
return Optional.ofNullable(search(request))
.map(SearchResponse::getEntry)
.map(entryMapper::map);
}
/**
* Find all.
*
* @param request the request
* @return the collection
*/
default Collection<LdapEntry> findAll(@NotNull SearchRequest request) {
return Optional.ofNullable(search(request))
.map(SearchResponse::getEntries)
.orElseGet(Collections::emptyList);
}
/**
* Find all.
*
* @param <T> the type parameter
* @param request the request
* @param entryMapper the entry mapper
* @return the stream
*/
default <T> Stream<T> findAll(
@NotNull SearchRequest request,
@NotNull LdaptiveEntryMapper<T> entryMapper) {
return Optional.ofNullable(search(request))
.map(SearchResponse::getEntries)
.orElseGet(Collections::emptyList)
.stream()
.map(entryMapper::map);
}
/**
* Exists.
*
* @param dn the dn
* @return the boolean
*/
boolean exists(@NotNull String dn);
/**
* Exists.
*
* @param <T> the type parameter
* @param domainObject the domain object
* @param entryMapper the entry mapper
* @return the boolean
*/
default <T> boolean exists(@NotNull T domainObject, @NotNull LdaptiveEntryMapper<T> entryMapper) {
return exists(entryMapper.mapDn(domainObject));
}
/**
* Save t.
*
* @param <T> the type parameter
* @param domainObject the domain object
* @param entryMapper the entry mapper
* @return the t
*/
<T> T save(T domainObject, LdaptiveEntryMapper<T> entryMapper);
/**
* Save all stream.
*
* @param <T> the type parameter
* @param domainObjects the domain objects
* @param entryMapper the entry mapper
* @return the stream
*/
default <T> Stream<T> saveAll(
@Nullable Collection<T> domainObjects,
@NotNull LdaptiveEntryMapper<T> entryMapper) {
return Optional.ofNullable(domainObjects)
.map(col -> col.stream()
.filter(Objects::nonNull)
.map(domainObject -> save(domainObject, entryMapper)))
.orElseGet(Stream::empty);
}
/**
* Remove.
*
* @param <T> the type parameter
* @param domainObject the domain object
* @param entryMapper the entry mapper
*/
default <T> void remove(
@NotNull T domainObject,
@NotNull LdaptiveEntryMapper<T> entryMapper) {
delete(DeleteRequest.builder().dn(entryMapper.mapDn(domainObject)).build());
}
/**
* Remove all.
*
* @param <T> the type parameter
* @param domainObjects the domain objects
* @param entryMapper the entry mapper
*/
default <T> void removeAll(
@Nullable Collection<T> domainObjects,
@NotNull LdaptiveEntryMapper<T> entryMapper) {
Optional.ofNullable(domainObjects)
.ifPresent(col -> col.forEach(domainObject -> remove(domainObject, entryMapper)));
}
}
| |
package org.apache.lucene.codecs.lucene3x;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.Closeable;
import java.io.IOException;
import java.util.Comparator;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.FieldInfos;
import org.apache.lucene.index.IndexFileNames;
import org.apache.lucene.index.Term;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.IOContext;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.CloseableThreadLocal;
import org.apache.lucene.util.DoubleBarrelLRUCache;
import org.apache.lucene.util.IOUtils;
/** This stores a monotonically increasing set of <Term, TermInfo> pairs in a
* Directory. Pairs are accessed either by Term or by ordinal position the
* set
* @deprecated (4.0) This class has been replaced by
* FormatPostingsTermsDictReader, except for reading old segments.
* @lucene.experimental
*/
@Deprecated
final class TermInfosReader implements Closeable {
private final Directory directory;
private final String segment;
private final FieldInfos fieldInfos;
private final CloseableThreadLocal<ThreadResources> threadResources = new CloseableThreadLocal<ThreadResources>();
private final SegmentTermEnum origEnum;
private final long size;
private final TermInfosReaderIndex index;
private final int indexLength;
private final int totalIndexInterval;
private final static int DEFAULT_CACHE_SIZE = 1024;
// Just adds term's ord to TermInfo
private final static class TermInfoAndOrd extends TermInfo {
final long termOrd;
public TermInfoAndOrd(TermInfo ti, long termOrd) {
super(ti);
assert termOrd >= 0;
this.termOrd = termOrd;
}
}
private static class CloneableTerm extends DoubleBarrelLRUCache.CloneableKey {
Term term;
public CloneableTerm(Term t) {
this.term = t;
}
@Override
public boolean equals(Object other) {
CloneableTerm t = (CloneableTerm) other;
return this.term.equals(t.term);
}
@Override
public int hashCode() {
return term.hashCode();
}
@Override
public CloneableTerm clone() {
return new CloneableTerm(term);
}
}
private final DoubleBarrelLRUCache<CloneableTerm,TermInfoAndOrd> termsCache = new DoubleBarrelLRUCache<CloneableTerm,TermInfoAndOrd>(DEFAULT_CACHE_SIZE);
/**
* Per-thread resources managed by ThreadLocal
*/
private static final class ThreadResources {
SegmentTermEnum termEnum;
}
TermInfosReader(Directory dir, String seg, FieldInfos fis, IOContext context, int indexDivisor)
throws CorruptIndexException, IOException {
boolean success = false;
if (indexDivisor < 1 && indexDivisor != -1) {
throw new IllegalArgumentException("indexDivisor must be -1 (don't load terms index) or greater than 0: got " + indexDivisor);
}
try {
directory = dir;
segment = seg;
fieldInfos = fis;
origEnum = new SegmentTermEnum(directory.openInput(IndexFileNames.segmentFileName(segment, "", Lucene3xPostingsFormat.TERMS_EXTENSION),
context), fieldInfos, false);
size = origEnum.size;
if (indexDivisor != -1) {
// Load terms index
totalIndexInterval = origEnum.indexInterval * indexDivisor;
final String indexFileName = IndexFileNames.segmentFileName(segment, "", Lucene3xPostingsFormat.TERMS_INDEX_EXTENSION);
final SegmentTermEnum indexEnum = new SegmentTermEnum(directory.openInput(indexFileName,
context), fieldInfos, true);
try {
index = new TermInfosReaderIndex(indexEnum, indexDivisor, dir.fileLength(indexFileName), totalIndexInterval);
indexLength = index.length();
} finally {
indexEnum.close();
}
} else {
// Do not load terms index:
totalIndexInterval = -1;
index = null;
indexLength = -1;
}
success = true;
} finally {
// With lock-less commits, it's entirely possible (and
// fine) to hit a FileNotFound exception above. In
// this case, we want to explicitly close any subset
// of things that were opened so that we don't have to
// wait for a GC to do so.
if (!success) {
close();
}
}
}
public int getSkipInterval() {
return origEnum.skipInterval;
}
public int getMaxSkipLevels() {
return origEnum.maxSkipLevels;
}
public void close() throws IOException {
IOUtils.close(origEnum, threadResources);
}
/** Returns the number of term/value pairs in the set. */
long size() {
return size;
}
private ThreadResources getThreadResources() {
ThreadResources resources = threadResources.get();
if (resources == null) {
resources = new ThreadResources();
resources.termEnum = terms();
threadResources.set(resources);
}
return resources;
}
private static final Comparator<BytesRef> legacyComparator =
BytesRef.getUTF8SortedAsUTF16Comparator();
private final int compareAsUTF16(Term term1, Term term2) {
if (term1.field().equals(term2.field())) {
return legacyComparator.compare(term1.bytes(), term2.bytes());
} else {
return term1.field().compareTo(term2.field());
}
}
/** Returns the TermInfo for a Term in the set, or null. */
TermInfo get(Term term) throws IOException {
return get(term, false);
}
/** Returns the TermInfo for a Term in the set, or null. */
private TermInfo get(Term term, boolean mustSeekEnum) throws IOException {
if (size == 0) return null;
ensureIndexIsRead();
TermInfoAndOrd tiOrd = termsCache.get(new CloneableTerm(term));
ThreadResources resources = getThreadResources();
if (!mustSeekEnum && tiOrd != null) {
return tiOrd;
}
return seekEnum(resources.termEnum, term, tiOrd, true);
}
public void cacheCurrentTerm(SegmentTermEnum enumerator) {
termsCache.put(new CloneableTerm(enumerator.term()),
new TermInfoAndOrd(enumerator.termInfo,
enumerator.position));
}
static Term deepCopyOf(Term other) {
return new Term(other.field(), BytesRef.deepCopyOf(other.bytes()));
}
TermInfo seekEnum(SegmentTermEnum enumerator, Term term, boolean useCache) throws IOException {
if (useCache) {
return seekEnum(enumerator, term,
termsCache.get(new CloneableTerm(deepCopyOf(term))),
useCache);
} else {
return seekEnum(enumerator, term, null, useCache);
}
}
TermInfo seekEnum(SegmentTermEnum enumerator, Term term, TermInfoAndOrd tiOrd, boolean useCache) throws IOException {
if (size == 0) {
return null;
}
// optimize sequential access: first try scanning cached enum w/o seeking
if (enumerator.term() != null // term is at or past current
&& ((enumerator.prev() != null && compareAsUTF16(term, enumerator.prev())> 0)
|| compareAsUTF16(term, enumerator.term()) >= 0)) {
int enumOffset = (int)(enumerator.position/totalIndexInterval)+1;
if (indexLength == enumOffset // but before end of block
|| index.compareTo(term, enumOffset) < 0) {
// no need to seek
final TermInfo ti;
int numScans = enumerator.scanTo(term);
if (enumerator.term() != null && compareAsUTF16(term, enumerator.term()) == 0) {
ti = enumerator.termInfo;
if (numScans > 1) {
// we only want to put this TermInfo into the cache if
// scanEnum skipped more than one dictionary entry.
// This prevents RangeQueries or WildcardQueries to
// wipe out the cache when they iterate over a large numbers
// of terms in order
if (tiOrd == null) {
if (useCache) {
termsCache.put(new CloneableTerm(deepCopyOf(term)),
new TermInfoAndOrd(ti, enumerator.position));
}
} else {
assert sameTermInfo(ti, tiOrd, enumerator);
assert (int) enumerator.position == tiOrd.termOrd;
}
}
} else {
ti = null;
}
return ti;
}
}
// random-access: must seek
final int indexPos;
if (tiOrd != null) {
indexPos = (int) (tiOrd.termOrd / totalIndexInterval);
} else {
// Must do binary search:
indexPos = index.getIndexOffset(term);
}
index.seekEnum(enumerator, indexPos);
enumerator.scanTo(term);
final TermInfo ti;
if (enumerator.term() != null && compareAsUTF16(term, enumerator.term()) == 0) {
ti = enumerator.termInfo;
if (tiOrd == null) {
if (useCache) {
termsCache.put(new CloneableTerm(deepCopyOf(term)),
new TermInfoAndOrd(ti, enumerator.position));
}
} else {
assert sameTermInfo(ti, tiOrd, enumerator);
assert enumerator.position == tiOrd.termOrd;
}
} else {
ti = null;
}
return ti;
}
// called only from asserts
private boolean sameTermInfo(TermInfo ti1, TermInfo ti2, SegmentTermEnum enumerator) {
if (ti1.docFreq != ti2.docFreq) {
return false;
}
if (ti1.freqPointer != ti2.freqPointer) {
return false;
}
if (ti1.proxPointer != ti2.proxPointer) {
return false;
}
// skipOffset is only valid when docFreq >= skipInterval:
if (ti1.docFreq >= enumerator.skipInterval &&
ti1.skipOffset != ti2.skipOffset) {
return false;
}
return true;
}
private void ensureIndexIsRead() {
if (index == null) {
throw new IllegalStateException("terms index was not loaded when this reader was created");
}
}
/** Returns the position of a Term in the set or -1. */
long getPosition(Term term) throws IOException {
if (size == 0) return -1;
ensureIndexIsRead();
int indexOffset = index.getIndexOffset(term);
SegmentTermEnum enumerator = getThreadResources().termEnum;
index.seekEnum(enumerator, indexOffset);
while(compareAsUTF16(term, enumerator.term()) > 0 && enumerator.next()) {}
if (compareAsUTF16(term, enumerator.term()) == 0)
return enumerator.position;
else
return -1;
}
/** Returns an enumeration of all the Terms and TermInfos in the set. */
public SegmentTermEnum terms() {
return origEnum.clone();
}
/** Returns an enumeration of terms starting at or after the named term. */
public SegmentTermEnum terms(Term term) throws IOException {
get(term, true);
return getThreadResources().termEnum.clone();
}
}
| |
/*
* Copyright (c) 2012 Socialize Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.socialize.networks.facebook.v2;
import android.app.Activity;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import com.socialize.Socialize;
import com.socialize.SocializeService;
import com.socialize.android.ioc.IBeanFactory;
import com.socialize.api.action.ShareType;
import com.socialize.auth.AuthProviderType;
import com.socialize.auth.facebook.FacebookSessionStore;
import com.socialize.config.SocializeConfig;
import com.socialize.entity.Entity;
import com.socialize.entity.PropagationInfo;
import com.socialize.entity.PropagationInfoResponse;
import com.socialize.entity.Share;
import com.socialize.error.SocializeException;
import com.socialize.facebook.AsyncFacebookRunner;
import com.socialize.facebook.AsyncFacebookRunner.RequestListener;
import com.socialize.facebook.Facebook;
import com.socialize.facebook.FacebookError;
import com.socialize.log.SocializeLogger;
import com.socialize.networks.*;
import com.socialize.networks.facebook.FacebookUtilsProxy;
import com.socialize.util.ImageUtils;
import com.socialize.util.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/**
* Posts to the Facebook wall.
* @author Jason Polites
*/
@Deprecated
public class DefaultFacebookWallPoster implements FacebookWallPoster {
private SocializeLogger logger;
private ImageUtils imageUtils;
private FacebookUtilsProxy facebookUtils;
private IBeanFactory<AsyncFacebookRunner> facebookRunnerFactory;
private SocializeConfig config;
@Override
public void postLike(Activity parent, Entity entity, PropagationInfo propInfo, SocialNetworkListener listener) {
if(config.isOGLike()) {
Map<String, Object> params = new HashMap<String, Object>();
params.put("object", propInfo.getEntityUrl());
post(parent, "me/og.likes", params, listener);
}
else {
post(parent, entity, "", propInfo, listener);
}
}
@Override
public void postComment(Activity parent, Entity entity, String comment, PropagationInfo propInfo, SocialNetworkListener listener) {
post(parent, entity, comment, propInfo, listener);
}
@Override
public void postOG(Activity parent, Entity entity, String message, String action, PropagationInfo propInfo, SocialNetworkListener listener) {
String entityUrl = propInfo.getEntityUrl();
String linkName = entityUrl;
String link = entityUrl;
if(entity != null) {
linkName = entity.getDisplayName();
}
final Map<String, Object> params = new HashMap<String, Object>();
params.put("name", linkName);
params.put("message", message);
params.put("link", link);
params.put("type", "link");
DefaultPostData postData = new DefaultPostData();
postData.setPostValues(params);
postData.setEntity(entity);
postData.setPropagationInfo(propInfo);
post(parent, listener, postData);
}
@Override
public void post(Activity parent, Entity entity, String message, PropagationInfo propInfo, SocialNetworkListener listener) {
postOG(parent, entity, message, null, propInfo, listener);
}
@Override
public void post(Activity parent, SocialNetworkListener listener, PostData postData) {
boolean okToGo = true;
if(listener != null) {
okToGo = !listener.onBeforePost(parent, SocialNetwork.FACEBOOK, postData);
}
if(okToGo) {
Bundle bundle = new Bundle();
Map<String, Object> postValues = postData.getPostValues();
if(postValues != null) {
Set<Entry<String, Object>> entries = postValues.entrySet();
for (Entry<String, Object> entry : entries) {
if(entry != null) {
Object value = entry.getValue();
String key = entry.getKey();
if(key != null && value != null) {
if(value instanceof byte[]) {
bundle.putByteArray(entry.getKey(), (byte[]) value);
}
else {
bundle.putString(entry.getKey(), value.toString());
}
}
}
}
}
Facebook fb = getFacebook(parent);
final FacebookSessionStore store = newFacebookSessionStore();
store.restore(fb, parent);
AsyncFacebookRunner runner = newAsyncFacebookRunner(fb);
RequestListener requestListener = newRequestListener(parent, listener);
String path = postData.getPath();
if(StringUtils.isEmpty(path)) {
path = "me/links";
}
runner.request(path, bundle, "POST", requestListener, null);
}
}
@Override
public void postPhoto(Activity parent, Share share, String comment, Uri photoUri, SocialNetworkListener listener) {
PropagationInfoResponse propagationInfoResponse = share.getPropagationInfoResponse();
PropagationInfo propInfo = propagationInfoResponse.getPropagationInfo(ShareType.FACEBOOK);
if(propInfo != null) {
String link = propInfo.getAppUrl();
String appId = getFacebookAppId();
if(!StringUtils.isEmpty(appId)) {
postPhoto(parent, link, comment, photoUri, listener);
}
else {
String msg = "Cannot post message to Facebook. No app id found. Make sure you specify facebook.app.id in socialize.properties";
onError(parent, msg, new SocializeException(msg), listener);
}
}
else {
String msg = "Cannot post message to Facebook. No propagation info found";
onError(parent, msg, new SocializeException(msg), listener);
}
}
@Override
public void postPhoto(Activity parent, String link, String caption, Uri photoUri, SocialNetworkListener listener) {
try {
Bundle params = new Bundle();
params.putString("caption", caption + ": " + link);
params.putByteArray("photo", imageUtils.scaleImage(parent, photoUri));
Facebook fb = getFacebook(parent);
final FacebookSessionStore store = newFacebookSessionStore();
store.restore(fb, parent);
AsyncFacebookRunner runner = newAsyncFacebookRunner(fb);
RequestListener requestListener = newRequestListener(parent, listener);
runner.request("me/photos", params, "POST", requestListener, null);
}
catch (IOException e) {
if(listener != null) {
listener.onNetworkError(parent, SocialNetwork.FACEBOOK, e);
}
if(logger != null) {
logger.error("Unable to scale image for upload", e);
}
else {
SocializeLogger.e(e.getMessage(), e);
}
}
}
@Override
public void post(Activity parent, String graphPath, Map<String, Object> postData, SocialNetworkPostListener listener) {
doFacebookCall(parent, postData, graphPath, "POST", listener);
}
@Override
public void get(Activity parent, String graphPath, Map<String, Object> postData, SocialNetworkPostListener listener) {
doFacebookCall(parent, postData, graphPath, "GET", listener);
}
@Override
public void delete(Activity parent, String graphPath, Map<String, Object> postData, SocialNetworkPostListener listener) {
doFacebookCall(parent, postData, graphPath, "DELETE", listener);
}
protected void doFacebookCall(Activity parent, Map<String, Object> postData, String graphPath, String method, SocialNetworkPostListener listener) {
Bundle bundle = new Bundle();
if(postData != null) {
Set<Entry<String, Object>> entries = postData.entrySet();
for (Entry<String, Object> entry : entries) {
Object value = entry.getValue();
if(value instanceof byte[]) {
bundle.putByteArray(entry.getKey(), (byte[]) value);
}
else {
bundle.putString(entry.getKey(), value.toString());
}
}
}
doFacebookCall(parent, bundle, graphPath, method, listener);
}
public void getCurrentPermissions(final Activity parent, String token, final FacebookPermissionCallback callback) {
Facebook fb = new Facebook(getFacebookAppId());
fb.setAccessToken(token);
AsyncFacebookRunner runner = newAsyncFacebookRunner(fb);
runner.request("me/permissions", new RequestListener() {
@Override
public void onMalformedURLException(MalformedURLException e, Object state) {
handlePermissionError(parent, callback, e);
}
@Override
public void onIOException(IOException e, Object state) {
handlePermissionError(parent, callback, e);
}
@Override
public void onFileNotFoundException(FileNotFoundException e, Object state) {
handlePermissionError(parent, callback, e);
}
@Override
public void onFacebookError(FacebookError e, Object state) {
handlePermissionError(parent, callback, e);
}
@Override
public void onComplete(final String response, final Object state) {
if(callback != null) {
parent.runOnUiThread(new Runnable() {
@Override
public void run() {
callback.onComplete(response, state);
}
});
}
}
});
}
protected void handlePermissionError(Activity parent, final FacebookPermissionCallback callback, final Exception e) {
if(callback != null) {
parent.runOnUiThread(new Runnable() {
@Override
public void run() {
callback.onError(SocializeException.wrap(e));
}
});
}
}
protected void doFacebookCall(Activity parent, Bundle data, String graphPath, String method, SocialNetworkPostListener listener) {
Facebook fb = getFacebook(parent);
FacebookSessionStore store = newFacebookSessionStore();
store.restore(fb, parent);
AsyncFacebookRunner runner = newAsyncFacebookRunner(fb);
RequestListener requestListener = newRequestListener(parent, listener);
runner.request(graphPath, data, method, requestListener, null);
}
// So we can mock
protected Facebook getFacebook(Context context) {
return facebookUtils.getFacebook(context);
}
// So we can mock
protected RequestListener newRequestListener(final Activity parent, final SocialNetworkPostListener listener) {
final String defaultErrorMessage = "Facebook Error";
return new RequestListener() {
public void onMalformedURLException(MalformedURLException e, Object state) {
handleFacebookError(parent, 0, defaultErrorMessage, e, listener);
}
public void onIOException(IOException e, Object state) {
handleFacebookError(parent, 0, defaultErrorMessage, e, listener);
}
public void onFileNotFoundException(final FileNotFoundException e, Object state) {
handleFacebookError(parent, 0, defaultErrorMessage, e, listener);
}
public void onFacebookError(FacebookError e, Object state) {
handleFacebookError(parent, 0, defaultErrorMessage, e, listener);
}
public void onComplete(final String response, Object state) {
JSONObject responseObject = null;
if(!StringUtils.isEmpty(response)) {
try {
responseObject = newJSONObject(response);
if(responseObject.has("error")) {
JSONObject error = responseObject.getJSONObject("error");
int code = 0;
if(error.has("code") && !error.isNull("code")) {
code = error.getInt("code");
}
if(error.has("message") && !error.isNull("message")) {
String msg = error.getString("message");
if(logger != null) {
logger.error(msg);
}
else {
System.err.println(msg);
}
handleFacebookError(parent, code, msg, new SocializeException(msg), listener);
}
else {
handleFacebookError(parent, code, defaultErrorMessage, new SocializeException("Facebook Error (Unknown)"), listener);
}
return;
}
}
catch (JSONException e) {
onError(parent, defaultErrorMessage, e, listener);
return;
}
}
if(listener != null) {
final JSONObject fResponse = responseObject;
parent.runOnUiThread(new Runnable() {
@Override
public void run() {
listener.onAfterPost(parent, SocialNetwork.FACEBOOK, fResponse);
}
});
}
}
};
}
protected void handleFacebookError(final Activity parent, int code, String msg, Throwable e, SocialNetworkPostListener listener) {
// Check for token error:
// http://fbdevwiki.com/wiki/Error_codes
if(code == 190) {
// Clear the session cache
getSocialize().clear3rdPartySession(parent, AuthProviderType.FACEBOOK);
}
onError(parent, msg, e, listener);
}
protected JSONObject newJSONObject(String response) throws JSONException {
return new JSONObject(response);
}
// So we can mock
protected AsyncFacebookRunner newAsyncFacebookRunner(Facebook fb) {
if(facebookRunnerFactory != null) {
return facebookRunnerFactory.getBean(fb);
}
return new AsyncFacebookRunner(fb);
}
// So we can mock
protected FacebookSessionStore newFacebookSessionStore() {
return new FacebookSessionStore();
}
// So we can mock
protected SocializeService getSocialize() {
return Socialize.getSocialize();
}
// So we can mock
protected String getFacebookAppId() {
return config.getProperty(SocializeConfig.FACEBOOK_APP_ID);
}
public void setLogger(SocializeLogger logger) {
this.logger = logger;
}
protected void onError(final Activity parent, final String msg, final Throwable e, final SocialNetworkPostListener listener) {
if(logger != null) {
if(e != null) {
logger.error(msg, e);
}
else {
logger.error(msg);
}
}
else {
if(e != null) {
SocializeLogger.e(msg, e);
}
else {
System.err.println(msg);
}
}
if(listener != null) {
parent.runOnUiThread(new Runnable() {
@Override
public void run() {
listener.onNetworkError(parent, SocialNetwork.FACEBOOK, SocializeException.wrap(e));
}
});
}
}
public void setImageUtils(ImageUtils imageUtils) {
this.imageUtils = imageUtils;
}
public void setFacebookRunnerFactory(IBeanFactory<AsyncFacebookRunner> facebookRunnerFactory) {
this.facebookRunnerFactory = facebookRunnerFactory;
}
public void setFacebookUtils(FacebookUtilsProxy facebookUtils) {
this.facebookUtils = facebookUtils;
}
public void setConfig(SocializeConfig config) {
this.config = config;
}
}
| |
/*
* Copyright 2014-2016 CyberVision, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kaaproject.kaa.server.common.dao.model.sql;
import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;
import org.kaaproject.kaa.common.dto.event.EventClassDto;
import org.kaaproject.kaa.common.dto.event.EventClassType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import static org.kaaproject.kaa.server.common.dao.DaoConstants.EVENT_CLASS_EVENT_CLASS_FAMILY_VERSION_ID;
import static org.kaaproject.kaa.server.common.dao.DaoConstants.EVENT_CLASS_FQN;
import static org.kaaproject.kaa.server.common.dao.DaoConstants.EVENT_CLASS_TABLE_NAME;
import static org.kaaproject.kaa.server.common.dao.DaoConstants.EVENT_CLASS_TENANT_ID;
import static org.kaaproject.kaa.server.common.dao.DaoConstants.EVENT_CLASS_TYPE;
import static org.kaaproject.kaa.server.common.dao.model.sql.ModelUtils.getLongId;
@Entity
@Table(name = EVENT_CLASS_TABLE_NAME)
public class EventClass extends BaseSchema<EventClassDto> {
private static final long serialVersionUID = 3766947955702551264L;
@ManyToOne
@JoinColumn(name = EVENT_CLASS_TENANT_ID, nullable = false)
@OnDelete(action = OnDeleteAction.CASCADE)
private Tenant tenant;
@ManyToOne
@JoinColumn(name = EVENT_CLASS_EVENT_CLASS_FAMILY_VERSION_ID, nullable = false)
@OnDelete(action = OnDeleteAction.CASCADE)
private EventClassFamilyVersion ecfv;
@Column(name = EVENT_CLASS_FQN)
private String fqn;
@Column(name = EVENT_CLASS_TYPE)
@Enumerated(EnumType.STRING)
private EventClassType type;
public EventClass() {
}
public EventClass(Long id) {
this.id = id;
}
public EventClass(EventClassDto dto) {
super(dto);
this.id = getLongId(dto.getId());
Long tenantId = getLongId(dto.getTenantId());
if (tenantId != null) {
this.tenant = new Tenant(tenantId);
}
this.fqn = dto.getFqn();
this.type = dto.getType();
Long ecfvId = getLongId(dto.getEcfvId());
if (ecfvId != null) {
this.ecfv = new EventClassFamilyVersion(ecfvId);
}
this.version = dto.getVersion();
this.name = dto.getName();
this.description = dto.getDescription();
this.createdUsername = dto.getCreatedUsername();
this.createdTime = dto.getCreatedTime();
Long ctlId = getLongId(dto.getCtlSchemaId());
if (ctlId != null) {
this.setCtlSchema(new CTLSchema(ctlId));
}
}
public Tenant getTenant() {
return tenant;
}
public void setTenant(Tenant tenant) {
this.tenant = tenant;
}
public EventClassFamilyVersion getEcfv() {
return ecfv;
}
public void setEcfv(EventClassFamilyVersion ecfv) {
this.ecfv = ecfv;
}
public String getFqn() {
return fqn;
}
public void setFqn(String fqn) {
this.fqn = fqn;
}
public EventClassType getType() {
return type;
}
public void setType(EventClassType type) {
this.type = type;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((ecfv == null) ? 0 : ecfv.hashCode());
result = prime * result + ((fqn == null) ? 0 : fqn.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((getCtlSchema() == null) ? 0 : getCtlSchema().hashCode());
result = prime * result + ((tenant == null) ? 0 : tenant.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
EventClass other = (EventClass) obj;
if (ecfv == null) {
if (other.ecfv != null) {
return false;
}
} else if (!ecfv.equals(other.ecfv)) {
return false;
}
if (fqn == null) {
if (other.fqn != null) {
return false;
}
} else if (!fqn.equals(other.fqn)) {
return false;
}
if (id == null) {
if (other.id != null) {
return false;
}
} else if (!id.equals(other.id)) {
return false;
}
if (getCtlSchema() == null) {
if (other.getCtlSchema() != null) {
return false;
}
} else if (!getCtlSchema().equals(other.getCtlSchema())) {
return false;
}
if (tenant == null) {
if (other.tenant != null) {
return false;
}
} else if (!tenant.equals(other.tenant)) {
return false;
}
if (type == null) {
if (other.type != null) {
return false;
}
} else if (!type.equals(other.type)) {
return false;
}
return true;
}
@Override
protected EventClassDto createDto() {
return new EventClassDto();
}
@Override
protected GenericModel<EventClassDto> newInstance(Long id) {
return new EventClass(id);
}
@Override
public EventClassDto toDto() {
EventClassDto dto = createDto();
dto.setId(getStringId());
if (tenant != null) {
dto.setTenantId(tenant.getStringId());
}
if (ecfv != null) {
dto.setEcfvId(ecfv.getStringId());
}
dto.setFqn(fqn);
dto.setType(type);
dto.setCreatedUsername(createdUsername);
dto.setCreatedTime(createdTime);
dto.setDescription(description);
dto.setName(name);
dto.setVersion(version);
dto.setCtlSchemaId(getCtlSchema().getStringId());
return dto;
}
@Override
public String toString() {
return "EventClass [ecfv=" + ecfv + ", fqn=" + fqn + ", type=" + type + ", ctlSchema=" + getCtlSchema() + ", id=" + id + "]";
}
}
| |
/*
* Copyright 2015 Realm 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 io.realm;
import android.os.Handler;
import android.os.Looper;
import java.io.Closeable;
import java.io.File;
import java.lang.ref.WeakReference;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import io.realm.exceptions.RealmMigrationNeededException;
import io.realm.internal.SharedGroupManager;
import io.realm.internal.Table;
import io.realm.internal.TableView;
import io.realm.internal.UncheckedRow;
import io.realm.internal.android.DebugAndroidLogger;
import io.realm.internal.android.ReleaseAndroidLogger;
import io.realm.internal.async.RealmThreadPoolExecutor;
import io.realm.internal.log.RealmLog;
import rx.Observable;
/**
* Base class for all Realm instances.
*
* @see io.realm.Realm
* @see io.realm.DynamicRealm
*/
abstract class BaseRealm implements Closeable {
protected static final long UNVERSIONED = -1;
private static final String INCORRECT_THREAD_CLOSE_MESSAGE = "Realm access from incorrect thread. Realm instance can only be closed on the thread it was created.";
private static final String INCORRECT_THREAD_MESSAGE = "Realm access from incorrect thread. Realm objects can only be accessed on the thread they were created.";
private static final String CLOSED_REALM_MESSAGE = "This Realm instance has already been closed, making it unusable.";
private static final String CANNOT_REFRESH_INSIDE_OF_TRANSACTION_MESSAGE = "Cannot refresh inside of a transaction.";
// Map between a Handler and the canonical path to a Realm file
protected static final Map<Handler, String> handlers = new ConcurrentHashMap<Handler, String>();
// Thread pool for all async operations (Query & transaction)
static final RealmThreadPoolExecutor asyncQueryExecutor = RealmThreadPoolExecutor.getInstance();
protected long threadId;
protected RealmConfiguration configuration;
protected SharedGroupManager sharedGroupManager;
protected boolean autoRefresh;
RealmSchema schema;
Handler handler;
HandlerController handlerController;
static {
RealmLog.add(BuildConfig.DEBUG ? new DebugAndroidLogger() : new ReleaseAndroidLogger());
}
protected BaseRealm(RealmConfiguration configuration, boolean autoRefresh) {
this.threadId = Thread.currentThread().getId();
this.configuration = configuration;
this.sharedGroupManager = new SharedGroupManager(configuration);
this.schema = new RealmSchema(this, sharedGroupManager.getTransaction());
setAutoRefresh(autoRefresh);
}
/**
* Sets the auto-refresh status of the Realm instance.
* <p>
* Auto-refresh is a feature that enables automatic update of the current Realm instance and all its derived objects
* (RealmResults and RealmObjects instances) when a commit is performed on a Realm acting on the same file in
* another thread. This feature is only available if the Realm instance lives is a {@link android.os.Looper} enabled
* thread.
*
* @param autoRefresh {@code true} will turn auto-refresh on, {@code false} will turn it off.
*/
public void setAutoRefresh(boolean autoRefresh) {
checkIfValid();
if (autoRefresh && Looper.myLooper() == null) {
throw new IllegalStateException("Cannot set auto-refresh in a Thread without a Looper");
}
if (autoRefresh && !this.autoRefresh) { // Switch it on
handlerController = new HandlerController(this);
handler = new Handler(handlerController);
handlers.put(handler, configuration.getPath());
} else if (!autoRefresh && this.autoRefresh && handler != null) { // Switch it off
removeHandler();
}
this.autoRefresh = autoRefresh;
}
/**
* Retrieves the auto-refresh status of the Realm instance.
*
* @return the auto-refresh status.
*/
public boolean isAutoRefresh() {
return autoRefresh;
}
/**
* Checks if the Realm is currently in a transaction.
*
* @return {@code true} if inside a transaction, {@code false} otherwise.
*/
public boolean isInTransaction() {
checkIfValid();
return !sharedGroupManager.isImmutable();
}
/**
* Adds a change listener to the Realm.
* <p>
* The listeners will be executed:
* <ul>
* <li>Immediately if a change was committed by the local thread</li>
* <li>On every loop of a Handler thread if changes were committed by another thread</li>
* <li>On every call to {@link io.realm.Realm#refresh()}</li>
* </ul>
*
* Listeners are stored as a strong reference, you need to remove the added listeners using {@link #removeChangeListener(RealmChangeListener)}
* or {@link #removeAllChangeListeners()} which removes all listeners including the ones added via anonymous classes.
*
* @param listener the change listener.
* @throws IllegalStateException if you try to register a listener from a non-Looper Thread.
* @see io.realm.RealmChangeListener
* @see #removeChangeListener(RealmChangeListener)
* @see #removeAllChangeListeners()
*/
public void addChangeListener(RealmChangeListener listener) {
checkIfValid();
if (handler == null) {
throw new IllegalStateException("You can't register a listener from a non-Looper thread ");
}
handlerController.addChangeListener(listener);
}
/**
* Removes the specified change listener.
*
* @param listener the change listener to be removed.
* @see io.realm.RealmChangeListener
* @see #addChangeListener(RealmChangeListener)
*/
public void removeChangeListener(RealmChangeListener listener) {
checkIfValid();
handlerController.removeChangeListener(listener);
}
/**
* Returns an Rx Observable that monitors changes to this Realm. It will emit the current state when subscribed
* to.
*
* @return RxJava Observable
* @throws UnsupportedOperationException if the required RxJava framework is not on the classpath.
* @see <a href="https://realm.io/docs/java/latest/#rxjava">RxJava and Realm</a>
*/
public abstract Observable asObservable();
/**
* Removes all user-defined change listeners.
*
* @see io.realm.RealmChangeListener
* @see #addChangeListener(RealmChangeListener)
*/
public void removeAllChangeListeners() {
checkIfValid();
handlerController.removeAllChangeListeners();
}
void setHandler (Handler handler) {
// remove the old one
handlers.remove(this.handler);
handlers.put(handler, configuration.getPath());
this.handler = handler;
}
/**
* Removes and stops the current thread handler as gracefully as possible.
*/
protected void removeHandler() {
handlers.remove(handler);
// Warning: This only clears the Looper queue. Handler.Callback is not removed.
handler.removeCallbacksAndMessages(null);
this.handler = null;
}
/**
* Writes a compacted copy of the Realm to the given destination File.
* <p>
* The destination file cannot already exist.
* <p>
* Note that if this is called from within a transaction it writes the current data, and not the data as it was when
* the last transaction was committed.
*
* @param destination file to save the Realm to.
* @throws java.io.IOException if any write operation fails.
*/
public void writeCopyTo(File destination) throws java.io.IOException {
writeEncryptedCopyTo(destination, null);
}
/**
* Writes a compacted and encrypted copy of the Realm to the given destination File.
* <p>
* The destination file cannot already exist.
* <p>
* Note that if this is called from within a transaction it writes the current data, and not the data as it was when
* the last transaction was committed.
* <p>
*
* @param destination file to save the Realm to.
* @param key a 64-byte encryption key.
* @throws java.io.IOException if any write operation fails.
*/
public void writeEncryptedCopyTo(File destination, byte[] key) throws java.io.IOException {
if (destination == null) {
throw new IllegalArgumentException("The destination argument cannot be null");
}
checkIfValid();
sharedGroupManager.copyToFile(destination, key);
}
/**
* Refreshes the Realm instance and all the RealmResults and RealmObjects instances coming from it.
* It also calls the listeners associated to the Realm instance.
*/
@SuppressWarnings("UnusedDeclaration")
public void refresh() {
checkIfValid();
if (isInTransaction()) {
throw new IllegalStateException(BaseRealm.CANNOT_REFRESH_INSIDE_OF_TRANSACTION_MESSAGE);
}
sharedGroupManager.advanceRead();
if (handlerController != null) {
handlerController.notifyGlobalListeners();
handlerController.notifyTypeBasedListeners();
// if we have empty async RealmObject then rerun
if (handlerController.threadContainsAsyncEmptyRealmObject()) {
handlerController.updateAsyncEmptyRealmObject();
}
}
}
/**
* Starts a transaction, this must be closed with {@link io.realm.Realm#commitTransaction()} or aborted by
* {@link io.realm.Realm#cancelTransaction()}. Transactions are used to atomically create, update and delete objects
* within a Realm.
* <br>
* Before beginning the transaction, {@link io.realm.Realm#beginTransaction()} updates the realm in the case of
* pending updates from other threads.
* <br>
* Notice: it is not possible to nest transactions. If you start a transaction within a transaction an exception is
* thrown.
*/
public void beginTransaction() {
checkIfValid();
sharedGroupManager.promoteToWrite();
}
/**
* All changes since {@link io.realm.Realm#beginTransaction()} are persisted to disk and the Realm reverts back to
* being read-only. An event is sent to notify all other Realm instances that a change has occurred. When the event
* is received, the other Realms will get their objects and {@link io.realm.RealmResults} updated to reflect the
* changes from this commit.
*/
public void commitTransaction() {
checkIfValid();
sharedGroupManager.commitAndContinueAsRead();
for (Map.Entry<Handler, String> handlerIntegerEntry : handlers.entrySet()) {
Handler handler = handlerIntegerEntry.getKey();
String realmPath = handlerIntegerEntry.getValue();
// Notify at once on thread doing the commit
if (handler.equals(this.handler)) {
handlerController.notifyGlobalListeners();
// notify RealmResults & RealmObject callbacks
handlerController.notifyTypeBasedListeners();
// if we have empty async RealmObject then rerun
if (handlerController.threadContainsAsyncEmptyRealmObject()) {
handlerController.updateAsyncEmptyRealmObject();
}
continue;
}
// For all other threads, use the Handler
// Note there is a race condition with handler.hasMessages() and handler.sendEmptyMessage()
// as the target thread consumes messages at the same time. In this case it is not a problem as worst
// case we end up with two REALM_CHANGED messages in the queue.
if (
realmPath.equals(configuration.getPath()) // It's the right realm
&& !handler.hasMessages(HandlerController.REALM_CHANGED) // The right message
&& handler.getLooper().getThread().isAlive() // The receiving thread is alive
) {
if (!handler.sendEmptyMessage(HandlerController.REALM_CHANGED)) {
RealmLog.w("Cannot update Looper threads when the Looper has quit. Use realm.setAutoRefresh(false) " +
"to prevent this.");
}
}
}
}
/**
* Reverts all writes (created, updated, or deleted objects) made in the current write transaction and end the
* transaction.
* <br>
* The Realm reverts back to read-only.
* <br>
* Calling this when not in a transaction will throw an exception.
*/
public void cancelTransaction() {
checkIfValid();
sharedGroupManager.rollbackAndContinueAsRead();
}
/**
* Checks if a Realm's underlying resources are still available or not getting accessed from the wrong thread.
*/
protected void checkIfValid() {
// Check if the Realm instance has been closed
if (sharedGroupManager == null || !sharedGroupManager.isOpen()) {
throw new IllegalStateException(BaseRealm.CLOSED_REALM_MESSAGE);
}
// Check if we are in the right thread
if (threadId != Thread.currentThread().getId()) {
throw new IllegalStateException(BaseRealm.INCORRECT_THREAD_MESSAGE);
}
}
/**
* Returns the canonical path to where this Realm is persisted on disk.
*
* @return the canonical path to the Realm file.
* @see File#getCanonicalPath()
*/
public String getPath() {
return configuration.getPath();
}
/**
* Returns the {@link RealmConfiguration} for this Realm.
*
* @return the {@link RealmConfiguration} for this Realm.
*/
public RealmConfiguration getConfiguration() {
return configuration;
}
/**
* Returns the schema version for this Realm.
*
* @return the schema version for the Realm file backing this Realm.
*/
public long getVersion() {
if (!sharedGroupManager.hasTable(Table.METADATA_TABLE_NAME)) {
return UNVERSIONED;
}
Table metadataTable = sharedGroupManager.getTable(Table.METADATA_TABLE_NAME);
return metadataTable.getLong(0, 0);
}
/**
* Closes the Realm instance and all its resources.
* <p>
* It's important to always remember to close Realm instances when you're done with it in order not to leak memory,
* file descriptors or grow the size of Realm file out of measure.
*/
@Override
public void close() {
if (this.threadId != Thread.currentThread().getId()) {
throw new IllegalStateException(INCORRECT_THREAD_CLOSE_MESSAGE);
}
RealmCache.release(this);
}
/**
* Closes the Realm instances and all its resources without checking the {@link RealmCache}.
*/
void doClose() {
if (sharedGroupManager != null) {
sharedGroupManager.close();
sharedGroupManager = null;
}
if (handler != null) {
removeHandler();
}
}
/**
* Checks if the {@link io.realm.Realm} instance has already been closed.
*
* @return {@code true} if closed, {@code false} otherwise.
*/
public boolean isClosed() {
if (this.threadId != Thread.currentThread().getId()) {
throw new IllegalStateException(INCORRECT_THREAD_MESSAGE);
}
return sharedGroupManager == null || !sharedGroupManager.isOpen();
}
/**
* Checks if this {@link io.realm.Realm} contains any objects.
*
* @return {@code true} if empty, @{code false} otherwise.
*/
public boolean isEmpty() {
checkIfValid();
return sharedGroupManager.getTransaction().isObjectTablesEmpty();
}
boolean hasChanged() {
return sharedGroupManager.hasChanged();
}
// package protected so unit tests can access it
void setVersion(long version) {
Table metadataTable = sharedGroupManager.getTable(Table.METADATA_TABLE_NAME);
if (metadataTable.getColumnCount() == 0) {
metadataTable.addColumn(RealmFieldType.INTEGER, "version");
metadataTable.addEmptyRow();
}
metadataTable.setLong(0, 0, version);
}
/**
* Sort a table using the given field names and sorting directions. If a field name does not
* exist in the table an {@link IllegalArgumentException} will be thrown.
*/
protected TableView doMultiFieldSort(String[] fieldNames, Sort sortOrders[], Table table) {
long columnIndices[] = new long[fieldNames.length];
for (int i = 0; i < fieldNames.length; i++) {
String fieldName = fieldNames[i];
long columnIndex = table.getColumnIndex(fieldName);
if (columnIndex == -1) {
throw new IllegalArgumentException(String.format("Field name '%s' does not exist.", fieldName));
}
columnIndices[i] = columnIndex;
}
return table.getSortedView(columnIndices, sortOrders);
}
protected void checkAllObjectsSortedParameters(String[] fieldNames, Sort[] sortOrders) {
if (fieldNames == null) {
throw new IllegalArgumentException("fieldNames must be provided.");
} else if (sortOrders == null) {
throw new IllegalArgumentException("sortOrders must be provided.");
}
}
protected void checkNotNullFieldName(String fieldName) {
if (fieldName == null) {
throw new IllegalArgumentException("fieldName must be provided.");
}
}
/**
* Returns the schema for this Realm.
*
* @return The {@link RealmSchema} for this Realm.
*/
public RealmSchema getSchema() {
return schema;
}
<E extends RealmObject> E get(Class<E> clazz, long rowIndex) {
Table table = schema.getTable(clazz);
UncheckedRow row = table.getUncheckedRow(rowIndex);
E result = configuration.getSchemaMediator().newInstance(clazz, schema.getColumnInfo(clazz));
result.row = row;
result.realm = this;
result.setTableVersion();
if (handlerController != null) {
handlerController.addToRealmObjects(result);
}
return result;
}
// Used by RealmList/RealmResults
// Invariant: if dynamicClassName != null -> clazz == DynamicRealmObject
<E extends RealmObject> E get(Class<E> clazz, String dynamicClassName, long rowIndex) {
Table table;
E result;
if (dynamicClassName != null) {
table = schema.getTable(dynamicClassName);
@SuppressWarnings("unchecked")
E dynamicObj = (E) new DynamicRealmObject();
result = dynamicObj;
} else {
table = schema.getTable(clazz);
result = configuration.getSchemaMediator().newInstance(clazz, schema.getColumnInfo(clazz));
}
result.row = table.getUncheckedRow(rowIndex);
result.realm = this;
result.setTableVersion();
if (handlerController != null) {
handlerController.addToRealmObjects(result);
}
return result;
}
/**
* Deletes the Realm file defined by the given configuration.
*/
static boolean deleteRealm(final RealmConfiguration configuration) {
final AtomicBoolean realmDeleted = new AtomicBoolean(true);
RealmCache.invokeWithGlobalRefCount(configuration, new RealmCache.Callback() {
@Override
public void onResult(int count) {
if (count != 0) {
throw new IllegalStateException("It's not allowed to delete the file associated with an open Realm. " +
"Remember to close() all the instances of the Realm before deleting its file.");
}
String canonicalPath = configuration.getPath();
File realmFolder = configuration.getRealmFolder();
String realmFileName = configuration.getRealmFileName();
List<File> filesToDelete = Arrays.asList(new File(canonicalPath),
new File(realmFolder, realmFileName + ".lock"),
new File(realmFolder, realmFileName + ".log_a"),
new File(realmFolder, realmFileName + ".log_b"),
new File(realmFolder, realmFileName + ".log"));
for (File fileToDelete : filesToDelete) {
if (fileToDelete.exists()) {
boolean deleteResult = fileToDelete.delete();
if (!deleteResult) {
realmDeleted.set(false);
RealmLog.w("Could not delete the file " + fileToDelete);
}
}
}
}
});
return realmDeleted.get();
}
/**
* Compacts the Realm file defined by the given configuration.
*/
static boolean compactRealm(final RealmConfiguration configuration) {
if (configuration.getEncryptionKey() != null) {
throw new IllegalArgumentException("Cannot currently compact an encrypted Realm.");
}
return SharedGroupManager.compact(configuration);
}
/**
* Migrates the Realm file defined by the given configuration using the provided migration block.
*
* @param configuration configuration for the Realm that should be migrated
* @param migration if set, this migration block will override what is set in {@link RealmConfiguration}
* @param callback callback for specific Realm type behaviors.
*/
protected static void migrateRealm(final RealmConfiguration configuration, final RealmMigration migration,
final MigrationCallback callback) {
if (configuration == null) {
throw new IllegalArgumentException("RealmConfiguration must be provided");
}
if (migration == null && configuration.getMigration() == null) {
throw new RealmMigrationNeededException(configuration.getPath(), "RealmMigration must be provided");
}
RealmCache.invokeWithGlobalRefCount(configuration, new RealmCache.Callback() {
@Override
public void onResult(int count) {
if (count != 0) {
throw new IllegalStateException("Cannot migrate a Realm file that is already open: " + configuration.getPath());
}
RealmMigration realmMigration = (migration == null) ? configuration.getMigration() : migration;
DynamicRealm realm = null;
try {
realm = DynamicRealm.getInstance(configuration);
realm.beginTransaction();
long currentVersion = realm.getVersion();
realmMigration.migrate(realm, currentVersion, configuration.getSchemaVersion());
realm.setVersion(configuration.getSchemaVersion());
realm.commitTransaction();
} catch (RuntimeException e) {
if (realm != null) {
realm.cancelTransaction();
}
throw e;
} finally {
if (realm != null) {
realm.close();
callback.migrationComplete();
}
}
}
});
}
// Internal delegate for migrations
protected interface MigrationCallback {
void migrationComplete();
}
}
| |
/*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.pubsub.v1.stub;
import static com.google.cloud.pubsub.v1.SubscriptionAdminClient.ListSnapshotsPagedResponse;
import static com.google.cloud.pubsub.v1.SubscriptionAdminClient.ListSubscriptionsPagedResponse;
import com.google.api.gax.core.BackgroundResource;
import com.google.api.gax.core.BackgroundResourceAggregation;
import com.google.api.gax.grpc.GrpcCallSettings;
import com.google.api.gax.grpc.GrpcStubCallableFactory;
import com.google.api.gax.rpc.BidiStreamingCallable;
import com.google.api.gax.rpc.ClientContext;
import com.google.api.gax.rpc.UnaryCallable;
import com.google.common.collect.ImmutableMap;
import com.google.iam.v1.GetIamPolicyRequest;
import com.google.iam.v1.Policy;
import com.google.iam.v1.SetIamPolicyRequest;
import com.google.iam.v1.TestIamPermissionsRequest;
import com.google.iam.v1.TestIamPermissionsResponse;
import com.google.longrunning.stub.GrpcOperationsStub;
import com.google.protobuf.Empty;
import com.google.pubsub.v1.AcknowledgeRequest;
import com.google.pubsub.v1.CreateSnapshotRequest;
import com.google.pubsub.v1.DeleteSnapshotRequest;
import com.google.pubsub.v1.DeleteSubscriptionRequest;
import com.google.pubsub.v1.GetSnapshotRequest;
import com.google.pubsub.v1.GetSubscriptionRequest;
import com.google.pubsub.v1.ListSnapshotsRequest;
import com.google.pubsub.v1.ListSnapshotsResponse;
import com.google.pubsub.v1.ListSubscriptionsRequest;
import com.google.pubsub.v1.ListSubscriptionsResponse;
import com.google.pubsub.v1.ModifyAckDeadlineRequest;
import com.google.pubsub.v1.ModifyPushConfigRequest;
import com.google.pubsub.v1.PullRequest;
import com.google.pubsub.v1.PullResponse;
import com.google.pubsub.v1.SeekRequest;
import com.google.pubsub.v1.SeekResponse;
import com.google.pubsub.v1.Snapshot;
import com.google.pubsub.v1.StreamingPullRequest;
import com.google.pubsub.v1.StreamingPullResponse;
import com.google.pubsub.v1.Subscription;
import com.google.pubsub.v1.UpdateSnapshotRequest;
import com.google.pubsub.v1.UpdateSubscriptionRequest;
import io.grpc.MethodDescriptor;
import io.grpc.protobuf.ProtoUtils;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.annotation.Generated;
// AUTO-GENERATED DOCUMENTATION AND CLASS.
/**
* gRPC stub implementation for the Subscriber service API.
*
* <p>This class is for advanced usage and reflects the underlying API directly.
*/
@Generated("by gapic-generator-java")
public class GrpcSubscriberStub extends SubscriberStub {
private static final MethodDescriptor<Subscription, Subscription>
createSubscriptionMethodDescriptor =
MethodDescriptor.<Subscription, Subscription>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName("google.pubsub.v1.Subscriber/CreateSubscription")
.setRequestMarshaller(ProtoUtils.marshaller(Subscription.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(Subscription.getDefaultInstance()))
.build();
private static final MethodDescriptor<GetSubscriptionRequest, Subscription>
getSubscriptionMethodDescriptor =
MethodDescriptor.<GetSubscriptionRequest, Subscription>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName("google.pubsub.v1.Subscriber/GetSubscription")
.setRequestMarshaller(
ProtoUtils.marshaller(GetSubscriptionRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(Subscription.getDefaultInstance()))
.build();
private static final MethodDescriptor<UpdateSubscriptionRequest, Subscription>
updateSubscriptionMethodDescriptor =
MethodDescriptor.<UpdateSubscriptionRequest, Subscription>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName("google.pubsub.v1.Subscriber/UpdateSubscription")
.setRequestMarshaller(
ProtoUtils.marshaller(UpdateSubscriptionRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(Subscription.getDefaultInstance()))
.build();
private static final MethodDescriptor<ListSubscriptionsRequest, ListSubscriptionsResponse>
listSubscriptionsMethodDescriptor =
MethodDescriptor.<ListSubscriptionsRequest, ListSubscriptionsResponse>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName("google.pubsub.v1.Subscriber/ListSubscriptions")
.setRequestMarshaller(
ProtoUtils.marshaller(ListSubscriptionsRequest.getDefaultInstance()))
.setResponseMarshaller(
ProtoUtils.marshaller(ListSubscriptionsResponse.getDefaultInstance()))
.build();
private static final MethodDescriptor<DeleteSubscriptionRequest, Empty>
deleteSubscriptionMethodDescriptor =
MethodDescriptor.<DeleteSubscriptionRequest, Empty>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName("google.pubsub.v1.Subscriber/DeleteSubscription")
.setRequestMarshaller(
ProtoUtils.marshaller(DeleteSubscriptionRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(Empty.getDefaultInstance()))
.build();
private static final MethodDescriptor<ModifyAckDeadlineRequest, Empty>
modifyAckDeadlineMethodDescriptor =
MethodDescriptor.<ModifyAckDeadlineRequest, Empty>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName("google.pubsub.v1.Subscriber/ModifyAckDeadline")
.setRequestMarshaller(
ProtoUtils.marshaller(ModifyAckDeadlineRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(Empty.getDefaultInstance()))
.build();
private static final MethodDescriptor<AcknowledgeRequest, Empty> acknowledgeMethodDescriptor =
MethodDescriptor.<AcknowledgeRequest, Empty>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName("google.pubsub.v1.Subscriber/Acknowledge")
.setRequestMarshaller(ProtoUtils.marshaller(AcknowledgeRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(Empty.getDefaultInstance()))
.build();
private static final MethodDescriptor<PullRequest, PullResponse> pullMethodDescriptor =
MethodDescriptor.<PullRequest, PullResponse>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName("google.pubsub.v1.Subscriber/Pull")
.setRequestMarshaller(ProtoUtils.marshaller(PullRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(PullResponse.getDefaultInstance()))
.build();
private static final MethodDescriptor<StreamingPullRequest, StreamingPullResponse>
streamingPullMethodDescriptor =
MethodDescriptor.<StreamingPullRequest, StreamingPullResponse>newBuilder()
.setType(MethodDescriptor.MethodType.BIDI_STREAMING)
.setFullMethodName("google.pubsub.v1.Subscriber/StreamingPull")
.setRequestMarshaller(
ProtoUtils.marshaller(StreamingPullRequest.getDefaultInstance()))
.setResponseMarshaller(
ProtoUtils.marshaller(StreamingPullResponse.getDefaultInstance()))
.build();
private static final MethodDescriptor<ModifyPushConfigRequest, Empty>
modifyPushConfigMethodDescriptor =
MethodDescriptor.<ModifyPushConfigRequest, Empty>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName("google.pubsub.v1.Subscriber/ModifyPushConfig")
.setRequestMarshaller(
ProtoUtils.marshaller(ModifyPushConfigRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(Empty.getDefaultInstance()))
.build();
private static final MethodDescriptor<GetSnapshotRequest, Snapshot> getSnapshotMethodDescriptor =
MethodDescriptor.<GetSnapshotRequest, Snapshot>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName("google.pubsub.v1.Subscriber/GetSnapshot")
.setRequestMarshaller(ProtoUtils.marshaller(GetSnapshotRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(Snapshot.getDefaultInstance()))
.build();
private static final MethodDescriptor<ListSnapshotsRequest, ListSnapshotsResponse>
listSnapshotsMethodDescriptor =
MethodDescriptor.<ListSnapshotsRequest, ListSnapshotsResponse>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName("google.pubsub.v1.Subscriber/ListSnapshots")
.setRequestMarshaller(
ProtoUtils.marshaller(ListSnapshotsRequest.getDefaultInstance()))
.setResponseMarshaller(
ProtoUtils.marshaller(ListSnapshotsResponse.getDefaultInstance()))
.build();
private static final MethodDescriptor<CreateSnapshotRequest, Snapshot>
createSnapshotMethodDescriptor =
MethodDescriptor.<CreateSnapshotRequest, Snapshot>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName("google.pubsub.v1.Subscriber/CreateSnapshot")
.setRequestMarshaller(
ProtoUtils.marshaller(CreateSnapshotRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(Snapshot.getDefaultInstance()))
.build();
private static final MethodDescriptor<UpdateSnapshotRequest, Snapshot>
updateSnapshotMethodDescriptor =
MethodDescriptor.<UpdateSnapshotRequest, Snapshot>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName("google.pubsub.v1.Subscriber/UpdateSnapshot")
.setRequestMarshaller(
ProtoUtils.marshaller(UpdateSnapshotRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(Snapshot.getDefaultInstance()))
.build();
private static final MethodDescriptor<DeleteSnapshotRequest, Empty>
deleteSnapshotMethodDescriptor =
MethodDescriptor.<DeleteSnapshotRequest, Empty>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName("google.pubsub.v1.Subscriber/DeleteSnapshot")
.setRequestMarshaller(
ProtoUtils.marshaller(DeleteSnapshotRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(Empty.getDefaultInstance()))
.build();
private static final MethodDescriptor<SeekRequest, SeekResponse> seekMethodDescriptor =
MethodDescriptor.<SeekRequest, SeekResponse>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName("google.pubsub.v1.Subscriber/Seek")
.setRequestMarshaller(ProtoUtils.marshaller(SeekRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(SeekResponse.getDefaultInstance()))
.build();
private static final MethodDescriptor<SetIamPolicyRequest, Policy> setIamPolicyMethodDescriptor =
MethodDescriptor.<SetIamPolicyRequest, Policy>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName("google.iam.v1.IAMPolicy/SetIamPolicy")
.setRequestMarshaller(ProtoUtils.marshaller(SetIamPolicyRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(Policy.getDefaultInstance()))
.build();
private static final MethodDescriptor<GetIamPolicyRequest, Policy> getIamPolicyMethodDescriptor =
MethodDescriptor.<GetIamPolicyRequest, Policy>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName("google.iam.v1.IAMPolicy/GetIamPolicy")
.setRequestMarshaller(ProtoUtils.marshaller(GetIamPolicyRequest.getDefaultInstance()))
.setResponseMarshaller(ProtoUtils.marshaller(Policy.getDefaultInstance()))
.build();
private static final MethodDescriptor<TestIamPermissionsRequest, TestIamPermissionsResponse>
testIamPermissionsMethodDescriptor =
MethodDescriptor.<TestIamPermissionsRequest, TestIamPermissionsResponse>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName("google.iam.v1.IAMPolicy/TestIamPermissions")
.setRequestMarshaller(
ProtoUtils.marshaller(TestIamPermissionsRequest.getDefaultInstance()))
.setResponseMarshaller(
ProtoUtils.marshaller(TestIamPermissionsResponse.getDefaultInstance()))
.build();
private final UnaryCallable<Subscription, Subscription> createSubscriptionCallable;
private final UnaryCallable<GetSubscriptionRequest, Subscription> getSubscriptionCallable;
private final UnaryCallable<UpdateSubscriptionRequest, Subscription> updateSubscriptionCallable;
private final UnaryCallable<ListSubscriptionsRequest, ListSubscriptionsResponse>
listSubscriptionsCallable;
private final UnaryCallable<ListSubscriptionsRequest, ListSubscriptionsPagedResponse>
listSubscriptionsPagedCallable;
private final UnaryCallable<DeleteSubscriptionRequest, Empty> deleteSubscriptionCallable;
private final UnaryCallable<ModifyAckDeadlineRequest, Empty> modifyAckDeadlineCallable;
private final UnaryCallable<AcknowledgeRequest, Empty> acknowledgeCallable;
private final UnaryCallable<PullRequest, PullResponse> pullCallable;
private final BidiStreamingCallable<StreamingPullRequest, StreamingPullResponse>
streamingPullCallable;
private final UnaryCallable<ModifyPushConfigRequest, Empty> modifyPushConfigCallable;
private final UnaryCallable<GetSnapshotRequest, Snapshot> getSnapshotCallable;
private final UnaryCallable<ListSnapshotsRequest, ListSnapshotsResponse> listSnapshotsCallable;
private final UnaryCallable<ListSnapshotsRequest, ListSnapshotsPagedResponse>
listSnapshotsPagedCallable;
private final UnaryCallable<CreateSnapshotRequest, Snapshot> createSnapshotCallable;
private final UnaryCallable<UpdateSnapshotRequest, Snapshot> updateSnapshotCallable;
private final UnaryCallable<DeleteSnapshotRequest, Empty> deleteSnapshotCallable;
private final UnaryCallable<SeekRequest, SeekResponse> seekCallable;
private final UnaryCallable<SetIamPolicyRequest, Policy> setIamPolicyCallable;
private final UnaryCallable<GetIamPolicyRequest, Policy> getIamPolicyCallable;
private final UnaryCallable<TestIamPermissionsRequest, TestIamPermissionsResponse>
testIamPermissionsCallable;
private final BackgroundResource backgroundResources;
private final GrpcOperationsStub operationsStub;
private final GrpcStubCallableFactory callableFactory;
public static final GrpcSubscriberStub create(SubscriberStubSettings settings)
throws IOException {
return new GrpcSubscriberStub(settings, ClientContext.create(settings));
}
public static final GrpcSubscriberStub create(ClientContext clientContext) throws IOException {
return new GrpcSubscriberStub(SubscriberStubSettings.newBuilder().build(), clientContext);
}
public static final GrpcSubscriberStub create(
ClientContext clientContext, GrpcStubCallableFactory callableFactory) throws IOException {
return new GrpcSubscriberStub(
SubscriberStubSettings.newBuilder().build(), clientContext, callableFactory);
}
/**
* Constructs an instance of GrpcSubscriberStub, using the given settings. This is protected so
* that it is easy to make a subclass, but otherwise, the static factory methods should be
* preferred.
*/
protected GrpcSubscriberStub(SubscriberStubSettings settings, ClientContext clientContext)
throws IOException {
this(settings, clientContext, new GrpcSubscriberCallableFactory());
}
/**
* Constructs an instance of GrpcSubscriberStub, using the given settings. This is protected so
* that it is easy to make a subclass, but otherwise, the static factory methods should be
* preferred.
*/
protected GrpcSubscriberStub(
SubscriberStubSettings settings,
ClientContext clientContext,
GrpcStubCallableFactory callableFactory)
throws IOException {
this.callableFactory = callableFactory;
this.operationsStub = GrpcOperationsStub.create(clientContext, callableFactory);
GrpcCallSettings<Subscription, Subscription> createSubscriptionTransportSettings =
GrpcCallSettings.<Subscription, Subscription>newBuilder()
.setMethodDescriptor(createSubscriptionMethodDescriptor)
.setParamsExtractor(
request -> {
ImmutableMap.Builder<String, String> params = ImmutableMap.builder();
params.put("name", String.valueOf(request.getName()));
return params.build();
})
.build();
GrpcCallSettings<GetSubscriptionRequest, Subscription> getSubscriptionTransportSettings =
GrpcCallSettings.<GetSubscriptionRequest, Subscription>newBuilder()
.setMethodDescriptor(getSubscriptionMethodDescriptor)
.setParamsExtractor(
request -> {
ImmutableMap.Builder<String, String> params = ImmutableMap.builder();
params.put("subscription", String.valueOf(request.getSubscription()));
return params.build();
})
.build();
GrpcCallSettings<UpdateSubscriptionRequest, Subscription> updateSubscriptionTransportSettings =
GrpcCallSettings.<UpdateSubscriptionRequest, Subscription>newBuilder()
.setMethodDescriptor(updateSubscriptionMethodDescriptor)
.setParamsExtractor(
request -> {
ImmutableMap.Builder<String, String> params = ImmutableMap.builder();
params.put(
"subscription.name", String.valueOf(request.getSubscription().getName()));
return params.build();
})
.build();
GrpcCallSettings<ListSubscriptionsRequest, ListSubscriptionsResponse>
listSubscriptionsTransportSettings =
GrpcCallSettings.<ListSubscriptionsRequest, ListSubscriptionsResponse>newBuilder()
.setMethodDescriptor(listSubscriptionsMethodDescriptor)
.setParamsExtractor(
request -> {
ImmutableMap.Builder<String, String> params = ImmutableMap.builder();
params.put("project", String.valueOf(request.getProject()));
return params.build();
})
.build();
GrpcCallSettings<DeleteSubscriptionRequest, Empty> deleteSubscriptionTransportSettings =
GrpcCallSettings.<DeleteSubscriptionRequest, Empty>newBuilder()
.setMethodDescriptor(deleteSubscriptionMethodDescriptor)
.setParamsExtractor(
request -> {
ImmutableMap.Builder<String, String> params = ImmutableMap.builder();
params.put("subscription", String.valueOf(request.getSubscription()));
return params.build();
})
.build();
GrpcCallSettings<ModifyAckDeadlineRequest, Empty> modifyAckDeadlineTransportSettings =
GrpcCallSettings.<ModifyAckDeadlineRequest, Empty>newBuilder()
.setMethodDescriptor(modifyAckDeadlineMethodDescriptor)
.setParamsExtractor(
request -> {
ImmutableMap.Builder<String, String> params = ImmutableMap.builder();
params.put("subscription", String.valueOf(request.getSubscription()));
return params.build();
})
.build();
GrpcCallSettings<AcknowledgeRequest, Empty> acknowledgeTransportSettings =
GrpcCallSettings.<AcknowledgeRequest, Empty>newBuilder()
.setMethodDescriptor(acknowledgeMethodDescriptor)
.setParamsExtractor(
request -> {
ImmutableMap.Builder<String, String> params = ImmutableMap.builder();
params.put("subscription", String.valueOf(request.getSubscription()));
return params.build();
})
.build();
GrpcCallSettings<PullRequest, PullResponse> pullTransportSettings =
GrpcCallSettings.<PullRequest, PullResponse>newBuilder()
.setMethodDescriptor(pullMethodDescriptor)
.setParamsExtractor(
request -> {
ImmutableMap.Builder<String, String> params = ImmutableMap.builder();
params.put("subscription", String.valueOf(request.getSubscription()));
return params.build();
})
.build();
GrpcCallSettings<StreamingPullRequest, StreamingPullResponse> streamingPullTransportSettings =
GrpcCallSettings.<StreamingPullRequest, StreamingPullResponse>newBuilder()
.setMethodDescriptor(streamingPullMethodDescriptor)
.build();
GrpcCallSettings<ModifyPushConfigRequest, Empty> modifyPushConfigTransportSettings =
GrpcCallSettings.<ModifyPushConfigRequest, Empty>newBuilder()
.setMethodDescriptor(modifyPushConfigMethodDescriptor)
.setParamsExtractor(
request -> {
ImmutableMap.Builder<String, String> params = ImmutableMap.builder();
params.put("subscription", String.valueOf(request.getSubscription()));
return params.build();
})
.build();
GrpcCallSettings<GetSnapshotRequest, Snapshot> getSnapshotTransportSettings =
GrpcCallSettings.<GetSnapshotRequest, Snapshot>newBuilder()
.setMethodDescriptor(getSnapshotMethodDescriptor)
.setParamsExtractor(
request -> {
ImmutableMap.Builder<String, String> params = ImmutableMap.builder();
params.put("snapshot", String.valueOf(request.getSnapshot()));
return params.build();
})
.build();
GrpcCallSettings<ListSnapshotsRequest, ListSnapshotsResponse> listSnapshotsTransportSettings =
GrpcCallSettings.<ListSnapshotsRequest, ListSnapshotsResponse>newBuilder()
.setMethodDescriptor(listSnapshotsMethodDescriptor)
.setParamsExtractor(
request -> {
ImmutableMap.Builder<String, String> params = ImmutableMap.builder();
params.put("project", String.valueOf(request.getProject()));
return params.build();
})
.build();
GrpcCallSettings<CreateSnapshotRequest, Snapshot> createSnapshotTransportSettings =
GrpcCallSettings.<CreateSnapshotRequest, Snapshot>newBuilder()
.setMethodDescriptor(createSnapshotMethodDescriptor)
.setParamsExtractor(
request -> {
ImmutableMap.Builder<String, String> params = ImmutableMap.builder();
params.put("name", String.valueOf(request.getName()));
return params.build();
})
.build();
GrpcCallSettings<UpdateSnapshotRequest, Snapshot> updateSnapshotTransportSettings =
GrpcCallSettings.<UpdateSnapshotRequest, Snapshot>newBuilder()
.setMethodDescriptor(updateSnapshotMethodDescriptor)
.setParamsExtractor(
request -> {
ImmutableMap.Builder<String, String> params = ImmutableMap.builder();
params.put("snapshot.name", String.valueOf(request.getSnapshot().getName()));
return params.build();
})
.build();
GrpcCallSettings<DeleteSnapshotRequest, Empty> deleteSnapshotTransportSettings =
GrpcCallSettings.<DeleteSnapshotRequest, Empty>newBuilder()
.setMethodDescriptor(deleteSnapshotMethodDescriptor)
.setParamsExtractor(
request -> {
ImmutableMap.Builder<String, String> params = ImmutableMap.builder();
params.put("snapshot", String.valueOf(request.getSnapshot()));
return params.build();
})
.build();
GrpcCallSettings<SeekRequest, SeekResponse> seekTransportSettings =
GrpcCallSettings.<SeekRequest, SeekResponse>newBuilder()
.setMethodDescriptor(seekMethodDescriptor)
.setParamsExtractor(
request -> {
ImmutableMap.Builder<String, String> params = ImmutableMap.builder();
params.put("subscription", String.valueOf(request.getSubscription()));
return params.build();
})
.build();
GrpcCallSettings<SetIamPolicyRequest, Policy> setIamPolicyTransportSettings =
GrpcCallSettings.<SetIamPolicyRequest, Policy>newBuilder()
.setMethodDescriptor(setIamPolicyMethodDescriptor)
.setParamsExtractor(
request -> {
ImmutableMap.Builder<String, String> params = ImmutableMap.builder();
params.put("resource", String.valueOf(request.getResource()));
return params.build();
})
.build();
GrpcCallSettings<GetIamPolicyRequest, Policy> getIamPolicyTransportSettings =
GrpcCallSettings.<GetIamPolicyRequest, Policy>newBuilder()
.setMethodDescriptor(getIamPolicyMethodDescriptor)
.setParamsExtractor(
request -> {
ImmutableMap.Builder<String, String> params = ImmutableMap.builder();
params.put("resource", String.valueOf(request.getResource()));
return params.build();
})
.build();
GrpcCallSettings<TestIamPermissionsRequest, TestIamPermissionsResponse>
testIamPermissionsTransportSettings =
GrpcCallSettings.<TestIamPermissionsRequest, TestIamPermissionsResponse>newBuilder()
.setMethodDescriptor(testIamPermissionsMethodDescriptor)
.setParamsExtractor(
request -> {
ImmutableMap.Builder<String, String> params = ImmutableMap.builder();
params.put("resource", String.valueOf(request.getResource()));
return params.build();
})
.build();
this.createSubscriptionCallable =
callableFactory.createUnaryCallable(
createSubscriptionTransportSettings,
settings.createSubscriptionSettings(),
clientContext);
this.getSubscriptionCallable =
callableFactory.createUnaryCallable(
getSubscriptionTransportSettings, settings.getSubscriptionSettings(), clientContext);
this.updateSubscriptionCallable =
callableFactory.createUnaryCallable(
updateSubscriptionTransportSettings,
settings.updateSubscriptionSettings(),
clientContext);
this.listSubscriptionsCallable =
callableFactory.createUnaryCallable(
listSubscriptionsTransportSettings,
settings.listSubscriptionsSettings(),
clientContext);
this.listSubscriptionsPagedCallable =
callableFactory.createPagedCallable(
listSubscriptionsTransportSettings,
settings.listSubscriptionsSettings(),
clientContext);
this.deleteSubscriptionCallable =
callableFactory.createUnaryCallable(
deleteSubscriptionTransportSettings,
settings.deleteSubscriptionSettings(),
clientContext);
this.modifyAckDeadlineCallable =
callableFactory.createUnaryCallable(
modifyAckDeadlineTransportSettings,
settings.modifyAckDeadlineSettings(),
clientContext);
this.acknowledgeCallable =
callableFactory.createUnaryCallable(
acknowledgeTransportSettings, settings.acknowledgeSettings(), clientContext);
this.pullCallable =
callableFactory.createUnaryCallable(
pullTransportSettings, settings.pullSettings(), clientContext);
this.streamingPullCallable =
callableFactory.createBidiStreamingCallable(
streamingPullTransportSettings, settings.streamingPullSettings(), clientContext);
this.modifyPushConfigCallable =
callableFactory.createUnaryCallable(
modifyPushConfigTransportSettings, settings.modifyPushConfigSettings(), clientContext);
this.getSnapshotCallable =
callableFactory.createUnaryCallable(
getSnapshotTransportSettings, settings.getSnapshotSettings(), clientContext);
this.listSnapshotsCallable =
callableFactory.createUnaryCallable(
listSnapshotsTransportSettings, settings.listSnapshotsSettings(), clientContext);
this.listSnapshotsPagedCallable =
callableFactory.createPagedCallable(
listSnapshotsTransportSettings, settings.listSnapshotsSettings(), clientContext);
this.createSnapshotCallable =
callableFactory.createUnaryCallable(
createSnapshotTransportSettings, settings.createSnapshotSettings(), clientContext);
this.updateSnapshotCallable =
callableFactory.createUnaryCallable(
updateSnapshotTransportSettings, settings.updateSnapshotSettings(), clientContext);
this.deleteSnapshotCallable =
callableFactory.createUnaryCallable(
deleteSnapshotTransportSettings, settings.deleteSnapshotSettings(), clientContext);
this.seekCallable =
callableFactory.createUnaryCallable(
seekTransportSettings, settings.seekSettings(), clientContext);
this.setIamPolicyCallable =
callableFactory.createUnaryCallable(
setIamPolicyTransportSettings, settings.setIamPolicySettings(), clientContext);
this.getIamPolicyCallable =
callableFactory.createUnaryCallable(
getIamPolicyTransportSettings, settings.getIamPolicySettings(), clientContext);
this.testIamPermissionsCallable =
callableFactory.createUnaryCallable(
testIamPermissionsTransportSettings,
settings.testIamPermissionsSettings(),
clientContext);
this.backgroundResources =
new BackgroundResourceAggregation(clientContext.getBackgroundResources());
}
public GrpcOperationsStub getOperationsStub() {
return operationsStub;
}
@Override
public UnaryCallable<Subscription, Subscription> createSubscriptionCallable() {
return createSubscriptionCallable;
}
@Override
public UnaryCallable<GetSubscriptionRequest, Subscription> getSubscriptionCallable() {
return getSubscriptionCallable;
}
@Override
public UnaryCallable<UpdateSubscriptionRequest, Subscription> updateSubscriptionCallable() {
return updateSubscriptionCallable;
}
@Override
public UnaryCallable<ListSubscriptionsRequest, ListSubscriptionsResponse>
listSubscriptionsCallable() {
return listSubscriptionsCallable;
}
@Override
public UnaryCallable<ListSubscriptionsRequest, ListSubscriptionsPagedResponse>
listSubscriptionsPagedCallable() {
return listSubscriptionsPagedCallable;
}
@Override
public UnaryCallable<DeleteSubscriptionRequest, Empty> deleteSubscriptionCallable() {
return deleteSubscriptionCallable;
}
@Override
public UnaryCallable<ModifyAckDeadlineRequest, Empty> modifyAckDeadlineCallable() {
return modifyAckDeadlineCallable;
}
@Override
public UnaryCallable<AcknowledgeRequest, Empty> acknowledgeCallable() {
return acknowledgeCallable;
}
@Override
public UnaryCallable<PullRequest, PullResponse> pullCallable() {
return pullCallable;
}
@Override
public BidiStreamingCallable<StreamingPullRequest, StreamingPullResponse>
streamingPullCallable() {
return streamingPullCallable;
}
@Override
public UnaryCallable<ModifyPushConfigRequest, Empty> modifyPushConfigCallable() {
return modifyPushConfigCallable;
}
@Override
public UnaryCallable<GetSnapshotRequest, Snapshot> getSnapshotCallable() {
return getSnapshotCallable;
}
@Override
public UnaryCallable<ListSnapshotsRequest, ListSnapshotsResponse> listSnapshotsCallable() {
return listSnapshotsCallable;
}
@Override
public UnaryCallable<ListSnapshotsRequest, ListSnapshotsPagedResponse>
listSnapshotsPagedCallable() {
return listSnapshotsPagedCallable;
}
@Override
public UnaryCallable<CreateSnapshotRequest, Snapshot> createSnapshotCallable() {
return createSnapshotCallable;
}
@Override
public UnaryCallable<UpdateSnapshotRequest, Snapshot> updateSnapshotCallable() {
return updateSnapshotCallable;
}
@Override
public UnaryCallable<DeleteSnapshotRequest, Empty> deleteSnapshotCallable() {
return deleteSnapshotCallable;
}
@Override
public UnaryCallable<SeekRequest, SeekResponse> seekCallable() {
return seekCallable;
}
@Override
public UnaryCallable<SetIamPolicyRequest, Policy> setIamPolicyCallable() {
return setIamPolicyCallable;
}
@Override
public UnaryCallable<GetIamPolicyRequest, Policy> getIamPolicyCallable() {
return getIamPolicyCallable;
}
@Override
public UnaryCallable<TestIamPermissionsRequest, TestIamPermissionsResponse>
testIamPermissionsCallable() {
return testIamPermissionsCallable;
}
@Override
public final void close() {
try {
backgroundResources.close();
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new IllegalStateException("Failed to close resource", e);
}
}
@Override
public void shutdown() {
backgroundResources.shutdown();
}
@Override
public boolean isShutdown() {
return backgroundResources.isShutdown();
}
@Override
public boolean isTerminated() {
return backgroundResources.isTerminated();
}
@Override
public void shutdownNow() {
backgroundResources.shutdownNow();
}
@Override
public boolean awaitTermination(long duration, TimeUnit unit) throws InterruptedException {
return backgroundResources.awaitTermination(duration, unit);
}
}
| |
package com.syncano.android.lib.modules.data;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import com.syncano.android.lib.modules.Params;
import com.syncano.android.lib.modules.Response;
/**
* Creates a new Data Object. collection_id/collection_key parameter means that one can use either one of them -
* collection_id or collection_key.
*/
public class ParamsDataNew extends Params {
/** Project id */
@Expose
@SerializedName(value = "project_id")
private String projectId;
/** Collection id */
@Expose
@SerializedName(value = "collection_id")
private String collectionId;
/** Collection key */
@Expose
@SerializedName(value = "collection_key")
private String collectionKey;
/** Data key */
@Expose
@SerializedName(value = "dataKey")
private String dataKey;
/** User name */
@Expose
@SerializedName(value = "user_name")
private String userName;
/** Source url */
@Expose
@SerializedName(value = "source_url")
private String sourceUrl;
/** Title */
@Expose
private String title;
/** Text */
@Expose
private String text;
/** Link */
@Expose
private String link;
/** Image base64 */
@Expose
private String image;
/** Image url */
@Expose
@SerializedName(value = "image_url")
private String imageUrl;
/** Folder */
@Expose
private String folder;
/** State */
@Expose
private String state;
/** Parent id */
@Expose
@SerializedName(value = "parent_id")
private String parentId;
public ParamsDataNew(String projectId, String collectionId, String collectionKey, String state) {
setProjectId(projectId);
setCollectionId(collectionId);
setCollectionKey(collectionKey);
setState(state);
}
@Override
public Response instantiateResponse() {
return new ResponseDataNew();
}
@Override
public String getMethodName() {
return "data.new";
}
/**
* @return project id
*/
public String getProjectId() {
return projectId;
}
/**
* Sets project id
*
* @param projectId
*/
public void setProjectId(String projectId) {
this.projectId = projectId;
}
/**
* @return collection key
*/
public String getCollectionKey() {
return collectionKey;
}
/**
* Sets collection key
*
* @param collectionKey
*/
public void setCollectionKey(String collectionKey) {
this.collectionKey = collectionKey;
}
/**
* @return collection id
*/
public String getCollectionId() {
return collectionId;
}
/**
* Sets collection id
*
* @param collectionId
*/
public void setCollectionId(String collectionId) {
this.collectionId = collectionId;
}
/**
* @return user name
*/
public String getUserName() {
return userName;
}
/**
* Sets user name
*
* @param userName
*/
public void setUserName(String userName) {
this.userName = userName;
}
/**
*
* @return source url
*/
public String getSourceUrl() {
return sourceUrl;
}
/**
* Sets source url
*
* @param sourceUrl
*/
public void setSourceUrl(String sourceUrl) {
this.sourceUrl = sourceUrl;
}
/**
* @return title
*/
public String getTitle() {
return title;
}
/**
* Sets title
*
* @param title
*/
public void setTitle(String title) {
this.title = title;
}
/**
* @return text
*/
public String getText() {
return text;
}
/**
* Sets text
*
* @param text
*/
public void setText(String text) {
this.text = text;
}
/**
* @return link
*/
public String getLink() {
return link;
}
/**
* Sets link
*
* @param link
*/
public void setLink(String link) {
this.link = link;
}
/**
*
* @return image in base 64
*/
public String getImage() {
return image;
}
/**
* Sets image in base 64
*
* @param image
*/
public void setImage(String image) {
this.image = image;
}
/**
*
* @return image url
*/
public String getImageUrl() {
return imageUrl;
}
/**
* Sets image url
*
* @param imageUrl
*/
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
/**
* @return folder
*/
public String getFolder() {
return folder;
}
/**
* Sets folder
*
* @param folder
*/
public void setFolder(String folder) {
this.folder = folder;
}
/**
* @return state
*/
public String getState() {
return state;
}
/**
* Sets state
*
* @param state
*/
public void setState(String state) {
this.state = state;
}
/**
* @return data key
*/
public String getDataKey() {
return dataKey;
}
/**
* Sets data key
*
* @param dataKey
*/
public void setData_key(String dataKey) {
this.dataKey = dataKey;
}
/**
* @return parent id
*/
public String getParentId() {
return parentId;
}
/**
* Sets parent id
*
* @param parentId
*/
public void setParentId(String parentId) {
this.parentId = parentId;
}
}
| |
/*!
* Copyright 2018 - 2019 Hitachi Vantara. 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.pentaho.requirejs.impl.types;
import org.json.simple.parser.JSONParser;
import org.junit.Before;
import org.junit.Test;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.*;
public class MetaInfRequireJsonTest {
private static final int TEST_FILE_BASE_NUMBER_OF_MODULES = 6;
private static final int TEST_FILE_BASE_NUMBER_OF_CONFIGS = 2;
private static final int TEST_FILE_BASE_NUMBER_OF_MAPS = 2;
private static final int TEST_FILE_BASE_NUMBER_OF_SHIMS = 5;
private static final int TEST_FILE_BASE_NUMBER_OF_DEPS = 3;
private HashMap<String, Object> requireMeta;
@Before
public void setUp() throws Exception {
requireMeta = (HashMap<String, Object>) (new JSONParser()).parse( new InputStreamReader( this.getClass().getResourceAsStream( "/require.meta.json" ) ) );
}
@Test
public void getName() {
MetaInfRequireJson requireJson = new MetaInfRequireJson( requireMeta );
assertEquals( "Get name from only module of first version of first artifact info", "angular", requireJson.getName() );
}
@Test
public void getNameMultipleModules() {
( (Map<String, Map<String, Map<String, Map<String, Object>>>>) requireMeta.get( "requirejs-osgi-meta" ) ).get( "artifacts" ).get( "org.webjars/angularjs" ).get( "1.3.0-SNAPSHOT" ).put( "5.6", new HashMap<>() );
MetaInfRequireJson requireJson = new MetaInfRequireJson( requireMeta );
assertEquals( "Get name from first artifact info", "angularjs", requireJson.getName() );
}
@Test
public void getNameNoArtifactInfo() {
( (Map<String, Map<String, Map<String, Map<String, Object>>>>) requireMeta.get( "requirejs-osgi-meta" ) ).remove( "artifacts" );
MetaInfRequireJson requireJson = new MetaInfRequireJson( requireMeta );
assertEquals( "Get name from first module info", "angular", requireJson.getName() );
}
@Test
public void getNameNoArtifactAndModuleInfo() {
final Map<String, Map<String, Map<String, Map<String, Object>>>> meta = (Map<String, Map<String, Map<String, Map<String, Object>>>>) requireMeta.get( "requirejs-osgi-meta" );
meta.remove( "artifacts" );
meta.remove( "modules" );
MetaInfRequireJson requireJson = new MetaInfRequireJson( requireMeta );
assertEquals( "", requireJson.getName() );
}
@Test
public void getVersion() {
MetaInfRequireJson requireJson = new MetaInfRequireJson( requireMeta );
assertEquals( "1.3.0-SNAPSHOT", requireJson.getVersion() );
}
@Test
public void getWebRootPath() {
MetaInfRequireJson requireJson = new MetaInfRequireJson( requireMeta );
assertEquals( "angular@1.3.0-SNAPSHOT", requireJson.getWebRootPath() );
}
@Test
public void preferGlobal() {
MetaInfRequireJson requireJson = new MetaInfRequireJson( requireMeta );
assertEquals( false, requireJson.preferGlobal() );
}
@Test
public void preferGlobalNoNAme() {
final Map<String, Map<String, Map<String, Map<String, Object>>>> meta = (Map<String, Map<String, Map<String, Map<String, Object>>>>) requireMeta.get( "requirejs-osgi-meta" );
meta.remove( "artifacts" );
meta.remove( "modules" );
MetaInfRequireJson requireJson = new MetaInfRequireJson( requireMeta );
assertEquals( true, requireJson.preferGlobal() );
}
@Test
public void getModules() {
MetaInfRequireJson requireJson = new MetaInfRequireJson( requireMeta );
final Map<String, String> modules = requireJson.getModules();
assertEquals( TEST_FILE_BASE_NUMBER_OF_MODULES, modules.size() );
assertTrue( "Remove versioning from known modules", modules.containsKey( "angular" ) );
assertTrue( "Remove versioning from known modules", modules.containsKey( "angular-ui-router.stateHelper" ) );
assertTrue( "Remove versioning from known modules", modules.containsKey( "smart-table-min" ) );
assertTrue( "Remove versioning from known modules", modules.containsKey( "smart-table" ) );
assertTrue( "Leave as-is unknown modules", modules.containsKey( "other" ) );
assertTrue( "Leave as-is unknown modules", modules.containsKey( "simple" ) );
assertEquals( "Resolve known locations", "/some-folder", modules.get( "other" ) );
}
@Test
public void getModuleMainFile() {
MetaInfRequireJson requireJson = new MetaInfRequireJson( requireMeta );
assertNull( requireJson.getModuleMainFile( "angular" ) );
assertNull( requireJson.getModuleMainFile( "smart-table-min" ) );
assertNull( requireJson.getModuleMainFile( "smart-table" ) );
assertEquals( "statehelper", requireJson.getModuleMainFile( "angular-ui-router.stateHelper" ) );
assertEquals( "main", requireJson.getModuleMainFile( "other" ) );
assertEquals( "main", requireJson.getModuleMainFile( "simple" ) );
}
@Test
public void getDependencies() {
MetaInfRequireJson requireJson = new MetaInfRequireJson( requireMeta );
final Map<String, String> dependencies = requireJson.getDependencies();
assertEquals( TEST_FILE_BASE_NUMBER_OF_DEPS, dependencies.size() );
}
@Test
public void hasScript() {
MetaInfRequireJson requireJson = new MetaInfRequireJson( requireMeta );
assertFalse( requireJson.hasScript( "preconfig" ) );
}
@Test
public void getScriptResource() {
MetaInfRequireJson requireJson = new MetaInfRequireJson( requireMeta );
assertNull( requireJson.getScriptResource( "preconfig" ) );
}
@Test
public void getConfig() {
MetaInfRequireJson requireJson = new MetaInfRequireJson( requireMeta );
final Map<String, ?> config = requireJson.getConfig();
assertEquals( TEST_FILE_BASE_NUMBER_OF_CONFIGS, config.size() );
assertTrue( "Remove versioning from known modules", config.containsKey( "smart-table" ) );
assertTrue( "Leave as-is unknown modules", config.containsKey( "something-unknown@2.0.1" ) );
}
@Test
public void getMap() {
MetaInfRequireJson requireJson = new MetaInfRequireJson( requireMeta );
Map<String, Map<String, String>> map = requireJson.getMap();
assertEquals( TEST_FILE_BASE_NUMBER_OF_MAPS, map.size() );
assertTrue( "Remove versioning from known modules", map.containsKey( "smart-table" ) );
assertTrue( "Leave as-is unknown modules", map.get( "smart-table" ).containsKey( "other-unknown@3.0.7" ) );
assertEquals( "Leave as-is unknown modules", "better-unknown@3.0.0", map.get( "smart-table" ).get( "other-unknown@3.0.7" ) );
assertTrue( "Leave as-is unknown modules", map.containsKey( "something-unknown@2.0.1" ) );
assertTrue( "Remove versioning from known modules", map.get( "something-unknown@2.0.1" ).containsKey( "angular" ) );
assertEquals( "Remove versioning from known modules", "angular-ui-router.stateHelper", map.get( "something-unknown@2.0.1" ).get( "angular" ) );
}
@Test
public void getShim() {
MetaInfRequireJson requireJson = new MetaInfRequireJson( requireMeta );
Map<String, Map<String, ?>> shim = requireJson.getShim();
assertEquals( TEST_FILE_BASE_NUMBER_OF_SHIMS, shim.size() );
assertTrue( "Leave as-is unknown modules", shim.containsKey( "something-unknown@2.0.1" ) );
assertTrue( "Remove versioning from known modules", shim.containsKey( "angular" ) );
assertTrue( "Remove versioning from known modules", shim.containsKey( "angular-ui-router.stateHelper" ) );
assertTrue( "Remove versioning from known modules", shim.containsKey( "angular-ui-router.stateHelper/statehelper" ) );
assertTrue( "Remove versioning from known modules", shim.containsKey( "smart-table" ) );
}
@Test
public void isAmdPackage() {
MetaInfRequireJson requireJson = new MetaInfRequireJson( requireMeta );
assertTrue( requireJson.isAmdPackage() );
}
@Test
public void isAmdPackageOneNot() {
final Map<String, Map<String, Map<String, Map<String, Object>>>> meta = (Map<String, Map<String, Map<String, Map<String, Object>>>>) requireMeta.get( "requirejs-osgi-meta" );
meta.get( "modules" ).get( "smart-table" ).get( "2.0.3-1" ).put( "isAmdPackage", false );
MetaInfRequireJson requireJson = new MetaInfRequireJson( requireMeta );
assertFalse( requireJson.isAmdPackage() );
}
@Test
public void getExports() {
MetaInfRequireJson requireJson = new MetaInfRequireJson( requireMeta );
assertNull( requireJson.getExports() );
}
@Test
public void getExportsLastNonAmd() {
final Map<String, Map<String, Map<String, Map<String, Object>>>> meta = (Map<String, Map<String, Map<String, Map<String, Object>>>>) requireMeta.get( "requirejs-osgi-meta" );
meta.get( "modules" ).get( "smart-table" ).get( "2.0.3-1" ).put( "isAmdPackage", false );
meta.get( "modules" ).get( "smart-table" ).get( "2.0.3-1" ).put( "exports", "var1" );
meta.get( "modules" ).get( "smart-table-min" ).get( "2.0.3-1" ).put( "isAmdPackage", false );
meta.get( "modules" ).get( "smart-table-min" ).get( "2.0.3-1" ).put( "exports", "var2" );
MetaInfRequireJson requireJson = new MetaInfRequireJson( requireMeta );
assertEquals( "var2", requireJson.getExports() );
}
@Test
public void getExportsOnlyIfNonAmd() {
final Map<String, Map<String, Map<String, Map<String, Object>>>> meta = (Map<String, Map<String, Map<String, Map<String, Object>>>>) requireMeta.get( "requirejs-osgi-meta" );
meta.get( "modules" ).get( "smart-table" ).get( "2.0.3-1" ).put( "isAmdPackage", true );
meta.get( "modules" ).get( "smart-table" ).get( "2.0.3-1" ).put( "exports", "var1" );
meta.get( "modules" ).get( "smart-table-min" ).get( "2.0.3-1" ).put( "isAmdPackage", true );
meta.get( "modules" ).get( "smart-table-min" ).get( "2.0.3-1" ).put( "exports", "var2" );
MetaInfRequireJson requireJson = new MetaInfRequireJson( requireMeta );
assertNull( requireJson.getExports() );
}
@Test
public void testOverridesAddPath() {
final Map<String, Object> meta = (Map<String, Object>) requireMeta.get( "requirejs-osgi-meta" );
Map<String, Object> overrides = new HashMap<>();
final HashMap<String, Object> paths = new HashMap<>();
overrides.put( "paths", paths );
paths.put( "newPath", "asdsa" );
meta.put( "overrides", overrides );
MetaInfRequireJson requireJson = new MetaInfRequireJson( requireMeta );
final Map<String, String> modules = requireJson.getModules();
assertEquals( TEST_FILE_BASE_NUMBER_OF_MODULES + 1, modules.size() );
assertTrue( modules.containsKey( "newPath" ) );
}
@Test
public void testOverridesRemovePath() {
final Map<String, Object> meta = (Map<String, Object>) requireMeta.get( "requirejs-osgi-meta" );
Map<String, Object> overrides = new HashMap<>();
final HashMap<String, Object> paths = new HashMap<>();
overrides.put( "paths", paths );
paths.put( "smart-table", null );
meta.put( "overrides", overrides );
MetaInfRequireJson requireJson = new MetaInfRequireJson( requireMeta );
final Map<String, String> modules = requireJson.getModules();
assertEquals( TEST_FILE_BASE_NUMBER_OF_MODULES - 1, modules.size() );
assertFalse( modules.containsKey( "smart-table" ) );
}
@Test
public void testOverridesReplacesPath() {
final Map<String, Object> meta = (Map<String, Object>) requireMeta.get( "requirejs-osgi-meta" );
Map<String, Object> overrides = new HashMap<>();
final HashMap<String, Object> paths = new HashMap<>();
overrides.put( "paths", paths );
paths.put( "angular", "/some/new/path" );
meta.put( "overrides", overrides );
MetaInfRequireJson requireJson = new MetaInfRequireJson( requireMeta );
final Map<String, String> modules = requireJson.getModules();
assertEquals( TEST_FILE_BASE_NUMBER_OF_MODULES, modules.size() );
assertEquals( "/some/new/path", modules.get( "angular" ) );
}
@Test
public void testOverridesAddPackages() {
final Map<String, Object> meta = (Map<String, Object>) requireMeta.get( "requirejs-osgi-meta" );
Map<String, Object> overrides = new HashMap<>();
final List<Object> packs = new ArrayList<>();
overrides.put( "packages", packs );
packs.add( "newPack" );
HashMap<String, String> otherPack = new HashMap<>();
otherPack.put( "name", "yetAnotherPack" );
otherPack.put( "location", "/extra-packs" );
otherPack.put( "main", "top" );
packs.add( otherPack );
meta.put( "overrides", overrides );
MetaInfRequireJson requireJson = new MetaInfRequireJson( requireMeta );
final Map<String, String> modules = requireJson.getModules();
assertEquals( TEST_FILE_BASE_NUMBER_OF_MODULES + 2, modules.size() );
assertTrue( modules.containsKey( "newPack" ) );
assertEquals( "/newPack", modules.get( "newPack" ) );
assertEquals( "main", requireJson.getModuleMainFile( "newPack" ) );
assertTrue( modules.containsKey( "yetAnotherPack" ) );
assertEquals( "/extra-packs", modules.get( "yetAnotherPack" ) );
assertEquals( "top", requireJson.getModuleMainFile( "yetAnotherPack" ) );
}
@Test
public void testOverridesReplacePackage() {
final Map<String, Object> meta = (Map<String, Object>) requireMeta.get( "requirejs-osgi-meta" );
Map<String, Object> overrides = new HashMap<>();
final List<Object> packs = new ArrayList<>();
overrides.put( "packages", packs );
HashMap<String, String> otherPack = new HashMap<>();
otherPack.put( "name", "other" );
otherPack.put( "location", "/different/path" );
otherPack.put( "main", "different-main" );
packs.add( otherPack );
meta.put( "overrides", overrides );
MetaInfRequireJson requireJson = new MetaInfRequireJson( requireMeta );
final Map<String, String> modules = requireJson.getModules();
assertEquals( TEST_FILE_BASE_NUMBER_OF_MODULES, modules.size() );
assertTrue( modules.containsKey( "other" ) );
assertEquals( "/different/path", modules.get( "other" ) );
assertEquals( "different-main", requireJson.getModuleMainFile( "other" ) );
}
@Test
public void testOverridesAddConfig() {
final Map<String, Object> meta = (Map<String, Object>) requireMeta.get( "requirejs-osgi-meta" );
Map<String, Object> overrides = new HashMap<>();
final HashMap<String, Object> configOverrides = new HashMap<>();
overrides.put( "config", configOverrides );
configOverrides.put( "newConfig", new HashMap<>() );
meta.put( "overrides", overrides );
MetaInfRequireJson requireJson = new MetaInfRequireJson( requireMeta );
final Map<String, Map<String, ?>> config = requireJson.getConfig();
assertEquals( TEST_FILE_BASE_NUMBER_OF_CONFIGS + 1, config.size() );
assertTrue( config.containsKey( "newConfig" ) );
}
@Test
public void testOverridesRemoveConfig() {
final Map<String, Object> meta = (Map<String, Object>) requireMeta.get( "requirejs-osgi-meta" );
Map<String, Object> overrides = new HashMap<>();
final HashMap<String, Object> configOverrides = new HashMap<>();
overrides.put( "config", configOverrides );
configOverrides.put( "smart-table", null );
meta.put( "overrides", overrides );
MetaInfRequireJson requireJson = new MetaInfRequireJson( requireMeta );
final Map<String, Map<String, ?>> config = requireJson.getConfig();
assertEquals( TEST_FILE_BASE_NUMBER_OF_CONFIGS - 1, config.size() );
assertFalse( config.containsKey( "smart-table" ) );
}
@Test
public void testOverridesReplacesConfig() {
final Map<String, Object> meta = (Map<String, Object>) requireMeta.get( "requirejs-osgi-meta" );
Map<String, Object> overrides = new HashMap<>();
final HashMap<String, Object> configOverrides = new HashMap<>();
overrides.put( "config", configOverrides );
final HashMap<Object, Object> newConfig = new HashMap<>();
newConfig.put( "prop", "value" );
configOverrides.put( "smart-table", newConfig );
meta.put( "overrides", overrides );
MetaInfRequireJson requireJson = new MetaInfRequireJson( requireMeta );
final Map<String, Map<String, ?>> config = requireJson.getConfig();
assertEquals( TEST_FILE_BASE_NUMBER_OF_CONFIGS, config.size() );
assertTrue( config.containsKey( "smart-table" ) );
assertTrue( config.get( "smart-table" ).containsKey( "prop" ) );
assertEquals( "value", config.get( "smart-table" ).get( "prop" ) );
}
@Test
public void testOverridesAddMapConfig() {
final Map<String, Object> meta = (Map<String, Object>) requireMeta.get( "requirejs-osgi-meta" );
Map<String, Object> overrides = new HashMap<>();
final HashMap<String, Object> mapOverrides = new HashMap<>();
overrides.put( "map", mapOverrides );
final HashMap<Object, Object> newMap = new HashMap<>();
newMap.put( "original", "mapped" );
mapOverrides.put( "newMap", newMap );
meta.put( "overrides", overrides );
MetaInfRequireJson requireJson = new MetaInfRequireJson( requireMeta );
final Map<String, Map<String, String>> map = requireJson.getMap();
assertEquals( TEST_FILE_BASE_NUMBER_OF_MAPS + 1, map.size() );
assertTrue( map.containsKey( "newMap" ) );
assertEquals( 1, map.get( "newMap" ).size() );
assertTrue( map.get( "newMap" ).containsKey( "original" ) );
assertEquals( "mapped", map.get( "newMap" ).get( "original" ) );
}
@Test
public void testOverridesAddMap() {
final Map<String, Object> meta = (Map<String, Object>) requireMeta.get( "requirejs-osgi-meta" );
Map<String, Object> overrides = new HashMap<>();
final HashMap<String, Object> mapOverrides = new HashMap<>();
overrides.put( "map", mapOverrides );
final HashMap<Object, Object> newMap = new HashMap<>();
newMap.put( "original", "mapped" );
mapOverrides.put( "smart-table", newMap );
meta.put( "overrides", overrides );
MetaInfRequireJson requireJson = new MetaInfRequireJson( requireMeta );
final Map<String, Map<String, String>> map = requireJson.getMap();
assertEquals( TEST_FILE_BASE_NUMBER_OF_MAPS, map.size() );
assertTrue( map.containsKey( "smart-table" ) );
assertEquals( 3, map.get( "smart-table" ).size() );
assertTrue( map.get( "smart-table" ).containsKey( "original" ) );
assertEquals( "mapped", map.get( "smart-table" ).get( "original" ) );
}
@Test
public void testOverridesRemoveMapConfig() {
final Map<String, Object> meta = (Map<String, Object>) requireMeta.get( "requirejs-osgi-meta" );
Map<String, Object> overrides = new HashMap<>();
final HashMap<String, Object> mapOverrides = new HashMap<>();
overrides.put( "map", mapOverrides );
mapOverrides.put( "smart-table", null );
meta.put( "overrides", overrides );
MetaInfRequireJson requireJson = new MetaInfRequireJson( requireMeta );
final Map<String, Map<String, String>> map = requireJson.getMap();
assertEquals( TEST_FILE_BASE_NUMBER_OF_MAPS - 1, map.size() );
assertFalse( map.containsKey( "smart-table" ) );
}
@Test
public void testOverridesRemoveMap() {
final Map<String, Object> meta = (Map<String, Object>) requireMeta.get( "requirejs-osgi-meta" );
Map<String, Object> overrides = new HashMap<>();
final HashMap<String, Object> mapOverrides = new HashMap<>();
overrides.put( "map", mapOverrides );
final HashMap<Object, Object> newMap = new HashMap<>();
newMap.put( "angular", null );
mapOverrides.put( "smart-table", newMap );
meta.put( "overrides", overrides );
MetaInfRequireJson requireJson = new MetaInfRequireJson( requireMeta );
final Map<String, Map<String, String>> map = requireJson.getMap();
assertEquals( TEST_FILE_BASE_NUMBER_OF_MAPS, map.size() );
assertTrue( map.containsKey( "smart-table" ) );
assertEquals( 1, map.get( "smart-table" ).size() );
assertFalse( map.get( "smart-table" ).containsKey( "angular" ) );
}
@Test
public void testOverridesReplacesMap() {
final Map<String, Object> meta = (Map<String, Object>) requireMeta.get( "requirejs-osgi-meta" );
Map<String, Object> overrides = new HashMap<>();
final HashMap<String, Object> mapOverrides = new HashMap<>();
overrides.put( "map", mapOverrides );
final HashMap<Object, Object> newMap = new HashMap<>();
newMap.put( "angular", "the-new-module" );
mapOverrides.put( "smart-table", newMap );
meta.put( "overrides", overrides );
MetaInfRequireJson requireJson = new MetaInfRequireJson( requireMeta );
final Map<String, Map<String, String>> map = requireJson.getMap();
assertEquals( TEST_FILE_BASE_NUMBER_OF_MAPS, map.size() );
assertTrue( map.containsKey( "smart-table" ) );
assertTrue( map.get( "smart-table" ).containsKey( "angular" ) );
assertEquals( "the-new-module", map.get( "smart-table" ).get( "angular" ) );
}
@Test
public void testOverridesAddShimConfig() {
final Map<String, Object> meta = (Map<String, Object>) requireMeta.get( "requirejs-osgi-meta" );
Map<String, Object> overrides = new HashMap<>();
final HashMap<String, Object> shimOverrides = new HashMap<>();
overrides.put( "shim", shimOverrides );
final HashMap<Object, Object> newShim = new HashMap<>();
newShim.put( "original", "shimped" );
shimOverrides.put( "newShim", newShim );
meta.put( "overrides", overrides );
MetaInfRequireJson requireJson = new MetaInfRequireJson( requireMeta );
final Map<String, Map<String, ?>> shim = requireJson.getShim();
assertEquals( TEST_FILE_BASE_NUMBER_OF_SHIMS + 1, shim.size() );
assertTrue( shim.containsKey( "newShim" ) );
assertEquals( 1, shim.get( "newShim" ).size() );
assertTrue( shim.get( "newShim" ).containsKey( "original" ) );
assertEquals( "shimped", shim.get( "newShim" ).get( "original" ) );
}
@Test
public void testOverridesRemoveShimConfig() {
final Map<String, Object> meta = (Map<String, Object>) requireMeta.get( "requirejs-osgi-meta" );
Map<String, Object> overrides = new HashMap<>();
final HashMap<String, Object> shimOverrides = new HashMap<>();
overrides.put( "shim", shimOverrides );
shimOverrides.put( "smart-table", null );
meta.put( "overrides", overrides );
MetaInfRequireJson requireJson = new MetaInfRequireJson( requireMeta );
final Map<String, Map<String, ?>> shim = requireJson.getShim();
assertEquals( TEST_FILE_BASE_NUMBER_OF_SHIMS - 1, shim.size() );
assertFalse( shim.containsKey( "smart-table" ) );
}
@Test
public void testOverridesReplacesShim() {
final Map<String, Object> meta = (Map<String, Object>) requireMeta.get( "requirejs-osgi-meta" );
Map<String, Object> overrides = new HashMap<>();
final HashMap<String, Object> shimOverrides = new HashMap<>();
overrides.put( "shim", shimOverrides );
final HashMap<Object, Object> newShim = new HashMap<>();
newShim.put( "angular", "the-new-module" );
shimOverrides.put( "smart-table", newShim );
meta.put( "overrides", overrides );
MetaInfRequireJson requireJson = new MetaInfRequireJson( requireMeta );
final Map<String, Map<String, ?>> shim = requireJson.getShim();
assertEquals( TEST_FILE_BASE_NUMBER_OF_SHIMS, shim.size() );
assertTrue( shim.containsKey( "smart-table" ) );
assertTrue( shim.get( "smart-table" ).containsKey( "angular" ) );
assertEquals( "the-new-module", shim.get( "smart-table" ).get( "angular" ) );
}
@Test
public void testOverridesAddDependency() {
final Map<String, Object> meta = (Map<String, Object>) requireMeta.get( "requirejs-osgi-meta" );
Map<String, Object> overrides = new HashMap<>();
final HashMap<String, Object> dependencies = new HashMap<>();
overrides.put( "dependencies", dependencies );
dependencies.put( "newDependency", "1.2" );
meta.put( "overrides", overrides );
MetaInfRequireJson requireJson = new MetaInfRequireJson( requireMeta );
final Map<String, String> deps = requireJson.getDependencies();
assertEquals( TEST_FILE_BASE_NUMBER_OF_DEPS + 1, deps.size() );
assertTrue( deps.containsKey( "newDependency" ) );
assertEquals( "1.2", deps.get( "newDependency" ) );
}
@Test
public void testOverridesRemoveDependency() {
final Map<String, Object> meta = (Map<String, Object>) requireMeta.get( "requirejs-osgi-meta" );
Map<String, Object> overrides = new HashMap<>();
final HashMap<String, Object> dependencies = new HashMap<>();
overrides.put( "dependencies", dependencies );
dependencies.put( "angular", null );
meta.put( "overrides", overrides );
MetaInfRequireJson requireJson = new MetaInfRequireJson( requireMeta );
final Map<String, String> deps = requireJson.getDependencies();
assertEquals( TEST_FILE_BASE_NUMBER_OF_DEPS - 1, deps.size() );
assertFalse( deps.containsKey( "angular" ) );
}
@Test
public void testOverridesReplacesDependency() {
final Map<String, Object> meta = (Map<String, Object>) requireMeta.get( "requirejs-osgi-meta" );
Map<String, Object> overrides = new HashMap<>();
final HashMap<String, Object> dependencies = new HashMap<>();
overrides.put( "dependencies", dependencies );
dependencies.put( "angular", "9.8" );
meta.put( "overrides", overrides );
MetaInfRequireJson requireJson = new MetaInfRequireJson( requireMeta );
final Map<String, String> deps = requireJson.getDependencies();
assertEquals( TEST_FILE_BASE_NUMBER_OF_DEPS, deps.size() );
assertEquals( "9.8", deps.get( "angular" ) );
}
}
| |
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.diff.impl.processing;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.diff.LineTokenizer;
import com.intellij.openapi.diff.ex.DiffFragment;
import com.intellij.openapi.diff.impl.ComparisonPolicy;
import com.intellij.openapi.diff.impl.DiffUtil;
import com.intellij.openapi.diff.impl.highlighting.FragmentSide;
import com.intellij.openapi.diff.impl.highlighting.Util;
import com.intellij.openapi.util.text.StringUtil;
import java.util.ArrayList;
public interface DiffCorrection {
DiffFragment[] correct(DiffFragment[] fragments);
class TrueLineBlocks implements DiffCorrection, FragmentProcessor<FragmentsCollector> {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.diff.impl.processing.DiffCorrection.TrueLineBlocks");
private final DiffPolicy myDiffPolicy;
private final ComparisonPolicy myComparisonPolicy;
public TrueLineBlocks(ComparisonPolicy comparisonPolicy) {
myDiffPolicy = new DiffPolicy.LineBlocks(comparisonPolicy);
myComparisonPolicy = comparisonPolicy;
}
public DiffFragment[] correct(DiffFragment[] fragments) {
FragmentsCollector collector = new FragmentsCollector();
collector.processAll(fragments, this);
return collector.toArray();
}
public void process(DiffFragment fragment, FragmentsCollector collector) {
if (!fragment.isEqual()) {
if (myComparisonPolicy.isEqual(fragment))
fragment = myComparisonPolicy.createFragment(fragment.getText1(), fragment.getText2());
collector.add(fragment);
} else {
String[] lines1 = new LineTokenizer(fragment.getText1()).execute();
String[] lines2 = new LineTokenizer(fragment.getText2()).execute();
LOG.assertTrue(lines1.length == lines2.length);
for (int i = 0; i < lines1.length; i++)
collector.addAll(myDiffPolicy.buildFragments(lines1[i], lines2[i]));
}
}
public DiffFragment[] correctAndNormalize(DiffFragment[] fragments) {
return Normalize.INSTANCE.correct(correct(fragments));
}
}
class ChangedSpace implements DiffCorrection, FragmentProcessor<FragmentsCollector> {
private final DiffPolicy myDiffPolicy;
private final ComparisonPolicy myComparisonPolicy;
public ChangedSpace(ComparisonPolicy policy) {
myComparisonPolicy = policy;
myDiffPolicy = new DiffPolicy.ByChar(myComparisonPolicy);
}
public void process(DiffFragment fragment, FragmentsCollector collector) {
if (!fragment.isChange()) {
collector.add(fragment);
return;
}
String text1 = fragment.getText1();
String text2 = fragment.getText2();
while (StringUtil.startsWithChar(text1, '\n') || StringUtil.startsWithChar(text2, '\n')) {
String newLine1 = null;
String newLine2 = null;
if (StringUtil.startsWithChar(text1, '\n')) {
newLine1 = "\n";
text1 = text1.substring(1);
}
if (StringUtil.startsWithChar(text2, '\n')) {
newLine2 = "\n";
text2 = text2.substring(1);
}
collector.add(new DiffFragment(newLine1, newLine2));
}
String spaces1 = leadingSpaces(text1);
String spaces2 = leadingSpaces(text2);
if (spaces1.length() == 0 && spaces2.length() == 0) {
DiffFragment trailing = myComparisonPolicy.createFragment(text1, text2);
collector.add(trailing);
return;
}
collector.addAll(myDiffPolicy.buildFragments(spaces1, spaces2));
DiffFragment textFragment = myComparisonPolicy.createFragment(text1.substring(spaces1.length(), text1.length()),
text2.substring(spaces2.length(), text2.length()));
collector.add(textFragment);
}
private String leadingSpaces(String text) {
int i = 0;
while (i < text.length() && text.charAt(i) == ' ') i++;
return text.substring(0, i);
}
public DiffFragment[] correct(DiffFragment[] fragments) {
FragmentsCollector collector = new FragmentsCollector();
collector.processAll(fragments, this);
return collector.toArray();
}
}
interface FragmentProcessor<Collector> {
void process(DiffFragment fragment, Collector collector);
}
class BaseFragmentRunner<ActualRunner extends BaseFragmentRunner> {
private final ArrayList<DiffFragment> myItems = new ArrayList<DiffFragment>();
private int myIndex = 0;
private DiffFragment[] myFragments;
public void add(DiffFragment fragment) {
actualAdd(fragment);
}
protected final void actualAdd(DiffFragment fragment) {
if (DiffUtil.isEmpty(fragment)) return;
myItems.add(fragment);
}
public DiffFragment[] toArray() {
return myItems.toArray(new DiffFragment[myItems.size()]);
}
protected int getIndex() { return myIndex; }
public DiffFragment[] getFragments() { return myFragments; }
public void processAll(DiffFragment[] fragments, FragmentProcessor<ActualRunner> processor) {
myFragments = fragments;
for (;myIndex < myFragments.length; myIndex++) {
DiffFragment fragment = myFragments[myIndex];
processor.process(fragment, (ActualRunner)this);
}
}
}
class FragmentsCollector extends BaseFragmentRunner<FragmentsCollector> {
public void addAll(DiffFragment[] fragments) {
for (int i = 0; i < fragments.length; i++) {
add(fragments[i]);
}
}
}
class FragmentBuffer extends BaseFragmentRunner<FragmentBuffer> {
private int myMark = -1;
private int myMarkMode = -1;
public void markIfNone(int mode) {
if (mode == myMarkMode || myMark == -1) {
if (myMark == -1) myMark = getIndex();
} else {
flushMarked();
myMark = getIndex();
}
myMarkMode = mode;
}
public void add(DiffFragment fragment) {
flushMarked();
super.add(fragment);
}
protected void flushMarked() {
if (myMark != -1) {
actualAdd(Util.concatenate(getFragments(), myMark, getIndex()));
myMark = -1;
}
}
public void processAll(DiffFragment[] fragments, FragmentProcessor<FragmentBuffer> processor) {
super.processAll(fragments, processor);
flushMarked();
}
}
class ConcatenateSingleSide implements DiffCorrection, FragmentProcessor<FragmentBuffer> {
public static final DiffCorrection INSTANCE = new ConcatenateSingleSide();
private static final int DEFAULT_MODE = 1;
public DiffFragment[] correct(DiffFragment[] fragments) {
FragmentBuffer buffer = new FragmentBuffer();
buffer.processAll(fragments, this);
return buffer.toArray();
}
public void process(DiffFragment fragment, FragmentBuffer buffer) {
if (fragment.isOneSide()) buffer.markIfNone(DEFAULT_MODE);
else buffer.add(fragment);
}
}
class UnitEquals implements DiffCorrection, FragmentProcessor<FragmentBuffer> {
public static final DiffCorrection INSTANCE = new UnitEquals();
private static final int EQUAL_MODE = 1;
private static final int FORMATTING_MODE = 2;
public DiffFragment[] correct(DiffFragment[] fragments) {
FragmentBuffer buffer = new FragmentBuffer();
buffer.processAll(fragments, this);
return buffer.toArray();
}
public void process(DiffFragment fragment, FragmentBuffer buffer) {
if (fragment.isEqual()) buffer.markIfNone(EQUAL_MODE);
else if (ComparisonPolicy.TRIM_SPACE.isEqual(fragment)) buffer.markIfNone(FORMATTING_MODE);
else buffer.add(fragment);
}
}
class Normalize implements DiffCorrection {
public static final DiffCorrection INSTANCE = new Normalize();
private Normalize() {}
public DiffFragment[] correct(DiffFragment[] fragments) {
return UnitEquals.INSTANCE.correct(ConcatenateSingleSide.INSTANCE.correct(fragments));
}
}
class ConnectSingleSideToChange implements DiffCorrection, FragmentProcessor<FragmentBuffer> {
public static final ConnectSingleSideToChange INSTANCE = new ConnectSingleSideToChange();
private static final int CHANGE = 1;
public DiffFragment[] correct(DiffFragment[] fragments) {
FragmentBuffer buffer = new FragmentBuffer();
buffer.processAll(fragments, this);
return buffer.toArray();
}
public void process(DiffFragment fragment, FragmentBuffer buffer) {
if (fragment.isEqual()) buffer.add(fragment);
else if (fragment.isOneSide()) {
String text = FragmentSide.chooseSide(fragment).getText(fragment);
if (StringUtil.endsWithChar(text, '\n'))
buffer.add(fragment);
else
buffer.markIfNone(CHANGE);
} else buffer.markIfNone(CHANGE);
}
}
}
| |
/*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.debugger.v2.stub;
import com.google.api.gax.core.BackgroundResource;
import com.google.api.gax.core.BackgroundResourceAggregation;
import com.google.api.gax.grpc.GrpcCallSettings;
import com.google.api.gax.grpc.GrpcStubCallableFactory;
import com.google.api.gax.rpc.ClientContext;
import com.google.api.gax.rpc.UnaryCallable;
import com.google.common.collect.ImmutableMap;
import com.google.devtools.clouddebugger.v2.ListActiveBreakpointsRequest;
import com.google.devtools.clouddebugger.v2.ListActiveBreakpointsResponse;
import com.google.devtools.clouddebugger.v2.RegisterDebuggeeRequest;
import com.google.devtools.clouddebugger.v2.RegisterDebuggeeResponse;
import com.google.devtools.clouddebugger.v2.UpdateActiveBreakpointRequest;
import com.google.devtools.clouddebugger.v2.UpdateActiveBreakpointResponse;
import com.google.longrunning.stub.GrpcOperationsStub;
import io.grpc.MethodDescriptor;
import io.grpc.protobuf.ProtoUtils;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import javax.annotation.Generated;
// AUTO-GENERATED DOCUMENTATION AND CLASS.
/**
* gRPC stub implementation for the Controller2 service API.
*
* <p>This class is for advanced usage and reflects the underlying API directly.
*/
@Generated("by gapic-generator-java")
public class GrpcController2Stub extends Controller2Stub {
private static final MethodDescriptor<RegisterDebuggeeRequest, RegisterDebuggeeResponse>
registerDebuggeeMethodDescriptor =
MethodDescriptor.<RegisterDebuggeeRequest, RegisterDebuggeeResponse>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName("google.devtools.clouddebugger.v2.Controller2/RegisterDebuggee")
.setRequestMarshaller(
ProtoUtils.marshaller(RegisterDebuggeeRequest.getDefaultInstance()))
.setResponseMarshaller(
ProtoUtils.marshaller(RegisterDebuggeeResponse.getDefaultInstance()))
.build();
private static final MethodDescriptor<ListActiveBreakpointsRequest, ListActiveBreakpointsResponse>
listActiveBreakpointsMethodDescriptor =
MethodDescriptor.<ListActiveBreakpointsRequest, ListActiveBreakpointsResponse>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName(
"google.devtools.clouddebugger.v2.Controller2/ListActiveBreakpoints")
.setRequestMarshaller(
ProtoUtils.marshaller(ListActiveBreakpointsRequest.getDefaultInstance()))
.setResponseMarshaller(
ProtoUtils.marshaller(ListActiveBreakpointsResponse.getDefaultInstance()))
.build();
private static final MethodDescriptor<
UpdateActiveBreakpointRequest, UpdateActiveBreakpointResponse>
updateActiveBreakpointMethodDescriptor =
MethodDescriptor
.<UpdateActiveBreakpointRequest, UpdateActiveBreakpointResponse>newBuilder()
.setType(MethodDescriptor.MethodType.UNARY)
.setFullMethodName(
"google.devtools.clouddebugger.v2.Controller2/UpdateActiveBreakpoint")
.setRequestMarshaller(
ProtoUtils.marshaller(UpdateActiveBreakpointRequest.getDefaultInstance()))
.setResponseMarshaller(
ProtoUtils.marshaller(UpdateActiveBreakpointResponse.getDefaultInstance()))
.build();
private final UnaryCallable<RegisterDebuggeeRequest, RegisterDebuggeeResponse>
registerDebuggeeCallable;
private final UnaryCallable<ListActiveBreakpointsRequest, ListActiveBreakpointsResponse>
listActiveBreakpointsCallable;
private final UnaryCallable<UpdateActiveBreakpointRequest, UpdateActiveBreakpointResponse>
updateActiveBreakpointCallable;
private final BackgroundResource backgroundResources;
private final GrpcOperationsStub operationsStub;
private final GrpcStubCallableFactory callableFactory;
public static final GrpcController2Stub create(Controller2StubSettings settings)
throws IOException {
return new GrpcController2Stub(settings, ClientContext.create(settings));
}
public static final GrpcController2Stub create(ClientContext clientContext) throws IOException {
return new GrpcController2Stub(Controller2StubSettings.newBuilder().build(), clientContext);
}
public static final GrpcController2Stub create(
ClientContext clientContext, GrpcStubCallableFactory callableFactory) throws IOException {
return new GrpcController2Stub(
Controller2StubSettings.newBuilder().build(), clientContext, callableFactory);
}
/**
* Constructs an instance of GrpcController2Stub, using the given settings. This is protected so
* that it is easy to make a subclass, but otherwise, the static factory methods should be
* preferred.
*/
protected GrpcController2Stub(Controller2StubSettings settings, ClientContext clientContext)
throws IOException {
this(settings, clientContext, new GrpcController2CallableFactory());
}
/**
* Constructs an instance of GrpcController2Stub, using the given settings. This is protected so
* that it is easy to make a subclass, but otherwise, the static factory methods should be
* preferred.
*/
protected GrpcController2Stub(
Controller2StubSettings settings,
ClientContext clientContext,
GrpcStubCallableFactory callableFactory)
throws IOException {
this.callableFactory = callableFactory;
this.operationsStub = GrpcOperationsStub.create(clientContext, callableFactory);
GrpcCallSettings<RegisterDebuggeeRequest, RegisterDebuggeeResponse>
registerDebuggeeTransportSettings =
GrpcCallSettings.<RegisterDebuggeeRequest, RegisterDebuggeeResponse>newBuilder()
.setMethodDescriptor(registerDebuggeeMethodDescriptor)
.build();
GrpcCallSettings<ListActiveBreakpointsRequest, ListActiveBreakpointsResponse>
listActiveBreakpointsTransportSettings =
GrpcCallSettings
.<ListActiveBreakpointsRequest, ListActiveBreakpointsResponse>newBuilder()
.setMethodDescriptor(listActiveBreakpointsMethodDescriptor)
.setParamsExtractor(
request -> {
ImmutableMap.Builder<String, String> params = ImmutableMap.builder();
params.put("debuggee_id", String.valueOf(request.getDebuggeeId()));
return params.build();
})
.build();
GrpcCallSettings<UpdateActiveBreakpointRequest, UpdateActiveBreakpointResponse>
updateActiveBreakpointTransportSettings =
GrpcCallSettings
.<UpdateActiveBreakpointRequest, UpdateActiveBreakpointResponse>newBuilder()
.setMethodDescriptor(updateActiveBreakpointMethodDescriptor)
.setParamsExtractor(
request -> {
ImmutableMap.Builder<String, String> params = ImmutableMap.builder();
params.put("breakpoint.id", String.valueOf(request.getBreakpoint().getId()));
params.put("debuggee_id", String.valueOf(request.getDebuggeeId()));
return params.build();
})
.build();
this.registerDebuggeeCallable =
callableFactory.createUnaryCallable(
registerDebuggeeTransportSettings, settings.registerDebuggeeSettings(), clientContext);
this.listActiveBreakpointsCallable =
callableFactory.createUnaryCallable(
listActiveBreakpointsTransportSettings,
settings.listActiveBreakpointsSettings(),
clientContext);
this.updateActiveBreakpointCallable =
callableFactory.createUnaryCallable(
updateActiveBreakpointTransportSettings,
settings.updateActiveBreakpointSettings(),
clientContext);
this.backgroundResources =
new BackgroundResourceAggregation(clientContext.getBackgroundResources());
}
public GrpcOperationsStub getOperationsStub() {
return operationsStub;
}
@Override
public UnaryCallable<RegisterDebuggeeRequest, RegisterDebuggeeResponse>
registerDebuggeeCallable() {
return registerDebuggeeCallable;
}
@Override
public UnaryCallable<ListActiveBreakpointsRequest, ListActiveBreakpointsResponse>
listActiveBreakpointsCallable() {
return listActiveBreakpointsCallable;
}
@Override
public UnaryCallable<UpdateActiveBreakpointRequest, UpdateActiveBreakpointResponse>
updateActiveBreakpointCallable() {
return updateActiveBreakpointCallable;
}
@Override
public final void close() {
try {
backgroundResources.close();
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new IllegalStateException("Failed to close resource", e);
}
}
@Override
public void shutdown() {
backgroundResources.shutdown();
}
@Override
public boolean isShutdown() {
return backgroundResources.isShutdown();
}
@Override
public boolean isTerminated() {
return backgroundResources.isTerminated();
}
@Override
public void shutdownNow() {
backgroundResources.shutdownNow();
}
@Override
public boolean awaitTermination(long duration, TimeUnit unit) throws InterruptedException {
return backgroundResources.awaitTermination(duration, unit);
}
}
| |
package grails.plugins.mongodb;
import com.google.code.morphia.annotations.Embedded;
import com.google.code.morphia.annotations.Reference;
import com.google.code.morphia.annotations.Transient;
import com.google.code.morphia.mapping.MappedClass;
import grails.util.GrailsNameUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.codehaus.groovy.grails.commons.GrailsDomainClass;
import org.codehaus.groovy.grails.commons.GrailsDomainClassProperty;
import org.codehaus.groovy.grails.validation.ConstrainedProperty;
import java.beans.PropertyDescriptor;
import java.lang.reflect.*;
import java.util.*;
/**
* Author: Juri Kuehn
* Date: 02.06.2010
*/
public class MongoDomainClassProperty implements GrailsDomainClassProperty {
private Class ownerClass;
private Field field;
private String name;
private Class type;
private MongoDomainClass domainClass;
private Method getter;
private boolean persistent = true;
private boolean identity = false;
public MongoDomainClassProperty(MongoDomainClass domain, Field field, PropertyDescriptor descriptor) {
this.ownerClass = domain.getClazz();
this.domainClass = domain;
this.field = field;
this.name = descriptor.getName();
this.type = descriptor.getPropertyType();
this.getter = descriptor.getReadMethod();
this.persistent = checkPersistence(descriptor, field);
checkIfTransient();
}
private boolean checkPersistence(PropertyDescriptor descriptor, Field field) {
// no transients
if ((field.getModifiers() & Modifier.TRANSIENT) > 0 || field.getAnnotation(Transient.class) != null) {
return false;
}
// check if type is supported
if (!MappedClass.isSupportedType(field.getType())
&& field.getAnnotation(Embedded.class) == null
&& field.getAnnotation(Reference.class) == null) {
return false;
}
// check if groovy/java property
if (descriptor.getName().equals("class")
|| descriptor.getName().equals("metaClass")) {
return false;
}
return true;
}
// Checks whether this property is transient... copied from DefaultGrailsDomainClassProperty.
private void checkIfTransient() {
if (isAnnotatedWith(Transient.class)) {
this.persistent = false;
} else {
List transientProps = getTransients(domainClass);
if (transientProps != null) {
for (Object currentObj : transientProps) {
// make sure its a string otherwise ignore. Note: Again maybe a warning?
if (currentObj instanceof String) {
String propertyName = (String) currentObj;
// if the property name is on the not persistant list
// then set persistant to false
if (propertyName.equals(this.name)) {
this.persistent = false;
if (!isAnnotatedWith(Transient.class))
domainClass.log(ownerClass.getName() + "." + this.name + " should be annotated with morphias Transient!");
break;
}
}
}
}
}
}
// Retrieves the transient properties... copied from DefaultGrailsDomainClassProperty.
private List getTransients(GrailsDomainClass domainClass) {
List transientProps;
transientProps = domainClass.getPropertyValue(TRANSIENT, List.class);
// Undocumented feature alert! Steve insisted on this :-)
List evanescent = domainClass.getPropertyValue(EVANESCENT, List.class);
if (evanescent != null) {
if (transientProps == null) {
transientProps = new ArrayList();
}
transientProps.addAll(evanescent);
}
return transientProps;
}
public int getFetchMode() {
return FETCH_EAGER;
}
public String getName() {
return this.name;
}
public Class getType() {
return this.type;
}
public Class getReferencedPropertyType() {
if (Collection.class.isAssignableFrom(getType())) {
final Type genericType = field.getGenericType();
if (genericType instanceof ParameterizedType) {
final Type[] arguments = ((ParameterizedType) genericType).getActualTypeArguments();
if (arguments.length > 0) {
if (arguments[0] instanceof ParameterizedType) { // in case it is also parameterized, e.g. List<Key<DomainClass>>
return (Class)((ParameterizedType)arguments[0]).getRawType();
} else if (arguments[0] instanceof Class) {
return (Class)arguments[0];
}
}
}
}
return getType();
}
public GrailsDomainClassProperty getOtherSide() {
return null;
}
public String getTypePropertyName() {
return GrailsNameUtils.getPropertyName(getType());
}
public GrailsDomainClass getDomainClass() {
return domainClass;
}
public boolean isPersistent() {
return persistent;
}
public boolean isOptional() {
ConstrainedProperty constrainedProperty = (ConstrainedProperty) domainClass.getConstrainedProperties().get(name);
return (constrainedProperty != null) && constrainedProperty.isNullable();
}
public boolean isIdentity() {
return identity;
}
public void setIdentity(boolean identity) {
this.identity = identity;
}
public boolean isOneToMany() {
return false;
}
public boolean isManyToOne() {
return false;
}
public boolean isManyToMany() {
return false;
}
public boolean isBidirectional() {
return false;
}
public String getFieldName() {
return getName().toUpperCase();
}
public boolean isOneToOne() {
return false;
}
public GrailsDomainClass getReferencedDomainClass() {
return null;
}
public boolean isAssociation() {
return false;
}
public boolean isEnum() {
return false;
}
public String getNaturalName() {
return GrailsNameUtils.getNaturalName(name);
}
public void setReferencedDomainClass(GrailsDomainClass referencedGrailsDomainClass) {
}
public void setOtherSide(GrailsDomainClassProperty referencedProperty) {
}
public boolean isInherited() {
return false;
}
public boolean isOwningSide() {
return false;
}
public boolean isCircular() {
return getType().equals(ownerClass);
}
public String getReferencedPropertyName() {
return null;
}
public boolean isEmbedded() {
return false;
}
public GrailsDomainClass getComponent() {
return null;
}
public void setOwningSide(boolean b) {
}
public boolean isBasicCollectionType() {
// @todo cache result?
Class c = this.type;
boolean found = (c == Collection.class);
while (c != null && !found) {
found = (ArrayUtils.contains(c.getInterfaces(), Collection.class));
c = c.getSuperclass();
}
return found;
}
public boolean isAnnotatedWith(Class annotation) {
return (field != null && field.getAnnotation(annotation) != null) || (getter != null && getter.getAnnotation(annotation) != null);
}
// grails 1.2 GrailsDomainClass
public boolean isHasOne() {
return false;
}
public void setDerived(boolean derived) {
// no action
}
public boolean isDerived() {
return false;
}
public String toString() {
String assType = null;
if (isManyToMany()) {
assType = "many-to-many";
} else if (isOneToMany()) {
assType = "one-to-many";
} else if (isOneToOne()) {
assType = "one-to-one";
} else if (isManyToOne()) {
assType = "many-to-one";
} else if (isEmbedded()) {
assType = "embedded";
}
return new ToStringBuilder(this).append("name", this.name).append("type", this.type).append("persistent", isPersistent()).append("optional", isOptional()).append("association", isAssociation()).append("bidirectional", isBidirectional()).append("association-type", assType).toString();
}
}
| |
/*
* Copyright 2009-2013 by The Regents of the University of California
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* you may obtain a copy of the License from
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.uci.ics.hyracks.dataflow.std.file;
import java.io.IOException;
import java.io.Reader;
import java.util.Arrays;
public class FieldCursorForDelimitedDataParser {
private enum State {
INIT,
IN_RECORD,
EOR,
CR,
EOF
}
// public variables will be used by delimited data parser
public char[] buffer;
public int fStart;
public int fEnd;
public int recordCount;
public int fieldCount;
public int doubleQuoteCount;
public boolean isDoubleQuoteIncludedInThisField;
private static final int INITIAL_BUFFER_SIZE = 4096;
private static final int INCREMENT = 4096;
private final Reader in;
private int start;
private int end;
private State state;
private int lastQuotePosition;
private int lastDoubleQuotePosition;
private int lastDelimiterPosition;
private int quoteCount;
private boolean startedQuote;
private char quote;
private char fieldDelimiter;
public FieldCursorForDelimitedDataParser(Reader in, char fieldDelimiter, char quote) {
this.in = in;
buffer = new char[INITIAL_BUFFER_SIZE];
start = 0;
end = 0;
state = State.INIT;
this.quote = quote;
this.fieldDelimiter = fieldDelimiter;
lastDelimiterPosition = -99;
lastQuotePosition = -99;
lastDoubleQuotePosition = -99;
quoteCount = 0;
doubleQuoteCount = 0;
startedQuote = false;
isDoubleQuoteIncludedInThisField = false;
recordCount = 0;
fieldCount = 0;
}
public boolean nextRecord() throws IOException {
recordCount++;
fieldCount = 0;
while (true) {
switch (state) {
case INIT:
boolean eof = !readMore();
if (eof) {
state = State.EOF;
return false;
} else {
state = State.IN_RECORD;
return true;
}
case IN_RECORD:
int p = start;
while (true) {
if (p >= end) {
int s = start;
eof = !readMore();
if (eof) {
state = State.EOF;
return start < end;
}
p -= (s - start);
lastQuotePosition -= (s - start);
lastDoubleQuotePosition -= (s - start);
lastDelimiterPosition -= (s - start);
}
char ch = buffer[p];
// We perform rough format correctness (delimiter, quote) check here
// to set the starting position of a record.
// In the field level, more checking will be conducted.
if (ch == quote) {
startedQuote = true;
// check two quotes in a row - "". This is an escaped quote
if (lastQuotePosition == p - 1 && start != p - 1 && lastDoubleQuotePosition != p - 1) {
lastDoubleQuotePosition = p;
}
lastQuotePosition = p;
} else if (ch == fieldDelimiter) {
if (startedQuote && lastQuotePosition == p - 1 && lastDoubleQuotePosition != p - 1) {
startedQuote = false;
lastDelimiterPosition = p;
}
} else if (ch == '\n' && !startedQuote) {
start = p + 1;
state = State.EOR;
lastDelimiterPosition = p;
break;
} else if (ch == '\r' && !startedQuote) {
start = p + 1;
state = State.CR;
lastDelimiterPosition = p;
break;
}
++p;
}
break;
case CR:
if (start >= end) {
eof = !readMore();
if (eof) {
state = State.EOF;
return false;
}
}
char ch = buffer[start];
if (ch == '\n' && !startedQuote) {
++start;
state = State.EOR;
} else {
state = State.IN_RECORD;
return true;
}
case EOR:
if (start >= end) {
eof = !readMore();
if (eof) {
state = State.EOF;
return false;
}
}
state = State.IN_RECORD;
lastDelimiterPosition = start;
return start < end;
case EOF:
return false;
}
}
}
public boolean nextField() throws IOException {
fieldCount++;
switch (state) {
case INIT:
case EOR:
case EOF:
case CR:
return false;
case IN_RECORD:
boolean eof;
// reset quote related values
startedQuote = false;
isDoubleQuoteIncludedInThisField = false;
lastQuotePosition = -99;
lastDoubleQuotePosition = -99;
quoteCount = 0;
doubleQuoteCount = 0;
int p = start;
while (true) {
if (p >= end) {
int s = start;
eof = !readMore();
p -= (s - start);
lastQuotePosition -= (s - start);
lastDoubleQuotePosition -= (s - start);
lastDelimiterPosition -= (s - start);
if (eof) {
state = State.EOF;
if (startedQuote && lastQuotePosition == p - 1 && lastDoubleQuotePosition != p - 1
&& quoteCount == doubleQuoteCount * 2 + 2) {
// set the position of fStart to +1, fEnd to -1 to remove quote character
fStart = start + 1;
fEnd = p - 1;
} else {
fStart = start;
fEnd = p;
}
return true;
}
}
char ch = buffer[p];
if (ch == quote) {
// If this is first quote in the field, then it needs to be placed in the beginning.
if (!startedQuote) {
if (lastDelimiterPosition == p - 1 || lastDelimiterPosition == -99) {
startedQuote = true;
} else {
// In this case, we don't have a quote in the beginning of a field.
throw new IOException(
"At record: "
+ recordCount
+ ", field#: "
+ fieldCount
+ " - a quote enclosing a field needs to be placed in the beginning of that field.");
}
}
// Check double quotes - "". We check [start != p-2]
// to avoid false positive where there is no value in a field,
// since it looks like a double quote. However, it's not a double quote.
// (e.g. if field2 has no value:
// field1,"",field3 ... )
if (lastQuotePosition == p - 1 && lastDelimiterPosition != p - 2
&& lastDoubleQuotePosition != p - 1) {
isDoubleQuoteIncludedInThisField = true;
doubleQuoteCount++;
lastDoubleQuotePosition = p;
}
lastQuotePosition = p;
quoteCount++;
} else if (ch == fieldDelimiter) {
// If there was no quote in the field,
// then we assume that the field contains a valid string.
if (!startedQuote) {
fStart = start;
fEnd = p;
start = p + 1;
lastDelimiterPosition = p;
return true;
} else if (startedQuote) {
if (lastQuotePosition == p - 1 && lastDoubleQuotePosition != p - 1) {
// There is a quote right before the delimiter (e.g. ",) and it is not two quote,
// then the field contains a valid string.
// We set the position of fStart to +1, fEnd to -1 to remove quote character
fStart = start + 1;
fEnd = p - 1;
start = p + 1;
lastDelimiterPosition = p;
startedQuote = false;
return true;
} else if (lastQuotePosition < p - 1 && lastQuotePosition != lastDoubleQuotePosition
&& quoteCount == doubleQuoteCount * 2 + 2) {
// There is a quote before the delimiter, however it is not directly placed before the delimiter.
// In this case, we throw an exception.
// quoteCount == doubleQuoteCount * 2 + 2 : only true when we have two quotes except double-quotes.
throw new IOException("At record: " + recordCount + ", field#: " + fieldCount
+ " - A quote enclosing a field needs to be followed by the delimiter.");
}
}
// If the control flow reaches here: we have a delimiter in this field and
// there should be a quote in the beginning and the end of
// this field. So, just continue reading next character
} else if (ch == '\n') {
if (!startedQuote) {
fStart = start;
fEnd = p;
start = p + 1;
state = State.EOR;
lastDelimiterPosition = p;
return true;
} else if (startedQuote && lastQuotePosition == p - 1 && lastDoubleQuotePosition != p - 1
&& quoteCount == doubleQuoteCount * 2 + 2) {
// set the position of fStart to +1, fEnd to -1 to remove quote character
fStart = start + 1;
fEnd = p - 1;
lastDelimiterPosition = p;
start = p + 1;
state = State.EOR;
startedQuote = false;
return true;
}
} else if (ch == '\r') {
if (!startedQuote) {
fStart = start;
fEnd = p;
start = p + 1;
state = State.CR;
lastDelimiterPosition = p;
return true;
} else if (startedQuote && lastQuotePosition == p - 1 && lastDoubleQuotePosition != p - 1
&& quoteCount == doubleQuoteCount * 2 + 2) {
// set the position of fStart to +1, fEnd to -1 to remove quote character
fStart = start + 1;
fEnd = p - 1;
lastDelimiterPosition = p;
start = p + 1;
state = State.CR;
startedQuote = false;
return true;
}
}
++p;
}
}
throw new IllegalStateException();
}
protected boolean readMore() throws IOException {
if (start > 0) {
System.arraycopy(buffer, start, buffer, 0, end - start);
}
end -= start;
start = 0;
if (end == buffer.length) {
buffer = Arrays.copyOf(buffer, buffer.length + INCREMENT);
}
int n = in.read(buffer, end, buffer.length - end);
if (n < 0) {
return false;
}
end += n;
return true;
}
// Eliminate escaped double quotes("") in a field
public void eliminateDoubleQuote(char[] buffer, int start, int length) {
int lastDoubleQuotePosition = -99;
int writepos = start;
int readpos = start;
// Find positions where double quotes appear
for (int i = 0; i < length; i++) {
// Skip double quotes
if (buffer[readpos] == quote && lastDoubleQuotePosition != readpos - 1) {
lastDoubleQuotePosition = readpos;
readpos++;
} else {
// Moving characters except double quote to the front
if (writepos != readpos) {
buffer[writepos] = buffer[readpos];
}
writepos++;
readpos++;
}
}
}
}
| |
/*
* MIT License
*
* Copyright (c) 2016. Dmytro Karataiev
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.adkdevelopment.e_contact.data.model;
import android.os.Parcel;
import android.os.Parcelable;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class TaskUser implements Parcelable {
@SerializedName("id")
@Expose
private int id;
@SerializedName("first_name")
@Expose
private String firstName;
@SerializedName("last_name")
@Expose
private String lastName;
@SerializedName("middle_name")
@Expose
private String middleName;
@SerializedName("email")
@Expose
private String email;
@SerializedName("birthday")
@Expose
private long birthday;
@SerializedName("address")
@Expose
private TaskAddress address;
@SerializedName("fb_registered")
@Expose
private int fbRegistered;
/**
*
* @return
* The id
*/
public int getId() {
return id;
}
/**
*
* @param id
* The id
*/
public void setId(int id) {
this.id = id;
}
/**
*
* @return
* The firstName
*/
public String getFirstName() {
return firstName;
}
/**
*
* @param firstName
* The first_name
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
*
* @return
* The lastName
*/
public String getLastName() {
return lastName;
}
/**
*
* @param lastName
* The last_name
*/
public void setLastName(String lastName) {
this.lastName = lastName;
}
/**
*
* @return
* The middleName
*/
public String getMiddleName() {
return middleName;
}
/**
*
* @param middleName
* The middle_name
*/
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
/**
*
* @return
* The email
*/
public String getEmail() {
return email;
}
/**
*
* @param email
* The email
*/
public void setEmail(String email) {
this.email = email;
}
/**
*
* @return
* The birthday
*/
public long getBirthday() {
return birthday;
}
/**
*
* @param birthday
* The birthday
*/
public void setBirthday(long birthday) {
this.birthday = birthday;
}
/**
*
* @return
* The address
*/
public TaskAddress getAddress() {
return address;
}
/**
*
* @param address
* The address
*/
public void setAddress(TaskAddress address) {
this.address = address;
}
/**
*
* @return
* The fbRegistered
*/
public int getFbRegistered() {
return fbRegistered;
}
/**
*
* @param fbRegistered
* The fb_registered
*/
public void setFbRegistered(int fbRegistered) {
this.fbRegistered = fbRegistered;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(this.id);
dest.writeString(this.firstName);
dest.writeString(this.lastName);
dest.writeString(this.middleName);
dest.writeString(this.email);
dest.writeLong(this.birthday);
dest.writeParcelable(this.address, flags);
dest.writeInt(this.fbRegistered);
}
public TaskUser() {
}
protected TaskUser(Parcel in) {
this.id = in.readInt();
this.firstName = in.readString();
this.lastName = in.readString();
this.middleName = in.readString();
this.email = in.readString();
this.birthday = in.readLong();
this.address = in.readParcelable(TaskAddress.class.getClassLoader());
this.fbRegistered = in.readInt();
}
public static final Parcelable.Creator<TaskUser> CREATOR = new Parcelable.Creator<TaskUser>() {
@Override
public TaskUser createFromParcel(Parcel source) {
return new TaskUser(source);
}
@Override
public TaskUser[] newArray(int size) {
return new TaskUser[size];
}
};
}
| |
package com.google.android.gms.internal;
import android.os.SystemClock;
import java.io.EOFException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public final class zzv
implements zzb
{
private final Map<String, zza> zzaw = new LinkedHashMap(16, 0.75F, true);
private long zzax = 0L;
private final File zzay;
private final int zzaz;
private zzv(File paramFile)
{
this.zzay = paramFile;
this.zzaz = 5242880;
}
public zzv(File paramFile, byte paramByte)
{
this(paramFile);
}
private void remove(String paramString)
{
try
{
boolean bool = zzf(paramString).delete();
zza localzza = (zza)this.zzaw.get(paramString);
if (localzza != null)
{
this.zzax -= localzza.zzaA;
this.zzaw.remove(paramString);
}
if (!bool)
{
Object[] arrayOfObject = new Object[2];
arrayOfObject[0] = paramString;
arrayOfObject[1] = zze(paramString);
zzs.zzb("Could not delete cache entry for key=%s, filename=%s", arrayOfObject);
}
return;
}
finally {}
}
private static int zza(InputStream paramInputStream)
throws IOException
{
int i = paramInputStream.read();
if (i == -1) {
throw new EOFException();
}
return i;
}
static void zza(OutputStream paramOutputStream, int paramInt)
throws IOException
{
paramOutputStream.write(0xFF & paramInt >> 0);
paramOutputStream.write(0xFF & paramInt >> 8);
paramOutputStream.write(0xFF & paramInt >> 16);
paramOutputStream.write(0xFF & paramInt >> 24);
}
static void zza(OutputStream paramOutputStream, long paramLong)
throws IOException
{
paramOutputStream.write((byte)(int)(paramLong >>> 0));
paramOutputStream.write((byte)(int)(paramLong >>> 8));
paramOutputStream.write((byte)(int)(paramLong >>> 16));
paramOutputStream.write((byte)(int)(paramLong >>> 24));
paramOutputStream.write((byte)(int)(paramLong >>> 32));
paramOutputStream.write((byte)(int)(paramLong >>> 40));
paramOutputStream.write((byte)(int)(paramLong >>> 48));
paramOutputStream.write((byte)(int)(paramLong >>> 56));
}
static void zza(OutputStream paramOutputStream, String paramString)
throws IOException
{
byte[] arrayOfByte = paramString.getBytes("UTF-8");
zza(paramOutputStream, arrayOfByte.length);
paramOutputStream.write(arrayOfByte, 0, arrayOfByte.length);
}
private void zza(String paramString, zza paramzza)
{
if (!this.zzaw.containsKey(paramString)) {}
zza localzza;
for (this.zzax += paramzza.zzaA;; this.zzax += paramzza.zzaA - localzza.zzaA)
{
this.zzaw.put(paramString, paramzza);
return;
localzza = (zza)this.zzaw.get(paramString);
}
}
private static byte[] zza(InputStream paramInputStream, int paramInt)
throws IOException
{
byte[] arrayOfByte = new byte[paramInt];
int i = 0;
while (i < paramInt)
{
int j = paramInputStream.read(arrayOfByte, i, paramInt - i);
if (j == -1) {
break;
}
i += j;
}
if (i != paramInt) {
throw new IOException("Expected " + paramInt + " bytes, read " + i + " bytes");
}
return arrayOfByte;
}
static int zzb(InputStream paramInputStream)
throws IOException
{
return 0x0 | zza(paramInputStream) << 0 | zza(paramInputStream) << 8 | zza(paramInputStream) << 16 | zza(paramInputStream) << 24;
}
static long zzc(InputStream paramInputStream)
throws IOException
{
return 0L | (0xFF & zza(paramInputStream)) << 0 | (0xFF & zza(paramInputStream)) << 8 | (0xFF & zza(paramInputStream)) << 16 | (0xFF & zza(paramInputStream)) << 24 | (0xFF & zza(paramInputStream)) << 32 | (0xFF & zza(paramInputStream)) << 40 | (0xFF & zza(paramInputStream)) << 48 | (0xFF & zza(paramInputStream)) << 56;
}
static String zzd(InputStream paramInputStream)
throws IOException
{
return new String(zza(paramInputStream, (int)zzc(paramInputStream)), "UTF-8");
}
private static String zze(String paramString)
{
int i = paramString.length() / 2;
String str = String.valueOf(paramString.substring(0, i).hashCode());
return str + String.valueOf(paramString.substring(i).hashCode());
}
static Map<String, String> zze(InputStream paramInputStream)
throws IOException
{
int i = zzb(paramInputStream);
if (i == 0) {}
for (Object localObject = Collections.emptyMap();; localObject = new HashMap(i)) {
for (int j = 0; j < i; j++) {
((Map)localObject).put(zzd(paramInputStream).intern(), zzd(paramInputStream).intern());
}
}
return localObject;
}
private File zzf(String paramString)
{
return new File(this.zzay, zze(paramString));
}
/* Error */
public final zzb.zza zza(String paramString)
{
// Byte code:
// 0: aload_0
// 1: monitorenter
// 2: aload_0
// 3: getfield 28 com/google/android/gms/internal/zzv:zzaw Ljava/util/Map;
// 6: aload_1
// 7: invokeinterface 56 2 0
// 12: checkcast 58 com/google/android/gms/internal/zzv$zza
// 15: astore_3
// 16: aload_3
// 17: ifnonnull +11 -> 28
// 20: aconst_null
// 21: astore 10
// 23: aload_0
// 24: monitorexit
// 25: aload 10
// 27: areturn
// 28: aload_0
// 29: aload_1
// 30: invokespecial 44 com/google/android/gms/internal/zzv:zzf (Ljava/lang/String;)Ljava/io/File;
// 33: astore 4
// 35: new 201 com/google/android/gms/internal/zzv$zzb
// 38: dup
// 39: new 203 java/io/FileInputStream
// 42: dup
// 43: aload 4
// 45: invokespecial 204 java/io/FileInputStream:<init> (Ljava/io/File;)V
// 48: iconst_0
// 49: invokespecial 207 com/google/android/gms/internal/zzv$zzb:<init> (Ljava/io/InputStream;B)V
// 52: astore 5
// 54: aload 5
// 56: invokestatic 210 com/google/android/gms/internal/zzv$zza:zzf (Ljava/io/InputStream;)Lcom/google/android/gms/internal/zzv$zza;
// 59: pop
// 60: aload 5
// 62: aload 4
// 64: invokevirtual 213 java/io/File:length ()J
// 67: aload 5
// 69: invokestatic 216 com/google/android/gms/internal/zzv$zzb:zza (Lcom/google/android/gms/internal/zzv$zzb;)I
// 72: i2l
// 73: lsub
// 74: l2i
// 75: invokestatic 157 com/google/android/gms/internal/zzv:zza (Ljava/io/InputStream;I)[B
// 78: astore 14
// 80: new 218 com/google/android/gms/internal/zzb$zza
// 83: dup
// 84: invokespecial 219 com/google/android/gms/internal/zzb$zza:<init> ()V
// 87: astore 15
// 89: aload 15
// 91: aload 14
// 93: putfield 223 com/google/android/gms/internal/zzb$zza:data [B
// 96: aload 15
// 98: aload_3
// 99: getfield 226 com/google/android/gms/internal/zzv$zza:zzb Ljava/lang/String;
// 102: putfield 227 com/google/android/gms/internal/zzb$zza:zzb Ljava/lang/String;
// 105: aload 15
// 107: aload_3
// 108: getfield 229 com/google/android/gms/internal/zzv$zza:zzc J
// 111: putfield 230 com/google/android/gms/internal/zzb$zza:zzc J
// 114: aload 15
// 116: aload_3
// 117: getfield 232 com/google/android/gms/internal/zzv$zza:zzd J
// 120: putfield 233 com/google/android/gms/internal/zzb$zza:zzd J
// 123: aload 15
// 125: aload_3
// 126: getfield 235 com/google/android/gms/internal/zzv$zza:zze J
// 129: putfield 236 com/google/android/gms/internal/zzb$zza:zze J
// 132: aload 15
// 134: aload_3
// 135: getfield 238 com/google/android/gms/internal/zzv$zza:zzf J
// 138: putfield 239 com/google/android/gms/internal/zzb$zza:zzf J
// 141: aload 15
// 143: aload_3
// 144: getfield 242 com/google/android/gms/internal/zzv$zza:zzg Ljava/util/Map;
// 147: putfield 243 com/google/android/gms/internal/zzb$zza:zzg Ljava/util/Map;
// 150: aload 5
// 152: invokevirtual 246 com/google/android/gms/internal/zzv$zzb:close ()V
// 155: aload 15
// 157: astore 10
// 159: goto -136 -> 23
// 162: astore 16
// 164: aconst_null
// 165: astore 10
// 167: goto -144 -> 23
// 170: astore 6
// 172: aconst_null
// 173: astore 7
// 175: iconst_2
// 176: anewarray 4 java/lang/Object
// 179: astore 11
// 181: aload 11
// 183: iconst_0
// 184: aload 4
// 186: invokevirtual 249 java/io/File:getAbsolutePath ()Ljava/lang/String;
// 189: aastore
// 190: aload 11
// 192: iconst_1
// 193: aload 6
// 195: invokevirtual 250 java/io/IOException:toString ()Ljava/lang/String;
// 198: aastore
// 199: ldc 252
// 201: aload 11
// 203: invokestatic 75 com/google/android/gms/internal/zzs:zzb (Ljava/lang/String;[Ljava/lang/Object;)V
// 206: aload_0
// 207: aload_1
// 208: invokespecial 254 com/google/android/gms/internal/zzv:remove (Ljava/lang/String;)V
// 211: aload 7
// 213: ifnull +8 -> 221
// 216: aload 7
// 218: invokevirtual 246 com/google/android/gms/internal/zzv$zzb:close ()V
// 221: aconst_null
// 222: astore 10
// 224: goto -201 -> 23
// 227: astore 12
// 229: aconst_null
// 230: astore 10
// 232: goto -209 -> 23
// 235: astore 8
// 237: aconst_null
// 238: astore 5
// 240: aload 5
// 242: ifnull +8 -> 250
// 245: aload 5
// 247: invokevirtual 246 com/google/android/gms/internal/zzv$zzb:close ()V
// 250: aload 8
// 252: athrow
// 253: astore_2
// 254: aload_0
// 255: monitorexit
// 256: aload_2
// 257: athrow
// 258: astore 9
// 260: aconst_null
// 261: astore 10
// 263: goto -240 -> 23
// 266: astore 8
// 268: goto -28 -> 240
// 271: astore 8
// 273: aload 7
// 275: astore 5
// 277: goto -37 -> 240
// 280: astore 6
// 282: aload 5
// 284: astore 7
// 286: goto -111 -> 175
// Local variable table:
// start length slot name signature
// 0 289 0 this zzv
// 0 289 1 paramString String
// 253 4 2 localObject1 Object
// 15 129 3 localzza zza
// 33 152 4 localFile File
// 52 231 5 localObject2 Object
// 170 24 6 localIOException1 IOException
// 280 1 6 localIOException2 IOException
// 173 112 7 localObject3 Object
// 235 16 8 localObject4 Object
// 266 1 8 localObject5 Object
// 271 1 8 localObject6 Object
// 258 1 9 localIOException3 IOException
// 21 241 10 localObject7 Object
// 179 23 11 arrayOfObject Object[]
// 227 1 12 localIOException4 IOException
// 78 14 14 arrayOfByte byte[]
// 87 69 15 localzza1 zzb.zza
// 162 1 16 localIOException5 IOException
// Exception table:
// from to target type
// 150 155 162 java/io/IOException
// 35 54 170 java/io/IOException
// 216 221 227 java/io/IOException
// 35 54 235 finally
// 2 16 253 finally
// 28 35 253 finally
// 150 155 253 finally
// 216 221 253 finally
// 245 250 253 finally
// 250 253 253 finally
// 245 250 258 java/io/IOException
// 54 150 266 finally
// 175 211 271 finally
// 54 150 280 java/io/IOException
}
/* Error */
public final void zza()
{
// Byte code:
// 0: aload_0
// 1: monitorenter
// 2: aload_0
// 3: getfield 32 com/google/android/gms/internal/zzv:zzay Ljava/io/File;
// 6: invokevirtual 257 java/io/File:exists ()Z
// 9: ifne +41 -> 50
// 12: aload_0
// 13: getfield 32 com/google/android/gms/internal/zzv:zzay Ljava/io/File;
// 16: invokevirtual 260 java/io/File:mkdirs ()Z
// 19: ifne +28 -> 47
// 22: iconst_1
// 23: anewarray 4 java/lang/Object
// 26: astore 17
// 28: aload 17
// 30: iconst_0
// 31: aload_0
// 32: getfield 32 com/google/android/gms/internal/zzv:zzay Ljava/io/File;
// 35: invokevirtual 249 java/io/File:getAbsolutePath ()Ljava/lang/String;
// 38: aastore
// 39: ldc_w 262
// 42: aload 17
// 44: invokestatic 264 com/google/android/gms/internal/zzs:zzc (Ljava/lang/String;[Ljava/lang/Object;)V
// 47: aload_0
// 48: monitorexit
// 49: return
// 50: aload_0
// 51: getfield 32 com/google/android/gms/internal/zzv:zzay Ljava/io/File;
// 54: invokevirtual 268 java/io/File:listFiles ()[Ljava/io/File;
// 57: astore_2
// 58: aload_2
// 59: ifnull -12 -> 47
// 62: aload_2
// 63: arraylength
// 64: istore_3
// 65: iconst_0
// 66: istore 4
// 68: iload 4
// 70: iload_3
// 71: if_icmpge -24 -> 47
// 74: aload_2
// 75: iload 4
// 77: aaload
// 78: astore 5
// 80: aconst_null
// 81: astore 6
// 83: new 270 java/io/BufferedInputStream
// 86: dup
// 87: new 203 java/io/FileInputStream
// 90: dup
// 91: aload 5
// 93: invokespecial 204 java/io/FileInputStream:<init> (Ljava/io/File;)V
// 96: invokespecial 273 java/io/BufferedInputStream:<init> (Ljava/io/InputStream;)V
// 99: astore 7
// 101: aload 7
// 103: invokestatic 210 com/google/android/gms/internal/zzv$zza:zzf (Ljava/io/InputStream;)Lcom/google/android/gms/internal/zzv$zza;
// 106: astore 14
// 108: aload 14
// 110: aload 5
// 112: invokevirtual 213 java/io/File:length ()J
// 115: putfield 61 com/google/android/gms/internal/zzv$zza:zzaA J
// 118: aload_0
// 119: aload 14
// 121: getfield 276 com/google/android/gms/internal/zzv$zza:key Ljava/lang/String;
// 124: aload 14
// 126: invokespecial 278 com/google/android/gms/internal/zzv:zza (Ljava/lang/String;Lcom/google/android/gms/internal/zzv$zza;)V
// 129: aload 7
// 131: invokevirtual 279 java/io/BufferedInputStream:close ()V
// 134: iinc 4 1
// 137: goto -69 -> 68
// 140: astore 16
// 142: aconst_null
// 143: astore 7
// 145: aload 5
// 147: ifnull +9 -> 156
// 150: aload 5
// 152: invokevirtual 50 java/io/File:delete ()Z
// 155: pop
// 156: aload 7
// 158: ifnull -24 -> 134
// 161: aload 7
// 163: invokevirtual 279 java/io/BufferedInputStream:close ()V
// 166: goto -32 -> 134
// 169: astore 9
// 171: goto -37 -> 134
// 174: astore 11
// 176: aload 6
// 178: ifnull +8 -> 186
// 181: aload 6
// 183: invokevirtual 279 java/io/BufferedInputStream:close ()V
// 186: aload 11
// 188: athrow
// 189: astore_1
// 190: aload_0
// 191: monitorexit
// 192: aload_1
// 193: athrow
// 194: astore 15
// 196: goto -62 -> 134
// 199: astore 12
// 201: goto -15 -> 186
// 204: astore 10
// 206: aload 7
// 208: astore 6
// 210: aload 10
// 212: astore 11
// 214: goto -38 -> 176
// 217: astore 8
// 219: goto -74 -> 145
// Local variable table:
// start length slot name signature
// 0 222 0 this zzv
// 189 4 1 localObject1 Object
// 57 18 2 arrayOfFile File[]
// 64 8 3 i int
// 66 69 4 j int
// 78 73 5 localFile File
// 81 128 6 localObject2 Object
// 99 108 7 localBufferedInputStream java.io.BufferedInputStream
// 217 1 8 localIOException1 IOException
// 169 1 9 localIOException2 IOException
// 204 7 10 localObject3 Object
// 174 13 11 localObject4 Object
// 212 1 11 localObject5 Object
// 199 1 12 localIOException3 IOException
// 106 19 14 localzza zza
// 194 1 15 localIOException4 IOException
// 140 1 16 localIOException5 IOException
// 26 17 17 arrayOfObject Object[]
// Exception table:
// from to target type
// 83 101 140 java/io/IOException
// 161 166 169 java/io/IOException
// 83 101 174 finally
// 2 47 189 finally
// 50 58 189 finally
// 62 65 189 finally
// 74 80 189 finally
// 129 134 189 finally
// 161 166 189 finally
// 181 186 189 finally
// 186 189 189 finally
// 129 134 194 java/io/IOException
// 181 186 199 java/io/IOException
// 101 129 204 finally
// 150 156 204 finally
// 101 129 217 java/io/IOException
}
public final void zza(String paramString, zzb.zza paramzza)
{
int i = 0;
for (;;)
{
FileOutputStream localFileOutputStream;
zza localzza1;
try
{
int j = paramzza.data.length;
zza localzza2;
if (this.zzax + j >= this.zzaz)
{
if (zzs.DEBUG) {
zzs.zza("Pruning old cache entries.", new Object[0]);
}
long l1 = this.zzax;
long l2 = SystemClock.elapsedRealtime();
Iterator localIterator = this.zzaw.entrySet().iterator();
if (!localIterator.hasNext()) {
break label405;
}
localzza2 = (zza)((Map.Entry)localIterator.next()).getValue();
if (!zzf(localzza2.key).delete()) {
continue;
}
this.zzax -= localzza2.zzaA;
localIterator.remove();
k = i + 1;
if ((float)(this.zzax + j) >= 0.9F * this.zzaz) {
break label399;
}
if (zzs.DEBUG)
{
Object[] arrayOfObject3 = new Object[3];
arrayOfObject3[0] = Integer.valueOf(k);
arrayOfObject3[1] = Long.valueOf(this.zzax - l1);
arrayOfObject3[2] = Long.valueOf(SystemClock.elapsedRealtime() - l2);
zzs.zza("pruned %d files, %d bytes, %d ms", arrayOfObject3);
}
}
File localFile = zzf(paramString);
try
{
localFileOutputStream = new FileOutputStream(localFile);
localzza1 = new zza(paramString, paramzza);
if (localzza1.zza(localFileOutputStream)) {
break label375;
}
localFileOutputStream.close();
Object[] arrayOfObject2 = new Object[1];
arrayOfObject2[0] = localFile.getAbsolutePath();
zzs.zzb("Failed to write header for %s", arrayOfObject2);
throw new IOException();
}
catch (IOException localIOException)
{
if (!localFile.delete())
{
Object[] arrayOfObject1 = new Object[1];
arrayOfObject1[0] = localFile.getAbsolutePath();
zzs.zzb("Could not clean up file %s", arrayOfObject1);
}
}
return;
Object[] arrayOfObject4 = new Object[2];
arrayOfObject4[0] = localzza2.key;
arrayOfObject4[1] = zze(localzza2.key);
zzs.zzb("Could not delete cache entry for key=%s, filename=%s", arrayOfObject4);
continue;
localFileOutputStream.write(paramzza.data);
}
finally {}
label375:
localFileOutputStream.close();
zza(paramString, localzza1);
continue;
label399:
i = k;
continue;
label405:
int k = i;
}
}
static final class zza
{
public String key;
public long zzaA;
public String zzb;
public long zzc;
public long zzd;
public long zze;
public long zzf;
public Map<String, String> zzg;
private zza() {}
public zza(String paramString, zzb.zza paramzza)
{
this.key = paramString;
this.zzaA = paramzza.data.length;
this.zzb = paramzza.zzb;
this.zzc = paramzza.zzc;
this.zzd = paramzza.zzd;
this.zze = paramzza.zze;
this.zzf = paramzza.zzf;
this.zzg = paramzza.zzg;
}
public static zza zzf(InputStream paramInputStream)
throws IOException
{
zza localzza = new zza();
if (zzv.zzb(paramInputStream) != 538247942) {
throw new IOException();
}
localzza.key = zzv.zzd(paramInputStream);
localzza.zzb = zzv.zzd(paramInputStream);
if (localzza.zzb.equals("")) {
localzza.zzb = null;
}
localzza.zzc = zzv.zzc(paramInputStream);
localzza.zzd = zzv.zzc(paramInputStream);
localzza.zze = zzv.zzc(paramInputStream);
localzza.zzf = zzv.zzc(paramInputStream);
localzza.zzg = zzv.zze(paramInputStream);
return localzza;
}
public final boolean zza(OutputStream paramOutputStream)
{
for (;;)
{
try
{
zzv.zza(paramOutputStream, 538247942);
zzv.zza(paramOutputStream, this.key);
if (this.zzb == null)
{
str = "";
zzv.zza(paramOutputStream, str);
zzv.zza(paramOutputStream, this.zzc);
zzv.zza(paramOutputStream, this.zzd);
zzv.zza(paramOutputStream, this.zze);
zzv.zza(paramOutputStream, this.zzf);
Map localMap = this.zzg;
if (localMap == null) {
break;
}
zzv.zza(paramOutputStream, localMap.size());
Iterator localIterator = localMap.entrySet().iterator();
if (!localIterator.hasNext()) {
break label187;
}
Map.Entry localEntry = (Map.Entry)localIterator.next();
zzv.zza(paramOutputStream, (String)localEntry.getKey());
zzv.zza(paramOutputStream, (String)localEntry.getValue());
continue;
}
Object[] arrayOfObject;
String str = this.zzb;
}
catch (IOException localIOException)
{
arrayOfObject = new Object[1];
arrayOfObject[0] = localIOException.toString();
zzs.zzb("%s", arrayOfObject);
return false;
}
}
zzv.zza(paramOutputStream, 0);
label187:
paramOutputStream.flush();
return true;
}
}
private static final class zzb
extends FilterInputStream
{
private int zzaB = 0;
private zzb(InputStream paramInputStream)
{
super();
}
public final int read()
throws IOException
{
int i = super.read();
if (i != -1) {
this.zzaB = (1 + this.zzaB);
}
return i;
}
public final int read(byte[] paramArrayOfByte, int paramInt1, int paramInt2)
throws IOException
{
int i = super.read(paramArrayOfByte, paramInt1, paramInt2);
if (i != -1) {
this.zzaB = (i + this.zzaB);
}
return i;
}
}
}
/* Location: F:\apktool\apktool\Google_Play_Store6.0.5\classes-dex2jar.jar
* Qualified Name: com.google.android.gms.internal.zzv
* JD-Core Version: 0.7.0.1
*/
| |
/*
* MIT License
*
* Copyright (c) 2021 EPAM Systems
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.epam.catgenome.util;
import com.epam.catgenome.entity.reference.motif.Motif;
import com.epam.catgenome.manager.gene.parser.StrandSerializable;
import com.epam.catgenome.util.motif.IupacRegexConverter;
import com.epam.catgenome.util.motif.MotifSearchIterator;
import com.epam.catgenome.util.motif.MotifSearcher;
import org.junit.Assert;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.regex.Pattern;
import java.util.stream.IntStream;
public class MotifSearcherTest {
public static final byte[] TEST_SEQUENCE = "cgCGcattgcGcaaGGG".getBytes(StandardCharsets.UTF_8);
public static final String SIMPLE_TEST_MOTIF = "ca";
public static final String SIMPLE_REVERSIBLE_TEST_REGEX = "(c[a])";
public static final String TEST_REGEX = "ca+?";
public static final String EXTENDED_TEST_REGEX = "tacyrw+?";
public static final String TEST_REFERENCE_SOURCE = "/templates/dm606.X.fa";
public static final int MAX_SIZE_SEARCH_RESULT_LIMIT = 2000000;
public static final int SIZE_SEARCH_RESULT_LOW_LIMIT = 20000;
@Test
public void searchTest() {
Assert.assertEquals(3,
MotifSearcher.search(TEST_SEQUENCE, SIMPLE_TEST_MOTIF, "", 0,
true, MAX_SIZE_SEARCH_RESULT_LIMIT).count());
Assert.assertEquals(3,
MotifSearcher.search(TEST_SEQUENCE, SIMPLE_REVERSIBLE_TEST_REGEX, "", 0,
true, MAX_SIZE_SEARCH_RESULT_LIMIT).count());
Assert.assertEquals(3,
MotifSearcher.search(TEST_SEQUENCE, TEST_REGEX, "", 0,
true, MAX_SIZE_SEARCH_RESULT_LIMIT).count());
}
@Test
public void searchPalindromeTest() {
final String simplePalindromeMotif = "gc";
final String simpleReversiblePalindromeRegex = "(g[c])";
final String palindromeRegex = "gc+?";
Assert.assertEquals(8,
MotifSearcher.search(TEST_SEQUENCE, simplePalindromeMotif, "", 0,
true, MAX_SIZE_SEARCH_RESULT_LIMIT).count());
Assert.assertEquals(8,
MotifSearcher.search(TEST_SEQUENCE, simpleReversiblePalindromeRegex, "", 0,
true, MAX_SIZE_SEARCH_RESULT_LIMIT).count());
Assert.assertEquals(8,
MotifSearcher.search(TEST_SEQUENCE, palindromeRegex, "", 0,
true, MAX_SIZE_SEARCH_RESULT_LIMIT).count());
}
@Test
public void searchStartAndEndEdgesWhenGivenSimpleTestMotif() {
final int[] actualResults = MotifSearcher.search(TEST_SEQUENCE, SIMPLE_TEST_MOTIF, "", 0,
true, MAX_SIZE_SEARCH_RESULT_LIMIT)
.flatMapToInt(motif -> IntStream.of(motif.getStart(), motif.getEnd()))
.toArray();
final int[] expectedResults = {4, 5, 7, 8, 11, 12};
Assert.assertArrayEquals(expectedResults, actualResults);
}
@Test
public void searchStartAndEndEdgesWhenGivenSimpleReversibleTestRegex() {
final int[] actualResults = MotifSearcher.search(TEST_SEQUENCE, SIMPLE_REVERSIBLE_TEST_REGEX, "", 0,
true, MAX_SIZE_SEARCH_RESULT_LIMIT)
.flatMapToInt(motif -> IntStream.of(motif.getStart(), motif.getEnd()))
.toArray();
final int[] expectedResults = {4, 5, 7, 8, 11, 12};
Assert.assertArrayEquals(expectedResults, actualResults);
}
@Test
public void searchStartAndEndEdgesWhenGivenTestRegex() {
final String testRegex = "ca+?";
final int[] actualResults = MotifSearcher.search(TEST_SEQUENCE, testRegex, "", 0,
true, MAX_SIZE_SEARCH_RESULT_LIMIT)
.flatMapToInt(motif -> IntStream.of(motif.getStart(), motif.getEnd()))
.toArray();
final int[] expectedResults = {4, 5, 7, 8, 11, 12};
Assert.assertArrayEquals(expectedResults, actualResults);
}
@Test
public void comparingSearchedSequenceWhenGivenSimpleTestMotif() {
final String[] actualResults = MotifSearcher.search(TEST_SEQUENCE, SIMPLE_TEST_MOTIF, "", 0,
true, MAX_SIZE_SEARCH_RESULT_LIMIT)
.map(Motif::getSequence)
.toArray(String[]::new);
final String[] expectedResults = {"ca", "tg", "ca"};
Assert.assertArrayEquals(expectedResults, actualResults);
}
@Test
public void comparingSearchedSequenceWhenGivenSimpleReversibleTestRegex() {
final String[] actualResults = MotifSearcher.search(TEST_SEQUENCE, SIMPLE_REVERSIBLE_TEST_REGEX, "", 0,
true, MAX_SIZE_SEARCH_RESULT_LIMIT)
.map(Motif::getSequence)
.toArray(String[]::new);
final String[] expectedResults = {"ca", "tg", "ca"};
Assert.assertArrayEquals(expectedResults, actualResults);
}
@Test
public void comparingSearchedSequenceWhenGivenTestRegex() {
final String[] actualResults = MotifSearcher.search(TEST_SEQUENCE, TEST_REGEX, "", 0,
true, MAX_SIZE_SEARCH_RESULT_LIMIT)
.map(Motif::getSequence)
.toArray(String[]::new);
final String[] expectedResults = {"ca", "tg", "ca"};
Assert.assertArrayEquals(expectedResults, actualResults);
}
@Test
public void searchInPositiveStrandWhenGivenSimpleTestMotif() {
Assert.assertEquals(2, MotifSearcher.search(TEST_SEQUENCE, SIMPLE_TEST_MOTIF,
StrandSerializable.POSITIVE, "", 0,
true, MAX_SIZE_SEARCH_RESULT_LIMIT).count());
}
@Test
public void searchInPositiveStrandWhenGivenSimpleReversibleTestRegex() {
Assert.assertEquals(2, MotifSearcher.search(TEST_SEQUENCE, SIMPLE_REVERSIBLE_TEST_REGEX,
StrandSerializable.POSITIVE, "", 0,
true, MAX_SIZE_SEARCH_RESULT_LIMIT).count());
}
@Test
public void searchInPositiveStrandWhenGivenTestRegex() {
Assert.assertEquals(2,
MotifSearcher.search(TEST_SEQUENCE, TEST_REGEX, StrandSerializable.POSITIVE, "", 0,
true, MAX_SIZE_SEARCH_RESULT_LIMIT).count());
}
@Test
public void searchInNegativeStrandWhenGivenSimpleTestMotif() {
Assert.assertEquals(1,
MotifSearcher.search(TEST_SEQUENCE, SIMPLE_TEST_MOTIF, StrandSerializable.NEGATIVE, "", 0,
true, MAX_SIZE_SEARCH_RESULT_LIMIT).count());
}
@Test
public void searchInNegativeStrandWhenGivenSimpleReversibleTestRegex() {
Assert.assertEquals(1,
MotifSearcher.search(TEST_SEQUENCE, SIMPLE_REVERSIBLE_TEST_REGEX, StrandSerializable.NEGATIVE, "", 0,
true, MAX_SIZE_SEARCH_RESULT_LIMIT).count());
}
@Test
public void searchInNegativeStrandWhenGivenTestRegex() {
Assert.assertEquals(1, MotifSearcher.search(TEST_SEQUENCE, TEST_REGEX, StrandSerializable.NEGATIVE, "", 0,
true, MAX_SIZE_SEARCH_RESULT_LIMIT).count());
}
@Test(expected = IllegalStateException.class)
public void searchThrowsExceptionOnInvalidSequenceWhenGivenTestRegex() {
byte[] testSequence = "zxcontig".getBytes(StandardCharsets.UTF_8);
String testRegex = "con+?";
MotifSearcher.search(testSequence, testRegex, "", 0, true, MAX_SIZE_SEARCH_RESULT_LIMIT);
}
@Test
public void convertIupacToRegexTest(){
String testRegex = "atcgrYmKsWhBvDn[ac]+";
String expectedResult = "atcg[rga][ytc][mac][kgt][sgc][wat][hact][bgtc][vgca][dgat].[ac]+";
Assert.assertEquals(expectedResult, IupacRegexConverter.convertIupacToRegex(testRegex));
}
@Test
public void convertIupactoComplementReversedRegexTest(){
String testRegex1 = "a[^a[tcg]rY]mK{23}sn[ac]+";
String expectedResult1 = "[gt]+.[cgs][acm]{23}[gtk][^[gar][tcy][cga]t]t";
Assert.assertEquals(expectedResult1, IupacRegexConverter.convertIupacToComplementReversedRegex(testRegex1));
String testRegex2 = "a+?c[gt]*?yr{2,}a{7,}";
String expectedResult2 = "t{7,}[tcy]{2,}[gar][ac]*?gt+?";
Assert.assertEquals(expectedResult2, IupacRegexConverter.convertIupacToComplementReversedRegex(testRegex2));
String testRegex3 = "(ac)|(tc)|[tcc]{12}";
String expectedResult3 = "[gga]{12}|(ga)|(gt)";
Assert.assertEquals(expectedResult3, IupacRegexConverter.convertIupacToComplementReversedRegex(testRegex3));
String testRegex4 = "((ac)|(tc))|([tcc]{12,23})";
String expectedResult4 = "([gga]{12,23})|((ga)|(gt))";
Assert.assertEquals(expectedResult4, IupacRegexConverter.convertIupacToComplementReversedRegex(testRegex4));
}
@Test
public void searchInLargeBufferWhenGivenSimpleTestMotif() throws IOException {
final int expectedSize = 57534;
final byte[] largeTestSequence = getTestSequenceFromResource(TEST_REFERENCE_SOURCE);
final String[] testMotifsAsRegexSubstitution =
{"taccat", "taccaa", "taccgt", "taccga", "tactat", "tactaa", "tactgt", "tactga"};
final int actualSize = IntStream.range(0, testMotifsAsRegexSubstitution.length)
.map(i -> (int) MotifSearcher.search(largeTestSequence, testMotifsAsRegexSubstitution[i], "", 0,
true, MAX_SIZE_SEARCH_RESULT_LIMIT).count())
.sum();
Assert.assertEquals(expectedSize, actualSize);
}
@Test
public void searchInLargeBufferWhenGivenSimpleReversibleTestRegex() throws IOException {
final int expectedSize = 57534;
final byte[] largeTestSequence = getTestSequenceFromResource(TEST_REFERENCE_SOURCE);
final String simpleReversibleTestRegex = "(tacyrw)";
Assert.assertEquals(expectedSize,
MotifSearcher.search(largeTestSequence, simpleReversibleTestRegex, "", 0,
true, MAX_SIZE_SEARCH_RESULT_LIMIT).count());
}
@Test
public void searchInLargeBufferWhenGivenTestRegex() throws IOException {
final int expectedSize = 57534;
final byte[] largeTestSequence = getTestSequenceFromResource(TEST_REFERENCE_SOURCE);
final String testRegex = "tacyrw+?";
Assert.assertEquals(expectedSize, MotifSearcher.search(largeTestSequence, testRegex, "", 0,
true, MAX_SIZE_SEARCH_RESULT_LIMIT).count());
}
@Test
public void searchInLargeBufferInPositiveAndNegativeStrandWhenGivenSimpleTestMotif() throws IOException {
final int expectedSize = 57534;
final byte[] largeTestSequence = getTestSequenceFromResource(TEST_REFERENCE_SOURCE);
final String[] testMotifsAsRegexSubstitution =
{"taccat", "taccaa", "taccgt", "taccga", "tactat", "tactaa", "tactgt", "tactga"};
final int actualSize = Arrays.stream(testMotifsAsRegexSubstitution)
.mapToInt(s ->
(int) MotifSearcher.search(largeTestSequence, s,
StrandSerializable.POSITIVE, "", 0,
true, MAX_SIZE_SEARCH_RESULT_LIMIT).count()
+ (int) MotifSearcher.search(largeTestSequence, s,
StrandSerializable.NEGATIVE, "", 0,
true, MAX_SIZE_SEARCH_RESULT_LIMIT).count())
.sum();
Assert.assertEquals(expectedSize, actualSize);
}
@Test
public void searchInLargeBufferInPositiveAndNegativeStrandWhenGivenTestRegex() throws IOException {
final int expectedSize = 57534;
final byte[] largeTestSequence = getTestSequenceFromResource(TEST_REFERENCE_SOURCE);
final String testRegex = "tacyrw+?";
final long sumResult =
MotifSearcher.search(largeTestSequence, testRegex, StrandSerializable.POSITIVE, "", 0,
true, MAX_SIZE_SEARCH_RESULT_LIMIT).count() +
MotifSearcher.search(largeTestSequence, testRegex, StrandSerializable.NEGATIVE, "", 0,
true, MAX_SIZE_SEARCH_RESULT_LIMIT).count();
Assert.assertEquals(expectedSize, sumResult);
}
@Test(expected = IllegalArgumentException.class)
public void searchInLargeBufferOnPositiveStrandWhenGivenShortestTestRegexAndSetModestResultSizeLimitShouldFail()
throws IOException {
new MotifSearchIterator(getTestSequenceFromResource(TEST_REFERENCE_SOURCE), EXTENDED_TEST_REGEX,
StrandSerializable.NEGATIVE, "", 0, true, SIZE_SEARCH_RESULT_LOW_LIMIT);
}
@Test(expected = IllegalArgumentException.class)
public void searchInLargeBufferOnNegativeStrandWhenGivenShortestTestRegexAndSetModestResultSizeLimitShouldFail()
throws IOException {
new MotifSearchIterator(getTestSequenceFromResource(TEST_REFERENCE_SOURCE), EXTENDED_TEST_REGEX,
StrandSerializable.NEGATIVE, "", 0, true, SIZE_SEARCH_RESULT_LOW_LIMIT);
}
private byte[] getTestSequenceFromResource(final String path) throws IOException {
final InputStream resourceAsStream = getClass().getResourceAsStream(path);
byte[] buf = new byte[resourceAsStream.available()];
resourceAsStream.read(buf);
resourceAsStream.close();
return Pattern.compile("[^ATCGNatcgn]").matcher(new String(buf))
.replaceAll("n").getBytes(StandardCharsets.UTF_8);
}
}
| |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.search.aggregations.bucket.histogram;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.xcontent.ObjectParser;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregatorFactories;
import org.elasticsearch.search.aggregations.AggregatorFactories.Builder;
import org.elasticsearch.search.aggregations.AggregatorFactory;
import org.elasticsearch.search.aggregations.BucketOrder;
import org.elasticsearch.search.aggregations.InternalOrder;
import org.elasticsearch.search.aggregations.InternalOrder.CompoundOrder;
import org.elasticsearch.search.aggregations.bucket.MultiBucketAggregationBuilder;
import org.elasticsearch.search.aggregations.support.ValueType;
import org.elasticsearch.search.aggregations.support.ValuesSource;
import org.elasticsearch.search.aggregations.support.ValuesSource.Numeric;
import org.elasticsearch.search.aggregations.support.ValuesSourceAggregationBuilder;
import org.elasticsearch.search.aggregations.support.ValuesSourceAggregatorFactory;
import org.elasticsearch.search.aggregations.support.ValuesSourceConfig;
import org.elasticsearch.search.aggregations.support.ValuesSourceParserHelper;
import org.elasticsearch.search.aggregations.support.ValuesSourceType;
import org.elasticsearch.search.internal.SearchContext;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
* A builder for histograms on numeric fields.
*/
public class HistogramAggregationBuilder extends ValuesSourceAggregationBuilder<ValuesSource.Numeric, HistogramAggregationBuilder>
implements MultiBucketAggregationBuilder {
public static final String NAME = "histogram";
private static final ObjectParser<double[], Void> EXTENDED_BOUNDS_PARSER = new ObjectParser<>(
Histogram.EXTENDED_BOUNDS_FIELD.getPreferredName(),
() -> new double[]{ Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY });
static {
EXTENDED_BOUNDS_PARSER.declareDouble((bounds, d) -> bounds[0] = d, new ParseField("min"));
EXTENDED_BOUNDS_PARSER.declareDouble((bounds, d) -> bounds[1] = d, new ParseField("max"));
}
private static final ObjectParser<HistogramAggregationBuilder, Void> PARSER;
static {
PARSER = new ObjectParser<>(HistogramAggregationBuilder.NAME);
ValuesSourceParserHelper.declareNumericFields(PARSER, true, true, false);
PARSER.declareDouble(HistogramAggregationBuilder::interval, Histogram.INTERVAL_FIELD);
PARSER.declareDouble(HistogramAggregationBuilder::offset, Histogram.OFFSET_FIELD);
PARSER.declareBoolean(HistogramAggregationBuilder::keyed, Histogram.KEYED_FIELD);
PARSER.declareLong(HistogramAggregationBuilder::minDocCount, Histogram.MIN_DOC_COUNT_FIELD);
PARSER.declareField((histogram, extendedBounds) -> {
histogram.extendedBounds(extendedBounds[0], extendedBounds[1]);
}, parser -> EXTENDED_BOUNDS_PARSER.apply(parser, null), ExtendedBounds.EXTENDED_BOUNDS_FIELD, ObjectParser.ValueType.OBJECT);
PARSER.declareObjectArray(HistogramAggregationBuilder::order, (p, c) -> InternalOrder.Parser.parseOrderParam(p),
Histogram.ORDER_FIELD);
}
public static HistogramAggregationBuilder parse(String aggregationName, XContentParser parser) throws IOException {
return PARSER.parse(parser, new HistogramAggregationBuilder(aggregationName), null);
}
private double interval;
private double offset = 0;
private double minBound = Double.POSITIVE_INFINITY;
private double maxBound = Double.NEGATIVE_INFINITY;
private BucketOrder order = BucketOrder.key(true);
private boolean keyed = false;
private long minDocCount = 0;
/** Create a new builder with the given name. */
public HistogramAggregationBuilder(String name) {
super(name, ValuesSourceType.NUMERIC, ValueType.DOUBLE);
}
protected HistogramAggregationBuilder(HistogramAggregationBuilder clone, Builder factoriesBuilder, Map<String, Object> metaData) {
super(clone, factoriesBuilder, metaData);
this.interval = clone.interval;
this.offset = clone.offset;
this.minBound = clone.minBound;
this.maxBound = clone.maxBound;
this.order = clone.order;
this.keyed = clone.keyed;
this.minDocCount = clone.minDocCount;
}
@Override
protected AggregationBuilder shallowCopy(Builder factoriesBuilder, Map<String, Object> metaData) {
return new HistogramAggregationBuilder(this, factoriesBuilder, metaData);
}
/** Read from a stream, for internal use only. */
public HistogramAggregationBuilder(StreamInput in) throws IOException {
super(in, ValuesSourceType.NUMERIC, ValueType.DOUBLE);
order = InternalOrder.Streams.readHistogramOrder(in, true);
keyed = in.readBoolean();
minDocCount = in.readVLong();
interval = in.readDouble();
offset = in.readDouble();
minBound = in.readDouble();
maxBound = in.readDouble();
}
@Override
protected void innerWriteTo(StreamOutput out) throws IOException {
InternalOrder.Streams.writeHistogramOrder(order, out, true);
out.writeBoolean(keyed);
out.writeVLong(minDocCount);
out.writeDouble(interval);
out.writeDouble(offset);
out.writeDouble(minBound);
out.writeDouble(maxBound);
}
/** Get the current interval that is set on this builder. */
public double interval() {
return interval;
}
/** Set the interval on this builder, and return the builder so that calls can be chained. */
public HistogramAggregationBuilder interval(double interval) {
if (interval <= 0) {
throw new IllegalArgumentException("[interval] must be >0 for histogram aggregation [" + name + "]");
}
this.interval = interval;
return this;
}
/** Get the current offset that is set on this builder. */
public double offset() {
return offset;
}
/** Set the offset on this builder, and return the builder so that calls can be chained. */
public HistogramAggregationBuilder offset(double offset) {
this.offset = offset;
return this;
}
/** Get the current minimum bound that is set on this builder. */
public double minBound() {
return minBound;
}
/** Get the current maximum bound that is set on this builder. */
public double maxBound() {
return maxBound;
}
/**
* Set extended bounds on this builder: buckets between {@code minBound} and
* {@code maxBound} will be created even if no documents fell into these
* buckets.
*
* @throws IllegalArgumentException
* if maxBound is less that minBound, or if either of the bounds
* are not finite.
*/
public HistogramAggregationBuilder extendedBounds(double minBound, double maxBound) {
if (Double.isFinite(minBound) == false) {
throw new IllegalArgumentException("minBound must be finite, got: " + minBound);
}
if (Double.isFinite(maxBound) == false) {
throw new IllegalArgumentException("maxBound must be finite, got: " + maxBound);
}
if (maxBound < minBound) {
throw new IllegalArgumentException("maxBound [" + maxBound + "] must be greater than minBound [" + minBound + "]");
}
this.minBound = minBound;
this.maxBound = maxBound;
return this;
}
/** Return the order to use to sort buckets of this histogram. */
public BucketOrder order() {
return order;
}
/** Set a new order on this builder and return the builder so that calls
* can be chained. A tie-breaker may be added to avoid non-deterministic ordering. */
public HistogramAggregationBuilder order(BucketOrder order) {
if (order == null) {
throw new IllegalArgumentException("[order] must not be null: [" + name + "]");
}
if(order instanceof CompoundOrder || InternalOrder.isKeyOrder(order)) {
this.order = order; // if order already contains a tie-breaker we are good to go
} else { // otherwise add a tie-breaker by using a compound order
this.order = BucketOrder.compound(order);
}
return this;
}
/**
* Sets the order in which the buckets will be returned. A tie-breaker may be added to avoid non-deterministic
* ordering.
*/
public HistogramAggregationBuilder order(List<BucketOrder> orders) {
if (orders == null) {
throw new IllegalArgumentException("[orders] must not be null: [" + name + "]");
}
// if the list only contains one order use that to avoid inconsistent xcontent
order(orders.size() > 1 ? BucketOrder.compound(orders) : orders.get(0));
return this;
}
/** Return whether buckets should be returned as a hash. In case
* {@code keyed} is false, buckets will be returned as an array. */
public boolean keyed() {
return keyed;
}
/** Set whether to return buckets as a hash or as an array, and return the
* builder so that calls can be chained. */
public HistogramAggregationBuilder keyed(boolean keyed) {
this.keyed = keyed;
return this;
}
/** Return the minimum count of documents that buckets need to have in order
* to be included in the response. */
public long minDocCount() {
return minDocCount;
}
/** Set the minimum count of matching documents that buckets need to have
* and return this builder so that calls can be chained. */
public HistogramAggregationBuilder minDocCount(long minDocCount) {
if (minDocCount < 0) {
throw new IllegalArgumentException(
"[minDocCount] must be greater than or equal to 0. Found [" + minDocCount + "] in [" + name + "]");
}
this.minDocCount = minDocCount;
return this;
}
@Override
protected XContentBuilder doXContentBody(XContentBuilder builder, Params params) throws IOException {
builder.field(Histogram.INTERVAL_FIELD.getPreferredName(), interval);
builder.field(Histogram.OFFSET_FIELD.getPreferredName(), offset);
if (order != null) {
builder.field(Histogram.ORDER_FIELD.getPreferredName());
order.toXContent(builder, params);
}
builder.field(Histogram.KEYED_FIELD.getPreferredName(), keyed);
builder.field(Histogram.MIN_DOC_COUNT_FIELD.getPreferredName(), minDocCount);
if (Double.isFinite(minBound) || Double.isFinite(maxBound)) {
builder.startObject(Histogram.EXTENDED_BOUNDS_FIELD.getPreferredName());
if (Double.isFinite(minBound)) {
builder.field("min", minBound);
}
if (Double.isFinite(maxBound)) {
builder.field("max", maxBound);
}
builder.endObject();
}
return builder;
}
@Override
public String getType() {
return NAME;
}
@Override
protected ValuesSourceAggregatorFactory<Numeric, ?> innerBuild(SearchContext context, ValuesSourceConfig<Numeric> config,
AggregatorFactory<?> parent, Builder subFactoriesBuilder) throws IOException {
return new HistogramAggregatorFactory(name, config, interval, offset, order, keyed, minDocCount, minBound, maxBound,
context, parent, subFactoriesBuilder, metaData);
}
@Override
protected int innerHashCode() {
return Objects.hash(order, keyed, minDocCount, interval, offset, minBound, maxBound);
}
@Override
protected boolean innerEquals(Object obj) {
HistogramAggregationBuilder other = (HistogramAggregationBuilder) obj;
return Objects.equals(order, other.order)
&& Objects.equals(keyed, other.keyed)
&& Objects.equals(minDocCount, other.minDocCount)
&& Objects.equals(interval, other.interval)
&& Objects.equals(offset, other.offset)
&& Objects.equals(minBound, other.minBound)
&& Objects.equals(maxBound, other.maxBound);
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.drill.exec.store.parquet.columnreaders;
import io.netty.buffer.DrillBuf;
import java.math.BigDecimal;
import org.apache.drill.common.exceptions.ExecutionSetupException;
import org.apache.drill.exec.expr.holders.Decimal28SparseHolder;
import org.apache.drill.exec.expr.holders.Decimal38SparseHolder;
import org.apache.drill.exec.expr.holders.IntervalHolder;
import org.apache.drill.exec.store.ParquetOutputRecordWriter;
import org.apache.drill.exec.store.parquet.ParquetReaderUtility;
import org.apache.drill.exec.util.DecimalUtility;
import org.apache.drill.exec.vector.DateVector;
import org.apache.drill.exec.vector.Decimal28SparseVector;
import org.apache.drill.exec.vector.Decimal38SparseVector;
import org.apache.drill.exec.vector.IntervalVector;
import org.apache.drill.exec.vector.ValueVector;
import org.apache.drill.exec.vector.VariableWidthVector;
import org.joda.time.DateTimeUtils;
import org.apache.parquet.column.ColumnDescriptor;
import org.apache.parquet.format.SchemaElement;
import org.apache.parquet.hadoop.metadata.ColumnChunkMetaData;
import org.apache.parquet.io.api.Binary;
class FixedByteAlignedReader extends ColumnReader {
protected DrillBuf bytebuf;
FixedByteAlignedReader(ParquetRecordReader parentReader, int allocateSize, ColumnDescriptor descriptor, ColumnChunkMetaData columnChunkMetaData,
boolean fixedLength, ValueVector v, SchemaElement schemaElement) throws ExecutionSetupException {
super(parentReader, allocateSize, descriptor, columnChunkMetaData, fixedLength, v, schemaElement);
}
// this method is called by its superclass during a read loop
@Override
protected void readField(long recordsToReadInThisPass) {
recordsReadInThisIteration = Math.min(pageReader.currentPageCount
- pageReader.valuesRead, recordsToReadInThisPass - valuesReadInCurrentPass);
readStartInBytes = pageReader.readPosInBytes;
readLengthInBits = recordsReadInThisIteration * dataTypeLengthInBits;
readLength = (int) Math.ceil(readLengthInBits / 8.0);
bytebuf = pageReader.pageData;
// vectorData is assigned by the superclass read loop method
writeData();
}
protected void writeData() {
vectorData.writeBytes(bytebuf, (int) readStartInBytes, (int) readLength);
}
public static class FixedBinaryReader extends FixedByteAlignedReader {
// TODO - replace this with fixed binary type in drill
VariableWidthVector castedVector;
FixedBinaryReader(ParquetRecordReader parentReader, int allocateSize, ColumnDescriptor descriptor, ColumnChunkMetaData columnChunkMetaData,
VariableWidthVector v, SchemaElement schemaElement) throws ExecutionSetupException {
super(parentReader, allocateSize, descriptor, columnChunkMetaData, true, v, schemaElement);
castedVector = v;
}
@Override
protected void readField(long recordsToReadInThisPass) {
// we can use the standard read method to transfer the data
super.readField(recordsToReadInThisPass);
// TODO - replace this with fixed binary type in drill
// now we need to write the lengths of each value
int byteLength = dataTypeLengthInBits / 8;
for (int i = 0; i < recordsToReadInThisPass; i++) {
castedVector.getMutator().setValueLengthSafe(valuesReadInCurrentPass + i, byteLength);
}
}
}
public static abstract class ConvertedReader extends FixedByteAlignedReader {
protected int dataTypeLengthInBytes;
ConvertedReader(ParquetRecordReader parentReader, int allocateSize, ColumnDescriptor descriptor, ColumnChunkMetaData columnChunkMetaData,
boolean fixedLength, ValueVector v, SchemaElement schemaElement) throws ExecutionSetupException {
super(parentReader, allocateSize, descriptor, columnChunkMetaData, fixedLength, v, schemaElement);
}
@Override
public void writeData() {
dataTypeLengthInBytes = (int) Math.ceil(dataTypeLengthInBits / 8.0);
for (int i = 0; i < recordsReadInThisIteration; i++) {
addNext((int)readStartInBytes + i * dataTypeLengthInBytes, i + valuesReadInCurrentPass);
}
}
/**
* Reads from bytebuf, converts, and writes to buffer
* @param start the index in bytes to start reading from
* @param index the index of the ValueVector
*/
abstract void addNext(int start, int index);
}
public static class DateReader extends ConvertedReader {
private final DateVector.Mutator mutator;
DateReader(ParquetRecordReader parentReader, int allocateSize, ColumnDescriptor descriptor, ColumnChunkMetaData columnChunkMetaData,
boolean fixedLength, ValueVector v, SchemaElement schemaElement) throws ExecutionSetupException {
super(parentReader, allocateSize, descriptor, columnChunkMetaData, fixedLength, v, schemaElement);
mutator = ((DateVector) v).getMutator();
}
@Override
void addNext(int start, int index) {
int intValue;
if (usingDictionary) {
intValue = pageReader.dictionaryValueReader.readInteger();
} else {
intValue = readIntLittleEndian(bytebuf, start);
}
mutator.set(index, DateTimeUtils.fromJulianDay(intValue - ParquetOutputRecordWriter.JULIAN_DAY_EPOC - 0.5));
}
}
public static class Decimal28Reader extends ConvertedReader {
Decimal28SparseVector decimal28Vector;
Decimal28Reader(ParquetRecordReader parentReader, int allocateSize, ColumnDescriptor descriptor, ColumnChunkMetaData columnChunkMetaData,
boolean fixedLength, ValueVector v, SchemaElement schemaElement) throws ExecutionSetupException {
super(parentReader, allocateSize, descriptor, columnChunkMetaData, fixedLength, v, schemaElement);
decimal28Vector = (Decimal28SparseVector) v;
}
@Override
void addNext(int start, int index) {
int width = Decimal28SparseHolder.WIDTH;
BigDecimal intermediate = DecimalUtility.getBigDecimalFromDrillBuf(bytebuf, start, dataTypeLengthInBytes,
schemaElement.getScale());
DecimalUtility.getSparseFromBigDecimal(intermediate, decimal28Vector.getBuffer(), index * width, schemaElement.getScale(),
schemaElement.getPrecision(), Decimal28SparseHolder.nDecimalDigits);
}
}
public static class Decimal38Reader extends ConvertedReader {
Decimal38SparseVector decimal38Vector;
Decimal38Reader(ParquetRecordReader parentReader, int allocateSize, ColumnDescriptor descriptor, ColumnChunkMetaData columnChunkMetaData,
boolean fixedLength, ValueVector v, SchemaElement schemaElement) throws ExecutionSetupException {
super(parentReader, allocateSize, descriptor, columnChunkMetaData, fixedLength, v, schemaElement);
decimal38Vector = (Decimal38SparseVector) v;
}
@Override
void addNext(int start, int index) {
int width = Decimal38SparseHolder.WIDTH;
BigDecimal intermediate = DecimalUtility.getBigDecimalFromDrillBuf(bytebuf, start, dataTypeLengthInBytes,
schemaElement.getScale());
DecimalUtility.getSparseFromBigDecimal(intermediate, decimal38Vector.getBuffer(), index * width, schemaElement.getScale(),
schemaElement.getPrecision(), Decimal38SparseHolder.nDecimalDigits);
}
}
public static class IntervalReader extends ConvertedReader {
IntervalVector intervalVector;
IntervalReader(ParquetRecordReader parentReader, int allocateSize, ColumnDescriptor descriptor, ColumnChunkMetaData columnChunkMetaData,
boolean fixedLength, ValueVector v, SchemaElement schemaElement) throws ExecutionSetupException {
super(parentReader, allocateSize, descriptor, columnChunkMetaData, fixedLength, v, schemaElement);
intervalVector = (IntervalVector) v;
}
@Override
void addNext(int start, int index) {
if (usingDictionary) {
byte[] input = pageReader.dictionaryValueReader.readBytes().getBytes();
intervalVector.getMutator().setSafe(index * 12,
ParquetReaderUtility.getIntFromLEBytes(input, 0),
ParquetReaderUtility.getIntFromLEBytes(input, 4),
ParquetReaderUtility.getIntFromLEBytes(input, 8));
}
intervalVector.getMutator().setSafe(index, bytebuf.getInt(start), bytebuf.getInt(start + 4), bytebuf.getInt(start + 8));
}
}
}
| |
/*
* 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.openapi.editor.impl;
import com.intellij.openapi.editor.ex.LineIterator;
import com.intellij.openapi.util.text.LineTokenizer;
import com.intellij.util.text.MergingCharSequence;
import gnu.trove.TByteArrayList;
import gnu.trove.TIntArrayList;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.TestOnly;
import java.util.Arrays;
/**
* Data structure specialized for working with document text lines, i.e. stores information about line mapping to document
* offsets and provides convenient ways to work with that information like retrieving target line by document offset etc.
* <p/>
* Immutable.
*/
public class LineSet{
private static final int MODIFIED_MASK = 0x4;
private static final int SEPARATOR_MASK = 0x3;
private final int[] myStarts;
private final byte[] myFlags;
private final int myLength;
private LineSet(int[] starts, byte[] flags, int length) {
myStarts = starts;
myFlags = flags;
myLength = length;
}
public static LineSet createLineSet(CharSequence text) {
return createLineSet(text, false);
}
private static LineSet createLineSet(CharSequence text, boolean markModified) {
TIntArrayList starts = new TIntArrayList();
TByteArrayList flags = new TByteArrayList();
LineTokenizer lineTokenizer = new LineTokenizer(text);
while (!lineTokenizer.atEnd()) {
starts.add(lineTokenizer.getOffset());
flags.add((byte) (lineTokenizer.getLineSeparatorLength() | (markModified ? MODIFIED_MASK : 0)));
lineTokenizer.advance();
}
return new LineSet(starts.toNativeArray(), flags.toNativeArray(), text.length());
}
LineSet update(CharSequence prevText, int _start, int _end, CharSequence replacement, boolean wholeTextReplaced) {
if (myLength == 0) {
return createLineSet(replacement, !wholeTextReplaced);
}
int startOffset = _start;
if (replacement.length() > 0 && replacement.charAt(0) == '\n' && startOffset > 0 && prevText.charAt(startOffset - 1) == '\r') {
startOffset--;
}
int startLine = findLineIndex(startOffset);
startOffset = getLineStart(startLine);
int endOffset = _end;
if (replacement.length() > 0 && replacement.charAt(replacement.length() - 1) == '\r' && endOffset < prevText.length() && prevText.charAt(endOffset) == '\n') {
endOffset++;
}
int endLine = findLineIndex(endOffset);
endOffset = getLineEnd(endLine);
if (!isLastEmptyLine(endLine)) endLine++;
replacement = new MergingCharSequence(
new MergingCharSequence(prevText.subSequence(startOffset, _start), replacement),
prevText.subSequence(_end, endOffset));
LineSet patch = createLineSet(replacement, true);
LineSet applied = applyPatch(startOffset, endOffset, startLine, endLine, patch);
if (doTest) {
final MergingCharSequence newText = new MergingCharSequence(
new MergingCharSequence(prevText.subSequence(0, startOffset), replacement),
prevText.subSequence(endOffset, prevText.length()));
applied.checkEquals(createLineSet(newText));
}
return wholeTextReplaced ? applied.clearModificationFlags() : applied;
}
private void checkEquals(LineSet fresh) {
if (getLineCount() != fresh.getLineCount()) {
throw new AssertionError();
}
for (int i = 0; i < getLineCount(); i++) {
boolean start = getLineStart(i) != fresh.getLineStart(i);
boolean end = getLineEnd(i) != fresh.getLineEnd(i);
boolean sep = getSeparatorLength(i) != fresh.getSeparatorLength(i);
if (start || end || sep) {
throw new AssertionError();
}
}
}
@NotNull
private LineSet applyPatch(int startOffset, int endOffset, int startLine, int endLine, LineSet patch) {
int lineShift = patch.myStarts.length - (endLine - startLine);
int lengthShift = patch.myLength - (endOffset - startOffset);
int newLineCount = myStarts.length + lineShift;
int[] starts = new int[newLineCount];
byte[] flags = new byte[newLineCount];
for (int i = 0; i < startLine; i++) {
starts[i] = myStarts[i];
flags[i] = myFlags[i];
}
for (int i = 0; i < patch.myStarts.length; i++) {
starts[startLine + i] = patch.myStarts[i] + startOffset;
flags[startLine + i] = patch.myFlags[i];
}
for (int i = endLine; i < myStarts.length; i++) {
starts[lineShift + i] = myStarts[i] + lengthShift;
flags[lineShift + i] = myFlags[i];
}
return new LineSet(starts, flags, myLength + lengthShift);
}
public int findLineIndex(int offset) {
if (offset < 0 || offset > myLength) {
throw new IndexOutOfBoundsException("Wrong offset: " + offset + ". Should be in range: [0, " + myLength + "]");
}
if (myLength == 0) return 0;
if (offset == myLength) return getLineCount() - 1;
int bsResult = Arrays.binarySearch(myStarts, offset);
return bsResult >= 0 ? bsResult : -bsResult - 2;
}
public LineIterator createIterator() {
return new LineIteratorImpl(this);
}
public final int getLineStart(int index) {
checkLineIndex(index);
return isLastEmptyLine(index) ? myLength : myStarts[index];
}
private boolean isLastEmptyLine(int index) {
return index == myFlags.length && index > 0 && (myFlags[index - 1] & SEPARATOR_MASK) > 0;
}
public final int getLineEnd(int index) {
checkLineIndex(index);
return index >= myStarts.length - 1 ? myLength : myStarts[index + 1];
}
private void checkLineIndex(int index) {
if (index < 0 || index >= getLineCount()) {
throw new IndexOutOfBoundsException("Wrong line: " + index + ". Available lines count: " + getLineCount());
}
}
final boolean isModified(int index) {
checkLineIndex(index);
return !isLastEmptyLine(index) && (myFlags[index] & MODIFIED_MASK) != 0;
}
final LineSet setModified(int index) {
if (isLastEmptyLine(index) || isModified(index)) return this;
byte[] flags = myFlags.clone();
flags[index] |= MODIFIED_MASK;
return new LineSet(myStarts, flags, myLength);
}
LineSet clearModificationFlags(int startLine, int endLine) {
if (startLine > endLine) {
throw new IllegalArgumentException("endLine < startLine: " + endLine + " < " + startLine + "; lineCount: " + getLineCount());
}
checkLineIndex(startLine);
checkLineIndex(endLine - 1);
if (isLastEmptyLine(endLine - 1)) endLine--;
if (startLine >= endLine) return this;
byte[] flags = myFlags.clone();
for (int i = startLine; i < endLine; i++) {
flags[i] &= ~MODIFIED_MASK;
}
return new LineSet(myStarts, flags, myLength);
}
LineSet clearModificationFlags() {
byte[] flags = myFlags.clone();
for (int i = 0; i < flags.length; i++) {
flags[i] &= ~MODIFIED_MASK;
}
return new LineSet(myStarts, flags, myLength);
}
final int getSeparatorLength(int index) {
checkLineIndex(index);
return index < myFlags.length ? myFlags[index] & SEPARATOR_MASK : 0;
}
final int getLineCount() {
return myStarts.length + (isLastEmptyLine(myStarts.length) ? 1 : 0);
}
@TestOnly
public static void setTestingMode(boolean testMode) {
doTest = testMode;
}
private static boolean doTest = false;
}
| |
/*
* Copyright 2001-2008 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.juddi.query.util;
import java.util.List;
import org.apache.juddi.v3.error.ErrorMessage;
import org.apache.juddi.v3.error.UnsupportedException;
import org.uddi.v3_service.DispositionReportFaultMessage;
/**
* @author <a href="mailto:jfaath@apache.org">Jeff Faath</a>
*/
public class FindQualifiers {
public static final String AND_ALL_KEYS = "andAllKeys";
public static final String AND_ALL_KEYS_TMODEL = "uddi:uddi.org:findqualifier:andallkeys";
public static final String APPROXIMATE_MATCH = "approximateMatch";
public static final String APPROXIMATE_MATCH_TMODEL = "uddi:uddi.org:findqualifier:approximatematch";
public static final String BINARY_SORT = "binarySort";
public static final String BINARY_SORT_TMODEL = "uddi:uddi.org:sortorder:binarysort";
public static final String BINDING_SUBSET = "bindingSubset";
public static final String BINDING_SUBSET_TMODEL = "uddi:uddi.org:findqualifier:bindingsubset";
public static final String CASE_INSENSITIVE_SORT = "caseInsensitiveSort";
public static final String CASE_INSENSITIVE_SORT_TMODEL = "uddi:uddi.org:findqualifier:caseinsensitivesort";
public static final String CASE_INSENSITIVE_MATCH = "caseInsensitiveMatch";
public static final String CASE_INSENSITIVE_MATCH_TMODEL = "uddi:uddi.org:findqualifier:caseinsensitivematch";
public static final String CASE_SENSITIVE_SORT = "caseSensitiveSort";
public static final String CASE_SENSITIVE_SORT_TMODEL = "uddi:uddi.org:findqualifier:casesensitivesort";
public static final String CASE_SENSITIVE_MATCH = "caseSensitiveMatch";
public static final String CASE_SENSITIVE_MATCH_TMODEL = "uddi:uddi.org:findqualifier:casesensitivematch";
public static final String COMBINE_CATEGORY_BAGS = "combineCategoryBags";
public static final String COMBINE_CATEGORY_BAGS_TMODEL = "uddi:uddi.org:findqualifier:combinecategorybags";
public static final String DIACRITIC_INSENSITIVE_MATCH = "diacriticInsensitiveMatch";
public static final String DIACRITIC_INSENSITIVE_MATCH_TMODEL = "uddi:uddi.org:findqualifier:diacriticsinsensitivematch";
public static final String DIACRITIC_SENSITIVE_MATCH = "diacriticSensitiveMatch";
public static final String DIACRITIC_SENSITIVE_MATCH_TMODEL = "uddi:uddi.org:findqualifier:diacriticssensitivematch";
public static final String EXACT_MATCH = "exactMatch";
public static final String EXACT_MATCH_TMODEL = "uddi:uddi.org:findqualifier:exactmatch";
public static final String EXACT_NAME_MATCH = "exactNameMatch";
public static final String EXACT_NAME_MATCH_TMODEL = "uddi:uddi.org:findqualifier:exactnamematch";
public static final String SIGNATURE_PRESENT = "signaturePresent";
public static final String SIGNATURE_PRESENT_TMODEL = "uddi:uddi.org:findqualifier:signaturepresent";
public static final String OR_ALL_KEYS = "orAllKeys";
public static final String OR_ALL_KEYS_TMODEL = "uddi:uddi.org:findqualifier:orallkeys";
public static final String OR_LIKE_KEYS = "orLikeKeys";
public static final String OR_LIKE_KEYS_TMODEL = "uddi:uddi.org:findqualifier:orlikekeys";
public static final String SERVICE_SUBSET = "serviceSubset";
public static final String SERVICE_SUBSET_TMODEL = "uddi:uddi.org:findqualifier:servicesubset";
public static final String SORT_BY_NAME_ASC = "sortByNameAsc";
public static final String SORT_BY_NAME_ASC_TMODEL = "uddi:uddi.org:findqualifier:sortbynameasc";
public static final String SORT_BY_NAME_DESC = "sortByNameDesc";
public static final String SORT_BY_NAME_DESC_TMODEL = "uddi:uddi.org:findqualifier:sortbynamedesc";
public static final String SORT_BY_DATE_ASC = "sortByDateAsc";
public static final String SORT_BY_DATE_ASC_TMODEL = "uddi:uddi.org:findqualifier:sortbydateasc";
public static final String SORT_BY_DATE_DESC = "sortByDateDesc";
public static final String SORT_BY_DATE_DESC_TMODEL = "uddi:uddi.org:findqualifier:sortbydatedesc";
public static final String SUPPRESS_PROJECTED_SERVICES = "suppressProjectedServices";
public static final String SUPPRESS_PROJECTED_SERVICES_TMODEL = "uddi:uddi.org:findqualifier:suppressprojectedservices";
public static final String UTS_10 = "UTS-10";
public static final String UTS_10_TMODEL = "uddi:uddi.org:sortorder:uts-10";
private boolean andAllKeys = false;
private boolean approximateMatch = false;
private boolean binarySort = false;
private boolean bindingSubset = false;
private boolean caseInsensitiveSort = false;
private boolean caseInsensitiveMatch = false;
private boolean caseSensitiveSort = false;
private boolean caseSensitiveMatch = false;
private boolean combineCategoryBags = false;
private boolean diacriticInsensitiveMatch = false;
private boolean diacriticSensitiveMatch = false;
private boolean exactMatch = false;
private boolean signaturePresent = false;
private boolean orAllKeys = false;
private boolean orLikeKeys = false;
private boolean serviceSubset = false;
private boolean sortByNameAsc = false;
private boolean sortByNameDesc = false;
private boolean sortByDateAsc = false;
private boolean sortByDateDesc = false;
private boolean suppressProjectedServices = false;
private boolean uts10 = false;
public FindQualifiers() {
// These are the defaults as defined by the UDDI specification.
this.setExactMatch(true);
this.setCaseSensitiveMatch(true);
this.setCaseSensitiveSort(true);
this.setDiacriticSensitiveMatch(true);
}
public void mapApiFindQualifiers(org.uddi.api_v3.FindQualifiers apiFindQualifiers)
throws DispositionReportFaultMessage {
if (apiFindQualifiers == null)
return;
List<String> fqList = apiFindQualifiers.getFindQualifier();
if (fqList != null) {
for (String fq : fqList) {
if (fq.equalsIgnoreCase(AND_ALL_KEYS) || fq.equalsIgnoreCase(AND_ALL_KEYS_TMODEL))
this.setAndAllKeys(true);
else if (fq.equalsIgnoreCase(APPROXIMATE_MATCH) || fq.equalsIgnoreCase(APPROXIMATE_MATCH_TMODEL))
this.setApproximateMatch(true);
else if (fq.equalsIgnoreCase(BINARY_SORT) || fq.equalsIgnoreCase(BINARY_SORT_TMODEL))
this.setBinarySort(true);
else if (fq.equalsIgnoreCase(BINDING_SUBSET) || fq.equalsIgnoreCase(BINDING_SUBSET_TMODEL))
this.setBindingSubset(true);
else if (fq.equalsIgnoreCase(CASE_INSENSITIVE_SORT) || fq.equalsIgnoreCase(CASE_INSENSITIVE_SORT_TMODEL))
this.setCaseInsensitiveSort(true);
else if (fq.equalsIgnoreCase(CASE_INSENSITIVE_MATCH) || fq.equalsIgnoreCase(CASE_INSENSITIVE_MATCH_TMODEL))
this.setCaseInsensitiveMatch(true);
else if (fq.equalsIgnoreCase(CASE_SENSITIVE_SORT) || fq.equalsIgnoreCase(CASE_SENSITIVE_SORT_TMODEL))
this.setCaseSensitiveSort(true);
else if (fq.equalsIgnoreCase(CASE_SENSITIVE_MATCH) || fq.equalsIgnoreCase(CASE_SENSITIVE_MATCH_TMODEL))
this.setCaseSensitiveMatch(true);
else if (fq.equalsIgnoreCase(COMBINE_CATEGORY_BAGS) || fq.equalsIgnoreCase(COMBINE_CATEGORY_BAGS_TMODEL))
this.setCombineCategoryBags(true);
else if (fq.equalsIgnoreCase(DIACRITIC_INSENSITIVE_MATCH) || fq.equalsIgnoreCase(DIACRITIC_INSENSITIVE_MATCH_TMODEL))
this.setDiacriticInsensitiveMatch(true);
else if (fq.equalsIgnoreCase(DIACRITIC_SENSITIVE_MATCH) || fq.equalsIgnoreCase(DIACRITIC_SENSITIVE_MATCH_TMODEL))
this.setDiacriticSensitiveMatch(true);
else if (fq.equalsIgnoreCase(EXACT_MATCH) || fq.equalsIgnoreCase(EXACT_MATCH_TMODEL))
this.setExactMatch(true);
else if (fq.equalsIgnoreCase(EXACT_NAME_MATCH) || fq.equalsIgnoreCase(EXACT_NAME_MATCH_TMODEL))
this.setExactMatch(true);
else if (fq.equalsIgnoreCase(SIGNATURE_PRESENT) || fq.equalsIgnoreCase(SIGNATURE_PRESENT_TMODEL))
this.setSignaturePresent(true);
else if (fq.equalsIgnoreCase(OR_ALL_KEYS) || fq.equalsIgnoreCase(OR_ALL_KEYS_TMODEL))
this.setOrAllKeys(true);
else if (fq.equalsIgnoreCase(OR_LIKE_KEYS) || fq.equalsIgnoreCase(OR_LIKE_KEYS_TMODEL))
this.setOrLikeKeys(true);
else if (fq.equalsIgnoreCase(SERVICE_SUBSET) || fq.equalsIgnoreCase(SERVICE_SUBSET_TMODEL))
this.setServiceSubset(true);
else if (fq.equalsIgnoreCase(SORT_BY_NAME_ASC) || fq.equalsIgnoreCase(SORT_BY_NAME_ASC_TMODEL))
this.setSortByNameAsc(true);
else if (fq.equalsIgnoreCase(SORT_BY_NAME_DESC) || fq.equalsIgnoreCase(SORT_BY_NAME_DESC_TMODEL))
this.setSortByNameDesc(true);
else if (fq.equalsIgnoreCase(SORT_BY_DATE_ASC) || fq.equalsIgnoreCase(SORT_BY_DATE_ASC_TMODEL))
this.setSortByDateAsc(true);
else if (fq.equalsIgnoreCase(SORT_BY_DATE_DESC) || fq.equalsIgnoreCase(SORT_BY_DATE_DESC_TMODEL))
this.setSortByDateDesc(true);
else if (fq.equalsIgnoreCase(SUPPRESS_PROJECTED_SERVICES) || fq.equalsIgnoreCase(SUPPRESS_PROJECTED_SERVICES_TMODEL))
this.setSuppressProjectedServices(true);
else if (fq.equalsIgnoreCase(UTS_10) || fq.equalsIgnoreCase(UTS_10_TMODEL))
this.setUts10(true);
else
throw new UnsupportedException(new ErrorMessage("errors.Unsupported.findQualifier", fq));
}
}
}
public boolean isAndAllKeys() {
return andAllKeys;
}
public void setAndAllKeys(boolean andAllKeys) {
this.andAllKeys = andAllKeys;
this.orAllKeys = !andAllKeys;
this.orLikeKeys = !andAllKeys;
}
public boolean isApproximateMatch() {
return approximateMatch;
}
public void setApproximateMatch(boolean approximateMatch) {
this.approximateMatch = approximateMatch;
this.exactMatch = !approximateMatch;
}
public boolean isBinarySort() {
return binarySort;
}
public void setBinarySort(boolean binarySort) {
this.binarySort = binarySort;
this.uts10 = !binarySort;
}
public boolean isBindingSubset() {
return bindingSubset;
}
public void setBindingSubset(boolean bindingSubset) {
this.bindingSubset = bindingSubset;
this.combineCategoryBags = !bindingSubset;
this.bindingSubset = !bindingSubset;
}
public boolean isCaseInsensitiveSort() {
return caseInsensitiveSort;
}
public void setCaseInsensitiveSort(boolean caseInsensitiveSort) {
this.caseInsensitiveSort = caseInsensitiveSort;
this.caseSensitiveSort = !caseInsensitiveSort;
}
public boolean isCaseInsensitiveMatch() {
return caseInsensitiveMatch;
}
public void setCaseInsensitiveMatch(boolean caseInsensitiveMatch) {
this.caseInsensitiveMatch = caseInsensitiveMatch;
this.caseSensitiveMatch = !caseInsensitiveMatch;
this.exactMatch = !caseInsensitiveMatch;
}
public boolean isCaseSensitiveSort() {
return caseSensitiveSort;
}
public void setCaseSensitiveSort(boolean caseSensitiveSort) {
this.caseSensitiveSort = caseSensitiveSort;
this.caseInsensitiveSort = !caseSensitiveSort;
}
public boolean isCaseSensitiveMatch() {
return caseSensitiveMatch;
}
public void setCaseSensitiveMatch(boolean caseSensitiveMatch) {
this.caseSensitiveMatch = caseSensitiveMatch;
this.caseInsensitiveMatch = !caseSensitiveMatch;
}
public boolean isCombineCategoryBags() {
return combineCategoryBags;
}
public void setCombineCategoryBags(boolean combineCategoryBags) {
this.combineCategoryBags = combineCategoryBags;
this.serviceSubset = !combineCategoryBags;
this.bindingSubset = !combineCategoryBags;
}
public boolean isDiacriticInsensitiveMatch() {
return diacriticInsensitiveMatch;
}
public void setDiacriticInsensitiveMatch(boolean diacriticInsensitiveMatch) {
this.diacriticInsensitiveMatch = diacriticInsensitiveMatch;
this.diacriticSensitiveMatch = !diacriticInsensitiveMatch;
}
public boolean isDiacriticSensitiveMatch() {
return diacriticSensitiveMatch;
}
public void setDiacriticSensitiveMatch(boolean diacriticSensitiveMatch) {
this.diacriticSensitiveMatch = diacriticSensitiveMatch;
this.diacriticInsensitiveMatch = !diacriticSensitiveMatch;
}
public boolean isExactMatch() {
return exactMatch;
}
public void setExactMatch(boolean exactMatch) {
this.exactMatch = exactMatch;
this.approximateMatch = !exactMatch;
this.caseInsensitiveMatch = !exactMatch;
}
public boolean isSignaturePresent() {
return signaturePresent;
}
public void setSignaturePresent(boolean signaturePresent) {
this.signaturePresent = signaturePresent;
}
public boolean isOrAllKeys() {
return orAllKeys;
}
public void setOrAllKeys(boolean orAllKeys) {
this.orAllKeys = orAllKeys;
this.andAllKeys = !orAllKeys;
this.orLikeKeys = !orAllKeys;
}
public boolean isOrLikeKeys() {
return orLikeKeys;
}
public void setOrLikeKeys(boolean orLikeKeys) {
this.orLikeKeys = orLikeKeys;
this.andAllKeys = !orLikeKeys;
this.orAllKeys = !orLikeKeys;
}
public boolean isServiceSubset() {
return serviceSubset;
}
public void setServiceSubset(boolean serviceSubset) {
this.serviceSubset = serviceSubset;
this.combineCategoryBags = !serviceSubset;
this.bindingSubset = !serviceSubset;
}
public boolean isSortByNameAsc() {
return sortByNameAsc;
}
public void setSortByNameAsc(boolean sortByNameAsc) {
this.sortByNameAsc = sortByNameAsc;
this.sortByNameDesc = !sortByNameAsc;
}
public boolean isSortByNameDesc() {
return sortByNameDesc;
}
public void setSortByNameDesc(boolean sortByNameDesc) {
this.sortByNameDesc = sortByNameDesc;
this.sortByNameAsc = !sortByNameDesc;
}
public boolean isSortByDateAsc() {
return sortByDateAsc;
}
public void setSortByDateAsc(boolean sortByDateAsc) {
this.sortByDateAsc = sortByDateAsc;
this.sortByDateDesc = !sortByDateAsc;
}
public boolean isSortByDateDesc() {
return sortByDateDesc;
}
public void setSortByDateDesc(boolean sortByDateDesc) {
this.sortByDateDesc = sortByDateDesc;
this.sortByDateAsc = !sortByDateDesc;
}
public boolean isSuppressProjectedServices() {
return suppressProjectedServices;
}
public void setSuppressProjectedServices(boolean suppressProjectedServices) {
this.suppressProjectedServices = suppressProjectedServices;
}
public boolean isUts10() {
return uts10;
}
public void setUts10(boolean uts10) {
this.uts10 = uts10;
this.binarySort = !uts10;
}
}
| |
/*
* Copyright 2006-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.consol.citrus.dsl.testng;
import javax.sql.DataSource;
import java.lang.reflect.Method;
import java.util.Date;
import com.consol.citrus.TestAction;
import com.consol.citrus.TestActionBuilder;
import com.consol.citrus.TestActionContainerBuilder;
import com.consol.citrus.TestCase;
import com.consol.citrus.TestCaseMetaInfo;
import com.consol.citrus.actions.AntRunAction;
import com.consol.citrus.actions.CreateVariablesAction;
import com.consol.citrus.actions.EchoAction;
import com.consol.citrus.actions.ExecutePLSQLAction;
import com.consol.citrus.actions.ExecuteSQLAction;
import com.consol.citrus.actions.ExecuteSQLQueryAction;
import com.consol.citrus.actions.FailAction;
import com.consol.citrus.actions.InputAction;
import com.consol.citrus.actions.JavaAction;
import com.consol.citrus.actions.LoadPropertiesAction;
import com.consol.citrus.actions.PurgeEndpointAction;
import com.consol.citrus.actions.ReceiveTimeoutAction;
import com.consol.citrus.actions.SleepAction;
import com.consol.citrus.actions.StartServerAction;
import com.consol.citrus.actions.StopServerAction;
import com.consol.citrus.actions.StopTimeAction;
import com.consol.citrus.actions.StopTimerAction;
import com.consol.citrus.actions.TraceVariablesAction;
import com.consol.citrus.actions.TransformAction;
import com.consol.citrus.container.Assert;
import com.consol.citrus.container.Async;
import com.consol.citrus.container.Catch;
import com.consol.citrus.container.Conditional;
import com.consol.citrus.container.FinallySequence;
import com.consol.citrus.container.Iterate;
import com.consol.citrus.container.Parallel;
import com.consol.citrus.container.RepeatOnErrorUntilTrue;
import com.consol.citrus.container.RepeatUntilTrue;
import com.consol.citrus.container.Sequence;
import com.consol.citrus.container.Template;
import com.consol.citrus.container.TestActionContainer;
import com.consol.citrus.container.Timer;
import com.consol.citrus.container.Wait;
import com.consol.citrus.context.TestContext;
import com.consol.citrus.dsl.builder.AssertSoapFaultBuilder;
import com.consol.citrus.dsl.builder.CamelRouteActionBuilder;
import com.consol.citrus.dsl.builder.DockerExecuteActionBuilder;
import com.consol.citrus.dsl.builder.HttpActionBuilder;
import com.consol.citrus.dsl.builder.KubernetesExecuteActionBuilder;
import com.consol.citrus.dsl.builder.PurgeJmsQueuesActionBuilder;
import com.consol.citrus.dsl.builder.PurgeMessageChannelActionBuilder;
import com.consol.citrus.dsl.builder.ReceiveMessageActionBuilder;
import com.consol.citrus.dsl.builder.SeleniumActionBuilder;
import com.consol.citrus.dsl.builder.SendMessageActionBuilder;
import com.consol.citrus.dsl.builder.SoapActionBuilder;
import com.consol.citrus.dsl.builder.ZooExecuteActionBuilder;
import com.consol.citrus.dsl.design.ApplyTestBehaviorAction;
import com.consol.citrus.dsl.design.TestBehavior;
import com.consol.citrus.dsl.design.TestDesigner;
import com.consol.citrus.endpoint.Endpoint;
import com.consol.citrus.script.GroovyAction;
import com.consol.citrus.server.Server;
import org.springframework.core.io.Resource;
import org.testng.ITestResult;
/**
* TestNG Citrus test provides Java DSL access to builder pattern methods in
* CitrusTestDesigner by simple method delegation.
*
* @author Christoph Deppisch
* @since 2.3
*/
public class TestNGCitrusTestDesigner extends TestNGCitrusTest implements TestDesigner {
/** Test builder delegate */
private TestDesigner testDesigner;
@Override
protected TestDesigner createTestDesigner(Method method, TestContext context) {
testDesigner = super.createTestDesigner(method, context);
return testDesigner;
}
@Override
protected void invokeTestMethod(ITestResult testResult, Method method, TestCase testCase, TestContext context, int invocationCount) {
if (isConfigure(method)) {
configure();
citrus.run(testCase, context);
} else {
super.invokeTestMethod(testResult, method, testCase, context, invocationCount);
}
}
@Override
protected final boolean isDesignerMethod(Method method) {
return true;
}
@Override
protected final boolean isRunnerMethod(Method method) {
return false;
}
/**
* Main entrance method for builder pattern usage. Subclasses may override
* this method and call Java DSL builder methods for adding test actions and
* basic test case properties.
*/
protected void configure() {
}
/**
* Checks if the given method is this designer's configure method.
* @param method
* @return
*/
private boolean isConfigure(Method method) {
return method.getDeclaringClass().equals(this.getClass()) && method.getName().equals("configure");
}
@Override
public TestCase getTestCase() {
return testDesigner.getTestCase();
}
@Override
public void testClass(Class<?> type) {
testDesigner.testClass(type);
}
@Override
public void name(String name) {
testDesigner.name(name);
}
@Override
public void description(String description) {
testDesigner.description(description);
}
@Override
public void author(String author) {
testDesigner.author(author);
}
@Override
public void packageName(String packageName) {
testDesigner.packageName(packageName);
}
@Override
public void status(TestCaseMetaInfo.Status status) {
testDesigner.status(status);
}
@Override
public void creationDate(Date date) {
testDesigner.creationDate(date);
}
@Override
public void groups(String[] groups) {
testDesigner.groups(groups);
}
@Override
public <T> T variable(String name, T value) {
return testDesigner.variable(name, value);
}
@Override
public CreateVariablesAction.Builder createVariable(String variableName, String value) {
return testDesigner.createVariable(variableName, value);
}
@Override
public void action(TestAction testAction) {
testDesigner.action(testAction);
}
@Override
public void action(TestActionBuilder<?> testAction) {
testDesigner.action(testAction);
}
@Override
public ApplyTestBehaviorAction.Builder applyBehavior(TestBehavior behavior) {
return testDesigner.applyBehavior(behavior);
}
@Override
public <T extends TestActionContainer, B extends TestActionContainerBuilder<T, B>> TestActionContainerBuilder<T, B> container(T container) {
return testDesigner.container(container);
}
@Override
public <T extends TestActionContainerBuilder<? extends TestActionContainer, ?>> T container(T container) {
return testDesigner.container(container);
}
@Override
public AntRunAction.Builder antrun(String buildFilePath) {
return testDesigner.antrun(buildFilePath);
}
@Override
public EchoAction.Builder echo(String message) {
return testDesigner.echo(message);
}
@Override
public ExecutePLSQLAction.Builder plsql(DataSource dataSource) {
return testDesigner.plsql(dataSource);
}
@Override
public ExecuteSQLAction.Builder sql(DataSource dataSource) {
return testDesigner.sql(dataSource);
}
@Override
public ExecuteSQLQueryAction.Builder query(DataSource dataSource) {
return testDesigner.query(dataSource);
}
@Override
public ReceiveTimeoutAction.Builder receiveTimeout(Endpoint messageEndpoint) {
return testDesigner.receiveTimeout(messageEndpoint);
}
@Override
public ReceiveTimeoutAction.Builder receiveTimeout(String messageEndpointName) {
return testDesigner.receiveTimeout(messageEndpointName);
}
@Override
public FailAction.Builder fail(String message) {
return testDesigner.fail(message);
}
@Override
public InputAction.Builder input() {
return testDesigner.input();
}
@Override
public JavaAction.Builder java(String className) {
return testDesigner.java(className);
}
@Override
public JavaAction.Builder java(Class<?> clazz) {
return testDesigner.java(clazz);
}
@Override
public JavaAction.Builder java(Object instance) {
return testDesigner.java(instance);
}
@Override
public LoadPropertiesAction.Builder load(String filePath) {
return testDesigner.load(filePath);
}
@Override
public PurgeJmsQueuesActionBuilder purgeQueues() {
return testDesigner.purgeQueues();
}
@Override
public PurgeMessageChannelActionBuilder purgeChannels() {
return testDesigner.purgeChannels();
}
@Override
public PurgeEndpointAction.Builder purgeEndpoints() {
return testDesigner.purgeEndpoints();
}
@Override
public ReceiveMessageActionBuilder<?> receive(Endpoint messageEndpoint) {
return testDesigner.receive(messageEndpoint);
}
@Override
public ReceiveMessageActionBuilder<?> receive(String messageEndpointName) {
return testDesigner.receive(messageEndpointName);
}
@Override
public SendMessageActionBuilder<?> send(Endpoint messageEndpoint) {
return testDesigner.send(messageEndpoint);
}
@Override
public SendMessageActionBuilder<?> send(String messageEndpointName) {
return testDesigner.send(messageEndpointName);
}
@Override
public SleepAction.Builder sleep() {
return testDesigner.sleep();
}
@Override
public SleepAction.Builder sleep(long milliseconds) {
return testDesigner.sleep(milliseconds);
}
@Override
public SleepAction.Builder sleep(double seconds) {
return testDesigner.sleep(seconds);
}
@Override
public Wait.Builder waitFor() {
return testDesigner.waitFor();
}
@Override
public StartServerAction.Builder start(Server... servers) {
return testDesigner.start(servers);
}
@Override
public StartServerAction.Builder start(Server server) {
return testDesigner.start(server);
}
@Override
public StopServerAction.Builder stop(Server... servers) {
return testDesigner.stop(servers);
}
@Override
public StopServerAction.Builder stop(Server server) {
return testDesigner.stop(server);
}
@Override
public StopTimeAction.Builder stopTime() {
return testDesigner.stopTime();
}
@Override
public StopTimeAction.Builder stopTime(String id) {
return testDesigner.stopTime(id);
}
@Override
public StopTimeAction.Builder stopTime(String id, String suffix) {
return testDesigner.stopTime(id, suffix);
}
@Override
public TraceVariablesAction.Builder traceVariables() {
return testDesigner.traceVariables();
}
@Override
public TraceVariablesAction.Builder traceVariables(String... variables) {
return testDesigner.traceVariables(variables);
}
@Override
public GroovyAction.Builder groovy(String script) {
return testDesigner.groovy(script);
}
@Override
public GroovyAction.Builder groovy(Resource scriptResource) {
return testDesigner.groovy(scriptResource);
}
@Override
public TransformAction.Builder transform() {
return testDesigner.transform();
}
@Override
public Assert.Builder assertException() {
return testDesigner.assertException();
}
@Override
public Catch.Builder catchException() {
return testDesigner.catchException();
}
@Override
public AssertSoapFaultBuilder assertSoapFault() {
return testDesigner.assertSoapFault();
}
@Override
public Conditional.Builder conditional() {
return testDesigner.conditional();
}
@Override
public Iterate.Builder iterate() {
return testDesigner.iterate();
}
@Override
public Parallel.Builder parallel() {
return testDesigner.parallel();
}
@Override
public RepeatOnErrorUntilTrue.Builder repeatOnError() {
return testDesigner.repeatOnError();
}
@Override
public RepeatUntilTrue.Builder repeat() {
return testDesigner.repeat();
}
@Override
public Sequence.Builder sequential() {
return testDesigner.sequential();
}
@Override
public Async.Builder async() {
return testDesigner.async();
}
@Override
public Timer.Builder timer() {
return testDesigner.timer();
}
@Override
public StopTimerAction.Builder stopTimer(String timerId) {
return testDesigner.stopTimer(timerId);
}
@Override
public StopTimerAction.Builder stopTimers() {
return testDesigner.stopTimers();
}
@Override
public DockerExecuteActionBuilder docker() {
return testDesigner.docker();
}
@Override
public KubernetesExecuteActionBuilder kubernetes() {
return testDesigner.kubernetes();
}
@Override
public SeleniumActionBuilder selenium() {
return testDesigner.selenium();
}
@Override
public HttpActionBuilder http() {
return testDesigner.http();
}
@Override
public SoapActionBuilder soap() {
return testDesigner.soap();
}
@Override
public CamelRouteActionBuilder camel() {
return testDesigner.camel();
}
@Override
public ZooExecuteActionBuilder zookeeper() {
return testDesigner.zookeeper();
}
@Override
public Template.Builder applyTemplate(String name) {
return testDesigner.applyTemplate(name);
}
@Override
public FinallySequence.Builder doFinally() {
return testDesigner.doFinally();
}
@Override
public void setTestContext(TestContext context) {
testDesigner.setTestContext(context);
}
}
| |
/**
* Copyright (C) 2013 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.engine.view.cycle;
import java.util.Collection;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.threeten.bp.Instant;
import com.opengamma.engine.cache.CacheSelectHint;
import com.opengamma.engine.cache.ViewComputationCache;
import com.opengamma.engine.calcnode.CalculationJob;
import com.opengamma.engine.calcnode.CalculationJobItem;
import com.opengamma.engine.calcnode.CalculationJobResult;
import com.opengamma.engine.calcnode.CalculationJobResultItem;
import com.opengamma.engine.calcnode.MutableExecutionLog;
import com.opengamma.engine.depgraph.DependencyGraph;
import com.opengamma.engine.exec.DefaultAggregatedExecutionLog;
import com.opengamma.engine.exec.DependencyGraphExecutionFuture;
import com.opengamma.engine.exec.DependencyGraphExecutor;
import com.opengamma.engine.exec.DependencyNodeJobExecutionResult;
import com.opengamma.engine.exec.DependencyNodeJobExecutionResultCache;
import com.opengamma.engine.function.FunctionDefinition;
import com.opengamma.engine.function.FunctionParameters;
import com.opengamma.engine.value.ComputedValueResult;
import com.opengamma.engine.value.ValueSpecification;
import com.opengamma.engine.view.AggregatedExecutionLog;
import com.opengamma.engine.view.ExecutionLog;
import com.opengamma.engine.view.ExecutionLogMode;
import com.opengamma.engine.view.impl.ExecutionLogModeSource;
import com.opengamma.engine.view.impl.InMemoryViewComputationResultModel;
import com.opengamma.util.async.Cancelable;
import com.opengamma.util.log.LogLevel;
import com.opengamma.util.log.SimpleLogEvent;
import com.opengamma.util.tuple.Pair;
/**
* State required by {@link SingleComputationCycle} during its execution only.
* <p>
* An instance of this object, owned by the cycle, will only exist while the {@link SingleComputationCycle#execute} method is being called.
*/
/* package */class SingleComputationCycleExecutor implements DependencyGraphExecutionFuture.Listener {
private static final Logger s_logger = LoggerFactory.getLogger(SingleComputationCycleExecutor.class);
private abstract static class Event {
public abstract void run(SingleComputationCycleExecutor executorComputation);
}
private static class GraphExecutionComplete extends Event {
private final String _calculationConfiguration;
public GraphExecutionComplete(final String calculationConfiguration) {
_calculationConfiguration = calculationConfiguration;
}
@Override
public void run(final SingleComputationCycleExecutor executor) {
s_logger.info("Execution of {} complete", _calculationConfiguration);
final ExecutingCalculationConfiguration calcConfig = executor._executing.remove(_calculationConfiguration);
if (calcConfig != null) {
SingleComputationCycle cycle = executor.getCycle();
final InMemoryViewComputationResultModel fragmentResultModel = cycle.constructTemplateResultModel();
calcConfig.buildResults(fragmentResultModel, cycle.getResultModel());
// TODO: Populate with durations from the component jobs
fragmentResultModel.setCalculationTime(Instant.now());
cycle.notifyFragmentCompleted(fragmentResultModel);
}
}
}
private static class CalculationJobComplete extends Event {
private final CalculationJob _job;
private final CalculationJobResult _jobResult;
public CalculationJobComplete(final CalculationJob job, final CalculationJobResult jobResult) {
_job = job;
_jobResult = jobResult;
}
@Override
public void run(final SingleComputationCycleExecutor executor) {
s_logger.debug("Execution of {} complete", _job);
executor.buildResults(_job, _jobResult);
}
}
private static class ExecutingCalculationConfiguration {
private final Cancelable _handle;
private final DependencyGraph _graph;
private final DependencyNodeJobExecutionResultCache _resultCache;
private final ViewComputationCache _computationCache;
private final Set<ValueSpecification> _terminalOutputs = new HashSet<ValueSpecification>();
public ExecutingCalculationConfiguration(final SingleComputationCycle cycle, final DependencyGraph graph, final Cancelable handle) {
_handle = handle;
_graph = graph;
_resultCache = cycle.getJobExecutionResultCache(graph.getCalculationConfigurationName());
_computationCache = cycle.getComputationCache(graph.getCalculationConfigurationName());
}
public void cancel() {
_handle.cancel(true);
}
public DependencyGraph getDependencyGraph() {
return _graph;
}
public DependencyNodeJobExecutionResultCache getResultCache() {
return _resultCache;
}
public Set<ValueSpecification> getTerminalOutputs() {
return _terminalOutputs;
}
public void buildResults(final InMemoryViewComputationResultModel fragmentResultModel, final InMemoryViewComputationResultModel fullResultModel) {
if (_terminalOutputs.isEmpty()) {
return;
}
final String calculationConfiguration = _graph.getCalculationConfigurationName();
for (Pair<ValueSpecification, Object> value : _computationCache.getValues(_terminalOutputs, CacheSelectHint.allShared())) {
final ValueSpecification valueSpec = value.getFirst();
final Object calculatedValue = value.getSecond();
if (calculatedValue != null) {
final ComputedValueResult computedValueResult = SingleComputationCycle.createComputedValueResult(valueSpec, calculatedValue, _resultCache.get(valueSpec));
fragmentResultModel.addValue(calculationConfiguration, computedValueResult);
fullResultModel.addValue(calculationConfiguration, computedValueResult);
}
}
_terminalOutputs.clear();
}
}
private final BlockingQueue<Event> _events = new LinkedBlockingQueue<Event>();
private final Map<String, ExecutingCalculationConfiguration> _executing = new HashMap<String, ExecutingCalculationConfiguration>();
private final SingleComputationCycle _cycle;
private boolean _issueFragmentResults;
public SingleComputationCycleExecutor(final SingleComputationCycle cycle) {
_cycle = cycle;
}
private SingleComputationCycle getCycle() {
return _cycle;
}
public void execute() throws InterruptedException {
final DependencyGraphExecutor executor = getCycle().getViewProcessContext().getDependencyGraphExecutorFactory().createExecutor(getCycle());
for (final String calcConfigurationName : getCycle().getAllCalculationConfigurationNames()) {
s_logger.info("Executing plans for calculation configuration {}", calcConfigurationName);
final DependencyGraph depGraph = getCycle().getDependencyGraph(calcConfigurationName);
final Set<ValueSpecification> sharedData = getCycle().getSharedValues(calcConfigurationName);
final Map<ValueSpecification, FunctionParameters> parameters = getCycle().createFunctionParameters(calcConfigurationName);
s_logger.info("Submitting {} for execution by {}", depGraph, executor);
final DependencyGraphExecutionFuture future = executor.execute(depGraph, sharedData, parameters);
_executing.put(calcConfigurationName, new ExecutingCalculationConfiguration(getCycle(), depGraph, future));
future.setListener(this);
}
try {
while (!_executing.isEmpty()) {
// Block for the first event
_events.take().run(this);
// Then run through any others as quickly as possible before dispatching a notification
Event e = _events.poll();
while (e != null) {
e.run(this);
e = _events.poll();
}
if (_issueFragmentResults) {
if (_executing.isEmpty()) {
s_logger.info("Discarding fragment completion message - overall execution is complete");
} else {
s_logger.debug("Building result fragment");
final InMemoryViewComputationResultModel fragmentResultModel = getCycle().constructTemplateResultModel();
final InMemoryViewComputationResultModel fullResultModel = getCycle().getResultModel();
for (ExecutingCalculationConfiguration calcConfig : _executing.values()) {
calcConfig.buildResults(fragmentResultModel, fullResultModel);
}
s_logger.info("Fragment execution complete");
// TODO: Populate the calculation duration with information from the component jobs
fragmentResultModel.setCalculationTime(Instant.now());
getCycle().notifyFragmentCompleted(fragmentResultModel);
}
_issueFragmentResults = false;
}
}
} catch (final InterruptedException e) {
Thread.interrupted();
// Cancel all outstanding jobs to free up resources
for (ExecutingCalculationConfiguration execution : _executing.values()) {
execution.cancel();
}
throw e;
}
}
private String toString(final String prefix, final Collection<?> values) {
final StringBuilder sb = new StringBuilder(prefix);
if (values.size() > 1) {
sb.append("s - { ");
int count = 0;
for (Object value : values) {
count++;
if (count > 1) {
sb.append(", ");
if (count > 10) {
sb.append("...");
break;
}
}
sb.append(value.toString());
}
sb.append(" }");
} else {
sb.append(" - ").append(values.iterator().next().toString());
}
return sb.toString();
}
private void buildResults(final CalculationJob job, final CalculationJobResult jobResult) {
final String calculationConfiguration = jobResult.getSpecification().getCalcConfigName();
final ExecutingCalculationConfiguration calcConfig = _executing.get(calculationConfiguration);
if (calcConfig == null) {
s_logger.warn("Job fragment result for already completed configuration {}", calculationConfiguration);
return;
}
final DependencyGraph graph = calcConfig.getDependencyGraph();
final Map<ValueSpecification, ?> graphTerminalOutputs = graph.getTerminalOutputs();
final Iterator<CalculationJobItem> jobItemItr = job.getJobItems().iterator();
final Iterator<CalculationJobResultItem> jobResultItr = jobResult.getResultItems().iterator();
final ExecutionLogModeSource logModes = getCycle().getLogModeSource();
final DependencyNodeJobExecutionResultCache jobExecutionResultCache = calcConfig.getResultCache();
final Set<ValueSpecification> executedTerminalOutputs = calcConfig.getTerminalOutputs();
final String computeNodeId = jobResult.getComputeNodeId();
while (jobItemItr.hasNext()) {
assert jobResultItr.hasNext();
final CalculationJobItem jobItem = jobItemItr.next();
final CalculationJobResultItem jobResultItem = jobResultItr.next();
// Process the streamed result fragment
final ExecutionLogMode executionLogMode = logModes.getLogMode(calculationConfiguration, jobItem.getOutputs()[0]);
final AggregatedExecutionLog aggregatedExecutionLog;
if (executionLogMode == ExecutionLogMode.FULL) {
final ExecutionLog log = jobResultItem.getExecutionLog();
MutableExecutionLog logCopy = null;
final Set<AggregatedExecutionLog> inputLogs = new LinkedHashSet<AggregatedExecutionLog>();
Set<ValueSpecification> missing = jobResultItem.getMissingInputs();
if (!missing.isEmpty()) {
logCopy = new MutableExecutionLog(log);
logCopy.add(new SimpleLogEvent(log.hasException() ? LogLevel.WARN : LogLevel.INFO, toString("Missing input", missing)));
}
missing = jobResultItem.getMissingOutputs();
if (!missing.isEmpty()) {
if (logCopy == null) {
logCopy = new MutableExecutionLog(log);
}
logCopy.add(new SimpleLogEvent(LogLevel.WARN, toString("Failed to produce output", missing)));
}
for (final ValueSpecification inputValueSpec : jobItem.getInputs()) {
final DependencyNodeJobExecutionResult nodeResult = jobExecutionResultCache.get(inputValueSpec);
if (nodeResult == null) {
// Market data
continue;
}
inputLogs.add(nodeResult.getAggregatedExecutionLog());
}
final String functionName;
final FunctionDefinition function = getCycle().getViewProcessContext().getFunctionResolver().getFunction(jobItem.getFunctionUniqueIdentifier());
if (function != null) {
functionName = function.getShortName();
} else {
functionName = jobItem.getFunctionUniqueIdentifier();
}
aggregatedExecutionLog = DefaultAggregatedExecutionLog.fullLogMode(functionName, jobItem.getComputationTargetSpecification(), (logCopy != null) ? logCopy : log, inputLogs);
} else {
EnumSet<LogLevel> logs = jobResultItem.getExecutionLog().getLogLevels();
boolean copied = false;
for (final ValueSpecification inputValueSpec : jobItem.getInputs()) {
final DependencyNodeJobExecutionResult nodeResult = jobExecutionResultCache.get(inputValueSpec);
if (nodeResult == null) {
// Market data
continue;
}
if (logs.containsAll(nodeResult.getAggregatedExecutionLog().getLogLevels())) {
continue;
}
if (!copied) {
copied = true;
logs = EnumSet.copyOf(logs);
}
logs.addAll(nodeResult.getAggregatedExecutionLog().getLogLevels());
}
aggregatedExecutionLog = DefaultAggregatedExecutionLog.indicatorLogMode(logs);
}
final DependencyNodeJobExecutionResult jobExecutionResult = new DependencyNodeJobExecutionResult(computeNodeId, jobResultItem, aggregatedExecutionLog);
for (final ValueSpecification outputValueSpec : jobItem.getOutputs()) {
if (graphTerminalOutputs.containsKey(outputValueSpec)) {
executedTerminalOutputs.add(outputValueSpec);
}
jobExecutionResultCache.put(outputValueSpec, jobExecutionResult);
}
}
_issueFragmentResults |= !executedTerminalOutputs.isEmpty();
}
/**
* Receives a job result fragment. These will be streamed in by the execution framework. Only one notification per job will be received (for example the execution framework might have
* repeated/duplicated jobs to handle node failures).
*
* @param job the job that was executed, not null
* @param jobResult the job result, not null
*/
public void jobCompleted(final CalculationJob job, final CalculationJobResult jobResult) {
_events.add(new CalculationJobComplete(job, jobResult));
}
@Override
public void graphCompleted(final String calculationConfiguration) {
_events.add(new GraphExecutionComplete(calculationConfiguration));
}
}
| |
/*
* SPDX-License-Identifier: Apache-2.0
*
* Copyright 2008-2022 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 griffon.javafx.beans.binding;
import griffon.annotations.core.Nonnull;
import javafx.beans.InvalidationListener;
import javafx.beans.binding.BooleanBinding;
import javafx.beans.binding.DoubleBinding;
import javafx.beans.binding.StringBinding;
import javafx.beans.property.ReadOnlyDoubleProperty;
import javafx.beans.property.ReadOnlyObjectProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableNumberValue;
import java.util.Locale;
import static java.util.Objects.requireNonNull;
/**
* @author Andres Almiray
* @since 3.0.0
*/
public class ReadOnlyDoublePropertyDecorator extends ReadOnlyDoubleProperty {
private final ReadOnlyDoubleProperty delegate;
public ReadOnlyDoublePropertyDecorator(@Nonnull ReadOnlyDoubleProperty delegate) {
this.delegate = requireNonNull(delegate, "Argument 'delegate' must not be null");
}
@Nonnull
protected final ReadOnlyDoubleProperty getDelegate() {
return delegate;
}
@Override
public String toString() {
return getClass().getName() + ":" + delegate.toString();
}
@Override
public ReadOnlyObjectProperty<Double> asObject() {
return delegate.asObject();
}
@Override
public int intValue() {
return delegate.intValue();
}
@Override
public long longValue() {
return delegate.longValue();
}
@Override
public float floatValue() {
return delegate.floatValue();
}
@Override
public double doubleValue() {
return delegate.doubleValue();
}
@Override
public Double getValue() {
return delegate.getValue();
}
@Override
public DoubleBinding negate() {
return delegate.negate();
}
@Override
public DoubleBinding add(ObservableNumberValue other) {
return delegate.add(other);
}
@Override
public DoubleBinding add(double other) {
return delegate.add(other);
}
@Override
public DoubleBinding add(float other) {
return delegate.add(other);
}
@Override
public DoubleBinding add(long other) {
return delegate.add(other);
}
@Override
public DoubleBinding add(int other) {
return delegate.add(other);
}
@Override
public DoubleBinding subtract(ObservableNumberValue other) {
return delegate.subtract(other);
}
@Override
public DoubleBinding subtract(double other) {
return delegate.subtract(other);
}
@Override
public DoubleBinding subtract(float other) {
return delegate.subtract(other);
}
@Override
public DoubleBinding subtract(long other) {
return delegate.subtract(other);
}
@Override
public DoubleBinding subtract(int other) {
return delegate.subtract(other);
}
@Override
public DoubleBinding multiply(ObservableNumberValue other) {
return delegate.multiply(other);
}
@Override
public DoubleBinding multiply(double other) {
return delegate.multiply(other);
}
@Override
public DoubleBinding multiply(float other) {
return delegate.multiply(other);
}
@Override
public DoubleBinding multiply(long other) {
return delegate.multiply(other);
}
@Override
public DoubleBinding multiply(int other) {
return delegate.multiply(other);
}
@Override
public DoubleBinding divide(ObservableNumberValue other) {
return delegate.divide(other);
}
@Override
public DoubleBinding divide(double other) {
return delegate.divide(other);
}
@Override
public DoubleBinding divide(float other) {
return delegate.divide(other);
}
@Override
public DoubleBinding divide(long other) {
return delegate.divide(other);
}
@Override
public DoubleBinding divide(int other) {
return delegate.divide(other);
}
@Override
public BooleanBinding isEqualTo(ObservableNumberValue other) {
return delegate.isEqualTo(other);
}
@Override
public BooleanBinding isEqualTo(ObservableNumberValue other, double epsilon) {
return delegate.isEqualTo(other, epsilon);
}
@Override
public BooleanBinding isEqualTo(double other, double epsilon) {
return delegate.isEqualTo(other, epsilon);
}
@Override
public BooleanBinding isEqualTo(float other, double epsilon) {
return delegate.isEqualTo(other, epsilon);
}
@Override
public BooleanBinding isEqualTo(long other) {
return delegate.isEqualTo(other);
}
@Override
public BooleanBinding isEqualTo(long other, double epsilon) {
return delegate.isEqualTo(other, epsilon);
}
@Override
public BooleanBinding isEqualTo(int other) {
return delegate.isEqualTo(other);
}
@Override
public BooleanBinding isEqualTo(int other, double epsilon) {
return delegate.isEqualTo(other, epsilon);
}
@Override
public BooleanBinding isNotEqualTo(ObservableNumberValue other) {
return delegate.isNotEqualTo(other);
}
@Override
public BooleanBinding isNotEqualTo(ObservableNumberValue other, double epsilon) {
return delegate.isNotEqualTo(other, epsilon);
}
@Override
public BooleanBinding isNotEqualTo(double other, double epsilon) {
return delegate.isNotEqualTo(other, epsilon);
}
@Override
public BooleanBinding isNotEqualTo(float other, double epsilon) {
return delegate.isNotEqualTo(other, epsilon);
}
@Override
public BooleanBinding isNotEqualTo(long other) {
return delegate.isNotEqualTo(other);
}
@Override
public BooleanBinding isNotEqualTo(long other, double epsilon) {
return delegate.isNotEqualTo(other, epsilon);
}
@Override
public BooleanBinding isNotEqualTo(int other) {
return delegate.isNotEqualTo(other);
}
@Override
public BooleanBinding isNotEqualTo(int other, double epsilon) {
return delegate.isNotEqualTo(other, epsilon);
}
@Override
public BooleanBinding greaterThan(ObservableNumberValue other) {
return delegate.greaterThan(other);
}
@Override
public BooleanBinding greaterThan(double other) {
return delegate.greaterThan(other);
}
@Override
public BooleanBinding greaterThan(float other) {
return delegate.greaterThan(other);
}
@Override
public BooleanBinding greaterThan(long other) {
return delegate.greaterThan(other);
}
@Override
public BooleanBinding greaterThan(int other) {
return delegate.greaterThan(other);
}
@Override
public BooleanBinding lessThan(ObservableNumberValue other) {
return delegate.lessThan(other);
}
@Override
public BooleanBinding lessThan(double other) {
return delegate.lessThan(other);
}
@Override
public BooleanBinding lessThan(float other) {
return delegate.lessThan(other);
}
@Override
public BooleanBinding lessThan(long other) {
return delegate.lessThan(other);
}
@Override
public BooleanBinding lessThan(int other) {
return delegate.lessThan(other);
}
@Override
public BooleanBinding greaterThanOrEqualTo(ObservableNumberValue other) {
return delegate.greaterThanOrEqualTo(other);
}
@Override
public BooleanBinding greaterThanOrEqualTo(double other) {
return delegate.greaterThanOrEqualTo(other);
}
@Override
public BooleanBinding greaterThanOrEqualTo(float other) {
return delegate.greaterThanOrEqualTo(other);
}
@Override
public BooleanBinding greaterThanOrEqualTo(long other) {
return delegate.greaterThanOrEqualTo(other);
}
@Override
public BooleanBinding greaterThanOrEqualTo(int other) {
return delegate.greaterThanOrEqualTo(other);
}
@Override
public BooleanBinding lessThanOrEqualTo(ObservableNumberValue other) {
return delegate.lessThanOrEqualTo(other);
}
@Override
public BooleanBinding lessThanOrEqualTo(double other) {
return delegate.lessThanOrEqualTo(other);
}
@Override
public BooleanBinding lessThanOrEqualTo(float other) {
return delegate.lessThanOrEqualTo(other);
}
@Override
public BooleanBinding lessThanOrEqualTo(long other) {
return delegate.lessThanOrEqualTo(other);
}
@Override
public BooleanBinding lessThanOrEqualTo(int other) {
return delegate.lessThanOrEqualTo(other);
}
@Override
public StringBinding asString() {
return delegate.asString();
}
@Override
public StringBinding asString(String format) {
return delegate.asString(format);
}
@Override
public StringBinding asString(Locale locale, String format) {
return delegate.asString(locale, format);
}
@Override
public void addListener(ChangeListener<? super Number> listener) {
delegate.addListener(listener);
}
@Override
public void removeListener(ChangeListener<? super Number> listener) {
delegate.removeListener(listener);
}
@Override
public void addListener(InvalidationListener listener) {
delegate.addListener(listener);
}
@Override
public void removeListener(InvalidationListener listener) {
delegate.removeListener(listener);
}
@Override
public double get() {
return delegate.get();
}
@Override
public Object getBean() {
return delegate.getBean();
}
@Override
public String getName() {
return delegate.getName();
}
}
| |
package versioned.host.exp.exponent.modules.api.components.barcodescanner;
import android.hardware.Camera;
import android.util.Log;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class BarCodeScanner {
private static BarCodeScanner ourInstance;
private final HashMap<Integer, CameraInfoWrapper> mCameraInfos;
private final HashMap<Integer, Integer> mCameraTypeToIndex;
private List<String> mBarCodeTypes = null;
private final Map<Number, Camera> mCameras;
private int mActualDeviceOrientation = 0;
private int mAdjustedDeviceOrientation = 0;
public static BarCodeScanner getInstance() {
return ourInstance;
}
public static void createInstance(int deviceOrientation) {
ourInstance = new BarCodeScanner(deviceOrientation);
}
public Camera acquireCameraInstance(int type) {
if (null == mCameras.get(type) && null != mCameraTypeToIndex.get(type)) {
try {
Camera camera = Camera.open(mCameraTypeToIndex.get(type));
mCameras.put(type, camera);
adjustPreviewLayout(type);
} catch (Exception e) {
Log.e("BarCodeScanner", "acquireCameraInstance failed", e);
}
}
return mCameras.get(type);
}
public void releaseCameraInstance(int type) {
if (null != mCameras.get(type)) {
mCameras.get(type).release();
mCameras.remove(type);
}
}
public int getPreviewWidth(int type) {
CameraInfoWrapper cameraInfo = mCameraInfos.get(type);
if (null == cameraInfo) {
return 0;
}
return cameraInfo.previewWidth;
}
public int getPreviewHeight(int type) {
CameraInfoWrapper cameraInfo = mCameraInfos.get(type);
if (null == cameraInfo) {
return 0;
}
return cameraInfo.previewHeight;
}
public Camera.Size getBestSize(List<Camera.Size> supportedSizes, int maxWidth, int maxHeight) {
Camera.Size bestSize = null;
for (Camera.Size size : supportedSizes) {
if (size.width > maxWidth || size.height > maxHeight) {
continue;
}
if (bestSize == null) {
bestSize = size;
continue;
}
int resultArea = bestSize.width * bestSize.height;
int newArea = size.width * size.height;
if (newArea > resultArea) {
bestSize = size;
}
}
return bestSize;
}
private Camera.Size getSmallestSize(List<Camera.Size> supportedSizes) {
Camera.Size smallestSize = null;
for (Camera.Size size : supportedSizes) {
if (smallestSize == null) {
smallestSize = size;
continue;
}
int resultArea = smallestSize.width * smallestSize.height;
int newArea = size.width * size.height;
if (newArea < resultArea) {
smallestSize = size;
}
}
return smallestSize;
}
public List<String> getBarCodeTypes() {
return mBarCodeTypes;
}
public void setBarCodeTypes(List<String> barCodeTypes) {
mBarCodeTypes = barCodeTypes;
}
public int getActualDeviceOrientation() {
return mActualDeviceOrientation;
}
public void setAdjustedDeviceOrientation(int orientation) {
mAdjustedDeviceOrientation = orientation;
}
public int getAdjustedDeviceOrientation() {
return mAdjustedDeviceOrientation;
}
public void setActualDeviceOrientation(int actualDeviceOrientation) {
mActualDeviceOrientation = actualDeviceOrientation;
adjustPreviewLayout(BarCodeScannerModule.RCT_CAMERA_TYPE_FRONT);
adjustPreviewLayout(BarCodeScannerModule.RCT_CAMERA_TYPE_BACK);
}
public void setTorchMode(int cameraType, int torchMode) {
Camera camera = mCameras.get(cameraType);
if (null == camera) {
return;
}
Camera.Parameters parameters = camera.getParameters();
String value = parameters.getFlashMode();
switch (torchMode) {
case BarCodeScannerModule.RCT_CAMERA_TORCH_MODE_ON:
value = Camera.Parameters.FLASH_MODE_TORCH;
break;
case BarCodeScannerModule.RCT_CAMERA_TORCH_MODE_OFF:
value = Camera.Parameters.FLASH_MODE_OFF;
break;
}
List<String> flashModes = parameters.getSupportedFlashModes();
if (flashModes != null && flashModes.contains(value)) {
parameters.setFlashMode(value);
camera.setParameters(parameters);
}
}
public void setFlashMode(int cameraType, int flashMode) {
Camera camera = mCameras.get(cameraType);
if (null == camera) {
return;
}
Camera.Parameters parameters = camera.getParameters();
String value = parameters.getFlashMode();
switch (flashMode) {
case BarCodeScannerModule.RCT_CAMERA_FLASH_MODE_AUTO:
value = Camera.Parameters.FLASH_MODE_AUTO;
break;
case BarCodeScannerModule.RCT_CAMERA_FLASH_MODE_ON:
value = Camera.Parameters.FLASH_MODE_ON;
break;
case BarCodeScannerModule.RCT_CAMERA_FLASH_MODE_OFF:
value = Camera.Parameters.FLASH_MODE_OFF;
break;
}
List<String> flashModes = parameters.getSupportedFlashModes();
if (flashModes != null && flashModes.contains(value)) {
parameters.setFlashMode(value);
camera.setParameters(parameters);
}
}
public void adjustCameraRotationToDeviceOrientation(int type, int deviceOrientation) {
Camera camera = mCameras.get(type);
if (null == camera) {
return;
}
CameraInfoWrapper cameraInfo = mCameraInfos.get(type);
int rotation;
int orientation = cameraInfo.info.orientation;
if (cameraInfo.info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
rotation = (orientation + deviceOrientation * 90) % 360;
} else {
rotation = (orientation - deviceOrientation * 90 + 360) % 360;
}
cameraInfo.rotation = rotation;
Camera.Parameters parameters = camera.getParameters();
parameters.setRotation(cameraInfo.rotation);
try {
camera.setParameters(parameters);
} catch (Exception e) {
e.printStackTrace();
}
}
public void adjustPreviewLayout(int type) {
Camera camera = mCameras.get(type);
if (null == camera) {
return;
}
CameraInfoWrapper cameraInfo = mCameraInfos.get(type);
int displayRotation;
int rotation;
int orientation = cameraInfo.info.orientation;
if (cameraInfo.info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
rotation = (orientation + mActualDeviceOrientation * 90) % 360;
displayRotation = (720 - orientation - mActualDeviceOrientation * 90) % 360;
} else {
rotation = (orientation - mActualDeviceOrientation * 90 + 360) % 360;
displayRotation = rotation;
}
cameraInfo.rotation = rotation;
setAdjustedDeviceOrientation(rotation);
camera.setDisplayOrientation(displayRotation);
Camera.Parameters parameters = camera.getParameters();
parameters.setRotation(cameraInfo.rotation);
// set preview size
// defaults to highest resolution available
Camera.Size optimalPreviewSize = getBestSize(parameters.getSupportedPreviewSizes(), Integer.MAX_VALUE, Integer.MAX_VALUE);
int width = optimalPreviewSize.width;
int height = optimalPreviewSize.height;
parameters.setPreviewSize(width, height);
try {
camera.setParameters(parameters);
} catch (Exception e) {
e.printStackTrace();
}
if (cameraInfo.rotation == 0 || cameraInfo.rotation == 180) {
cameraInfo.previewWidth = width;
cameraInfo.previewHeight = height;
} else {
cameraInfo.previewWidth = height;
cameraInfo.previewHeight = width;
}
}
private BarCodeScanner(int deviceOrientation) {
mCameras = new HashMap<>();
mCameraInfos = new HashMap<>();
mCameraTypeToIndex = new HashMap<>();
mActualDeviceOrientation = deviceOrientation;
// map camera types to camera indexes and collect cameras properties
for (int i = 0; i < Camera.getNumberOfCameras(); i++) {
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT && mCameraInfos.get(BarCodeScannerModule.RCT_CAMERA_TYPE_FRONT) == null) {
mCameraInfos.put(BarCodeScannerModule.RCT_CAMERA_TYPE_FRONT, new CameraInfoWrapper(info));
mCameraTypeToIndex.put(BarCodeScannerModule.RCT_CAMERA_TYPE_FRONT, i);
acquireCameraInstance(BarCodeScannerModule.RCT_CAMERA_TYPE_FRONT);
releaseCameraInstance(BarCodeScannerModule.RCT_CAMERA_TYPE_FRONT);
} else if (info.facing == Camera.CameraInfo.CAMERA_FACING_BACK && mCameraInfos.get(BarCodeScannerModule.RCT_CAMERA_TYPE_BACK) == null) {
mCameraInfos.put(BarCodeScannerModule.RCT_CAMERA_TYPE_BACK, new CameraInfoWrapper(info));
mCameraTypeToIndex.put(BarCodeScannerModule.RCT_CAMERA_TYPE_BACK, i);
acquireCameraInstance(BarCodeScannerModule.RCT_CAMERA_TYPE_BACK);
releaseCameraInstance(BarCodeScannerModule.RCT_CAMERA_TYPE_BACK);
}
}
}
private class CameraInfoWrapper {
public final Camera.CameraInfo info;
public int rotation = 0;
public int previewWidth = -1;
public int previewHeight = -1;
public CameraInfoWrapper(Camera.CameraInfo info) {
this.info = info;
}
}
}
| |
/*
* 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.xenei.jdbc4sparql.sparql.builders;
import java.sql.DatabaseMetaData;
import java.sql.Types;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.xenei.jdbc4sparql.iface.TypeConverter;
import org.xenei.jdbc4sparql.impl.rdf.RdfCatalog;
import org.xenei.jdbc4sparql.impl.rdf.RdfColumnDef;
import org.xenei.jdbc4sparql.impl.rdf.RdfKey;
import org.xenei.jdbc4sparql.impl.rdf.RdfKeySegment;
import org.xenei.jdbc4sparql.impl.rdf.RdfSchema;
import org.xenei.jdbc4sparql.impl.rdf.RdfTable;
import org.xenei.jdbc4sparql.impl.rdf.RdfTableDef;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.util.iterator.Filter;
import com.hp.hpl.jena.util.iterator.Map1;
import com.hp.hpl.jena.util.iterator.WrappedIterator;
/**
* A simple builder that builds tables for all subjects of [?x a rdfs:Class]
* triples. Columns for the tables are created from all predicates of all
* instances of the class.
*/
public class SimpleNormalizingBuilder extends SimpleBuilder {
public static final String BUILDER_NAME = "Smpl_Norm_Builder";
public static final String DESCRIPTION = "A simple normalizing schema builder that builds tables based on RDFS Class names";
// Params: namespace.
protected static final String TABLE_QUERY = " prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>"
+ " SELECT ?tName WHERE { ?tName a rdfs:Class . }";
// Params: class resource, namespace
protected static final String COLUMN_QUERY = "SELECT DISTINCT ?cName "
+ " WHERE { ?instance a <%s> ; ?cName [] ; }";
private static final String TABLE_SEGMENT = "%1$s <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <%2$s> .";
protected static final String COLUMN_SEGMENT = "%1$s <%3$s> %2$s .";
protected static final String ID_COLUMN_SEGMENT = "BIND( %1$s as %2$s)";
public RdfColumnDef idColumnDef;
public SimpleNormalizingBuilder() {
}
protected Map<String, String> addColumnDefs(final Set<RdfTable> tableSet,
final RdfCatalog catalog, final RdfSchema schema,
final RdfTableDef.Builder tableDefBuilder, final Resource tName,
final String tableQuerySegment) {
final Model model = catalog.getResource().getModel();
final Map<String, String> colNames = new LinkedHashMap<String, String>();
final List<QuerySolution> solns = catalog.executeQuery(String.format(
SimpleNormalizingBuilder.COLUMN_QUERY, tName));
colNames.put("id", SimpleNormalizingBuilder.ID_COLUMN_SEGMENT);
tableDefBuilder.addColumnDef(idColumnDef);
for (final QuerySolution soln : solns) {
final RdfColumnDef.Builder builder = new RdfColumnDef.Builder();
final Resource cName = soln.getResource("cName");
final String columnQuerySegment = String.format(
SimpleNormalizingBuilder.COLUMN_SEGMENT, "%1$s", "%2$s",
cName.getURI());
if (multipleCardinality(catalog, tableQuerySegment,
columnQuerySegment)) {
tableSet.add(makeSubTable(catalog, schema, tableQuerySegment,
columnQuerySegment, tName, cName));
}
else {
// might be a duplicate name
if (colNames.containsKey(cName.getLocalName())) {
int i = 2;
while (colNames.containsKey(cName.getLocalName() + i)) {
i++;
}
colNames.put(cName.getLocalName() + i, columnQuerySegment);
}
else {
colNames.put(cName.getLocalName(), columnQuerySegment);
}
final int scale = calculateSize(catalog, tableQuerySegment,
columnQuerySegment);
builder.setType(Types.VARCHAR)
.setNullable(DatabaseMetaData.columnNullable)
.setScale(scale).setReadOnly(true);
tableDefBuilder.addColumnDef(builder.build(model));
}
}
return colNames;
}
private void buildTable(final Set<RdfTable> tableSet,
final RdfCatalog catalog, final RdfSchema schema,
final Resource tName) {
final Model model = schema.getResource().getModel();
final RdfTableDef.Builder builder = new RdfTableDef.Builder();
final String tableQuerySegment = String.format(
SimpleNormalizingBuilder.TABLE_SEGMENT, "%1$s", tName.getURI());
final Map<String, String> colNames = addColumnDefs(tableSet, catalog,
schema, builder, tName, tableQuerySegment);
if (colNames.size() > 1) {
// add the key segments
final RdfKeySegment.Builder keySegBuilder = new RdfKeySegment.Builder();
keySegBuilder.setAscending(true);
keySegBuilder.setIdx(0);
final RdfKey.Builder keyBldr = new RdfKey.Builder();
keyBldr.setUnique(true);
keyBldr.addSegment(keySegBuilder.build(model));
builder.setPrimaryKey(keyBldr.build(model));
// build the def
final RdfTableDef tableDef = builder.build(model);
// build the table
final RdfTable.Builder tblBuilder = new RdfTable.Builder()
.setTableDef(tableDef)
.addQuerySegment(tableQuerySegment)
.setName(tName.getLocalName())
.setSchema(schema)
.setRemarks(
"created by "
+ SimpleNormalizingBuilder.BUILDER_NAME);
if (colNames.keySet().size() != tableDef.getColumnCount()) {
throw new IllegalArgumentException(String.format(
"There must be %s column names, %s provided",
tableDef.getColumnCount(), colNames.keySet().size()));
}
// set the columns
final Iterator<String> iter = colNames.keySet().iterator();
int i = 0;
while (iter.hasNext()) {
final String cName = iter.next();
tblBuilder
.setColumn(i, cName)
.getColumn(i)
.addQuerySegment(colNames.get(cName))
.setRemarks(
"created by "
+ SimpleNormalizingBuilder.BUILDER_NAME);
i++;
}
tableSet.add(tblBuilder.build(model));
}
}
@Override
protected int calculateSize(final RdfCatalog catalog, final String tableQS,
final String columnQS) {
final String queryStr = String.format(
"SELECT distinct ?col WHERE { %s %s }",
String.format(tableQS, "?tbl"),
String.format(columnQS, "?tbl", "?col"));
final List<QuerySolution> results = catalog.executeQuery(queryStr);
final Iterator<Integer> iter = WrappedIterator.create(
results.iterator()).mapWith(new Map1<QuerySolution, Integer>() {
@Override
public Integer map1(final QuerySolution o) {
final RDFNode node = o.get("col");
if (node == null) {
return 0;
}
if (node.isLiteral()) {
return TypeConverter.getJavaValue(node.asLiteral())
.toString().length();
}
return node.toString().length();
}
});
int retval = 0;
while (iter.hasNext()) {
final Integer i = iter.next();
if (retval < i) {
retval = i;
}
}
return retval;
}
@Override
public Set<RdfTable> getTables(final RdfSchema schema) {
final RdfCatalog catalog = schema.getCatalog();
final Model model = schema.getResource().getModel();
final RdfColumnDef.Builder colBuilder = new RdfColumnDef.Builder();
colBuilder.setType(Types.VARCHAR)
.setNullable(DatabaseMetaData.columnNoNulls).setReadOnly(true);
// FIXME does this need a scale?
idColumnDef = colBuilder.build(model);
final HashSet<RdfTable> retval = new HashSet<RdfTable>();
final List<QuerySolution> solns = catalog
.executeQuery(SimpleNormalizingBuilder.TABLE_QUERY);
for (final QuerySolution soln : solns) {
buildTable(retval, catalog, schema, soln.getResource("tName"));
}
return retval;
}
protected RdfTable makeSubTable(final RdfCatalog catalog,
final RdfSchema schema, final String tableQuerySegment,
final String columnQuerySegment, final Resource tName,
final Resource cName) {
final Model model = catalog.getResource().getModel();
final RdfTableDef.Builder tblDefBuilder = new RdfTableDef.Builder();
tblDefBuilder.addColumnDef(idColumnDef);
final RdfColumnDef.Builder builder = new RdfColumnDef.Builder();
final int scale = calculateSize(catalog, tableQuerySegment,
columnQuerySegment);
builder.setType(Types.VARCHAR)
.setNullable(DatabaseMetaData.columnNoNulls).setScale(scale)
.setReadOnly(true);
tblDefBuilder.addColumnDef(builder.build(model));
// add the key segments
RdfKeySegment.Builder keySegBuilder = new RdfKeySegment.Builder();
keySegBuilder.setAscending(true);
keySegBuilder.setIdx(0);
final RdfKey.Builder keyBldr = new RdfKey.Builder();
keyBldr.setUnique(true);
keyBldr.addSegment(keySegBuilder.build(model));
keySegBuilder = new RdfKeySegment.Builder();
keySegBuilder.setAscending(true);
keySegBuilder.setIdx(1);
keyBldr.addSegment(keySegBuilder.build(model));
tblDefBuilder.setPrimaryKey(keyBldr.build(model));
// FIXME add foreign keys when avail
final String tblName = String.format("%s%s", tName.getLocalName(),
cName.getLocalName());
final RdfTableDef tableDef = tblDefBuilder.build(model);
final RdfTable.Builder tblBuilder = new RdfTable.Builder()
.setTableDef(tableDef)
.addQuerySegment(tableQuerySegment)
.setName(tblName)
.setSchema(schema)
.setRemarks(
"created by " + SimpleNormalizingBuilder.BUILDER_NAME);
tblBuilder
.setColumn(0, "id")
.getColumn(0)
.addQuerySegment(SimpleNormalizingBuilder.ID_COLUMN_SEGMENT)
.setRemarks(
"created by " + SimpleNormalizingBuilder.BUILDER_NAME);
tblBuilder
.setColumn(1, cName.getLocalName())
.getColumn(1)
.addQuerySegment(columnQuerySegment)
.setRemarks(
"created by " + SimpleNormalizingBuilder.BUILDER_NAME);
return tblBuilder.build(model);
}
protected boolean multipleCardinality(final RdfCatalog catalog,
final String tableQS, final String columnQS) {
final String queryStr = String.format(
"SELECT (count(*) as ?count) WHERE { %s %s } GROUP BY ?tbl",
String.format(tableQS, "?tbl"),
String.format(columnQS, "?tbl", "?col"));
return WrappedIterator
.create(catalog.executeQuery(queryStr).iterator())
.filterKeep(new Filter<QuerySolution>() {
@Override
public boolean accept(final QuerySolution o) {
return o.get("count").asLiteral().getInt() > 1;
}
}).hasNext();
}
}
| |
package tray;
import java.awt.Image;
import java.awt.Menu;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import monitor.IBuildMonitor;
import monitor.MonitorInfo;
import monitor.MonitorInfo.BuildInfo;
import monitor.build.BuildMeta;
import monitor.build.IBuild.BuildStatus;
import core.Juggertray;
import tray.display.INotificationManager;
import tray.display.NotificationManager;
import util.IComponent;
import util.SystemTools;
import util.UiTools;
import util.logger.ILogger;
import util.notify.IChangeListener;
public class TrayManager implements ITrayManager, IChangeListener {
private enum IconType {
SAD, ANGRY, HAPPY
}
private ILogger logger;
private IComponent parent;
private IBuildMonitor monitor;
private INotificationManager notification;
private TrayIcon icon;
private boolean trigger;
public TrayManager(ILogger logger, IComponent parent, IBuildMonitor monitor) throws Exception {
this.logger = logger;
this.parent = parent;
this.monitor = monitor;
notification = new NotificationManager(logger, this);
icon = null;
trigger = false;
}
@Override
public void init() throws Exception {
if(SystemTray.isSupported()){
updateUI();
monitor.getChangeNotifier().addListener(this);
}else{
throw new Exception("System-Tray not supported");
}
}
@Override
public void shutdown() throws Exception {
monitor.getChangeNotifier().removeListener(this);
}
@Override
public void displayMessage(String message, MessageType type) {
if(icon != null){;
icon.displayMessage(Juggertray.APP_NAME, message, getIconMessageType(type));
}
}
private java.awt.TrayIcon.MessageType getIconMessageType(MessageType type) {
if(type == MessageType.INFO){
return java.awt.TrayIcon.MessageType.INFO;
}else if(type == MessageType.WARNING){
return java.awt.TrayIcon.MessageType.WARNING;
}else if(type == MessageType.ERROR){
return java.awt.TrayIcon.MessageType.ERROR;
}else{
return java.awt.TrayIcon.MessageType.NONE;
}
}
@Override
public void changed(Object object) {
if(object instanceof IBuildMonitor){
try{
updateUI();
}catch(Exception e){
logger.error(e);
displayMessage(e.getMessage(), MessageType.ERROR);
}
}
}
private void updateUI() throws Exception {
MonitorInfo data = monitor.getMonitorInfo();
setIcon(getIconType4BuildStatus(data.getStatus()));
setToolTip(data.getBuilds().size(), data.getBuilds(BuildStatus.OK).size());
setMenu(data.getBuilds());
notification.updateStatus(data, trigger);
trigger = false;
}
private void setIcon(IconType type) throws Exception {
if(icon != null){
icon.setImage(getIconImage(type));
}else{
createIcon(getIconImage(type));
}
}
private IconType getIconType4BuildStatus(BuildStatus status) {
if(status == BuildStatus.OK){
return IconType.HAPPY;
}else if(status == BuildStatus.ERROR){
return IconType.ANGRY;
}else{
return IconType.SAD;
}
}
private Image getIconImage(IconType type) throws Exception {
String path = "icon/"+type.toString().toLowerCase()+".gif";
URL url = getClass().getResource(path);
if(url != null){
return Toolkit.getDefaultToolkit().getImage(url);
}else{
throw new Exception("No ressource at: "+path);
}
}
private void createIcon(Image image) throws Exception {
icon = new TrayIcon(image);
icon.setImageAutoSize(true);
icon.addActionListener(new AbstractTrayAction(logger, this){
@Override
protected void action(ActionEvent event) throws Exception {
if(SystemTools.isWindowsOS() || SystemTools.isLinuxOS()){
triggerUpdate();
}
}
});
SystemTray tray = SystemTray.getSystemTray();
tray.add(icon);
}
private void setToolTip(int totalBuilds, int okBuilds) {
if(totalBuilds > 0){
icon.setToolTip(Juggertray.APP_NAME+" "+okBuilds+" / "+totalBuilds+" OK ("+(new Date()).toString().substring(11, 16)+")");
}else{
icon.setToolTip(Juggertray.APP_NAME+" (EMPTY)");
}
}
private void setMenu(ArrayList<BuildInfo> builds) {
PopupMenu popupMenu = new PopupMenu();
for(BuildInfo build : builds){
try{
BuildMeta meta = new BuildMeta(build.identifier);
String identifier = meta.name+"@"+meta.server;
MenuItem buildMenu = new MenuItem(identifier+" ("+build.status.toString()+")");
final String url = build.url;
buildMenu.addActionListener(new AbstractTrayAction(logger, this){
@Override
protected void action(ActionEvent event) throws Exception {
logger.info("open browser: "+url);
SystemTools.openBrowser(url);
}
});
popupMenu.add(buildMenu);
}catch(Exception e){
logger.error(e);
}
}
if(builds.size() > 0){
popupMenu.addSeparator();
}
Menu setupMenu = new Menu("Setup");
popupMenu.add(setupMenu);
MenuItem addMenuItem = new MenuItem("Add");
addMenuItem.addActionListener(new AbstractTrayAction(logger, this){
@Override
protected void action(ActionEvent event) throws Exception {
String identifier = UiTools.inputDialog("Add build (name@server)");
if(identifier != null && !identifier.isEmpty()){
monitor.addBuild(identifier);
monitor.updateMonitor();
}
}
});
setupMenu.add(addMenuItem);
if(builds.size() > 0){
MenuItem removeMenuItem = new MenuItem("Remove");
removeMenuItem.addActionListener(new AbstractTrayAction(logger, this){
@Override
protected void action(ActionEvent event) throws Exception {
String identifier = UiTools.optionDialog("Remove build", monitor.getMonitorInfo().getIdentifiers());
if(identifier != null && !identifier.isEmpty() && UiTools.confirmDialog("Remove build [ "+identifier+" ] ?")){
monitor.removeBuild(identifier);
monitor.updateMonitor();
}
}
});
setupMenu.add(removeMenuItem);
MenuItem editMenuItem = new MenuItem("Edit");
editMenuItem.addActionListener(new AbstractTrayAction(logger, this){
@Override
protected void action(ActionEvent event) throws Exception {
String identifier1 = UiTools.optionDialog("Edit build", monitor.getMonitorInfo().getIdentifiers());
if(identifier1 != null && !identifier1.isEmpty()){
String identifier2 = UiTools.inputDialog("Edit build (name@server)", identifier1);
if(identifier2 != null && !identifier2.isEmpty()){
monitor.removeBuild(identifier1);
monitor.addBuild(identifier2);
monitor.updateMonitor();
}
}
}
});
setupMenu.add(editMenuItem);
if(SystemTools.isMacOS()){
setupMenu.addSeparator();
MenuItem updateMenuItem = new MenuItem("Update");
updateMenuItem.addActionListener(new AbstractTrayAction(logger, this){
@Override
protected void action(ActionEvent event) throws Exception {
triggerUpdate();
}
});
setupMenu.add(updateMenuItem);
}
}
MenuItem quitMenuItem = new MenuItem("Quit");
quitMenuItem.addActionListener(new AbstractTrayAction(logger, this){
@Override
protected void action(ActionEvent event) throws Exception {
parent.shutdown();
}
});
popupMenu.add(quitMenuItem);
icon.setPopupMenu(popupMenu);
}
private void triggerUpdate() throws Exception {
trigger = true;
monitor.updateMonitor();
}
@Override
public boolean supportNewline() {
return SystemTools.isWindowsOS();
}
}
| |
/**
* Copyright (c) 2011 Perforce Software. All rights reserved.
*/
package com.perforce.p4java.tests.dev.unit.features112;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Paths;
import java.util.Properties;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.perforce.p4java.PropertyDefs;
import com.perforce.p4java.exception.P4JavaException;
import com.perforce.p4java.option.server.LoginOptions;
import com.perforce.p4java.server.AuthTicketsHelper;
import com.perforce.p4java.server.IOptionsServer;
import com.perforce.p4java.server.ServerFactory;
import com.perforce.p4java.server.callback.ICommandCallback;
import com.perforce.p4java.tests.dev.annotations.Jobs;
import com.perforce.p4java.tests.dev.annotations.TestId;
import com.perforce.p4java.tests.dev.unit.P4JavaTestCase;
/**
* Test 'p4 login -p'. The -p flag displays the ticket, but does not store it on
* the client machine.
*/
@Jobs({ "job047563" })
@TestId("Dev112_LoginTest")
public class LoginTest extends P4JavaTestCase {
IOptionsServer server = null;
String serverMessage = null;
static String defaultTicketFile = null;
private static Properties serverProps;
/**
* @BeforeClass annotation to a method to be run before all the tests in a
* class.
*/
@BeforeClass
public static void oneTimeSetUp() {
// one-time initialization code (before all the tests).
defaultTicketFile = Paths.get(System.getProperty("user.dir"),
File.separator, ".p4tickets").toString();
serverProps = new Properties();
serverProps.put(PropertyDefs.TICKET_PATH_KEY_SHORT_FORM, defaultTicketFile);
}
/**
* @AfterClass annotation to a method to be run after all the tests in a
* class.
*/
@AfterClass
public static void oneTimeTearDown() {
// one-time cleanup code (after all the tests).
}
/**
* @Before annotation to a method to be run before each test in a class.
*/
@Before
public void setUp() {
// initialization code (before each test).
}
/**
* @After annotation to a method to be run after each test in a class.
*/
@After
public void tearDown() {
// cleanup code (after each test).
if (server != null) {
this.endServerSession(server);
}
}
/**
* Test 'p4 login -p'. The -p flag displays the ticket, but does not store
* it on the client machine.
*/
@Test
public void testLoginShowAuthTicketOnly() {
String user = "p4jtestuser";
String password = "p4jtestuser";
try {
server = ServerFactory.getOptionsServer(this.serverUrlString, serverProps);
assertNotNull(server);
// Register callback
server.registerCallback(new ICommandCallback() {
public void receivedServerMessage(int key, int genericCode,
int severityCode, String message) {
serverMessage = message;
}
public void receivedServerInfoLine(int key, String infoLine) {
serverMessage = infoLine;
}
public void receivedServerErrorLine(int key, String errorLine) {
serverMessage = errorLine;
}
public void issuingServerCommand(int key, String command) {
serverMessage = command;
}
public void completedServerCommand(int key, long millisecsTaken) {
serverMessage = String.valueOf(millisecsTaken);
}
});
// Connect to the server.
server.connect();
if (server.isConnected()) {
if (server.supportsUnicode()) {
server.setCharsetName("utf8");
}
}
// Set the server user
server.setUserName(user);
// Login using the normal method (the auth ticket will be written to
// file)
server.login(password, new LoginOptions());
// Get the auth ticket after the login
String authTicket = AuthTicketsHelper.getTicketValue(server
.getUserName(), server.getServerInfo().getServerAddress(),
defaultTicketFile);
// We should have a ticket
assertNotNull(authTicket);
// Logout will remove the ticket from file
server.logout();
// Get the auth tickets after the logout
String authTicket2 = AuthTicketsHelper.getTicketValue(server
.getUserName(), server.getServerInfo().getServerAddress(),
defaultTicketFile);
// It should be null
assertNull(authTicket2);
// Login only display the ticket and not storing the ticket to file
StringBuffer authTicket3 = new StringBuffer();
server.login(password, authTicket3, new LoginOptions().setDontWriteTicket(true));
assertNotNull(authTicket3);
// The original ticket and this ticket should be the same
assertEquals(authTicket, authTicket3.toString());
// Get the auth tickets after the login
String authTicket4 = AuthTicketsHelper.getTicketValue(server
.getUserName(), server.getServerInfo().getServerAddress(),
defaultTicketFile);
// It should be null since we are using "login -p"
assertNull(authTicket4);
try {
// Login with the wrong password
server.login("wrong123456789", authTicket3,
new LoginOptions());
} catch (P4JavaException e) {
assertTrue(e.getLocalizedMessage()
.contains("Password invalid."));
}
// Restore the ticket
// Login using the normal method (the auth ticket will be written to
// file)
server.login(password, new LoginOptions());
// Get the auth tickets after the login
String authTicket5 = AuthTicketsHelper.getTicketValue(server
.getUserName(), server.getServerInfo().getServerAddress(),
defaultTicketFile);
assertNotNull(authTicket5);
// The original ticket and this ticket should be the same
assertEquals(authTicket, authTicket5);
} catch (P4JavaException e) {
fail("Unexpected exception: " + e.getLocalizedMessage());
} catch (URISyntaxException e) {
fail("Unexpected exception: " + e.getLocalizedMessage());
} catch (IOException e) {
fail("Unexpected exception: " + e.getLocalizedMessage());
}
}
}
| |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.fileChooser.ex;
import com.intellij.ide.IdeBundle;
import com.intellij.ide.PasteProvider;
import com.intellij.ide.SaveAndSyncHandler;
import com.intellij.ide.dnd.FileCopyPasteUtil;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.ide.util.treeView.NodeRenderer;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.application.ApplicationActivationListener;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.fileChooser.*;
import com.intellij.openapi.fileChooser.impl.FileChooserFactoryImpl;
import com.intellij.openapi.fileChooser.impl.FileChooserUtil;
import com.intellij.openapi.ide.CopyPasteManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.ComboBox;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Iconable;
import com.intellij.openapi.util.NlsContexts;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.*;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.openapi.wm.IdeFrame;
import com.intellij.ui.ScrollPaneFactory;
import com.intellij.ui.SideBorder;
import com.intellij.ui.SimpleListCellRenderer;
import com.intellij.ui.UIBundle;
import com.intellij.ui.components.labels.LinkLabel;
import com.intellij.ui.treeStructure.Tree;
import com.intellij.util.ArrayUtil;
import com.intellij.util.ArrayUtilRt;
import com.intellij.util.Consumer;
import com.intellij.util.IconUtil;
import com.intellij.util.io.URLUtil;
import com.intellij.util.ui.EmptyIcon;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;
import com.intellij.util.ui.update.MergingUpdateQueue;
import com.intellij.util.ui.update.UiNotifyConnector;
import com.intellij.util.ui.update.Update;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeExpansionListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.awt.datatransfer.Transferable;
import java.io.File;
import java.nio.file.Paths;
import java.util.List;
import java.util.*;
import java.util.function.Supplier;
public class FileChooserDialogImpl extends DialogWrapper implements FileChooserDialog, PathChooserDialog, FileLookup {
@NonNls public static final String FILE_CHOOSER_SHOW_PATH_PROPERTY = "FileChooser.ShowPath";
private static final String RECENT_FILES_KEY = "file.chooser.recent.files";
public static final @NotNull Supplier<@Nls String> DRAG_N_DROP_HINT = IdeBundle.messagePointer("tooltip.drag.drop.file");
private final FileChooserDescriptor myChooserDescriptor;
protected FileSystemTreeImpl myFileSystemTree;
private Project myProject;
private VirtualFile[] myChosenFiles = VirtualFile.EMPTY_ARRAY;
private JPanel myNorthPanel;
private TextFieldAction myTextFieldAction;
protected FileTextFieldImpl myPathTextField;
private ComboBox<String> myPath;
private MergingUpdateQueue myUiUpdater;
private boolean myTreeIsUpdating;
private static final DataKey<PathField> PATH_FIELD = DataKey.create("PathField");
public FileChooserDialogImpl(@NotNull final FileChooserDescriptor descriptor, @Nullable Project project) {
super(project, true);
myChooserDescriptor = descriptor;
myProject = project;
setTitle(getChooserTitle(descriptor));
}
public FileChooserDialogImpl(@NotNull final FileChooserDescriptor descriptor, @NotNull Component parent) {
this(descriptor, parent, null);
}
public FileChooserDialogImpl(@NotNull final FileChooserDescriptor descriptor, @NotNull Component parent, @Nullable Project project) {
super(parent, true);
myChooserDescriptor = descriptor;
myProject = project;
setTitle(getChooserTitle(descriptor));
}
private static @NlsContexts.DialogTitle String getChooserTitle(final FileChooserDescriptor descriptor) {
final String title = descriptor.getTitle();
return title != null ? title : UIBundle.message("file.chooser.default.title");
}
@Override
public VirtualFile @NotNull [] choose(@Nullable final Project project, final VirtualFile @NotNull ... toSelect) {
init();
if (myProject == null && project != null) {
myProject = project;
}
if (toSelect.length == 1) {
restoreSelection(toSelect[0]);
}
else if (toSelect.length == 0) {
restoreSelection(null); // select last opened file
}
else {
selectInTree(toSelect, true, true);
}
show();
return myChosenFiles;
}
@Override
public VirtualFile @NotNull [] choose(@Nullable final VirtualFile toSelect, @Nullable final Project project) {
if (toSelect == null) {
return choose(project);
}
return choose(project, toSelect);
}
@Override
public void choose(@Nullable VirtualFile toSelect, @NotNull Consumer<? super List<VirtualFile>> callback) {
init();
restoreSelection(toSelect);
show();
if (myChosenFiles.length > 0) {
callback.consume(Arrays.asList(myChosenFiles));
}
else if (callback instanceof FileChooser.FileChooserConsumer) {
((FileChooser.FileChooserConsumer)callback).cancelled();
}
}
protected void restoreSelection(@Nullable VirtualFile toSelect) {
final VirtualFile lastOpenedFile = FileChooserUtil.getLastOpenedFile(myProject);
final VirtualFile file = FileChooserUtil.getFileToSelect(myChooserDescriptor, myProject, toSelect, lastOpenedFile);
if (file != null && file.isValid()) {
myPathTextField.setText(VfsUtil.getReadableUrl(file), true, () ->
selectInTree(new VirtualFile[]{file}, false, false));
}
}
void storeSelection(@Nullable VirtualFile file) {
if (file != null) {
Pair<String, String> pair = file.getFileSystem().getProtocol() == StandardFileSystems.JAR_PROTOCOL ? URLUtil.splitJarUrl(file.getPath()) : null;
FileChooserUtil.setLastOpenedFile(myProject, pair == null ? file.toNioPath() : Paths.get(pair.getFirst()));
}
if (file != null && file.getFileSystem() instanceof LocalFileSystem) {
saveRecent(file.getPath());
}
}
private void saveRecent(String path) {
List<String> files = new ArrayList<>(Arrays.asList(getRecentFiles()));
files.remove(path);
files.add(0, path);
while (files.size() > 30) {
files.remove(files.size() - 1);
}
PropertiesComponent.getInstance().setValues(RECENT_FILES_KEY, ArrayUtilRt.toStringArray(files));
}
private String @NotNull [] getRecentFiles() {
String[] array = PropertiesComponent.getInstance().getValues(RECENT_FILES_KEY);
if (array == null) {
return ArrayUtil.EMPTY_STRING_ARRAY;
}
if (array.length > 0 && myPathTextField != null && myPathTextField.getField().getText().replace('\\', '/').equals(array[0])) {
return Arrays.copyOfRange(array, 1, array.length);
}
return array;
}
protected DefaultActionGroup createActionGroup() {
registerTreeActionShortcut("FileChooser.Delete");
registerTreeActionShortcut("FileChooser.Refresh");
return (DefaultActionGroup)ActionManager.getInstance().getAction("FileChooserToolbar");
}
private void registerTreeActionShortcut(@NonNls final String actionId) {
final JTree tree = myFileSystemTree.getTree();
final AnAction action = ActionManager.getInstance().getAction(actionId);
action.registerCustomShortcutSet(action.getShortcutSet(), tree, myDisposable);
}
@Override
@Nullable
protected final JComponent createTitlePane() {
final String description = myChooserDescriptor.getDescription();
if (StringUtil.isEmptyOrSpaces(description)) return null;
final JLabel label = new JLabel(description);
label.setBorder(BorderFactory.createCompoundBorder(
new SideBorder(UIUtil.getPanelBackground().darker(), SideBorder.BOTTOM),
JBUI.Borders.empty(0, 5, 10, 5)));
return label;
}
@Override
protected JComponent createCenterPanel() {
JPanel panel = new MyPanel();
myUiUpdater = new MergingUpdateQueue("FileChooserUpdater", 200, false, panel);
Disposer.register(myDisposable, myUiUpdater);
new UiNotifyConnector(panel, myUiUpdater);
panel.setBorder(JBUI.Borders.empty());
createTree();
final DefaultActionGroup group = createActionGroup();
ActionToolbar toolBar = ActionManager.getInstance().createActionToolbar("FileChooserDialog", group, true);
toolBar.setTargetComponent(panel);
final JPanel toolbarPanel = new JPanel(new BorderLayout());
toolbarPanel.add(toolBar.getComponent(), BorderLayout.CENTER);
myTextFieldAction = new TextFieldAction() {
@Override
public void linkSelected(final LinkLabel aSource, final Object aLinkData) {
toggleShowTextField();
}
};
toolbarPanel.add(myTextFieldAction, BorderLayout.EAST);
JPanel extraToolbarPanel = createExtraToolbarPanel();
if(extraToolbarPanel != null){
toolbarPanel.add(extraToolbarPanel, BorderLayout.SOUTH);
}
myPath = new ComboBox<>(getRecentFiles());
myPath.setEditable(true);
myPath.setRenderer(SimpleListCellRenderer.create((var label, @NlsContexts.Label var value, var index) -> {
label.setText(value);
VirtualFile file = LocalFileSystem.getInstance().findFileByIoFile(new File(value));
label.setIcon(file == null ? EmptyIcon.ICON_16 : IconUtil.getIcon(file, Iconable.ICON_FLAG_READ_STATUS, null));
}));
myPathTextField = new FileTextFieldImpl.Vfs(
(JTextField)myPath.getEditor().getEditorComponent(),
FileChooserFactoryImpl.getMacroMap(), getDisposable(),
new LocalFsFinder.FileChooserFilter(myChooserDescriptor, myFileSystemTree)) {
@Override
protected void onTextChanged(final String newValue) {
myUiUpdater.cancelAllUpdates();
updateTreeFromPath(newValue);
}
};
Disposer.register(myDisposable, myPathTextField);
myNorthPanel = new JPanel(new BorderLayout());
myNorthPanel.add(toolbarPanel, BorderLayout.NORTH);
updateTextFieldShowing();
panel.add(myNorthPanel, BorderLayout.NORTH);
registerMouseListener(group);
JScrollPane scrollPane = ScrollPaneFactory.createScrollPane(myFileSystemTree.getTree());
panel.add(scrollPane, BorderLayout.CENTER);
panel.setPreferredSize(JBUI.size(400));
JLabel dndLabel = new JLabel(DRAG_N_DROP_HINT.get(), SwingConstants.CENTER);
dndLabel.setFont(JBUI.Fonts.miniFont());
dndLabel.setForeground(UIUtil.getLabelDisabledForeground());
panel.add(dndLabel, BorderLayout.SOUTH);
ApplicationManager.getApplication().getMessageBus().connect(getDisposable())
.subscribe(ApplicationActivationListener.TOPIC, new ApplicationActivationListener() {
@Override
public void applicationActivated(@NotNull IdeFrame ideFrame) {
SaveAndSyncHandler.getInstance().maybeRefresh(ModalityState.current());
}
});
return panel;
}
@Nullable
protected JPanel createExtraToolbarPanel() {
return null;
}
@Override
public JComponent getPreferredFocusedComponent() {
if (isToShowTextField()) {
return myPathTextField != null ? myPathTextField.getField() : null;
}
else {
return myFileSystemTree != null ? myFileSystemTree.getTree() : null;
}
}
@Override
public final void dispose() {
LocalFileSystem.getInstance().removeWatchedRoots(myRequests.values());
super.dispose();
}
private boolean isTextFieldActive() {
return myPathTextField.getField().getRootPane() != null;
}
@Override
protected void doOKAction() {
if (!isOKActionEnabled()) {
return;
}
if (isTextFieldActive()) {
final String text = myPathTextField.getTextFieldText();
final LookupFile file = myPathTextField.getFile();
if (text == null || file == null || !file.exists()) {
setErrorText(IdeBundle.message("dialog.message.specified.path.cannot.be.found"), myPathTextField.getField());
return;
}
}
final List<VirtualFile> selectedFiles = Arrays.asList(getSelectedFilesInt());
final VirtualFile[] files = VfsUtilCore.toVirtualFileArray(FileChooserUtil.getChosenFiles(myChooserDescriptor, selectedFiles));
if (files.length == 0) {
myChosenFiles = VirtualFile.EMPTY_ARRAY;
close(CANCEL_EXIT_CODE);
return;
}
try {
myChooserDescriptor.validateSelectedFiles(files);
}
catch (Exception e) {
Messages.showErrorDialog(getContentPane(), e.getMessage(), getTitle());
return;
}
myChosenFiles = files;
storeSelection(files[files.length - 1]);
super.doOKAction();
}
@Override
public final void doCancelAction() {
myChosenFiles = VirtualFile.EMPTY_ARRAY;
super.doCancelAction();
}
protected JTree createTree() {
Tree internalTree = createInternalTree();
myFileSystemTree = new FileSystemTreeImpl(myProject, myChooserDescriptor, internalTree, null, null, null);
internalTree.setRootVisible(myChooserDescriptor.isTreeRootVisible());
internalTree.setShowsRootHandles(true);
Disposer.register(myDisposable, myFileSystemTree);
myFileSystemTree.addOkAction(this::doOKAction);
JTree tree = myFileSystemTree.getTree();
if (!Registry.is("file.chooser.async.tree.model")) tree.setCellRenderer(new NodeRenderer());
tree.getSelectionModel().addTreeSelectionListener(new FileTreeSelectionListener());
tree.addTreeExpansionListener(new FileTreeExpansionListener());
setOKActionEnabled(false);
myFileSystemTree.addListener(selection -> {
// myTreeIsUpdating makes no sense for AsyncTreeModel
if (myTreeIsUpdating && myFileSystemTree.getTreeBuilder() == null) myTreeIsUpdating = false;
updatePathFromTree(selection, false);
}, myDisposable);
new FileDrop(tree, new FileDrop.Target() {
@Override
public FileChooserDescriptor getDescriptor() {
return myChooserDescriptor;
}
@Override
public boolean isHiddenShown() {
return myFileSystemTree.areHiddensShown();
}
@Override
public void dropFiles(final List<? extends VirtualFile> files) {
if (!myChooserDescriptor.isChooseMultiple() && !files.isEmpty()) {
selectInTree(new VirtualFile[]{files.get(0)}, true, true);
}
else {
selectInTree(VfsUtilCore.toVirtualFileArray(files), true, true);
}
}
});
return tree;
}
@NotNull
protected Tree createInternalTree() {
return new Tree();
}
private void registerMouseListener(final ActionGroup group) {
myFileSystemTree.registerMouseListener(group);
}
private VirtualFile[] getSelectedFilesInt() {
if (myTreeIsUpdating || !myUiUpdater.isEmpty()) {
if (isTextFieldActive() && !StringUtil.isEmpty(myPathTextField.getTextFieldText())) {
LookupFile toFind = myPathTextField.getFile();
if (toFind instanceof LocalFsFinder.VfsFile && toFind.exists()) {
VirtualFile file = ((LocalFsFinder.VfsFile)toFind).getFile();
if (file != null) {
return new VirtualFile[]{file};
}
}
}
return VirtualFile.EMPTY_ARRAY;
}
return myFileSystemTree.getSelectedFiles();
}
private final Map<String, LocalFileSystem.WatchRequest> myRequests = new HashMap<>();
private static boolean isToShowTextField() {
return PropertiesComponent.getInstance().getBoolean(FILE_CHOOSER_SHOW_PATH_PROPERTY, true);
}
private static void setToShowTextField(boolean toShowTextField) {
PropertiesComponent.getInstance().setValue(FILE_CHOOSER_SHOW_PATH_PROPERTY, Boolean.toString(toShowTextField));
}
private final class FileTreeExpansionListener implements TreeExpansionListener {
@Override
public void treeExpanded(TreeExpansionEvent event) {
final Object[] path = event.getPath().getPath();
if (path.length == 2 && path[1] instanceof DefaultMutableTreeNode) {
// top node has been expanded => watch disk recursively
final DefaultMutableTreeNode node = (DefaultMutableTreeNode)path[1];
Object userObject = node.getUserObject();
if (userObject instanceof FileNodeDescriptor) {
final VirtualFile file = ((FileNodeDescriptor)userObject).getElement().getFile();
if (file != null && file.isDirectory()) {
final String rootPath = file.getPath();
if (myRequests.get(rootPath) == null) {
final LocalFileSystem.WatchRequest watchRequest = LocalFileSystem.getInstance().addRootToWatch(rootPath, true);
if (watchRequest != null) {
myRequests.put(rootPath, watchRequest);
}
}
}
}
}
}
@Override
public void treeCollapsed(TreeExpansionEvent event) {
}
}
private final class FileTreeSelectionListener implements TreeSelectionListener {
@Override
public void valueChanged(TreeSelectionEvent e) {
TreePath[] paths = e.getPaths();
boolean enabled = true;
for (TreePath treePath : paths) {
if (e.isAddedPath(treePath)) {
VirtualFile file = FileSystemTreeImpl.getVirtualFile(treePath);
if (file == null || !myChooserDescriptor.isFileSelectable(file)) enabled = false;
}
}
setOKActionEnabled(enabled);
}
}
protected final class MyPanel extends JPanel implements DataProvider {
final PasteProvider myPasteProvider = new PasteProvider() {
@Override
public void performPaste(@NotNull DataContext dataContext) {
if (myPathTextField != null) {
String path = calculatePath();
myPathTextField.setText(path, true, null);
updateTreeFromPath(path);
}
}
@Nullable
private String calculatePath() {
final Transferable contents = CopyPasteManager.getInstance().getContents();
if (contents != null) {
final List<File> fileList = FileCopyPasteUtil.getFileList(contents);
if (fileList != null) {
if (!fileList.isEmpty()) {
return fileList.get(0).getAbsolutePath();
}
}
}
return null;
}
@Override
public boolean isPastePossible(@NotNull DataContext dataContext) {
return isPasteEnabled(dataContext);
}
@Override
public boolean isPasteEnabled(@NotNull DataContext dataContext) {
return FileCopyPasteUtil.isFileListFlavorAvailable() && calculatePath() != null;
}
};
public MyPanel() {
super(new BorderLayout(0, 0));
}
@Override
public Object getData(@NotNull String dataId) {
if (PATH_FIELD.is(dataId)) {
return (PathField)FileChooserDialogImpl.this::toggleShowTextField;
}
if (FileSystemTree.DATA_KEY.is(dataId)) {
return myFileSystemTree;
}
if (PlatformDataKeys.PASTE_PROVIDER.is(dataId)) {
return myPasteProvider;
}
return myChooserDescriptor.getUserData(dataId);
}
}
public void toggleShowTextField() {
setToShowTextField(!isToShowTextField());
updateTextFieldShowing();
}
private void updateTextFieldShowing() {
myTextFieldAction.update();
myNorthPanel.remove(myPath);
if (isToShowTextField()) {
List<VirtualFile> selection = new ArrayList<>();
if (myFileSystemTree.getSelectedFile() != null) {
selection.add(myFileSystemTree.getSelectedFile());
}
updatePathFromTree(selection, true);
myNorthPanel.add(myPath, BorderLayout.CENTER);
}
else {
setErrorText(null);
}
IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown(() -> IdeFocusManager.getGlobalInstance().requestFocus(myPathTextField.getField(), true));
myNorthPanel.revalidate();
myNorthPanel.repaint();
}
private void updatePathFromTree(final List<? extends VirtualFile> selection, boolean now) {
if (!isToShowTextField() || myTreeIsUpdating) return;
String text = "";
if (!selection.isEmpty()) {
text = VfsUtil.getReadableUrl(selection.get(0));
}
else {
final List<VirtualFile> roots = myChooserDescriptor.getRoots();
if (!myFileSystemTree.getTree().isRootVisible() && roots.size() == 1) {
text = VfsUtil.getReadableUrl(roots.get(0));
}
}
if (myFileSystemTree.getTreeBuilder() == null) {
if (text.isEmpty()) return;
String old = myPathTextField.getTextFieldText();
if (old == null || old.equals(text)) return;
int index = old.length() - 1;
if (index == text.length() && File.separatorChar == old.charAt(index) && old.startsWith(text)) return;
}
myPathTextField.setText(text, now, () -> {
myPathTextField.getField().selectAll();
setErrorText(null);
});
}
private void updateTreeFromPath(final String text) {
if (!isToShowTextField()) return;
if (myPathTextField.isPathUpdating()) return;
if (text == null) return;
myUiUpdater.queue(new Update("treeFromPath.1") {
@Override
public void run() {
ApplicationManager.getApplication().executeOnPooledThread(() -> {
final LocalFsFinder.VfsFile toFind = (LocalFsFinder.VfsFile)myPathTextField.getFile();
if (toFind == null || !toFind.exists()) return;
myUiUpdater.queue(new Update("treeFromPath.2") {
@Override
public void run() {
selectInTree(toFind.getFile(), text);
}
});
});
}
});
}
private void selectInTree(final VirtualFile vFile, String fromText) {
if (vFile != null && vFile.isValid()) {
if (fromText == null || fromText.equalsIgnoreCase(myPathTextField.getTextFieldText())) {
selectInTree(new VirtualFile[]{vFile}, false, fromText == null);
}
}
else {
reportFileNotFound();
}
}
private void selectInTree(VirtualFile[] array, boolean requestFocus, boolean updatePathNeeded) {
myTreeIsUpdating = true;
final List<VirtualFile> fileList = Arrays.asList(array);
if (!Arrays.asList(myFileSystemTree.getSelectedFiles()).containsAll(fileList)) {
myFileSystemTree.select(array, () -> {
if (!myFileSystemTree.areHiddensShown() && !Arrays.asList(myFileSystemTree.getSelectedFiles()).containsAll(fileList)) {
// try to select files in hidden folders
myFileSystemTree.showHiddens(true);
selectInTree(array, requestFocus, updatePathNeeded);
return;
}
if (array.length == 1 && !Arrays.asList(myFileSystemTree.getSelectedFiles()).containsAll(fileList)) {
// try to select a parent of a missed file
VirtualFile parent = array[0].getParent();
if (parent != null && parent.isValid()) {
selectInTree(new VirtualFile[]{parent}, requestFocus, updatePathNeeded);
return;
}
}
reportFileNotFound();
if (updatePathNeeded) {
updatePathFromTree(fileList, true);
}
if (requestFocus) {
SwingUtilities.invokeLater(() -> myFileSystemTree.getTree().requestFocus());
}
});
}
else {
reportFileNotFound();
if (updatePathNeeded) {
updatePathFromTree(fileList, true);
}
}
}
private void reportFileNotFound() {
myTreeIsUpdating = false;
setErrorText(null);
}
@Override
protected String getDimensionServiceKey() {
return "FileChooserDialogImpl";
}
@Override
protected String getHelpId() {
return "select.path.dialog";
}
}
| |
/* Copyright 2016 Samsung Electronics Co., 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 org.gearvrf;
import android.content.pm.PackageManager;
import android.graphics.PixelFormat;
import android.opengl.EGL14;
import android.opengl.GLSurfaceView;
import android.opengl.GLSurfaceView.EGLConfigChooser;
import android.opengl.GLSurfaceView.EGLContextFactory;
import android.opengl.GLSurfaceView.EGLWindowSurfaceFactory;
import android.opengl.GLSurfaceView.Renderer;
import android.util.DisplayMetrics;
import android.view.Surface;
import android.view.SurfaceHolder;
import org.gearvrf.utility.Log;
import org.gearvrf.utility.VrAppSettings;
import java.lang.ref.WeakReference;
import java.util.concurrent.CountDownLatch;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLContext;
import javax.microedition.khronos.egl.EGLDisplay;
import javax.microedition.khronos.egl.EGLSurface;
import javax.microedition.khronos.opengles.GL10;
/**
* Keep Oculus-specifics here
*/
final class OvrVrapiActivityHandler implements OvrActivityHandler {
private final GVRApplication mApplication;
private long mPtr;
private GLSurfaceView mSurfaceView;
private EGLSurface mPixelBuffer;
// warning: writable static state; used to determine when vrapi can be safely uninitialized
private static WeakReference<OvrVrapiActivityHandler> sVrapiOwner = new WeakReference<>(null);
private OvrViewManager mViewManager;
private int mCurrentSurfaceWidth, mCurrentSurfaceHeight;
OvrVrapiActivityHandler(final GVRApplication application, final OvrActivityNative activityNative) throws VrapiNotAvailableException {
if (null == application) {
throw new IllegalArgumentException();
}
try {
application.getActivity().getPackageManager().getPackageInfo("com.oculus.systemdriver", PackageManager.GET_SIGNATURES);
} catch (final PackageManager.NameNotFoundException e) {
try {
application.getActivity().getPackageManager().getPackageInfo("com.oculus.systemactivities", PackageManager.GET_SIGNATURES);
} catch (PackageManager.NameNotFoundException e1) {
Log.e(TAG, "oculus packages missing, assuming vrapi will not work");
throw new VrapiNotAvailableException();
}
}
mApplication = application;
mPtr = activityNative.getNative();
if (null != sVrapiOwner.get()) {
nativeUninitializeVrApi();
}
if (VRAPI_INITIALIZE_UNKNOWN_ERROR == nativeInitializeVrApi(mPtr)) {
throw new VrapiNotAvailableException();
}
sVrapiOwner = new WeakReference<>(this);
}
@Override
public void onPause() {
if (null != mSurfaceView) {
final CountDownLatch cdl = new CountDownLatch(1);
mSurfaceView.onPause();
mSurfaceView.queueEvent(new Runnable() {
@Override
public void run() {
//these two must happen on the gl thread
nativeLeaveVrMode(mPtr);
destroySurfaceForTimeWarp();
cdl.countDown();
}
});
try {
cdl.await();
} catch (final InterruptedException e) {
}
}
mCurrentSurfaceWidth = mCurrentSurfaceHeight = 0;
}
@Override
public void onResume() {
final OvrVrapiActivityHandler currentOwner = sVrapiOwner.get();
if (this != currentOwner) {
nativeUninitializeVrApi();
nativeInitializeVrApi(mPtr);
sVrapiOwner = new WeakReference<>(this);
}
if (null != mSurfaceView) {
mSurfaceView.onResume();
}
}
@Override
public boolean onBack() {
if (null != mSurfaceView) {
mSurfaceView.queueEvent(new Runnable() {
@Override
public void run() {
nativeShowConfirmQuit(mPtr);
}
});
}
return true;
}
@Override
public void onDestroy() {
if (this == sVrapiOwner.get()) {
nativeUninitializeVrApi();
sVrapiOwner.clear();
}
}
@Override
public void setViewManager(GVRViewManager viewManager) {
mViewManager = (OvrViewManager)viewManager;
}
@Override
public void onSetScript() {
mSurfaceView = new GLSurfaceView(mApplication.getActivity());
mSurfaceView.setZOrderOnTop(true);
final DisplayMetrics metrics = new DisplayMetrics();
mApplication.getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
final VrAppSettings appSettings = mApplication.getAppSettings();
int defaultWidthPixels = Math.max(metrics.widthPixels, metrics.heightPixels);
int defaultHeightPixels = Math.min(metrics.widthPixels, metrics.heightPixels);
final int frameBufferWidth = appSettings.getFramebufferPixelsWide();
final int frameBufferHeight = appSettings.getFramebufferPixelsHigh();
final SurfaceHolder holder = mSurfaceView.getHolder();
holder.setFormat(PixelFormat.TRANSLUCENT);
if ((-1 != frameBufferHeight) && (-1 != frameBufferWidth)) {
if ((defaultWidthPixels != frameBufferWidth) && (defaultHeightPixels != frameBufferHeight)) {
Log.v(TAG, "--- window configuration ---");
Log.v(TAG, "--- width: %d", frameBufferWidth);
Log.v(TAG, "--- height: %d", frameBufferHeight);
//a different resolution of the native window requested
defaultWidthPixels = frameBufferWidth;
defaultHeightPixels = frameBufferHeight;
Log.v(TAG, "----------------------------");
}
}
holder.setFixedSize(defaultWidthPixels, defaultHeightPixels);
mSurfaceView.setPreserveEGLContextOnPause(true);
mSurfaceView.setEGLContextClientVersion(3);
mSurfaceView.setEGLContextFactory(mContextFactory);
mSurfaceView.setEGLConfigChooser(mConfigChooser);
mSurfaceView.setEGLWindowSurfaceFactory(mWindowSurfaceFactory);
mSurfaceView.setRenderer(mRenderer);
mSurfaceView.setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY);
mApplication.getActivity().setContentView(mSurfaceView);
}
private final EGLContextFactory mContextFactory = new EGLContextFactory() {
@Override
public void destroyContext(final EGL10 egl, final EGLDisplay display, final EGLContext context) {
Log.v(TAG, "EGLContextFactory.destroyContext 0x%X", context.hashCode());
egl.eglDestroyContext(display, context);
}
@Override
public EGLContext createContext(final EGL10 egl, final EGLDisplay display, final EGLConfig eglConfig) {
final int EGL_CONTEXT_CLIENT_VERSION = 0x3098;
final int[] contextAttribs = {
EGL_CONTEXT_CLIENT_VERSION, 3,
EGL10.EGL_NONE
};
final EGLContext context = egl.eglCreateContext(display, eglConfig, EGL10.EGL_NO_CONTEXT, contextAttribs);
if (context == EGL10.EGL_NO_CONTEXT) {
throw new IllegalStateException("eglCreateContext failed; egl error 0x"
+ Integer.toHexString(egl.eglGetError()));
}
Log.v(TAG, "EGLContextFactory.createContext 0x%X", context.hashCode());
return context;
}
};
private final EGLWindowSurfaceFactory mWindowSurfaceFactory = new EGLWindowSurfaceFactory() {
@Override
public void destroySurface(final EGL10 egl, final EGLDisplay display, final EGLSurface surface) {
Log.v(TAG, "EGLWindowSurfaceFactory.destroySurface 0x%X, mPixelBuffer 0x%X", surface.hashCode(), mPixelBuffer.hashCode());
boolean result = egl.eglDestroySurface(display, mPixelBuffer);
Log.v(TAG, "EGLWindowSurfaceFactory.destroySurface successful %b, egl error 0x%x", result, egl.eglGetError());
mPixelBuffer = null;
}
@Override
public EGLSurface createWindowSurface(final EGL10 egl, final EGLDisplay display, final EGLConfig config,
final Object ignoredNativeWindow) {
final int[] surfaceAttribs = {
EGL10.EGL_WIDTH, 16,
EGL10.EGL_HEIGHT, 16,
EGL10.EGL_NONE
};
mPixelBuffer = egl.eglCreatePbufferSurface(display, config, surfaceAttribs);
if (EGL10.EGL_NO_SURFACE == mPixelBuffer) {
throw new IllegalStateException("Pixel buffer surface not created; egl error 0x"
+ Integer.toHexString(egl.eglGetError()));
}
Log.v(TAG, "EGLWindowSurfaceFactory.eglCreatePbufferSurface 0x%X", mPixelBuffer.hashCode());
return mPixelBuffer;
}
};
private final EGLConfigChooser mConfigChooser = new EGLConfigChooser() {
@Override
public EGLConfig chooseConfig(final EGL10 egl, final EGLDisplay display) {
final int[] numberConfigs = new int[1];
if (!egl.eglGetConfigs(display, null, 0, numberConfigs)) {
throw new IllegalStateException("Unable to retrieve number of egl configs available.");
}
final EGLConfig[] configs = new EGLConfig[numberConfigs[0]];
if (!egl.eglGetConfigs(display, configs, configs.length, numberConfigs)) {
throw new IllegalStateException("Unable to retrieve egl configs available.");
}
final int[] configAttribs = new int[16];
int counter = 0;
configAttribs[counter++] = EGL10.EGL_ALPHA_SIZE;
configAttribs[counter++] = 8;
configAttribs[counter++] = EGL10.EGL_BLUE_SIZE;
configAttribs[counter++] = 8;
configAttribs[counter++] = EGL10.EGL_GREEN_SIZE;
configAttribs[counter++] = 8;
configAttribs[counter++] = EGL10.EGL_RED_SIZE;
configAttribs[counter++] = 8;
configAttribs[counter++] = EGL10.EGL_DEPTH_SIZE;
configAttribs[counter++] = 0;
configAttribs[counter++] = EGL10.EGL_SAMPLES;
configAttribs[counter++] = 0;
Log.v(TAG, "--- window surface configuration ---");
final VrAppSettings appSettings = mApplication.getAppSettings();
if (appSettings.useSrgbFramebuffer) {
final int EGL_GL_COLORSPACE_KHR = 0x309D;
final int EGL_GL_COLORSPACE_SRGB_KHR = 0x3089;
configAttribs[counter++] = EGL_GL_COLORSPACE_KHR;
configAttribs[counter++] = EGL_GL_COLORSPACE_SRGB_KHR;
}
Log.v(TAG, "--- srgb framebuffer: %b", appSettings.useSrgbFramebuffer);
if (appSettings.useProtectedFramebuffer) {
final int EGL_PROTECTED_CONTENT_EXT = 0x32c0;
configAttribs[counter++] = EGL_PROTECTED_CONTENT_EXT;
configAttribs[counter++] = EGL14.EGL_TRUE;
}
Log.v(TAG, "--- protected framebuffer: %b", appSettings.useProtectedFramebuffer);
configAttribs[counter++] = EGL10.EGL_NONE;
Log.v(TAG, "------------------------------------");
EGLConfig config = null;
for (int i = 0; i < numberConfigs[0]; ++i) {
final int[] value = new int[1];
final int EGL_OPENGL_ES3_BIT_KHR = 0x0040;
if (!egl.eglGetConfigAttrib(display, configs[i], EGL10.EGL_RENDERABLE_TYPE,
value)) {
Log.v(TAG, "eglGetConfigAttrib for EGL_RENDERABLE_TYPE failed");
continue;
}
if ((value[0] & EGL_OPENGL_ES3_BIT_KHR) != EGL_OPENGL_ES3_BIT_KHR) {
continue;
}
if (!egl.eglGetConfigAttrib(display, configs[i], EGL10.EGL_SURFACE_TYPE, value)) {
Log.v(TAG, "eglGetConfigAttrib for EGL_SURFACE_TYPE failed");
continue;
}
if ((value[0]
& (EGL10.EGL_WINDOW_BIT | EGL10.EGL_PBUFFER_BIT)) != (EGL10.EGL_WINDOW_BIT
| EGL10.EGL_PBUFFER_BIT)) {
continue;
}
int j = 0;
for (; configAttribs[j] != EGL10.EGL_NONE; j += 2) {
if (!egl.eglGetConfigAttrib(display, configs[i], configAttribs[j], value)) {
Log.v(TAG, "eglGetConfigAttrib for " + configAttribs[j] + " failed");
continue;
}
if (value[0] != configAttribs[j + 1]) {
break;
}
}
if (configAttribs[j] == EGL10.EGL_NONE) {
config = configs[i];
break;
}
}
return config;
}
};
private void destroySurfaceForTimeWarp() {
final EGL10 egl = (EGL10) EGLContext.getEGL();
final EGLDisplay display = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
final EGLContext context = egl.eglGetCurrentContext();
if (!egl.eglMakeCurrent(display, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, context)) {
Log.v(TAG, "destroySurfaceForTimeWarp makeCurrent NO_SURFACE failed, egl error 0x%x", egl.eglGetError());
}
}
private final Renderer mRenderer = new Renderer() {
@Override
public void onSurfaceCreated(final GL10 gl, final EGLConfig config) {
Log.i(TAG, "onSurfaceCreated");
nativeOnSurfaceCreated(mPtr);
mViewManager.onSurfaceCreated();
}
@Override
public void onSurfaceChanged(final GL10 gl, final int width, final int height) {
Log.i(TAG, "onSurfaceChanged; %d x %d", width, height);
if (width < height) {
Log.v(TAG, "short-circuiting onSurfaceChanged; surface in portrait");
return;
}
if (mCurrentSurfaceWidth == width && mCurrentSurfaceHeight == height) {
return;
}
mCurrentSurfaceWidth = width; mCurrentSurfaceHeight = height;
nativeLeaveVrMode(mPtr);
destroySurfaceForTimeWarp();
final EGL10 egl = (EGL10) EGLContext.getEGL();
final EGLDisplay display = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
final EGLContext context = egl.eglGetCurrentContext();
// necessary to explicitly make the pbuffer current for the rendering thread;
// TimeWarp took over the window surface
if (!egl.eglMakeCurrent(display, mPixelBuffer, mPixelBuffer, context)) {
throw new IllegalStateException("Failed to make context current ; egl error 0x"
+ Integer.toHexString(egl.eglGetError()));
}
nativeOnSurfaceChanged(mPtr, mSurfaceView.getHolder().getSurface());
mViewManager.onSurfaceChanged(width, height);
mViewManager.createSwapChain();
}
@Override
public void onDrawFrame(final GL10 gl) {
mViewManager.onDrawFrame();
}
};
@SuppressWarnings("serial")
static final class VrapiNotAvailableException extends RuntimeException {
}
private static native void nativeOnSurfaceCreated(long ptr);
private static native void nativeOnSurfaceChanged(long ptr, Surface surface);
private static native void nativeLeaveVrMode(long ptr);
private static native void nativeShowConfirmQuit(long appPtr);
private static native int nativeInitializeVrApi(long ptr);
static native int nativeUninitializeVrApi();
private static final int VRAPI_INITIALIZE_UNKNOWN_ERROR = -1;
private static final String TAG = "OvrVrapiActivityHandler";
}
| |
package com.jivesoftware.os.lab.io;
import com.jivesoftware.os.lab.io.api.IPointerReadable;
import com.jivesoftware.os.lab.io.api.UIO;
import com.jivesoftware.os.mlogger.core.MetricLogger;
import com.jivesoftware.os.mlogger.core.MetricLoggerFactory;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.util.Arrays;
/**
*
*/
public class PointerReadableByteBufferFile implements IPointerReadable {
public static final MetricLogger LOG = MetricLoggerFactory.getLogger();
public static final long MAX_BUFFER_SEGMENT_SIZE = UIO.chunkLength(30);
public static final long MAX_POSITION = MAX_BUFFER_SEGMENT_SIZE * 100;
private final long maxBufferSegmentSize;
private final File file;
private final boolean writeable;
private final long length;
private final ByteBuffer[] bbs;
private final int fShift;
private final long fseekMask;
public PointerReadableByteBufferFile(long maxBufferSegmentSize,
File file, boolean writeable) throws IOException {
this.maxBufferSegmentSize = Math.min(UIO.chunkLength(UIO.chunkPower(maxBufferSegmentSize, 0)), MAX_BUFFER_SEGMENT_SIZE);
this.file = file;
this.writeable = writeable;
// test power of 2
if ((this.maxBufferSegmentSize & (this.maxBufferSegmentSize - 1)) == 0) {
this.fShift = Long.numberOfTrailingZeros(this.maxBufferSegmentSize);
this.fseekMask = this.maxBufferSegmentSize - 1;
} else {
throw new IllegalArgumentException("It's hard to ensure powers of 2");
}
this.length = file.length();
long position = this.length;
int filerIndex = (int) (position >> fShift);
long filerSeek = position & fseekMask;
int newLength = filerIndex + 1;
ByteBuffer[] newFilers = new ByteBuffer[newLength];
for (int n = 0; n < newLength; n++) {
if (n < newLength - 1) {
newFilers[n] = allocate(n, maxBufferSegmentSize);
} else {
newFilers[n] = allocate(n, filerSeek);
}
}
bbs = newFilers;
}
@Override
public long length() {
return length;
}
private ByteBuffer allocate(int index, long length) throws IOException {
long segmentOffset = maxBufferSegmentSize * index;
long requiredLength = segmentOffset + length;
try (RandomAccessFile raf = new RandomAccessFile(file, writeable ? "rw" : "r")) {
if (requiredLength > raf.length()) {
raf.seek(requiredLength - 1);
raf.write(0);
}
raf.seek(segmentOffset);
try (FileChannel channel = raf.getChannel()) {
return channel.map(writeable ? FileChannel.MapMode.READ_WRITE : MapMode.READ_ONLY,
segmentOffset, Math.min(maxBufferSegmentSize, channel.size() - segmentOffset));
}
}
}
private int read(int bbIndex, int bbSeek) throws IOException {
if (!hasRemaining(bbIndex, bbSeek, 1)) {
return -1;
}
byte b = bbs[bbIndex].get(bbSeek);
return b & 0xFF;
}
@Override
public int read(long position) throws IOException {
int bbIndex = (int) (position >> fShift);
int bbSeek = (int) (position & fseekMask);
int read = read(bbIndex, bbSeek);
while (read == -1 && bbIndex < bbs.length - 1) {
bbIndex++;
read = read(bbIndex, 0);
}
return read;
}
private int readAtleastOne(long position) throws IOException {
int bbIndex = (int) (position >> fShift);
int bbSeek = (int) (position & fseekMask);
int r = read(bbIndex, bbSeek);
if (r == -1) {
throw new EOFException("Failed to fully read 1 byte");
}
return r;
}
private boolean hasRemaining(int bbIndex, int bbSeek, int length) {
return bbs[bbIndex].limit() - bbSeek >= length;
}
@Override
public int readInt(long position) throws IOException {
int bbIndex = (int) (position >> fShift);
int bbSeek = (int) (position & fseekMask);
if (hasRemaining(bbIndex, bbSeek, 4)) {
return bbs[bbIndex].getInt(bbSeek);
} else {
int b0 = readAtleastOne(position);
int b1 = readAtleastOne(position + 1);
int b2 = readAtleastOne(position + 2);
int b3 = readAtleastOne(position + 3);
int v = 0;
v |= (b0 & 0xFF);
v <<= 8;
v |= (b1 & 0xFF);
v <<= 8;
v |= (b2 & 0xFF);
v <<= 8;
v |= (b3 & 0xFF);
return v;
}
}
@Override
public long readLong(long position) throws IOException {
int bbIndex = (int) (position >> fShift);
int bbSeek = (int) (position & fseekMask);
if (hasRemaining(bbIndex, bbSeek, 8)) {
return bbs[bbIndex].getLong(bbSeek);
} else {
int b0 = readAtleastOne(position);
int b1 = readAtleastOne(position + 1);
int b2 = readAtleastOne(position + 2);
int b3 = readAtleastOne(position + 3);
int b4 = readAtleastOne(position + 4);
int b5 = readAtleastOne(position + 5);
int b6 = readAtleastOne(position + 6);
int b7 = readAtleastOne(position + 7);
long v = 0;
v |= (b0 & 0xFF);
v <<= 8;
v |= (b1 & 0xFF);
v <<= 8;
v |= (b2 & 0xFF);
v <<= 8;
v |= (b3 & 0xFF);
v <<= 8;
v |= (b4 & 0xFF);
v <<= 8;
v |= (b5 & 0xFF);
v <<= 8;
v |= (b6 & 0xFF);
v <<= 8;
v |= (b7 & 0xFF);
return v;
}
}
private int read(int bbIndex, int bbSeek, byte[] b, int _offset, int _len) throws IOException {
ByteBuffer bb = bbs[bbIndex];
int remaining = bb.limit() - bbSeek;
if (remaining <= 0) {
return -1;
}
int count = Math.min(_len, remaining);
for (int i = 0; i < count; i++) {
b[_offset + i] = bb.get(bbSeek + i);
}
return count;
}
@Override
public int read(long position, byte[] b, int offset, int len) throws IOException {
if (len == 0) {
return 0;
}
int bbIndex = (int) (position >> fShift);
int bbSeek = (int) (position & fseekMask);
int remaining = len;
int read = read(bbIndex, bbSeek, b, offset, remaining);
if (read == -1) {
read = 0;
}
offset += read;
remaining -= read;
while (remaining > 0 && bbIndex < bbs.length - 1) {
bbIndex++;
bbSeek = 0;
read = read(bbIndex, bbSeek, b, offset, remaining);
if (read == -1) {
read = 0;
}
offset += read;
remaining -= read;
}
if (len == remaining) {
return -1;
}
return offset;
}
@Override
public BolBuffer sliceIntoBuffer(long offset, int length, BolBuffer entryBuffer) throws IOException {
int bbIndex = (int) (offset >> fShift);
if (bbIndex == (int) (offset + length >> fShift)) {
int filerSeek = (int) (offset & fseekMask);
entryBuffer.force(bbs[bbIndex], filerSeek, length);
} else {
byte[] rawEntry = new byte[length]; // very rare only on bb boundaries
read(offset, rawEntry, 0, length);
entryBuffer.force(rawEntry, 0, length);
}
return entryBuffer;
}
@Override
public void close() throws IOException {
if (bbs.length > 0) {
ByteBuffer bb = bbs[0];
if (bb != null) {
DirectBufferCleaner.clean(bb);
}
}
}
public void write(long position, byte b) throws IOException {
int bbIndex = (int) (position >> fShift);
int bbSeek = (int) (position & fseekMask);
bbs[bbIndex].put(bbSeek, b);
}
public void writeShort(long position, short v) throws IOException {
int bbIndex = (int) (position >> fShift);
int bbSeek = (int) (position & fseekMask);
if (hasRemaining(bbIndex, bbSeek, 2)) {
bbs[bbIndex].putShort(bbSeek, v);
} else {
write(position, (byte) (v >>> 8));
write(position + 1, (byte) (v));
}
}
public void writeInt(long position, int v) throws IOException {
int bbIndex = (int) (position >> fShift);
int bbSeek = (int) (position & fseekMask);
if (hasRemaining(bbIndex, bbSeek, 4)) {
bbs[bbIndex].putInt(bbSeek, v);
} else {
write(position, (byte) (v >>> 24));
write(position + 1, (byte) (v >>> 16));
write(position + 2, (byte) (v >>> 8));
write(position + 3, (byte) (v));
}
}
public void writeLong(long position, long v) throws IOException {
int bbIndex = (int) (position >> fShift);
int bbSeek = (int) (position & fseekMask);
if (hasRemaining(bbIndex, bbSeek, 8)) {
bbs[bbIndex].putLong(bbSeek, v);
} else {
write(position, (byte) (v >>> 56));
write(position + 1, (byte) (v >>> 48));
write(position + 2, (byte) (v >>> 40));
write(position + 3, (byte) (v >>> 32));
write(position + 4, (byte) (v >>> 24));
write(position + 5, (byte) (v >>> 16));
write(position + 6, (byte) (v >>> 8));
write(position + 7, (byte) (v));
}
}
public long readVPLong(long fp, byte precision) throws IOException {
int bbIndex = (int) (fp >> fShift);
int bbSeek = (int) (fp & fseekMask);
if (hasRemaining(bbIndex, bbSeek, precision)) {
ByteBuffer bb = bbs[bbIndex];
byte b = bb.get(bbSeek);
boolean wasNegated = (b & 0x80) != 0;
b &= ~0x80;
long v = 0;
v |= (b & 0xFF);
for (int i = 1; i < precision; i++) {
v <<= 8;
v |= (bb.get(bbSeek + i) & 0xFF);
}
if (wasNegated) {
v = -v;
}
return v;
} else {
byte b = (byte) read(fp);
boolean wasNegated = (b & 0x80) != 0;
b &= ~0x80;
long v = 0;
v |= (b & 0xFF);
for (int i = 1; i < precision; i++) {
v <<= 8;
v |= (read(fp + i) & 0xFF);
}
if (wasNegated) {
v = -v;
}
return v;
}
}
public void writeVPLong(long fp, long value, byte precision) throws IOException {
int bbIndex = (int) (fp >> fShift);
int bbSeek = (int) (fp & fseekMask);
boolean needsNegation = false;
long flipped = value;
if (flipped < 0) {
needsNegation = true;
flipped = -flipped;
}
if (hasRemaining(bbIndex, bbSeek, precision)) {
ByteBuffer bb = bbs[bbIndex];
for (int i = 0, j = 0; i < precision; i++, j += 8) {
byte b = (byte) (flipped >>> j);
int offset = precision - i - 1;
if (offset == 0 && needsNegation) {
bb.put(bbSeek, (byte) (b | (0x80)));
} else {
bb.put(bbSeek + offset, b);
}
}
} else {
for (int i = 0, j = 0; i < precision; i++, j += 8) {
byte b = (byte) (flipped >>> j);
int offset = precision - i - 1;
if (i == offset && needsNegation) {
write(fp, (byte) (b | (0x80)));
} else {
write(fp + precision - i - 1, b);
}
}
}
}
public static void main(String[] args) {
long[] values = { -Long.MAX_VALUE, -Long.MAX_VALUE / 2, -65_536, -65_535, -65_534, -128, -127, -1, 0, 1, 127, 128, 65_534, 65_535, 65_536,
Long.MAX_VALUE / 2, Long.MAX_VALUE };
for (long value : values) {
int chunkPower = UIO.chunkPower(value + 1, 1);
int precision = Math.min(chunkPower / 8 + 1, 8);
boolean needsNegation = false;
long flipped = value;
if (flipped < 0) {
needsNegation = true;
flipped = -flipped;
}
byte[] bytes = new byte[precision];
for (int i = 0, j = 0; i < precision; i++, j += 8) {
bytes[precision - i - 1] = (byte) (flipped >>> j);
}
if (needsNegation) {
bytes[0] |= (0x80);
}
System.out.println(Arrays.toString(bytes));
boolean wasNegated = (bytes[0] & 0x80) != 0;
bytes[0] &= ~0x80;
long output = 0;
for (int i = 0; i < precision; i++) {
output <<= 8;
output |= (bytes[i] & 0xFF);
}
if (wasNegated) {
output = -output;
}
System.out.println(value + " (" + precision + ") -> " + output + " = " + (value == output));
}
}
}
| |
/*
* 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.activemq.artemis.core.server.impl;
import org.apache.activemq.artemis.api.core.BaseInterceptor;
import org.apache.activemq.artemis.api.core.Pair;
import org.apache.activemq.artemis.core.config.ConnectorServiceConfiguration;
import org.apache.activemq.artemis.core.server.ActiveMQMessageBundle;
import org.apache.activemq.artemis.core.server.ConnectorServiceFactory;
import org.apache.activemq.artemis.core.server.ServiceRegistry;
import org.apache.activemq.artemis.core.server.cluster.Transformer;
import org.apache.activemq.artemis.spi.core.remoting.AcceptorFactory;
import org.apache.activemq.artemis.utils.ClassloadingUtil;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
public class ServiceRegistryImpl implements ServiceRegistry {
private ExecutorService executorService;
private ScheduledExecutorService scheduledExecutorService;
/* We are using a List rather than HashMap here as ActiveMQ Artemis allows multiple instances of the same class to be added
* to the interceptor list
*/
private List<BaseInterceptor> incomingInterceptors;
private List<BaseInterceptor> outgoingInterceptors;
private Map<String, Transformer> divertTransformers;
private Map<String, Transformer> bridgeTransformers;
private Map<String, AcceptorFactory> acceptorFactories;
private Map<String, Pair<ConnectorServiceFactory, ConnectorServiceConfiguration>> connectorServices;
public ServiceRegistryImpl() {
this.incomingInterceptors = Collections.synchronizedList(new ArrayList<BaseInterceptor>());
this.outgoingInterceptors = Collections.synchronizedList(new ArrayList<BaseInterceptor>());
this.connectorServices = new ConcurrentHashMap<>();
this.divertTransformers = new ConcurrentHashMap<>();
this.bridgeTransformers = new ConcurrentHashMap<>();
this.acceptorFactories = new ConcurrentHashMap<>();
}
@Override
public ExecutorService getExecutorService() {
return executorService;
}
@Override
public void setExecutorService(ExecutorService executorService) {
this.executorService = executorService;
}
@Override
public ScheduledExecutorService getScheduledExecutorService() {
return scheduledExecutorService;
}
@Override
public void setScheduledExecutorService(ScheduledExecutorService scheduledExecutorService) {
this.scheduledExecutorService = scheduledExecutorService;
}
@Override
public void addConnectorService(ConnectorServiceFactory connectorServiceFactory,
ConnectorServiceConfiguration configuration) {
connectorServices.put(configuration.getConnectorName(), new Pair<>(connectorServiceFactory, configuration));
}
@Override
public void removeConnectorService(ConnectorServiceConfiguration configuration) {
connectorServices.remove(configuration.getConnectorName());
}
@Override
public Collection<Pair<ConnectorServiceFactory, ConnectorServiceConfiguration>> getConnectorServices(List<ConnectorServiceConfiguration> configs) {
if (configs != null) {
for (final ConnectorServiceConfiguration config : configs) {
if (connectorServices.get(config.getConnectorName()) == null) {
ConnectorServiceFactory factory = AccessController.doPrivileged(new PrivilegedAction<ConnectorServiceFactory>() {
public ConnectorServiceFactory run() {
return (ConnectorServiceFactory) ClassloadingUtil.newInstanceFromClassLoader(config.getFactoryClassName());
}
});
addConnectorService(factory, config);
}
}
}
return connectorServices.values();
}
@Override
public void addIncomingInterceptor(BaseInterceptor interceptor) {
incomingInterceptors.add(interceptor);
}
@Override
public List<BaseInterceptor> getIncomingInterceptors(List<String> classNames) {
List<BaseInterceptor> interceptors = new ArrayList<>(incomingInterceptors);
instantiateInterceptors(classNames, interceptors);
return interceptors;
}
@Override
public void addOutgoingInterceptor(BaseInterceptor interceptor) {
outgoingInterceptors.add(interceptor);
}
@Override
public List<BaseInterceptor> getOutgoingInterceptors(List<String> classNames) {
List<BaseInterceptor> interceptors = new ArrayList<>(outgoingInterceptors);
instantiateInterceptors(classNames, interceptors);
return interceptors;
}
@Override
public void addDivertTransformer(String name, Transformer transformer) {
divertTransformers.put(name, transformer);
}
@Override
public Transformer getDivertTransformer(String name, String className) {
Transformer transformer = divertTransformers.get(name);
if (transformer == null && className != null) {
transformer = instantiateTransformer(className);
addDivertTransformer(name, transformer);
}
return transformer;
}
@Override
public void addBridgeTransformer(String name, Transformer transformer) {
bridgeTransformers.put(name, transformer);
}
@Override
public Transformer getBridgeTransformer(String name, String className) {
Transformer transformer = bridgeTransformers.get(name);
if (transformer == null && className != null) {
transformer = instantiateTransformer(className);
addBridgeTransformer(name, transformer);
}
return transformer;
}
@Override
public AcceptorFactory getAcceptorFactory(String name, final String className) {
AcceptorFactory factory = acceptorFactories.get(name);
if (factory == null && className != null) {
factory = AccessController.doPrivileged(new PrivilegedAction<AcceptorFactory>() {
public AcceptorFactory run() {
return (AcceptorFactory) ClassloadingUtil.newInstanceFromClassLoader(className);
}
});
addAcceptorFactory(name, factory);
}
return factory;
}
@Override
public void addAcceptorFactory(String name, AcceptorFactory acceptorFactory) {
acceptorFactories.put(name, acceptorFactory);
}
private Transformer instantiateTransformer(final String className) {
Transformer transformer = null;
if (className != null) {
try {
transformer = AccessController.doPrivileged(new PrivilegedAction<Transformer>() {
public Transformer run() {
return (Transformer) ClassloadingUtil.newInstanceFromClassLoader(className);
}
});
}
catch (Exception e) {
throw ActiveMQMessageBundle.BUNDLE.errorCreatingTransformerClass(e, className);
}
}
return transformer;
}
private void instantiateInterceptors(List<String> classNames, List<BaseInterceptor> interceptors) {
if (classNames != null) {
for (final String className : classNames) {
BaseInterceptor interceptor = AccessController.doPrivileged(new PrivilegedAction<BaseInterceptor>() {
public BaseInterceptor run() {
return (BaseInterceptor) ClassloadingUtil.newInstanceFromClassLoader(className);
}
});
interceptors.add(interceptor);
}
}
}
}
| |
package io.moquette.fce.service.mqtt;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttAsyncClient;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import io.moquette.fce.context.FceContext;
import io.moquette.fce.event.internal.IFceMqttCallback;
import io.moquette.fce.event.internal.MqttManageHandler;
import io.moquette.fce.exception.FceSystemException;
import io.moquette.fce.service.mqtt.websocket.MqttWebSocketAsyncClient;
/**
* Internal Plugin MqttClient which connects to the broker. Provides method for
* publishing retained messages to store plugin information on the broker.
*
* @author lants1
*
*/
public class FceMqttClientWrapper implements MqttService {
private static final Logger LOGGER = Logger.getLogger(FceMqttClientWrapper.class.getName());
private static final int OOS_AT_LEAST_ONCE = 1;
private MqttAsyncClient client;
private MqttCallback callback;
private MqttConnectOptions options = new MqttConnectOptions();
private Map<String, IFceMqttCallback> subscribedTopics = new HashMap<>();
private FceContext context;
private boolean initialized = false;
public FceMqttClientWrapper(FceContext context, MqttCallback callback) {
this.context = context;
this.callback = callback;
}
/**
* Connects internal mqttclient to the broker and init subscriptions.
*
* @param initalizationSubscriptions List<String>
*/
public void initializeInternalMqttClient(final List<String> initalizationSubscriptions) {
try {
client = getMqttClient();
SSLSocketFactory ssf = configureSSLSocketFactory();
options.setUserName(context.getPluginUser());
options.setPassword(context.getPluginPw().toCharArray());
options.setSocketFactory(ssf);
options.setCleanSession(false);
options.setKeepAliveInterval(30);
//options.setMaxInflight(10000);
client.setCallback(callback);
client.connect(options, null, new IMqttActionListener() {
@Override
public void onSuccess(IMqttToken asyncActionToken) {
for (String subscriptionTopic : initalizationSubscriptions) {
addNewSubscription(subscriptionTopic);
setInitialized();
LOGGER.info("client connected");
}
}
@Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
LOGGER.log(Level.WARNING, "internal mqtt client can't connect to broker", exception);
}
});
} catch (Exception e) {
throw new FceSystemException(e);
}
}
public boolean isInitialized() {
return this.initialized;
}
public IFceMqttCallback getCallback(String topic) {
return subscribedTopics.getOrDefault(topic, new MqttManageHandler());
}
public void addNewSubscription(String topic) {
addNewSubscription(topic, null);
}
@Override
public void addNewSubscription(String topic, IFceMqttCallback handler) {
try {
subscribedTopics.put(topic, handler);
client.subscribe(topic, OOS_AT_LEAST_ONCE, null, new IMqttActionListener() {
@Override
public void onSuccess(IMqttToken asyncActionToken) {
setInitialized();
LOGGER.info("topics registered,client initialized");
}
@Override
public void onFailure(IMqttToken asyncActionToken, Throwable e) {
throw new FceSystemException("internal client can't connect to broker", e);
}
});
} catch (MqttException e) {
LOGGER.log(Level.INFO, "user subscription could not be registered", e);
}
}
public void unregisterSubscriptions() throws MqttException {
client.unsubscribe(subscribedTopics.keySet().toArray(new String[subscribedTopics.size()]));
subscribedTopics.clear();
}
@Override
public void publish(String topic, String json) {
publish(topic, json, true);
}
private void publish(String topic, String json, boolean retained) {
MqttMessage message = new MqttMessage();
message.setPayload(json.getBytes());
message.setRetained(retained);
message.setQos(OOS_AT_LEAST_ONCE);
try {
client.publish(topic, message, null, new IMqttActionListener() {
@Override
public void onSuccess(IMqttToken asyncActionToken) {
LOGGER.info("mqtt message for topic: " + topic + " with content: " + json
+ " published to internal broker");
}
@Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
LOGGER.log(Level.WARNING, "publish failed, retry", exception);
}
});
} catch (MqttException e) {
LOGGER.log(Level.WARNING, "mqtt message for topic: " + topic + " with content: " + json
+ " could not published to internal broker", e);
}
}
@Override
public void delete(String topic) {
MqttMessage message = new MqttMessage();
message.setPayload(new byte[0]);
message.setRetained(true);
message.setQos(OOS_AT_LEAST_ONCE);
try {
client.publish(topic, message, null, new IMqttActionListener() {
@Override
public void onSuccess(IMqttToken asyncActionToken) {
LOGGER.info("topic: " + topic + " deleted.");
}
@Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
LOGGER.log(Level.WARNING, "publish failed, retry", exception);
}
});
} catch (MqttException e) {
LOGGER.log(Level.WARNING, "delete retained message on topic: " + topic + " failed", e);
}
}
public void connect() throws MqttException {
client.setCallback(callback);
client.connect(options, null, new IMqttActionListener() {
@Override
public void onSuccess(IMqttToken asyncActionToken) {
LOGGER.info("client reconnected");
}
@Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
LOGGER.log(Level.WARNING, "internal mqtt client can't connect to broker", exception);
}
});
}
/**
* Disconnects the mqtt client.
*
* @throws MqttException
*/
public void disconnect() throws MqttException{
client.disconnect();
}
/**
* keystore generated into test/resources with command:
*
* keytool -keystore clientkeystore.jks -alias testclient -genkey -keyalg
* RSA -> mandatory to put the name surname -> password is passw0rd -> type
* yes at the end
*
* to generate the crt file from the keystore -- keytool -certreq -alias
* testclient -keystore clientkeystore.jks -file testclient.csr
*
* keytool -export -alias testclient -keystore clientkeystore.jks -file
* testclient.crt
*
* to import an existing certificate: keytool -keystore clientkeystore.jks
* -import -alias testclient -file testclient.crt -trustcacerts
*/
private SSLSocketFactory configureSSLSocketFactory() throws KeyManagementException, NoSuchAlgorithmException,
UnrecoverableKeyException, IOException, CertificateException, KeyStoreException {
KeyStore ks = KeyStore.getInstance("JKS");
LOGGER.info("configure PROPS_PLUGIN_JKS_PATH" + context.getJksPath());
InputStream jksInputStream = jksDatastore(context.getJksPath());
ks.load(jksInputStream, context.getKeyStorePassword().toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ks, context.getKeyManagerPassword().toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
SSLContext sc = SSLContext.getInstance("TLS");
TrustManager[] trustManagers = tmf.getTrustManagers();
sc.init(kmf.getKeyManagers(), trustManagers, null);
return sc.getSocketFactory();
}
private InputStream jksDatastore(String jksPath) throws FileNotFoundException {
URL jksUrl = getClass().getClassLoader().getResource(jksPath);
File jksFile = new File(jksPath);
if (jksFile.exists()) {
return new FileInputStream(jksFile);
}
if (jksUrl != null) {
return getClass().getClassLoader().getResourceAsStream(jksPath);
}
throw new FceSystemException("JKS is not found on path:" + jksPath);
}
private void setInitialized() {
this.initialized = true;
}
private MqttAsyncClient getMqttClient() throws MqttException {
MemoryPersistence dataStore = new MemoryPersistence();
String connection;
if (context.getSecureWebsocketPort().isEmpty()) {
connection = "ssl://localhost:" + context.getSslPort();
LOGGER.info("try to connect to connection:" + connection);
return new MqttAsyncClient(connection, context.getPluginIdentifier(), dataStore);
}
connection = "wss://localhost:" + context.getSecureWebsocketPort();
LOGGER.info("try to connect to connection:" + connection);
return new MqttWebSocketAsyncClient(connection, context.getPluginIdentifier(), dataStore);
}
}
| |
/**
*/
package gluemodel.impl;
import gluemodel.CIM.IEC61968.Metering.MeterAsset;
import gluemodel.GluemodelPackage;
import gluemodel.MeterAssetMMXUPair;
import gluemodel.substationStandard.LNNodes.LNGroupM.MMXU;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.MinimalEObjectImpl;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Meter Asset MMXU Pair</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link gluemodel.impl.MeterAssetMMXUPairImpl#getA <em>A</em>}</li>
* <li>{@link gluemodel.impl.MeterAssetMMXUPairImpl#getB <em>B</em>}</li>
* <li>{@link gluemodel.impl.MeterAssetMMXUPairImpl#getName <em>Name</em>}</li>
* <li>{@link gluemodel.impl.MeterAssetMMXUPairImpl#getAMag <em>AMag</em>}</li>
* <li>{@link gluemodel.impl.MeterAssetMMXUPairImpl#getAAng <em>AAng</em>}</li>
* <li>{@link gluemodel.impl.MeterAssetMMXUPairImpl#getBMag <em>BMag</em>}</li>
* <li>{@link gluemodel.impl.MeterAssetMMXUPairImpl#getBAng <em>BAng</em>}</li>
* <li>{@link gluemodel.impl.MeterAssetMMXUPairImpl#getCMag <em>CMag</em>}</li>
* <li>{@link gluemodel.impl.MeterAssetMMXUPairImpl#getCAng <em>CAng</em>}</li>
* <li>{@link gluemodel.impl.MeterAssetMMXUPairImpl#getNeutMag <em>Neut Mag</em>}</li>
* <li>{@link gluemodel.impl.MeterAssetMMXUPairImpl#getNeutAng <em>Neut Ang</em>}</li>
* <li>{@link gluemodel.impl.MeterAssetMMXUPairImpl#getNetMag <em>Net Mag</em>}</li>
* <li>{@link gluemodel.impl.MeterAssetMMXUPairImpl#getNetAng <em>Net Ang</em>}</li>
* <li>{@link gluemodel.impl.MeterAssetMMXUPairImpl#getResMag <em>Res Mag</em>}</li>
* <li>{@link gluemodel.impl.MeterAssetMMXUPairImpl#getResAng <em>Res Ang</em>}</li>
* </ul>
*
* @generated
*/
public class MeterAssetMMXUPairImpl extends MinimalEObjectImpl.Container implements MeterAssetMMXUPair {
/**
* The cached value of the '{@link #getA() <em>A</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getA()
* @generated
* @ordered
*/
protected MeterAsset a;
/**
* The cached value of the '{@link #getB() <em>B</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getB()
* @generated
* @ordered
*/
protected MMXU b;
/**
* The default value of the '{@link #getName() <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getName()
* @generated
* @ordered
*/
protected static final String NAME_EDEFAULT = null;
/**
* The cached value of the '{@link #getName() <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getName()
* @generated
* @ordered
*/
protected String name = NAME_EDEFAULT;
/**
* The default value of the '{@link #getAMag() <em>AMag</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getAMag()
* @generated
* @ordered
*/
protected static final double AMAG_EDEFAULT = 0.0;
/**
* The cached value of the '{@link #getAMag() <em>AMag</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getAMag()
* @generated
* @ordered
*/
protected double aMag = AMAG_EDEFAULT;
/**
* The default value of the '{@link #getAAng() <em>AAng</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getAAng()
* @generated
* @ordered
*/
protected static final double AANG_EDEFAULT = 0.0;
/**
* The cached value of the '{@link #getAAng() <em>AAng</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getAAng()
* @generated
* @ordered
*/
protected double aAng = AANG_EDEFAULT;
/**
* The default value of the '{@link #getBMag() <em>BMag</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getBMag()
* @generated
* @ordered
*/
protected static final double BMAG_EDEFAULT = 0.0;
/**
* The cached value of the '{@link #getBMag() <em>BMag</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getBMag()
* @generated
* @ordered
*/
protected double bMag = BMAG_EDEFAULT;
/**
* The default value of the '{@link #getBAng() <em>BAng</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getBAng()
* @generated
* @ordered
*/
protected static final double BANG_EDEFAULT = 0.0;
/**
* The cached value of the '{@link #getBAng() <em>BAng</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getBAng()
* @generated
* @ordered
*/
protected double bAng = BANG_EDEFAULT;
/**
* The default value of the '{@link #getCMag() <em>CMag</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getCMag()
* @generated
* @ordered
*/
protected static final double CMAG_EDEFAULT = 0.0;
/**
* The cached value of the '{@link #getCMag() <em>CMag</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getCMag()
* @generated
* @ordered
*/
protected double cMag = CMAG_EDEFAULT;
/**
* The default value of the '{@link #getCAng() <em>CAng</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getCAng()
* @generated
* @ordered
*/
protected static final double CANG_EDEFAULT = 0.0;
/**
* The cached value of the '{@link #getCAng() <em>CAng</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getCAng()
* @generated
* @ordered
*/
protected double cAng = CANG_EDEFAULT;
/**
* The default value of the '{@link #getNeutMag() <em>Neut Mag</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getNeutMag()
* @generated
* @ordered
*/
protected static final double NEUT_MAG_EDEFAULT = 0.0;
/**
* The cached value of the '{@link #getNeutMag() <em>Neut Mag</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getNeutMag()
* @generated
* @ordered
*/
protected double neutMag = NEUT_MAG_EDEFAULT;
/**
* The default value of the '{@link #getNeutAng() <em>Neut Ang</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getNeutAng()
* @generated
* @ordered
*/
protected static final double NEUT_ANG_EDEFAULT = 0.0;
/**
* The cached value of the '{@link #getNeutAng() <em>Neut Ang</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getNeutAng()
* @generated
* @ordered
*/
protected double neutAng = NEUT_ANG_EDEFAULT;
/**
* The default value of the '{@link #getNetMag() <em>Net Mag</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getNetMag()
* @generated
* @ordered
*/
protected static final double NET_MAG_EDEFAULT = 0.0;
/**
* The cached value of the '{@link #getNetMag() <em>Net Mag</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getNetMag()
* @generated
* @ordered
*/
protected double netMag = NET_MAG_EDEFAULT;
/**
* The default value of the '{@link #getNetAng() <em>Net Ang</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getNetAng()
* @generated
* @ordered
*/
protected static final double NET_ANG_EDEFAULT = 0.0;
/**
* The cached value of the '{@link #getNetAng() <em>Net Ang</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getNetAng()
* @generated
* @ordered
*/
protected double netAng = NET_ANG_EDEFAULT;
/**
* The default value of the '{@link #getResMag() <em>Res Mag</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getResMag()
* @generated
* @ordered
*/
protected static final double RES_MAG_EDEFAULT = 0.0;
/**
* The cached value of the '{@link #getResMag() <em>Res Mag</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getResMag()
* @generated
* @ordered
*/
protected double resMag = RES_MAG_EDEFAULT;
/**
* The default value of the '{@link #getResAng() <em>Res Ang</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getResAng()
* @generated
* @ordered
*/
protected static final double RES_ANG_EDEFAULT = 0.0;
/**
* The cached value of the '{@link #getResAng() <em>Res Ang</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getResAng()
* @generated
* @ordered
*/
protected double resAng = RES_ANG_EDEFAULT;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected MeterAssetMMXUPairImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return GluemodelPackage.Literals.METER_ASSET_MMXU_PAIR;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public MeterAsset getA() {
if (a != null && a.eIsProxy()) {
InternalEObject oldA = (InternalEObject)a;
a = (MeterAsset)eResolveProxy(oldA);
if (a != oldA) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, GluemodelPackage.METER_ASSET_MMXU_PAIR__A, oldA, a));
}
}
return a;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public MeterAsset basicGetA() {
return a;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setA(MeterAsset newA) {
MeterAsset oldA = a;
a = newA;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, GluemodelPackage.METER_ASSET_MMXU_PAIR__A, oldA, a));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public MMXU getB() {
if (b != null && b.eIsProxy()) {
InternalEObject oldB = (InternalEObject)b;
b = (MMXU)eResolveProxy(oldB);
if (b != oldB) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, GluemodelPackage.METER_ASSET_MMXU_PAIR__B, oldB, b));
}
}
return b;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public MMXU basicGetB() {
return b;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setB(MMXU newB) {
MMXU oldB = b;
b = newB;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, GluemodelPackage.METER_ASSET_MMXU_PAIR__B, oldB, b));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getName() {
return name;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setName(String newName) {
String oldName = name;
name = newName;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, GluemodelPackage.METER_ASSET_MMXU_PAIR__NAME, oldName, name));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public double getAMag() {
return aMag;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setAMag(double newAMag) {
double oldAMag = aMag;
aMag = newAMag;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, GluemodelPackage.METER_ASSET_MMXU_PAIR__AMAG, oldAMag, aMag));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public double getAAng() {
return aAng;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setAAng(double newAAng) {
double oldAAng = aAng;
aAng = newAAng;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, GluemodelPackage.METER_ASSET_MMXU_PAIR__AANG, oldAAng, aAng));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public double getBMag() {
return bMag;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setBMag(double newBMag) {
double oldBMag = bMag;
bMag = newBMag;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, GluemodelPackage.METER_ASSET_MMXU_PAIR__BMAG, oldBMag, bMag));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public double getBAng() {
return bAng;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setBAng(double newBAng) {
double oldBAng = bAng;
bAng = newBAng;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, GluemodelPackage.METER_ASSET_MMXU_PAIR__BANG, oldBAng, bAng));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public double getCMag() {
return cMag;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setCMag(double newCMag) {
double oldCMag = cMag;
cMag = newCMag;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, GluemodelPackage.METER_ASSET_MMXU_PAIR__CMAG, oldCMag, cMag));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public double getCAng() {
return cAng;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setCAng(double newCAng) {
double oldCAng = cAng;
cAng = newCAng;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, GluemodelPackage.METER_ASSET_MMXU_PAIR__CANG, oldCAng, cAng));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public double getNeutMag() {
return neutMag;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setNeutMag(double newNeutMag) {
double oldNeutMag = neutMag;
neutMag = newNeutMag;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, GluemodelPackage.METER_ASSET_MMXU_PAIR__NEUT_MAG, oldNeutMag, neutMag));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public double getNeutAng() {
return neutAng;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setNeutAng(double newNeutAng) {
double oldNeutAng = neutAng;
neutAng = newNeutAng;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, GluemodelPackage.METER_ASSET_MMXU_PAIR__NEUT_ANG, oldNeutAng, neutAng));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public double getNetMag() {
return netMag;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setNetMag(double newNetMag) {
double oldNetMag = netMag;
netMag = newNetMag;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, GluemodelPackage.METER_ASSET_MMXU_PAIR__NET_MAG, oldNetMag, netMag));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public double getNetAng() {
return netAng;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setNetAng(double newNetAng) {
double oldNetAng = netAng;
netAng = newNetAng;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, GluemodelPackage.METER_ASSET_MMXU_PAIR__NET_ANG, oldNetAng, netAng));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public double getResMag() {
return resMag;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setResMag(double newResMag) {
double oldResMag = resMag;
resMag = newResMag;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, GluemodelPackage.METER_ASSET_MMXU_PAIR__RES_MAG, oldResMag, resMag));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public double getResAng() {
return resAng;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setResAng(double newResAng) {
double oldResAng = resAng;
resAng = newResAng;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, GluemodelPackage.METER_ASSET_MMXU_PAIR__RES_ANG, oldResAng, resAng));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case GluemodelPackage.METER_ASSET_MMXU_PAIR__A:
if (resolve) return getA();
return basicGetA();
case GluemodelPackage.METER_ASSET_MMXU_PAIR__B:
if (resolve) return getB();
return basicGetB();
case GluemodelPackage.METER_ASSET_MMXU_PAIR__NAME:
return getName();
case GluemodelPackage.METER_ASSET_MMXU_PAIR__AMAG:
return getAMag();
case GluemodelPackage.METER_ASSET_MMXU_PAIR__AANG:
return getAAng();
case GluemodelPackage.METER_ASSET_MMXU_PAIR__BMAG:
return getBMag();
case GluemodelPackage.METER_ASSET_MMXU_PAIR__BANG:
return getBAng();
case GluemodelPackage.METER_ASSET_MMXU_PAIR__CMAG:
return getCMag();
case GluemodelPackage.METER_ASSET_MMXU_PAIR__CANG:
return getCAng();
case GluemodelPackage.METER_ASSET_MMXU_PAIR__NEUT_MAG:
return getNeutMag();
case GluemodelPackage.METER_ASSET_MMXU_PAIR__NEUT_ANG:
return getNeutAng();
case GluemodelPackage.METER_ASSET_MMXU_PAIR__NET_MAG:
return getNetMag();
case GluemodelPackage.METER_ASSET_MMXU_PAIR__NET_ANG:
return getNetAng();
case GluemodelPackage.METER_ASSET_MMXU_PAIR__RES_MAG:
return getResMag();
case GluemodelPackage.METER_ASSET_MMXU_PAIR__RES_ANG:
return getResAng();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case GluemodelPackage.METER_ASSET_MMXU_PAIR__A:
setA((MeterAsset)newValue);
return;
case GluemodelPackage.METER_ASSET_MMXU_PAIR__B:
setB((MMXU)newValue);
return;
case GluemodelPackage.METER_ASSET_MMXU_PAIR__NAME:
setName((String)newValue);
return;
case GluemodelPackage.METER_ASSET_MMXU_PAIR__AMAG:
setAMag((Double)newValue);
return;
case GluemodelPackage.METER_ASSET_MMXU_PAIR__AANG:
setAAng((Double)newValue);
return;
case GluemodelPackage.METER_ASSET_MMXU_PAIR__BMAG:
setBMag((Double)newValue);
return;
case GluemodelPackage.METER_ASSET_MMXU_PAIR__BANG:
setBAng((Double)newValue);
return;
case GluemodelPackage.METER_ASSET_MMXU_PAIR__CMAG:
setCMag((Double)newValue);
return;
case GluemodelPackage.METER_ASSET_MMXU_PAIR__CANG:
setCAng((Double)newValue);
return;
case GluemodelPackage.METER_ASSET_MMXU_PAIR__NEUT_MAG:
setNeutMag((Double)newValue);
return;
case GluemodelPackage.METER_ASSET_MMXU_PAIR__NEUT_ANG:
setNeutAng((Double)newValue);
return;
case GluemodelPackage.METER_ASSET_MMXU_PAIR__NET_MAG:
setNetMag((Double)newValue);
return;
case GluemodelPackage.METER_ASSET_MMXU_PAIR__NET_ANG:
setNetAng((Double)newValue);
return;
case GluemodelPackage.METER_ASSET_MMXU_PAIR__RES_MAG:
setResMag((Double)newValue);
return;
case GluemodelPackage.METER_ASSET_MMXU_PAIR__RES_ANG:
setResAng((Double)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case GluemodelPackage.METER_ASSET_MMXU_PAIR__A:
setA((MeterAsset)null);
return;
case GluemodelPackage.METER_ASSET_MMXU_PAIR__B:
setB((MMXU)null);
return;
case GluemodelPackage.METER_ASSET_MMXU_PAIR__NAME:
setName(NAME_EDEFAULT);
return;
case GluemodelPackage.METER_ASSET_MMXU_PAIR__AMAG:
setAMag(AMAG_EDEFAULT);
return;
case GluemodelPackage.METER_ASSET_MMXU_PAIR__AANG:
setAAng(AANG_EDEFAULT);
return;
case GluemodelPackage.METER_ASSET_MMXU_PAIR__BMAG:
setBMag(BMAG_EDEFAULT);
return;
case GluemodelPackage.METER_ASSET_MMXU_PAIR__BANG:
setBAng(BANG_EDEFAULT);
return;
case GluemodelPackage.METER_ASSET_MMXU_PAIR__CMAG:
setCMag(CMAG_EDEFAULT);
return;
case GluemodelPackage.METER_ASSET_MMXU_PAIR__CANG:
setCAng(CANG_EDEFAULT);
return;
case GluemodelPackage.METER_ASSET_MMXU_PAIR__NEUT_MAG:
setNeutMag(NEUT_MAG_EDEFAULT);
return;
case GluemodelPackage.METER_ASSET_MMXU_PAIR__NEUT_ANG:
setNeutAng(NEUT_ANG_EDEFAULT);
return;
case GluemodelPackage.METER_ASSET_MMXU_PAIR__NET_MAG:
setNetMag(NET_MAG_EDEFAULT);
return;
case GluemodelPackage.METER_ASSET_MMXU_PAIR__NET_ANG:
setNetAng(NET_ANG_EDEFAULT);
return;
case GluemodelPackage.METER_ASSET_MMXU_PAIR__RES_MAG:
setResMag(RES_MAG_EDEFAULT);
return;
case GluemodelPackage.METER_ASSET_MMXU_PAIR__RES_ANG:
setResAng(RES_ANG_EDEFAULT);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case GluemodelPackage.METER_ASSET_MMXU_PAIR__A:
return a != null;
case GluemodelPackage.METER_ASSET_MMXU_PAIR__B:
return b != null;
case GluemodelPackage.METER_ASSET_MMXU_PAIR__NAME:
return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name);
case GluemodelPackage.METER_ASSET_MMXU_PAIR__AMAG:
return aMag != AMAG_EDEFAULT;
case GluemodelPackage.METER_ASSET_MMXU_PAIR__AANG:
return aAng != AANG_EDEFAULT;
case GluemodelPackage.METER_ASSET_MMXU_PAIR__BMAG:
return bMag != BMAG_EDEFAULT;
case GluemodelPackage.METER_ASSET_MMXU_PAIR__BANG:
return bAng != BANG_EDEFAULT;
case GluemodelPackage.METER_ASSET_MMXU_PAIR__CMAG:
return cMag != CMAG_EDEFAULT;
case GluemodelPackage.METER_ASSET_MMXU_PAIR__CANG:
return cAng != CANG_EDEFAULT;
case GluemodelPackage.METER_ASSET_MMXU_PAIR__NEUT_MAG:
return neutMag != NEUT_MAG_EDEFAULT;
case GluemodelPackage.METER_ASSET_MMXU_PAIR__NEUT_ANG:
return neutAng != NEUT_ANG_EDEFAULT;
case GluemodelPackage.METER_ASSET_MMXU_PAIR__NET_MAG:
return netMag != NET_MAG_EDEFAULT;
case GluemodelPackage.METER_ASSET_MMXU_PAIR__NET_ANG:
return netAng != NET_ANG_EDEFAULT;
case GluemodelPackage.METER_ASSET_MMXU_PAIR__RES_MAG:
return resMag != RES_MAG_EDEFAULT;
case GluemodelPackage.METER_ASSET_MMXU_PAIR__RES_ANG:
return resAng != RES_ANG_EDEFAULT;
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (name: ");
result.append(name);
result.append(", AMag: ");
result.append(aMag);
result.append(", AAng: ");
result.append(aAng);
result.append(", BMag: ");
result.append(bMag);
result.append(", BAng: ");
result.append(bAng);
result.append(", CMag: ");
result.append(cMag);
result.append(", CAng: ");
result.append(cAng);
result.append(", NeutMag: ");
result.append(neutMag);
result.append(", NeutAng: ");
result.append(neutAng);
result.append(", NetMag: ");
result.append(netMag);
result.append(", NetAng: ");
result.append(netAng);
result.append(", ResMag: ");
result.append(resMag);
result.append(", ResAng: ");
result.append(resAng);
result.append(')');
return result.toString();
}
} //MeterAssetMMXUPairImpl
| |
package tech.oom.julian.utils;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.view.View;
/**
* Created by ubuntu_ivo on 22.07.15..
*/
public class AnimUtils {
/**
* translate along the x axis
*
* @param view
* @param from
* @param to
* @param duration
* @param listener animator listener adapter, can be null
* @return ObjectAnimator
*/
public static ObjectAnimator translateX(View view, float from, float to, int duration, AnimatorListenerAdapter listener) {
ObjectAnimator translationX = ObjectAnimator.ofFloat(view, "translationX", from, to);
translationX.setDuration(duration);
if (listener != null) {
translationX.addListener(listener);
}
translationX.start();
return translationX;
}
/**
* translate along the y axis
*
* @param view
* @param from
* @param to
* @param duration
* @param listener animator listener adapter, can be null
* @return ObjectAnimator
*/
public static ObjectAnimator translateY(View view, float from, float to, int duration, AnimatorListenerAdapter listener) {
ObjectAnimator translationY = ObjectAnimator.ofFloat(view, "translationY", from, to);
translationY.setDuration(duration);
if (listener != null) {
translationY.addListener(listener);
}
translationY.start();
return translationY;
}
/**
* apply alpha animation to given view
* @param view
* @param from
* @param to
* @param duration
* @param listener animator listener adapter, can be null
* @return ObjectAnimator
*/
public static ObjectAnimator fade(View view, float from, float to, int duration, AnimatorListenerAdapter listener) {
ObjectAnimator alpha = ObjectAnimator.ofFloat(view, "alpha", from, to);
alpha.setDuration(duration);
if (listener != null) {
alpha.addListener(listener);
}
alpha.start();
return alpha;
}
/**
* apply alpha animation to given view and set visibility to gone or visible
* @param view
* @param from have to be 1 or 0
* @param to have to be 1 or 0
* @param duration
* @return ObjectAnimator
*/
public static ObjectAnimator fadeThenGoneOrVisible(final View view, float from, final float to, int duration) {
if(from == 0){
view.setVisibility(View.VISIBLE);
}
ObjectAnimator alpha = ObjectAnimator.ofFloat(view, "alpha", from, to);
alpha.setDuration(duration);
alpha.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
if(to == 0){
view.setVisibility(View.GONE);
}
}
});
alpha.start();
return alpha;
}
/**
* rotate view
*
* @param view
* @param from
* @param to
* @param duration
* @param listener listener animator listener adapter, can be null
* @return ObjectAnimator
*/
public static ObjectAnimator rotateX(View view, float from, float to, int duration, AnimatorListenerAdapter listener) {
ObjectAnimator rotate = ObjectAnimator.ofFloat(view, "rotation", from, to);
rotate.setDuration(duration);
if (listener != null) {
rotate.addListener(listener);
}
rotate.start();
return rotate;
}
/**
* scale view
* @param view
* @param from
* @param to
* @param pivotX
* @param pivotY
* @param duration
* @param listener listener animator listener adapter, can be null
*/
public static void scale(View view, float from, float to, float pivotX, float pivotY, int duration, AnimatorListenerAdapter listener) {
view.setPivotX(pivotX);
view.setPivotY(pivotY);
ObjectAnimator scaleX = ObjectAnimator.ofFloat(view, "scaleX", from, to);
ObjectAnimator scaleY = ObjectAnimator.ofFloat(view, "scaleY", from, to);
scaleX.setDuration(duration);
scaleY.setDuration(duration);
if (listener != null) {
scaleX.addListener(listener);
}
scaleX.start();
scaleY.start();
}
/**
* scale view
* @param view
* @param from
* @param to
* @param duration
* @param listener listener animator listener adapter, can be null
*/
public static void scale(View view, float from, float to, int duration, AnimatorListenerAdapter listener) {
ObjectAnimator scaleX = ObjectAnimator.ofFloat(view, "scaleX", from, to);
ObjectAnimator scaleY = ObjectAnimator.ofFloat(view, "scaleY", from, to);
scaleX.setDuration(duration);
scaleY.setDuration(duration);
if (listener != null) {
scaleX.addListener(listener);
}
scaleX.start();
scaleY.start();
}
/**
* infinite fade animation
*
* @param view
* @param singleDuration duration of single alpha animation
* @return AnimatorSet
*/
public static AnimatorSet fadingInfinite(View view, long singleDuration){
ObjectAnimator firstFade = ObjectAnimator.ofFloat(view, "alpha", 0.0f, 1.0f).setDuration(singleDuration);
ObjectAnimator secondFade = ObjectAnimator.ofFloat(view, "alpha", 1.0f, 0.0f).setDuration(singleDuration);
final AnimatorSet animatorSet = new AnimatorSet();
animatorSet.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
animatorSet.start();
}
});
animatorSet.play(firstFade).before(secondFade);
animatorSet.start();
return animatorSet;
}
}
| |
/*
* MIT License
*
* Copyright (c) 2019 Choko (choko@curioswitch.org)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.curioswitch.common.server.framework;
import static com.google.common.collect.ImmutableList.toImmutableList;
import brave.Tracing;
import brave.propagation.TraceContext;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.util.concurrent.Futures;
import com.linecorp.armeria.common.HttpHeaderNames;
import com.linecorp.armeria.common.HttpResponse;
import com.linecorp.armeria.common.HttpStatus;
import com.linecorp.armeria.common.MediaType;
import com.linecorp.armeria.common.RequestContext;
import com.linecorp.armeria.common.auth.OAuth2Token;
import com.linecorp.armeria.common.grpc.GrpcSerializationFormats;
import com.linecorp.armeria.server.HttpService;
import com.linecorp.armeria.server.HttpServiceWithRoutes;
import com.linecorp.armeria.server.Server;
import com.linecorp.armeria.server.ServerBuilder;
import com.linecorp.armeria.server.ServerListener;
import com.linecorp.armeria.server.ServiceRequestContext;
import com.linecorp.armeria.server.auth.AuthService;
import com.linecorp.armeria.server.auth.AuthServiceBuilder;
import com.linecorp.armeria.server.brave.BraveService;
import com.linecorp.armeria.server.docs.DocService;
import com.linecorp.armeria.server.docs.DocServiceBuilder;
import com.linecorp.armeria.server.grpc.GrpcService;
import com.linecorp.armeria.server.grpc.GrpcServiceBuilder;
import com.linecorp.armeria.server.healthcheck.HealthCheckService;
import com.linecorp.armeria.server.healthcheck.HealthChecker;
import com.linecorp.armeria.server.healthcheck.SettableHealthChecker;
import com.linecorp.armeria.server.logging.LoggingService;
import com.linecorp.armeria.server.metric.MetricCollectingService;
import com.linecorp.armeria.server.metric.PrometheusExpositionService;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigBeanFactory;
import dagger.BindsOptionalOf;
import dagger.Lazy;
import dagger.Module;
import dagger.Provides;
import dagger.multibindings.Multibinds;
import dagger.producers.Production;
import io.grpc.BindableService;
import io.grpc.protobuf.services.ProtoReflectionService;
import io.micrometer.core.instrument.MeterRegistry;
import io.netty.handler.ssl.ApplicationProtocolConfig;
import io.netty.handler.ssl.ApplicationProtocolConfig.Protocol;
import io.netty.handler.ssl.ApplicationProtocolConfig.SelectedListenerFailureBehavior;
import io.netty.handler.ssl.ApplicationProtocolConfig.SelectorFailureBehavior;
import io.netty.handler.ssl.ApplicationProtocolNames;
import io.netty.handler.ssl.ClientAuth;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import io.netty.handler.ssl.util.SelfSignedCertificate;
import io.prometheus.client.CollectorRegistry;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.time.Duration;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Function;
import javax.inject.Singleton;
import javax.net.ssl.TrustManagerFactory;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.curioswitch.common.server.framework.armeria.SslContextKeyConverter;
import org.curioswitch.common.server.framework.auth.firebase.FirebaseAuthConfig;
import org.curioswitch.common.server.framework.auth.firebase.FirebaseAuthModule;
import org.curioswitch.common.server.framework.auth.firebase.FirebaseAuthorizer;
import org.curioswitch.common.server.framework.auth.jwt.JwtAuthorizer;
import org.curioswitch.common.server.framework.auth.jwt.JwtModule;
import org.curioswitch.common.server.framework.auth.jwt.JwtVerifier.Algorithm;
import org.curioswitch.common.server.framework.auth.ssl.RpcAclsCommonNamesProvider;
import org.curioswitch.common.server.framework.auth.ssl.SslAuthorizer;
import org.curioswitch.common.server.framework.auth.ssl.SslCommonNamesProvider;
import org.curioswitch.common.server.framework.config.JavascriptStaticConfig;
import org.curioswitch.common.server.framework.config.ModifiableJavascriptStaticConfig;
import org.curioswitch.common.server.framework.config.ModifiableServerConfig;
import org.curioswitch.common.server.framework.config.MonitoringConfig;
import org.curioswitch.common.server.framework.config.SecurityConfig;
import org.curioswitch.common.server.framework.config.ServerConfig;
import org.curioswitch.common.server.framework.files.FileWatcher;
import org.curioswitch.common.server.framework.files.WatchedPath;
import org.curioswitch.common.server.framework.filter.IpFilteringService;
import org.curioswitch.common.server.framework.grpc.GrpcServiceDefinition;
import org.curioswitch.common.server.framework.inject.CloseOnStop;
import org.curioswitch.common.server.framework.inject.EagerInit;
import org.curioswitch.common.server.framework.logging.LoggingModule;
import org.curioswitch.common.server.framework.logging.RequestLoggingContext;
import org.curioswitch.common.server.framework.monitoring.MetricsHttpService;
import org.curioswitch.common.server.framework.monitoring.MonitoringModule;
import org.curioswitch.common.server.framework.monitoring.RpcMetricLabels;
import org.curioswitch.common.server.framework.monitoring.StackdriverReporter;
import org.curioswitch.common.server.framework.security.HttpsOnlyService;
import org.curioswitch.common.server.framework.security.SecurityModule;
import org.curioswitch.common.server.framework.server.HttpServiceDefinition;
import org.curioswitch.common.server.framework.server.PostServerCustomizer;
import org.curioswitch.common.server.framework.server.ServerShutDownDelayer;
import org.curioswitch.common.server.framework.staticsite.JavascriptStaticService;
import org.curioswitch.common.server.framework.staticsite.StaticSiteService;
import org.curioswitch.common.server.framework.staticsite.StaticSiteServiceDefinition;
import org.curioswitch.common.server.framework.util.ResourceUtil;
import org.curioswitch.curiostack.gcloud.core.auth.GcloudAuthModule;
import org.curioswitch.curiostack.gcloud.iam.GcloudIamModule;
import org.jooq.DSLContext;
/**
* A {@link Module} which bootstraps a server, finding and registering GRPC services to expose. All
* servers should include this {@link Module} from an application-specific {@link Module} that binds
* services to be exposed to {@link BindableService} and add it to a {@link dagger.Component} which
* returns the initialized {@link Server}.
*
* <p>For example,
*
* <pre>{@code
* {@literal @}Module(includes = ServerModule.class)
* abstract class MyAppServerModule {
* {@literal @}Bind @IntoSet abstract BindableService myAppService(AppService service);
* }
*
* {@literal @}Component(modules = MyAppServerModule.class)
* interface MyAppComponent {
* Server server();
* }
* }</pre>
*/
@Module(
includes = {
ApplicationModule.class,
FirebaseAuthModule.class,
GcloudAuthModule.class,
GcloudIamModule.class,
MonitoringModule.class,
JwtModule.class,
LoggingModule.class,
SecurityModule.class
})
public abstract class ServerModule {
private static final Logger logger = LogManager.getLogger();
private static final ApplicationProtocolConfig HTTPS_ALPN_CFG =
new ApplicationProtocolConfig(
Protocol.ALPN,
// NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers.
SelectorFailureBehavior.NO_ADVERTISE,
// ACCEPT is currently the only mode supported by both OpenSsl and JDK providers.
SelectedListenerFailureBehavior.ACCEPT,
ApplicationProtocolNames.HTTP_2,
ApplicationProtocolNames.HTTP_1_1);
@Multibinds
abstract Set<BindableService> grpcServices();
@Multibinds
abstract Set<GrpcServiceDefinition> grpcServiceDefinitions();
@Multibinds
abstract Set<HttpServiceDefinition> httpServiceDefinitions();
@Multibinds
abstract Set<StaticSiteServiceDefinition> staticSites();
@Multibinds
abstract Set<Consumer<ServerBuilder>> serverCustomizers();
@Multibinds
abstract Set<PostServerCustomizer> postServerCustomizers();
@Multibinds
abstract Set<WatchedPath> watchedPaths();
@Multibinds
@EagerInit
abstract Set<Object> eagerInitializedDependencies();
@Multibinds
@CloseOnStop
abstract Set<Closeable> closeOnStopDependencies();
@Multibinds
abstract Set<ServerShutDownDelayer> serverShutDownDelayers();
@BindsOptionalOf
abstract SslCommonNamesProvider sslCommonNamesProvider();
@BindsOptionalOf
abstract DSLContext db();
@Provides
@Singleton
static ServerConfig serverConfig(Config config) {
return ConfigBeanFactory.create(config.getConfig("server"), ModifiableServerConfig.class)
.toImmutable();
}
@Provides
@Singleton
static JavascriptStaticConfig javascriptStaticConfig(Config config) {
return ConfigBeanFactory.create(
config.getConfig("javascriptConfig"), ModifiableJavascriptStaticConfig.class)
.toImmutable();
}
@Provides
static ServiceRequestContext context() {
return RequestContext.current();
}
@Provides
@Production
static Executor executor(ServiceRequestContext ctx) {
return ctx.eventLoop();
}
@Provides
@Singleton
static Optional<SelfSignedCertificate> selfSignedCertificate(ServerConfig serverConfig) {
if (!serverConfig.isGenerateSelfSignedCertificate()) {
return Optional.empty();
}
logger.warn("Generating self-signed certificate. This should only happen on local!!!");
try {
return Optional.of(new SelfSignedCertificate());
} catch (CertificateException e) {
// Can't happen.
throw new IllegalStateException(e);
}
}
@Provides
static Optional<TrustManagerFactory> caTrustManager(ServerConfig serverConfig) {
if (serverConfig.isDisableServerCertificateVerification()) {
return Optional.of(InsecureTrustManagerFactory.INSTANCE);
}
if (serverConfig.getCaCertificatePath().isEmpty()) {
return Optional.empty();
}
try {
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
keystore.load(null);
keystore.setCertificateEntry("caCert", readCertificate(serverConfig.getCaCertificatePath()));
if (!serverConfig.getAdditionalCaCertificatePath().isEmpty()) {
keystore.setCertificateEntry(
"additionalCaCert", readCertificate(serverConfig.getAdditionalCaCertificatePath()));
}
TrustManagerFactory trustManagerFactory =
TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keystore);
return Optional.of(trustManagerFactory);
} catch (CertificateException | IOException | KeyStoreException | NoSuchAlgorithmException e) {
throw new IllegalStateException("Could not load CA certificate.", e);
}
}
// TODO(choko): Understand this rule better.
@SuppressWarnings("FutureReturnValueIgnored")
@Provides
@Singleton
static Server armeriaServer(
Set<BindableService> grpcServices,
Set<GrpcServiceDefinition> grpcServiceDefinitions,
Set<HttpServiceDefinition> httpServiceDefinitions,
Set<StaticSiteServiceDefinition> staticSites,
Set<Consumer<ServerBuilder>> serverCustomizers,
Set<PostServerCustomizer> postServerCustomizers,
Set<WatchedPath> watchedPaths,
Function<HttpService, LoggingService> loggingService,
MetricsHttpService metricsHttpService,
CollectorRegistry collectorRegistry,
MeterRegistry meterRegistry,
Tracing tracing,
Lazy<FirebaseAuthorizer> firebaseAuthorizer,
Lazy<JwtAuthorizer.Factory> jwtAuthorizer,
Lazy<JavascriptStaticService> javascriptStaticService,
Optional<SelfSignedCertificate> selfSignedCertificate,
Optional<TrustManagerFactory> caTrustManager,
Optional<SslCommonNamesProvider> sslCommonNamesProvider,
FileWatcher.Builder fileWatcherBuilder,
Lazy<StackdriverReporter> stackdriverReporter,
ServerConfig serverConfig,
FirebaseAuthConfig authConfig,
HttpsOnlyService.Factory httpsOnlyServiceFactory,
JavascriptStaticConfig javascriptStaticConfig,
MonitoringConfig monitoringConfig,
SecurityConfig securityConfig,
Set<ServerShutDownDelayer> serverShutDownDelayers,
@CloseOnStop Set<Closeable> closeOnStopDependencies,
// Eagerly trigger bindings that are present, not actually used here.
@EagerInit Set<Object> eagerInitializedDependencies) {
for (WatchedPath watched : watchedPaths) {
fileWatcherBuilder.registerPath(watched.getPath(), watched.getHandler());
}
if (!sslCommonNamesProvider.isPresent()
&& !serverConfig.getRpcAclsPath().isEmpty()
&& !serverConfig.isDisableSslAuthorization()) {
Path path = Paths.get(serverConfig.getRpcAclsPath()).toAbsolutePath();
RpcAclsCommonNamesProvider commonNamesProvider = new RpcAclsCommonNamesProvider(path);
fileWatcherBuilder.registerPath(path, commonNamesProvider::processFile);
if (path.toFile().exists()) {
commonNamesProvider.processFile(path);
}
sslCommonNamesProvider = Optional.of(commonNamesProvider);
}
ServerBuilder sb = Server.builder().https(serverConfig.getPort());
if (selfSignedCertificate.isPresent()) {
SelfSignedCertificate certificate = selfSignedCertificate.get();
SslContextKeyConverter.execute(
ResourceUtil.openStream(certificate.certificate().getAbsolutePath()),
ResourceUtil.openStream(certificate.privateKey().getAbsolutePath()),
sb::tls);
sb.tlsCustomizer(
tls -> {
tls.trustManager(InsecureTrustManagerFactory.INSTANCE);
if (!serverConfig.isDisableSslAuthorization()) {
tls.clientAuth(ClientAuth.OPTIONAL);
}
});
} else if (serverConfig.getTlsCertificatePath().isEmpty()
|| serverConfig.getTlsPrivateKeyPath().isEmpty()
|| !caTrustManager.isPresent()) {
throw new IllegalStateException(
"No TLS configuration provided, Curiostack does not support non-TLS servers. "
+ "Use gradle-curio-cluster-plugin to set up a namespace and TLS.");
} else {
SslContextKeyConverter.execute(
ResourceUtil.openStream(serverConfig.getTlsCertificatePath()),
ResourceUtil.openStream(serverConfig.getTlsPrivateKeyPath()),
sb::tls);
sb.tlsCustomizer(
tls -> {
tls.trustManager(caTrustManager.get());
if (!serverConfig.isDisableSslAuthorization()) {
tls.clientAuth(ClientAuth.OPTIONAL);
}
});
}
serverCustomizers.forEach(c -> c.accept(sb));
Optional<Function<HttpService, IpFilteringService>> ipFilter = Optional.empty();
if (!serverConfig.getIpFilterRules().isEmpty()) {
ipFilter = Optional.of(IpFilteringService.newDecorator(serverConfig.getIpFilterRules()));
}
if (!serverConfig.isDisableDocService()) {
DocServiceBuilder docService = DocService.builder();
if (!authConfig.getServiceAccountBase64().isEmpty()) {
docService.injectedScripts(
"armeria.registerHeaderProvider(function() {\n"
+ " return firebase.auth().currentUser.getIdToken().then(token => { authorization: 'bearer ' + token });\n"
+ "});");
}
sb.serviceUnder(
"/internal/docs", internalService(docService.build(), ipFilter, serverConfig));
}
SettableHealthChecker settableHealthChecker = new SettableHealthChecker(true);
List<HealthChecker> healthCheckers =
serverShutDownDelayers.isEmpty()
? ImmutableList.of()
: ImmutableList.of(settableHealthChecker);
sb.service(
"/internal/health",
internalService(HealthCheckService.of(healthCheckers), ipFilter, serverConfig));
sb.service("/internal/dropwizard", internalService(metricsHttpService, ipFilter, serverConfig));
sb.service(
"/internal/metrics",
internalService(
new PrometheusExpositionService(collectorRegistry), ipFilter, serverConfig));
if (sslCommonNamesProvider.isPresent()) {
SslCommonNamesProvider namesProvider = sslCommonNamesProvider.get();
sb.service(
"/internal/rpcacls",
internalService(
(ctx, req) ->
HttpResponse.of(
HttpStatus.OK,
MediaType.PLAIN_TEXT_UTF_8,
String.join("\n", namesProvider.get())),
ipFilter,
serverConfig));
}
if (!grpcServices.isEmpty()) {
GrpcServiceDefinition definition =
new GrpcServiceDefinition.Builder()
.addAllServices(grpcServices)
.decorator(Function.identity())
.path(serverConfig.getGrpcPath())
.build();
grpcServiceDefinitions =
ImmutableSet.<GrpcServiceDefinition>builder()
.addAll(grpcServiceDefinitions)
.add(definition)
.build();
}
for (GrpcServiceDefinition definition : grpcServiceDefinitions) {
GrpcServiceBuilder serviceBuilder =
GrpcService.builder()
.supportedSerializationFormats(GrpcSerializationFormats.values())
.enableUnframedRequests(true);
definition.services().forEach(serviceBuilder::addService);
if (!serverConfig.isDisableGrpcServiceDiscovery()) {
serviceBuilder.addService(ProtoReflectionService.newInstance());
}
definition.customizer().accept(serviceBuilder);
HttpServiceWithRoutes service = serviceBuilder.build();
if (definition.path().equals("/")) {
Optional<SslCommonNamesProvider> sslCommonNamesProvider0 = sslCommonNamesProvider;
sb.service(
service,
s ->
decorateService(
s.decorate(definition.decorator()),
tracing,
firebaseAuthorizer,
jwtAuthorizer,
sslCommonNamesProvider0,
serverConfig,
authConfig));
} else {
sb.serviceUnder(
definition.path(),
decorateService(
service.decorate(definition.decorator()),
tracing,
firebaseAuthorizer,
jwtAuthorizer,
sslCommonNamesProvider,
serverConfig,
authConfig));
}
}
for (HttpServiceDefinition definition : httpServiceDefinitions) {
sb.service(
definition.route(),
decorateService(
definition.service(),
tracing,
firebaseAuthorizer,
jwtAuthorizer,
sslCommonNamesProvider,
serverConfig,
authConfig));
}
if (javascriptStaticConfig.getVersion() != 0) {
sb.service(
"/static/jsconfig-" + javascriptStaticConfig.getVersion(), javascriptStaticService.get());
}
for (StaticSiteServiceDefinition staticSite : staticSites) {
StaticSiteService.addToServer(
staticSite.urlRoot(), staticSite.staticPath(), staticSite.classpathRoot(), sb);
}
if (ipFilter.isPresent() && !serverConfig.getIpFilterInternalOnly()) {
sb.decorator(ipFilter.get());
}
if (securityConfig.getHttpsOnly()) {
sb.decorator(httpsOnlyServiceFactory.newDecorator());
}
sb.decorator(loggingService);
sb.meterRegistry(meterRegistry);
if (serverConfig.getEnableGracefulShutdown()) {
sb.gracefulShutdownTimeout(Duration.ofSeconds(10), Duration.ofSeconds(30));
}
postServerCustomizers.forEach((c) -> c.accept(sb));
sb.serverListener(
new ServerListener() {
@Override
public void serverStarting(Server server) {}
@Override
public void serverStarted(Server server) {}
@Override
public void serverStopping(Server server) {}
@Override
public void serverStopped(Server server) {
closeOnStopDependencies.forEach(
c -> {
try {
c.close();
} catch (IOException e) {
logger.info("Exception closing {}", c);
}
});
}
});
Server server = sb.build();
server
.start()
.whenComplete(
(unused, t) -> {
if (t != null) {
logger.error("Error starting server.", t);
} else {
logger.info("Server started on ports: " + server.activePorts());
}
});
Runtime.getRuntime()
.addShutdownHook(
new Thread(
() -> {
logger.info("Received shutdown signal.");
settableHealthChecker.setHealthy(false);
if (!serverShutDownDelayers.isEmpty()) {
Futures.getUnchecked(
Futures.successfulAsList(
serverShutDownDelayers.stream()
.map(ServerShutDownDelayer::readyForShutdown)
.collect(toImmutableList())));
}
logger.info("Server shutting down.");
server.stop().join();
}));
if (!fileWatcherBuilder.isEmpty()) {
FileWatcher fileWatcher = fileWatcherBuilder.build();
fileWatcher.start();
Runtime.getRuntime().addShutdownHook(new Thread(fileWatcher::close));
}
if (monitoringConfig.isReportTraces()) {
server
.nextEventLoop()
.scheduleAtFixedRate(
stackdriverReporter.get()::flush,
0,
monitoringConfig.getTraceReportInterval().getSeconds(),
TimeUnit.SECONDS);
}
return server;
}
private static HttpService decorateService(
HttpService service,
Tracing tracing,
Lazy<FirebaseAuthorizer> firebaseAuthorizer,
Lazy<JwtAuthorizer.Factory> jwtAuthorizer,
Optional<SslCommonNamesProvider> sslCommonNamesProvider,
ServerConfig serverConfig,
FirebaseAuthConfig authConfig) {
if (sslCommonNamesProvider.isPresent() && !serverConfig.isDisableSslAuthorization()) {
AuthServiceBuilder authServiceBuilder = AuthService.builder();
authServiceBuilder.add(new SslAuthorizer(sslCommonNamesProvider.get()));
service = service.decorate(authServiceBuilder.newDecorator());
}
if (serverConfig.isEnableIapAuthorization()) {
service =
service
.decorate(
(delegate, ctx, req) -> {
DecodedJWT jwt = ctx.attr(JwtAuthorizer.DECODED_JWT);
String loggedInUserEmail =
jwt != null ? jwt.getClaim("email").asString() : "unknown";
RequestLoggingContext.put(ctx, "logged_in_user", loggedInUserEmail);
return delegate.serve(ctx, req);
})
.decorate(
AuthService.builder()
.addTokenAuthorizer(
headers ->
OAuth2Token.of(
headers.get(HttpHeaderNames.of("x-goog-iap-jwt-assertion"))),
jwtAuthorizer
.get()
.create(
Algorithm.ES256, "https://www.gstatic.com/iap/verify/public_key"))
.newDecorator());
}
if (!authConfig.getServiceAccountBase64().isEmpty()) {
FirebaseAuthorizer authorizer = firebaseAuthorizer.get();
service =
service.decorate(
AuthService.builder().addOAuth2(authorizer).onFailure(authorizer).newDecorator());
}
service =
service
.decorate(
MetricCollectingService.newDecorator(
RpcMetricLabels.grpcRequestLabeler("grpc_services")))
.decorate(BraveService.newDecorator(tracing))
.decorate(
(delegate, ctx, req) -> {
TraceContext traceCtx = tracing.currentTraceContext().get();
if (traceCtx != null) {
RequestLoggingContext.put(ctx, "traceId", traceCtx.traceIdString());
RequestLoggingContext.put(ctx, "spanId", traceCtx.spanIdString());
}
return delegate.serve(ctx, req);
});
return service;
}
private static HttpService internalService(
HttpService service,
Optional<Function<HttpService, IpFilteringService>> ipFilter,
ServerConfig config) {
if (!ipFilter.isPresent() || !config.getIpFilterInternalOnly()) {
return service;
}
return service.decorate(ipFilter.get());
}
private static X509Certificate readCertificate(String path) throws CertificateException {
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
try (InputStream is = ResourceUtil.openStream(path)) {
return (X509Certificate) certificateFactory.generateCertificate(is);
} catch (IOException e) {
throw new UncheckedIOException("Error reading certificate from " + path, e);
}
}
}
| |
/*
* 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.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.serviceusage.v1beta1.model;
/**
* `Service` is the root object of Google API service configuration (service config). It describes
* the basic information about a logical service, such as the service name and the user-facing
* title, and delegates other aspects to sub-sections. Each sub-section is either a proto message or
* a repeated proto message that configures a specific aspect, such as auth. For more information,
* see each proto message definition. Example: type: google.api.Service name:
* calendar.googleapis.com title: Google Calendar API apis: - name: google.calendar.v3.Calendar
* visibility: rules: - selector: "google.calendar.v3.*" restriction: PREVIEW backend: rules: -
* selector: "google.calendar.v3.*" address: calendar.example.com authentication: providers: - id:
* google_calendar_auth jwks_uri: https://www.googleapis.com/oauth2/v1/certs issuer:
* https://securetoken.google.com rules: - selector: "*" requirements: provider_id:
* google_calendar_auth
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Service Usage API. For a detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class GoogleApiService extends com.google.api.client.json.GenericJson {
/**
* A list of API interfaces exported by this service. Only the `name` field of the
* google.protobuf.Api needs to be provided by the configuration author, as the remaining fields
* will be derived from the IDL during the normalization process. It is an error to specify an API
* interface here which cannot be resolved against the associated IDL files.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<Api> apis;
static {
// hack to force ProGuard to consider Api used, since otherwise it would be stripped out
// see https://github.com/google/google-api-java-client/issues/543
com.google.api.client.util.Data.nullOf(Api.class);
}
/**
* Auth configuration.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Authentication authentication;
/**
* API backend configuration.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Backend backend;
/**
* Billing configuration.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Billing billing;
/**
* Obsolete. Do not use. This field has no semantic meaning. The service config compiler always
* sets this field to `3`.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Long configVersion;
/**
* Context configuration.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Context context;
/**
* Configuration for the service control plane.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Control control;
/**
* Custom error configuration.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private CustomError customError;
/**
* Additional API documentation.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Documentation documentation;
/**
* Configuration for network endpoints. If this is empty, then an endpoint with the same name as
* the service is automatically generated to service all defined APIs.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<Endpoint> endpoints;
static {
// hack to force ProGuard to consider Endpoint used, since otherwise it would be stripped out
// see https://github.com/google/google-api-java-client/issues/543
com.google.api.client.util.Data.nullOf(Endpoint.class);
}
/**
* A list of all enum types included in this API service. Enums referenced directly or indirectly
* by the `apis` are automatically included. Enums which are not referenced but shall be included
* should be listed here by name by the configuration author. Example: enums: - name:
* google.someapi.v1.SomeEnum
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<ServiceUsageEnum> enums;
static {
// hack to force ProGuard to consider ServiceUsageEnum used, since otherwise it would be stripped out
// see https://github.com/google/google-api-java-client/issues/543
com.google.api.client.util.Data.nullOf(ServiceUsageEnum.class);
}
/**
* HTTP configuration.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Http http;
/**
* A unique ID for a specific instance of this message, typically assigned by the client for
* tracking purpose. Must be no longer than 63 characters and only lower case letters, digits,
* '.', '_' and '-' are allowed. If empty, the server may choose to generate one instead.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String id;
/**
* Logging configuration.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Logging logging;
/**
* Defines the logs used by this service.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<LogDescriptor> logs;
/**
* Defines the metrics used by this service.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<MetricDescriptor> metrics;
/**
* Defines the monitored resources used by this service. This is required by the
* Service.monitoring and Service.logging configurations.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<MonitoredResourceDescriptor> monitoredResources;
/**
* Monitoring configuration.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Monitoring monitoring;
/**
* The service name, which is a DNS-like logical identifier for the service, such as
* `calendar.googleapis.com`. The service name typically goes through DNS verification to make
* sure the owner of the service also owns the DNS name.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/**
* The Google project that owns this service.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String producerProjectId;
/**
* Quota configuration.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Quota quota;
/**
* Output only. The source information for this configuration if available.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private SourceInfo sourceInfo;
/**
* System parameter configuration.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private SystemParameters systemParameters;
/**
* A list of all proto message types included in this API service. It serves similar purpose as
* [google.api.Service.types], except that these types are not needed by user-defined APIs.
* Therefore, they will not show up in the generated discovery doc. This field should only be used
* to define system APIs in ESF.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<Type> systemTypes;
/**
* The product title for this service, it is the name displayed in Google Cloud Console.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String title;
/**
* A list of all proto message types included in this API service. Types referenced directly or
* indirectly by the `apis` are automatically included. Messages which are not referenced but
* shall be included, such as types used by the `google.protobuf.Any` type, should be listed here
* by name by the configuration author. Example: types: - name: google.protobuf.Int32
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<Type> types;
/**
* Configuration controlling usage of this service.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Usage usage;
/**
* A list of API interfaces exported by this service. Only the `name` field of the
* google.protobuf.Api needs to be provided by the configuration author, as the remaining fields
* will be derived from the IDL during the normalization process. It is an error to specify an API
* interface here which cannot be resolved against the associated IDL files.
* @return value or {@code null} for none
*/
public java.util.List<Api> getApis() {
return apis;
}
/**
* A list of API interfaces exported by this service. Only the `name` field of the
* google.protobuf.Api needs to be provided by the configuration author, as the remaining fields
* will be derived from the IDL during the normalization process. It is an error to specify an API
* interface here which cannot be resolved against the associated IDL files.
* @param apis apis or {@code null} for none
*/
public GoogleApiService setApis(java.util.List<Api> apis) {
this.apis = apis;
return this;
}
/**
* Auth configuration.
* @return value or {@code null} for none
*/
public Authentication getAuthentication() {
return authentication;
}
/**
* Auth configuration.
* @param authentication authentication or {@code null} for none
*/
public GoogleApiService setAuthentication(Authentication authentication) {
this.authentication = authentication;
return this;
}
/**
* API backend configuration.
* @return value or {@code null} for none
*/
public Backend getBackend() {
return backend;
}
/**
* API backend configuration.
* @param backend backend or {@code null} for none
*/
public GoogleApiService setBackend(Backend backend) {
this.backend = backend;
return this;
}
/**
* Billing configuration.
* @return value or {@code null} for none
*/
public Billing getBilling() {
return billing;
}
/**
* Billing configuration.
* @param billing billing or {@code null} for none
*/
public GoogleApiService setBilling(Billing billing) {
this.billing = billing;
return this;
}
/**
* Obsolete. Do not use. This field has no semantic meaning. The service config compiler always
* sets this field to `3`.
* @return value or {@code null} for none
*/
public java.lang.Long getConfigVersion() {
return configVersion;
}
/**
* Obsolete. Do not use. This field has no semantic meaning. The service config compiler always
* sets this field to `3`.
* @param configVersion configVersion or {@code null} for none
*/
public GoogleApiService setConfigVersion(java.lang.Long configVersion) {
this.configVersion = configVersion;
return this;
}
/**
* Context configuration.
* @return value or {@code null} for none
*/
public Context getContext() {
return context;
}
/**
* Context configuration.
* @param context context or {@code null} for none
*/
public GoogleApiService setContext(Context context) {
this.context = context;
return this;
}
/**
* Configuration for the service control plane.
* @return value or {@code null} for none
*/
public Control getControl() {
return control;
}
/**
* Configuration for the service control plane.
* @param control control or {@code null} for none
*/
public GoogleApiService setControl(Control control) {
this.control = control;
return this;
}
/**
* Custom error configuration.
* @return value or {@code null} for none
*/
public CustomError getCustomError() {
return customError;
}
/**
* Custom error configuration.
* @param customError customError or {@code null} for none
*/
public GoogleApiService setCustomError(CustomError customError) {
this.customError = customError;
return this;
}
/**
* Additional API documentation.
* @return value or {@code null} for none
*/
public Documentation getDocumentation() {
return documentation;
}
/**
* Additional API documentation.
* @param documentation documentation or {@code null} for none
*/
public GoogleApiService setDocumentation(Documentation documentation) {
this.documentation = documentation;
return this;
}
/**
* Configuration for network endpoints. If this is empty, then an endpoint with the same name as
* the service is automatically generated to service all defined APIs.
* @return value or {@code null} for none
*/
public java.util.List<Endpoint> getEndpoints() {
return endpoints;
}
/**
* Configuration for network endpoints. If this is empty, then an endpoint with the same name as
* the service is automatically generated to service all defined APIs.
* @param endpoints endpoints or {@code null} for none
*/
public GoogleApiService setEndpoints(java.util.List<Endpoint> endpoints) {
this.endpoints = endpoints;
return this;
}
/**
* A list of all enum types included in this API service. Enums referenced directly or indirectly
* by the `apis` are automatically included. Enums which are not referenced but shall be included
* should be listed here by name by the configuration author. Example: enums: - name:
* google.someapi.v1.SomeEnum
* @return value or {@code null} for none
*/
public java.util.List<ServiceUsageEnum> getEnums() {
return enums;
}
/**
* A list of all enum types included in this API service. Enums referenced directly or indirectly
* by the `apis` are automatically included. Enums which are not referenced but shall be included
* should be listed here by name by the configuration author. Example: enums: - name:
* google.someapi.v1.SomeEnum
* @param enums enums or {@code null} for none
*/
public GoogleApiService setEnums(java.util.List<ServiceUsageEnum> enums) {
this.enums = enums;
return this;
}
/**
* HTTP configuration.
* @return value or {@code null} for none
*/
public Http getHttp() {
return http;
}
/**
* HTTP configuration.
* @param http http or {@code null} for none
*/
public GoogleApiService setHttp(Http http) {
this.http = http;
return this;
}
/**
* A unique ID for a specific instance of this message, typically assigned by the client for
* tracking purpose. Must be no longer than 63 characters and only lower case letters, digits,
* '.', '_' and '-' are allowed. If empty, the server may choose to generate one instead.
* @return value or {@code null} for none
*/
public java.lang.String getId() {
return id;
}
/**
* A unique ID for a specific instance of this message, typically assigned by the client for
* tracking purpose. Must be no longer than 63 characters and only lower case letters, digits,
* '.', '_' and '-' are allowed. If empty, the server may choose to generate one instead.
* @param id id or {@code null} for none
*/
public GoogleApiService setId(java.lang.String id) {
this.id = id;
return this;
}
/**
* Logging configuration.
* @return value or {@code null} for none
*/
public Logging getLogging() {
return logging;
}
/**
* Logging configuration.
* @param logging logging or {@code null} for none
*/
public GoogleApiService setLogging(Logging logging) {
this.logging = logging;
return this;
}
/**
* Defines the logs used by this service.
* @return value or {@code null} for none
*/
public java.util.List<LogDescriptor> getLogs() {
return logs;
}
/**
* Defines the logs used by this service.
* @param logs logs or {@code null} for none
*/
public GoogleApiService setLogs(java.util.List<LogDescriptor> logs) {
this.logs = logs;
return this;
}
/**
* Defines the metrics used by this service.
* @return value or {@code null} for none
*/
public java.util.List<MetricDescriptor> getMetrics() {
return metrics;
}
/**
* Defines the metrics used by this service.
* @param metrics metrics or {@code null} for none
*/
public GoogleApiService setMetrics(java.util.List<MetricDescriptor> metrics) {
this.metrics = metrics;
return this;
}
/**
* Defines the monitored resources used by this service. This is required by the
* Service.monitoring and Service.logging configurations.
* @return value or {@code null} for none
*/
public java.util.List<MonitoredResourceDescriptor> getMonitoredResources() {
return monitoredResources;
}
/**
* Defines the monitored resources used by this service. This is required by the
* Service.monitoring and Service.logging configurations.
* @param monitoredResources monitoredResources or {@code null} for none
*/
public GoogleApiService setMonitoredResources(java.util.List<MonitoredResourceDescriptor> monitoredResources) {
this.monitoredResources = monitoredResources;
return this;
}
/**
* Monitoring configuration.
* @return value or {@code null} for none
*/
public Monitoring getMonitoring() {
return monitoring;
}
/**
* Monitoring configuration.
* @param monitoring monitoring or {@code null} for none
*/
public GoogleApiService setMonitoring(Monitoring monitoring) {
this.monitoring = monitoring;
return this;
}
/**
* The service name, which is a DNS-like logical identifier for the service, such as
* `calendar.googleapis.com`. The service name typically goes through DNS verification to make
* sure the owner of the service also owns the DNS name.
* @return value or {@code null} for none
*/
public java.lang.String getName() {
return name;
}
/**
* The service name, which is a DNS-like logical identifier for the service, such as
* `calendar.googleapis.com`. The service name typically goes through DNS verification to make
* sure the owner of the service also owns the DNS name.
* @param name name or {@code null} for none
*/
public GoogleApiService setName(java.lang.String name) {
this.name = name;
return this;
}
/**
* The Google project that owns this service.
* @return value or {@code null} for none
*/
public java.lang.String getProducerProjectId() {
return producerProjectId;
}
/**
* The Google project that owns this service.
* @param producerProjectId producerProjectId or {@code null} for none
*/
public GoogleApiService setProducerProjectId(java.lang.String producerProjectId) {
this.producerProjectId = producerProjectId;
return this;
}
/**
* Quota configuration.
* @return value or {@code null} for none
*/
public Quota getQuota() {
return quota;
}
/**
* Quota configuration.
* @param quota quota or {@code null} for none
*/
public GoogleApiService setQuota(Quota quota) {
this.quota = quota;
return this;
}
/**
* Output only. The source information for this configuration if available.
* @return value or {@code null} for none
*/
public SourceInfo getSourceInfo() {
return sourceInfo;
}
/**
* Output only. The source information for this configuration if available.
* @param sourceInfo sourceInfo or {@code null} for none
*/
public GoogleApiService setSourceInfo(SourceInfo sourceInfo) {
this.sourceInfo = sourceInfo;
return this;
}
/**
* System parameter configuration.
* @return value or {@code null} for none
*/
public SystemParameters getSystemParameters() {
return systemParameters;
}
/**
* System parameter configuration.
* @param systemParameters systemParameters or {@code null} for none
*/
public GoogleApiService setSystemParameters(SystemParameters systemParameters) {
this.systemParameters = systemParameters;
return this;
}
/**
* A list of all proto message types included in this API service. It serves similar purpose as
* [google.api.Service.types], except that these types are not needed by user-defined APIs.
* Therefore, they will not show up in the generated discovery doc. This field should only be used
* to define system APIs in ESF.
* @return value or {@code null} for none
*/
public java.util.List<Type> getSystemTypes() {
return systemTypes;
}
/**
* A list of all proto message types included in this API service. It serves similar purpose as
* [google.api.Service.types], except that these types are not needed by user-defined APIs.
* Therefore, they will not show up in the generated discovery doc. This field should only be used
* to define system APIs in ESF.
* @param systemTypes systemTypes or {@code null} for none
*/
public GoogleApiService setSystemTypes(java.util.List<Type> systemTypes) {
this.systemTypes = systemTypes;
return this;
}
/**
* The product title for this service, it is the name displayed in Google Cloud Console.
* @return value or {@code null} for none
*/
public java.lang.String getTitle() {
return title;
}
/**
* The product title for this service, it is the name displayed in Google Cloud Console.
* @param title title or {@code null} for none
*/
public GoogleApiService setTitle(java.lang.String title) {
this.title = title;
return this;
}
/**
* A list of all proto message types included in this API service. Types referenced directly or
* indirectly by the `apis` are automatically included. Messages which are not referenced but
* shall be included, such as types used by the `google.protobuf.Any` type, should be listed here
* by name by the configuration author. Example: types: - name: google.protobuf.Int32
* @return value or {@code null} for none
*/
public java.util.List<Type> getTypes() {
return types;
}
/**
* A list of all proto message types included in this API service. Types referenced directly or
* indirectly by the `apis` are automatically included. Messages which are not referenced but
* shall be included, such as types used by the `google.protobuf.Any` type, should be listed here
* by name by the configuration author. Example: types: - name: google.protobuf.Int32
* @param types types or {@code null} for none
*/
public GoogleApiService setTypes(java.util.List<Type> types) {
this.types = types;
return this;
}
/**
* Configuration controlling usage of this service.
* @return value or {@code null} for none
*/
public Usage getUsage() {
return usage;
}
/**
* Configuration controlling usage of this service.
* @param usage usage or {@code null} for none
*/
public GoogleApiService setUsage(Usage usage) {
this.usage = usage;
return this;
}
@Override
public GoogleApiService set(String fieldName, Object value) {
return (GoogleApiService) super.set(fieldName, value);
}
@Override
public GoogleApiService clone() {
return (GoogleApiService) super.clone();
}
}
| |
/*
* Copyright (C) 2014 Eric Butler
*
* 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.tapchatapp.android.client.model;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import com.google.common.collect.ImmutableMap;
import com.tapchatapp.android.R;
import com.tapchatapp.android.app.activity.InvalidConnectionCertActivity;
import com.tapchatapp.android.app.event.BufferAddedEvent;
import com.tapchatapp.android.app.event.BufferChangedEvent;
import com.tapchatapp.android.app.event.BufferRemovedEvent;
import com.tapchatapp.android.app.event.ConnectionChangedEvent;
import com.tapchatapp.android.client.MessageHandler;
import com.tapchatapp.android.app.TapchatApp;
import com.tapchatapp.android.client.TapchatService;
import com.tapchatapp.android.client.message.BufferArchivedMessage;
import com.tapchatapp.android.client.message.BufferEventMessage;
import com.tapchatapp.android.client.message.BufferUnarchivedMessage;
import com.tapchatapp.android.client.message.ConnectedMessage;
import com.tapchatapp.android.client.message.ConnectingCancelledMessage;
import com.tapchatapp.android.client.message.ConnectingFailedMessage;
import com.tapchatapp.android.client.message.ConnectingFinishedMessage;
import com.tapchatapp.android.client.message.ConnectingMessage;
import com.tapchatapp.android.client.message.ConnectingRetryMessage;
import com.tapchatapp.android.client.message.EndOfBacklogMessage;
import com.tapchatapp.android.client.message.InvalidCertMessage;
import com.tapchatapp.android.client.message.MakeBufferMessage;
import com.tapchatapp.android.client.message.MakeServerMessage;
import com.tapchatapp.android.client.message.Message;
import com.tapchatapp.android.client.message.OpenBufferMessage;
import com.tapchatapp.android.client.message.ResponseMessage;
import com.tapchatapp.android.client.message.ServerDetailsChangedMessage;
import com.tapchatapp.android.client.message.SocketClosedMessage;
import com.tapchatapp.android.client.message.WaitingToRetryMessage;
import com.tapchatapp.android.client.message.YouNickchangeMessage;
import com.tapchatapp.android.client.message.request.AcceptCertMessage;
import com.tapchatapp.android.client.message.request.DeleteBufferMessage;
import com.tapchatapp.android.client.message.request.DeleteConnectionMessage;
import com.tapchatapp.android.client.message.request.DisconnectMessage;
import com.tapchatapp.android.client.message.request.EditServerMessage;
import com.tapchatapp.android.client.message.request.JoinMessage;
import com.tapchatapp.android.client.message.request.PartMessage;
import com.tapchatapp.android.client.message.request.ReconnectMessage;
import com.tapchatapp.android.client.message.request.SayMessage;
import org.json.JSONException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class Connection {
public static final int STATE_DISCONNECTED = 0;
public static final int STATE_CONNECTING = 1;
public static final int STATE_RETRYING = 2;
public static final int STATE_CONNECTED = 3;
public static final Comparator<Connection> COMPARATOR = new Comparator<Connection>() {
@Override
public int compare(Connection connection, Connection connection2) {
int result = connection.getName().compareToIgnoreCase(connection2.getName());
if (result == 0) {
result = connection.getHostName().compareToIgnoreCase(connection2.getHostName());
}
return result;
}
};
private static final String TAG = "Connection";
private TapchatService mService;
private boolean mExists = false;
private boolean mIsBacklog = true;
private final Map<Long, Buffer> mBuffers = Collections.synchronizedMap(new TreeMap<Long, Buffer>());
private ConsoleBuffer mConsoleBuffer;
private int mState;
private String mName;
private long mId;
private String mNick;
private boolean mSSL;
private String mHostName;
private String mRealName;
private int mPort;
private String mPassword;
private String mPendingOpenBuffer;
public Connection(TapchatService service, MakeServerMessage message) throws Exception {
mService = service;
/*
{
"bid":-1,
"eid":-1,
"type":"makeserver",
"time":-1,
"highlight":false,
"num_buffers":5,
"cid":2135,
"name":"IRCCloud",
"nick":"fR",
"nickserv_nick":"fR",
"nickserv_pass":"",
"realname":"Eric",
"hostname":"irc.irccloud.com",
"port":6667,
"away":"",
"disconnected":false,
"away_timeout":0,
"autoback":true,
"ssl":false,
"server_pass":""
}
*/
mId = message.cid;
updateDetails(message);
}
public String getName() {
return mName;
}
public String getDisplayName() {
if (!TextUtils.isEmpty(mName)) {
return mName;
} else {
return mHostName;
}
}
public String getDisplayState(Context context) {
switch (mState) {
case STATE_DISCONNECTED:
return context.getString(R.string.disconnected_format, mName);
case Connection.STATE_CONNECTING:
return context.getString(R.string.connecting_format, mName);
case Connection.STATE_RETRYING:
return context.getString(R.string.retrying_format, mName);
case Connection.STATE_CONNECTED:
return context.getString(R.string.connected_format, mName);
}
return null;
}
public long getId() {
return mId;
}
public boolean isBacklog() {
return mIsBacklog;
}
public String getNick() {
return mNick;
}
public ConsoleBuffer getConsoleBuffer() {
return mConsoleBuffer;
}
public List<Buffer> getBuffers() {
synchronized (mBuffers) {
return new ArrayList<Buffer>(mBuffers.values());
}
}
public int getBufferCount() {
synchronized (mBuffers) {
return mBuffers.size();
}
}
public Buffer getBuffer(long id) {
synchronized (mBuffers) {
if (mBuffers.containsKey(id))
return mBuffers.get(id);
else if (mConsoleBuffer != null && mConsoleBuffer.getId() == id)
return mConsoleBuffer;
return null;
}
}
public int getBufferIndex(long bufferId) {
synchronized (mBuffers) {
return getBuffers().indexOf(getBuffer(bufferId));
}
}
public Buffer findBuffer(String name) {
synchronized (mBuffers) {
for (Buffer buffer : mBuffers.values()) {
if (buffer.getName().equalsIgnoreCase(name)) {
return buffer;
}
}
return null;
}
}
public boolean isSSL() {
return mSSL;
}
public String getPassword() {
return mPassword;
}
public String getHostName() {
return mHostName;
}
public String getRealName() {
return mRealName;
}
public int getPort() {
return mPort;
}
public int getState() {
return mState;
}
public void join(String channelName, TapchatService.PostCallback callback) {
ChannelBuffer channel = (ChannelBuffer) findBuffer(channelName);
if (channel != null && channel.isJoined()) {
startBufferActivity(channel);
if (callback != null) {
callback.run(null, null);
}
return;
}
JoinMessage message = new JoinMessage();
message.channel = channelName;
post(message, callback);
}
public void part(String channelName, TapchatService.PostCallback callback) {
PartMessage message = new PartMessage();
message.channel = channelName;
post(message, callback);
}
public void say(String to, String text, TapchatService.PostCallback callback) {
SayMessage message = new SayMessage();
message.to = to;
message.msg = text;
post(message, callback);
}
public void acceptCert(String fingerprint, boolean accept) {
AcceptCertMessage message = new AcceptCertMessage();
message.fingerprint = fingerprint;
message.accept = accept;
post(message, null);
}
public void openBuffer(String nick) {
Buffer buffer = findBuffer(nick);
if (buffer == null) {
say(nick, null, null);
} else {
buffer.unarchive();
startBufferActivity(buffer);
}
}
public void reconnect() {
post(new ReconnectMessage(), null);
}
public void disconnect() {
post(new DisconnectMessage(), null);
}
public void delete() {
post(new DeleteConnectionMessage(), null);
}
public void edit(String name, String hostname, String nickname, String port, String realname, boolean useSSL,
String password, TapchatService.PostCallback callback) {
EditServerMessage message = new EditServerMessage();
message.name = name;
message.hostname = hostname;
message.nickname = nickname;
message.port = port;
message.realname = realname;
message.ssl = useSSL ? "1" : "0";
message.server_pass = password;
// FIXME: Not implemented yet
// message.channels = "";
// message.nspass = "";
post(message, callback);
}
TapchatService getService() {
return mService;
}
public synchronized void processMessage(Message message) throws Exception {
String type = message.type;
if (mMessageHandlers.containsKey(type)) {
mMessageHandlers.get(type).handleMessage(message);
}
boolean isBacklogMessage = message.is_backlog;
if ((!isBacklogMessage) && (!mIsBacklog) && mInitializedMessageHandlers.containsKey(type)) {
mInitializedMessageHandlers.get(type).handleMessage(message);
}
if (message.bid != null && !message.type.equals(MakeBufferMessage.TYPE)) {
Buffer buffer = getBuffer(message.bid);
if (buffer != null) {
buffer.processMessage((BufferEventMessage) message);
}
}
}
public void handleResponse(ResponseMessage response, Message request) {
String type = response.type;
if (type != null && type.equals("open_buffer")) {
String bufferName = ((OpenBufferMessage) response.msg).name;
Buffer buffer = findBuffer(bufferName);
if (buffer == null) {
mPendingOpenBuffer = bufferName;
} else {
startBufferActivity(buffer);
mPendingOpenBuffer = null;
}
}
}
void notifyChanged() {
mService.postToBus(new ConnectionChangedEvent(this));
}
public void reload(MakeServerMessage message) throws JSONException {
updateDetails(message);
// FIXME: Notify all buffers that we're reloading?
}
public void post(Message message, TapchatService.PostCallback callback) {
message.cid = getId();
mService.post(message, callback);
}
private void startBufferActivity(Buffer buffer) {
Context appContext = TapchatApp.get();
Intent intent = new Intent(TapchatApp.ACTION_OPEN_BUFFER);
intent.putExtra("cid", String.valueOf(buffer.getConnection().getId()));
intent.putExtra("bid", String.valueOf(buffer.getId()));
appContext.sendOrderedBroadcast(intent, null);
}
@Override
public String toString() {
return String.format("Connection{id=%s, name=%s}", getId(), getName());
}
private Map<String, MessageHandler> mMessageHandlers = ImmutableMap.<String, MessageHandler>builder()
.put(EndOfBacklogMessage.TYPE, new MessageHandler<EndOfBacklogMessage>() {
@Override
public void handleMessage(EndOfBacklogMessage message) throws Exception {
mIsBacklog = false;
mService.updateLoadingProgress();
synchronized (mBuffers) {
for (Buffer buffer : mBuffers.values()) {
if (!buffer.exists()) {
removeBuffer(buffer);
}
}
}
}
})
.put(MakeBufferMessage.TYPE, new MessageHandler<MakeBufferMessage>() {
@Override public void handleMessage(MakeBufferMessage message) throws Exception {
long bid = message.bid;
Buffer buffer = getBuffer(bid);
if (buffer != null) {
buffer.reload(message);
return;
}
String bufferType = message.buffer_type;
switch (bufferType) {
case "channel":
buffer = new ChannelBuffer(Connection.this, message);
break;
case "conversation":
buffer = new ConversationBuffer(Connection.this, message);
break;
case "console":
buffer = new ConsoleBuffer(Connection.this, message);
mConsoleBuffer = (ConsoleBuffer) buffer;
return;
default:
throw new Exception("Unknown buffer type: " + bufferType);
}
synchronized (mBuffers) {
mBuffers.put(bid, buffer);
}
final Buffer theBuffer = buffer;
mService.postToBus(new BufferAddedEvent(theBuffer));
if (mPendingOpenBuffer != null && mPendingOpenBuffer.equals(buffer.getName())) {
startBufferActivity(buffer);
mPendingOpenBuffer = null;
}
}
})
.build();
private Map<String, MessageHandler> mInitializedMessageHandlers = new ImmutableMap.Builder<String, MessageHandler>()
.put(ServerDetailsChangedMessage.TYPE, new MessageHandler<ServerDetailsChangedMessage>() {
@Override
public void handleMessage(ServerDetailsChangedMessage message) throws Exception {
updateDetails(message);
}
})
.put(YouNickchangeMessage.TYPE, new MessageHandler<YouNickchangeMessage>() {
@Override public void handleMessage(YouNickchangeMessage message) throws Exception {
mNick = message.newnick;
notifyChanged();
}
})
.put(ConnectingMessage.TYPE, new MessageHandler<ConnectingMessage>() {
@Override public void handleMessage(ConnectingMessage message) throws Exception {
mNick = message.nick;
mState = STATE_CONNECTING;
notifyChanged();
}
})
.put(ConnectingRetryMessage.TYPE, new MessageHandler<ConnectingRetryMessage>() {
@Override public void handleMessage(ConnectingRetryMessage message) throws Exception {
mState = STATE_RETRYING;
notifyChanged();
}
})
.put(WaitingToRetryMessage.TYPE, new MessageHandler<WaitingToRetryMessage>() {
@Override public void handleMessage(WaitingToRetryMessage message) throws Exception {
mState = STATE_RETRYING;
notifyChanged();
}
})
.put(ConnectingCancelledMessage.TYPE, new MessageHandler<ConnectingCancelledMessage>() {
@Override public void handleMessage(ConnectingCancelledMessage message) throws Exception {
mState = STATE_DISCONNECTED;
notifyChanged();
}
})
.put(ConnectingFailedMessage.TYPE, new MessageHandler<ConnectingFailedMessage>() {
@Override public void handleMessage(ConnectingFailedMessage message) throws Exception {
mState = STATE_DISCONNECTED;
notifyChanged();
}
})
.put(ConnectedMessage.TYPE, new MessageHandler<ConnectedMessage>() {
@Override public void handleMessage(ConnectedMessage message) throws Exception {
// nop, just means the socket is established, wait for connecting_finished
}
})
.put(ConnectingFinishedMessage.TYPE, new MessageHandler<ConnectingFinishedMessage>() {
@Override public void handleMessage(ConnectingFinishedMessage message) throws Exception {
mState = STATE_CONNECTED;
notifyChanged();
}
})
.put(SocketClosedMessage.TYPE, new MessageHandler<SocketClosedMessage>() {
@Override public void handleMessage(SocketClosedMessage message) throws Exception {
mState = STATE_DISCONNECTED;
notifyChanged();
}
})
.put(InvalidCertMessage.TYPE, new MessageHandler<InvalidCertMessage>() {
@Override public void handleMessage(InvalidCertMessage message) throws Exception {
Context appContext = TapchatApp.get();
Intent intent = new Intent(TapchatApp.ACTION_INVALID_CERT);
intent.putExtra(InvalidConnectionCertActivity.EXTRA_CID, message.cid);
intent.putExtra(InvalidConnectionCertActivity.EXTRA_HOSTNAME, message.hostname);
intent.putExtra(InvalidConnectionCertActivity.EXTRA_FINGERPRINT, message.fingerprint);
intent.putExtra(InvalidConnectionCertActivity.EXTRA_ERROR, message.error);
appContext.sendBroadcast(intent, null);
}
})
.put(DeleteBufferMessage.TYPE, new MessageHandler<DeleteBufferMessage>() {
@Override public void handleMessage(DeleteBufferMessage message) throws Exception {
Buffer buffer = getBuffer(message.bid);
removeBuffer(buffer);
}
})
.put(BufferArchivedMessage.TYPE, new MessageHandler<BufferArchivedMessage>() {
@Override public void handleMessage(BufferArchivedMessage message) throws Exception {
Buffer buffer = getBuffer(message.bid);
buffer.setArchived(true);
mService.postToBus(new BufferChangedEvent(buffer));
}
})
.put(BufferUnarchivedMessage.TYPE, new MessageHandler<BufferUnarchivedMessage>() {
@Override public void handleMessage(BufferUnarchivedMessage message) throws Exception {
long bid = message.bid;
Buffer buffer = getBuffer(bid);
buffer.setArchived(false);
mService.postToBus(new BufferChangedEvent(buffer));
}
})
.build();
private void removeBuffer(Buffer buffer) {
buffer.notifyRemoved();
synchronized (mBuffers) {
mBuffers.remove(buffer.getId());
}
mService.postToBus(new BufferRemovedEvent(buffer));
}
private void updateDetails(ServerDetailsChangedMessage message) throws JSONException {
mExists = true;
mName = message.name;
mNick = message.nick;
mRealName = message.realname;
mHostName = message.hostname;
mPort = message.port;
mSSL = message.ssl;
mPassword = message.server_pass;
mIsBacklog = (mService.getConnectionState() != TapchatService.STATE_LOADED);
if (message.disconnected) {
// FIXME: What if the state should be "connecting"?
mState = STATE_DISCONNECTED;
} else {
mState = STATE_CONNECTED;
}
notifyChanged();
}
public void serviceDisconnected() {
mExists = false;
synchronized (mBuffers) {
for (Buffer buffer : mBuffers.values()) {
buffer.serviceDisconnected();
}
}
}
public boolean exists() {
return mExists;
}
}
| |
package ch.unibas.dmi.dbis.reqman.ui.common;
import ch.unibas.dmi.dbis.reqman.common.Version;
import ch.unibas.dmi.dbis.reqman.data.Milestone;
import ch.unibas.dmi.dbis.reqman.ui.svg.SVGLoader;
import ch.unibas.dmi.dbis.reqman.ui.svg.SVGNode;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import org.jetbrains.annotations.NotNull;
import org.kordamp.ikonli.javafx.FontIcon;
import org.kordamp.ikonli.openiconic.Openiconic;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
/**
* TODO: write JavaDoc
*
* @author loris.sauter
*/
public class Utils {
public static final String ARROW_DOWN = "\u25bc";
public static final String HEAVY_PLUS = "\u2795";
public static final String HEAVY_MINUS = "\u2212";
public static final String ARROW_UP = "\u25b2";
public static final String DASHICONS_CARET_UP = "dashicons-arrow-up";
public static final String DASHICONS_CARET_DOWN = "dashicons-arrow-down";
public static final String DASHICONS_CARET_UP_ALT = "dashicons-up-alt2";
public static final String DASHICONS_CARET_DONW_ALT = "dashicons-down-alt2";
public static final String DASHICONS_PLUS_THIN = "dashicons-plus-light";
public static final String DASHICONS_MINUS_THIN = "dashicons-minus-light";
public static final int ICON_WIDHT = 15; // px, totally magic
public static final FileChooser.ExtensionFilter[] JSON_ANY_FILTER = new FileChooser.ExtensionFilter[]{
new FileChooser.ExtensionFilter("JSON", "*.json"),
new FileChooser.ExtensionFilter("Any", "*.*")
};
private static Node arrowDownIcon = null;
private static Node arrowUpIcon = null;
private static List<Image> iconList = null;
public static List<Image> getIconList() {
if (iconList == null) {
List<String> pathList = new ArrayList<>();
iconList = new ArrayList<>();
for (int i = 16; i <= 1024; i *= 2) {
pathList.add("logo/logo" + i + ".png");
}
pathList.sort(Comparator.reverseOrder());
pathList.forEach(path -> iconList.add(new Image(Utils.class.getClassLoader().getResourceAsStream(path))));
}
return iconList;
}
public static void applyLogoIcon(Stage s) {
s.getIcons().addAll(getIconList());
}
/**
* Creates the widely used {@link GridPane} with its default styling.
*
* @return
*/
public static GridPane generateDefaultGridPane() {
GridPane grid = new GridPane();
applyDefaultGridSetup(grid);
return grid;
}
public static void applyDefaultGridSetup(GridPane grid) {
grid.setStyle("-fx-padding: 10px; -fx-spacing: 10px; -fx-hgap: 10px;-fx-vgap: 10px");
}
public static void applyDefaultFineGridSpacing(GridPane grid) {
grid.setStyle("-fx-padding: 2px; -fx-spacing: 2px; -fx-hgap: 2px;-fx-vgap: 1px");
}
public static void showInfoDialog(String title, String header, String content) {
showDialog(Alert.AlertType.INFORMATION, title, header, content);
}
public static void showInfoDialog(String header, String content) {
showInfoDialog("Information", header, content);
}
public static void showWarningDialog(String title, String header, String content) {
showDialog(Alert.AlertType.WARNING, title, header, content);
}
public static void showWarningDialog(String header, String content) {
showWarningDialog("Warning", header, content);
}
public static void showErrorDialog(String title, String header, String content) {
showDialog(Alert.AlertType.ERROR, title, header, content);
}
public static void showErrorDialog(String header, String content) {
showErrorDialog("Error", header, content);
}
public static Button createArrowUpButton() {
try {
SVGNode node = SVGLoader.getInstance().load("feather/chevron-up");
return new Button("", node);
} catch (IOException e) {
return new Button(ARROW_UP);
}
}
public static Button createArrowUpButton(boolean unicode) {
return createArrowButton(unicode, ARROW_UP, Openiconic.CARET_TOP);
}
public static Button createArrowDownButton() {
try {
SVGNode node = SVGLoader.getInstance().load("feather/chevron-down");
return new Button("", node);
} catch (IOException e) {
return new Button(ARROW_DOWN);
}
}
public static Button createArrowDownButton(boolean unicode) {
return unicode ? createUnicodCaretDown() : createArrowButton(unicode, ARROW_DOWN, Openiconic.CARET_BOTTOM);
}
public static Button createPlusButton() {
return createPlusButton(false);
}
public static Button createPlusButton(boolean unicode) {
if (unicode) {
return new Button(HEAVY_PLUS);
} else {
/*FontIcon fi = new FontIcon(Openiconic.PLUS);
fi.setIconSize(ICON_WIDHT);
return new Button("",fi);*/
try {
SVGNode node = SVGLoader.getInstance().load("feather/plus");
return new Button("", node);
} catch (IOException e) {
return new Button(HEAVY_PLUS);
}
}
}
public static Button createMinusButton() {
return createMinusButton(false);
}
public static Button createMinusButton(boolean unicode) {
if (unicode) {
return new Button(HEAVY_MINUS);
} else {
/* FontIcon fi = new FontIcon(Openiconic.MINUS);
fi.setIconSize(ICON_WIDHT);
return new Button("",fi);*/
try {
SVGNode node = SVGLoader.getInstance().load("feather/minus");
return new Button("", node);
} catch (IOException e) {
return new Button(HEAVY_MINUS);
}
}
}
public static ToggleButton createArrowUpToggle() {
return new ToggleButton("", arrowUpIcon);
}
public static Node createArrowUpNode() {
if (arrowUpIcon == null) {
try {
arrowUpIcon = SVGLoader.getInstance().load("feather/chevron-up");
} catch (IOException e) {
arrowUpIcon = new Label(ARROW_UP);
}
} else if (arrowUpIcon instanceof SVGNode) {
return ((SVGNode) arrowUpIcon).copy();
}
return arrowUpIcon;
}
public static ToggleButton createArrowDownToggle() {
return new ToggleButton("", createArrowDownNode());
}
public static FileChooser createCatalogueFileChooser(String action) {
FileChooser fc = new FileChooser();
fc.setTitle(action + " Catalogue");
fc.getExtensionFilters().addAll(JSON_ANY_FILTER);
return fc;
}
public static FileChooser createGroupFileChooser(String action) {
FileChooser fc = new FileChooser();
fc.setTitle(action + " Group");
fc.getExtensionFilters().addAll(JSON_ANY_FILTER);
return fc;
}
/**
* Creates a hfill element, similar to the latex {@code \hfill}.
* Suggested by <a href="https://stackoverflow.com/a/40884079">this SO answer</a>
*
* @return An hfill / rubber element, growing horizontally
*/
public static Node createHFill() {
final Region r = new Region();
HBox.setHgrow(r, Priority.ALWAYS);
return r;
}
public static boolean showConfirmationDialog(String header, String content) {
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setTitle("Caution");
alert.setHeaderText(header);
alert.setContentText(content);
Optional<ButtonType> out = alert.showAndWait();
if (out.isPresent()) {
return out.get().equals(ButtonType.OK);
}
return false;
}
public static void showFeatureDisabled(String featureName, String reason) {
showWarningDialog("Feature Disabled", String.format("Feature %s disabled", featureName), String.format("The feature %s, is in the current version (%s) disabled.\n\nThe reason for this is:\n%s", featureName, Version.getInstance().getVersion(), reason));
}
public static void showFeatureDisabled(String featureName) {
showFeatureDisabled(featureName, "");
}
public static DirectoryChooser createDirectoryChooser(String title) {
DirectoryChooser dc = new DirectoryChooser();
dc.setTitle(title);
return dc;
}
public static FileChooser createFileChooser(String title) {
FileChooser fc = new FileChooser();
fc.setTitle(title);
return fc;
}
public static void applyDefaultSpacing(Node node) {
node.setStyle("-fx-padding: 10px; -fx-spacing: 10px;" + node.getStyle());
}
public static Node createArrowDownNode() {
if (arrowDownIcon == null) {
try {
arrowDownIcon = SVGLoader.getInstance().load("feather/chevron-down");
} catch (IOException e) {
arrowDownIcon = new Label(ARROW_DOWN);
}
} else if (arrowDownIcon instanceof SVGNode) {
return ((SVGNode) arrowDownIcon).copy();
}
return arrowDownIcon;
}
@NotNull
private static Button createArrowButton(boolean unicode, String arrowUp, Openiconic icon) {
if (unicode) {
return createUnicodCaretUp();
} else {
FontIcon fi = new FontIcon(icon);
fi.setIconSize(ICON_WIDHT);
return new Button("", fi);
}
}
private static Button createUnicodCaretUp() {
Button b = new Button(ARROW_UP);
b.setStyle("-fx-text-fill: dimgray;");
return b;
}
private static Button createUnicodCaretDown() {
Button b = new Button(ARROW_DOWN);
b.setStyle("-fx-text-fill: dimgray;");
return b;
}
private static void showDialog(Alert.AlertType type, String title, String header, String content) {
Alert alert = new Alert(type);
alert.setTitle(title);
alert.setHeaderText(header);
alert.setContentText(content);
alert.showAndWait();
}
public static class MilestoneCell extends ListCell<Milestone> {
@Override
public void updateItem(Milestone item, boolean empty) {
super.updateItem(item, empty);
if (!empty) {
setText(item.getName());
} else {
setText("");
}
}
}
}
| |
/*
* 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 gov.nasa.jpl.mudrod.weblog.pre;
import gov.nasa.jpl.mudrod.driver.ESDriver;
import gov.nasa.jpl.mudrod.driver.SparkDriver;
import gov.nasa.jpl.mudrod.main.MudrodConstants;
import gov.nasa.jpl.mudrod.weblog.structure.RequestUrl;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.api.java.function.Function2;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.metrics.stats.Stats;
import org.elasticsearch.search.aggregations.metrics.stats.StatsAggregationBuilder;
import org.joda.time.DateTime;
import org.joda.time.Seconds;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
/**
* Supports ability to post-process session, including summarizing statistics
* and filtering
*/
public class SessionStatistic extends LogAbstract {
/**
*
*/
private static final long serialVersionUID = 1L;
private static final Logger LOG = LoggerFactory.getLogger(SessionStatistic.class);
public SessionStatistic(Properties props, ESDriver es, SparkDriver spark) {
super(props, es, spark);
}
@Override
public Object execute() {
LOG.info("Starting Session Summarization.");
startTime = System.currentTimeMillis();
try {
processSession();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
endTime = System.currentTimeMillis();
es.refreshIndex();
LOG.info("Session Summarization complete. Time elapsed {} seconds.", (endTime - startTime) / 1000);
return null;
}
public void processSession() throws InterruptedException, IOException, ExecutionException {
String processingType = props.getProperty(MudrodConstants.PROCESS_TYPE);
if (processingType.equals("sequential")) {
processSessionInSequential();
} else if (processingType.equals("parallel")) {
processSessionInParallel();
}
}
public void processSessionInSequential() throws IOException, InterruptedException, ExecutionException {
es.createBulkProcessor();
Terms Sessions = this.getSessionTerms();
int session_count = 0;
for (Terms.Bucket entry : Sessions.getBuckets()) {
if (entry.getDocCount() >= 3 && !entry.getKey().equals("invalid")) {
String sessionid = entry.getKey().toString();
int sessionNum = processSession(es, sessionid);
session_count += sessionNum;
}
}
LOG.info("Final Session count: {}", Integer.toString(session_count));
es.destroyBulkProcessor();
}
/**
* Extract the dataset ID from a long request
*
* @param request raw log request
* @return dataset ID
*/
public String findDataset(String request) {
String pattern1 = "/dataset/";
String pattern2;
if (request.contains("?")) {
pattern2 = "?";
} else {
pattern2 = " ";
}
Pattern p = Pattern.compile(Pattern.quote(pattern1) + "(.*?)" + Pattern.quote(pattern2));
Matcher m = p.matcher(request);
if (m.find()) {
return m.group(1);
}
return null;
}
public void processSessionInParallel() throws InterruptedException, IOException {
List<String> sessions = this.getSessions();
JavaRDD<String> sessionRDD = spark.sc.parallelize(sessions, partition);
int sessionCount = 0;
sessionCount = sessionRDD.mapPartitions(new FlatMapFunction<Iterator<String>, Integer>() {
@Override
public Iterator<Integer> call(Iterator<String> arg0) throws Exception {
ESDriver tmpES = new ESDriver(props);
tmpES.createBulkProcessor();
List<Integer> sessionNums = new ArrayList<Integer>();
sessionNums.add(0);
while (arg0.hasNext()) {
String s = arg0.next();
Integer sessionNum = processSession(tmpES, s);
sessionNums.add(sessionNum);
}
tmpES.destroyBulkProcessor();
tmpES.close();
return sessionNums.iterator();
}
}).reduce(new Function2<Integer, Integer, Integer>() {
@Override
public Integer call(Integer a, Integer b) {
return a + b;
}
});
LOG.info("Final Session count: {}", Integer.toString(sessionCount));
}
public int processSession(ESDriver es, String sessionId) throws IOException, InterruptedException, ExecutionException {
String inputType = cleanupType;
String outputType = sessionStats;
DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
String min = null;
String max = null;
DateTime start = null;
DateTime end = null;
int duration = 0;
float request_rate = 0;
int session_count = 0;
Pattern pattern = Pattern.compile("get (.*?) http/*");
StatsAggregationBuilder statsAgg = AggregationBuilders.stats("Stats").field("Time");
BoolQueryBuilder filter_search = new BoolQueryBuilder();
filter_search.must(QueryBuilders.termQuery("SessionID", sessionId));
SearchResponse sr = es.getClient().prepareSearch(logIndex).setTypes(inputType).setQuery(filter_search).addAggregation(statsAgg).execute().actionGet();
Stats agg = sr.getAggregations().get("Stats");
min = agg.getMinAsString();
max = agg.getMaxAsString();
start = fmt.parseDateTime(min);
end = fmt.parseDateTime(max);
duration = Seconds.secondsBetween(start, end).getSeconds();
int searchDataListRequest_count = 0;
int searchDataRequest_count = 0;
int searchDataListRequest_byKeywords_count = 0;
int ftpRequest_count = 0;
int keywords_num = 0;
String IP = null;
String keywords = "";
String views = "";
String downloads = "";
SearchResponse scrollResp = es.getClient().prepareSearch(logIndex).setTypes(inputType).setScroll(new TimeValue(60000)).setQuery(filter_search).setSize(100).execute().actionGet();
while (true) {
for (SearchHit hit : scrollResp.getHits().getHits()) {
Map<String, Object> result = hit.getSource();
String request = (String) result.get("Request");
String logType = (String) result.get("LogType");
IP = (String) result.get("IP");
Matcher matcher = pattern.matcher(request.trim().toLowerCase());
while (matcher.find()) {
request = matcher.group(1);
}
String datasetlist = "/datasetlist?";
String dataset = "/dataset/";
if (request.contains(datasetlist)) {
searchDataListRequest_count++;
RequestUrl requestURL = new RequestUrl();
String infoStr = requestURL.getSearchInfo(request) + ",";
String info = es.customAnalyzing(props.getProperty("indexName"), infoStr);
if (!info.equals(",")) {
if (keywords.equals("")) {
keywords = keywords + info;
} else {
String[] items = info.split(",");
String[] keywordList = keywords.split(",");
for (int m = 0; m < items.length; m++) {
if (!Arrays.asList(keywordList).contains(items[m])) {
keywords = keywords + items[m] + ",";
}
}
}
}
}
if (request.startsWith(dataset)) {
searchDataRequest_count++;
if (findDataset(request) != null) {
String view = findDataset(request);
if ("".equals(views)) {
views = view;
} else {
if (views.contains(view)) {
} else {
views = views + "," + view;
}
}
}
}
if ("ftp".equals(logType)) {
ftpRequest_count++;
String download = "";
String requestLowercase = request.toLowerCase();
if (requestLowercase.endsWith(".jpg") == false && requestLowercase.endsWith(".pdf") == false && requestLowercase.endsWith(".txt") == false && requestLowercase.endsWith(".gif") == false) {
download = request;
}
if ("".equals(downloads)) {
downloads = download;
} else {
if (downloads.contains(download)) {
} else {
downloads = downloads + "," + download;
}
}
}
}
scrollResp = es.getClient().prepareSearchScroll(scrollResp.getScrollId()).setScroll(new TimeValue(600000)).execute().actionGet();
// Break condition: No hits are returned
if (scrollResp.getHits().getHits().length == 0) {
break;
}
}
if (!keywords.equals("")) {
keywords_num = keywords.split(",").length;
}
if (searchDataListRequest_count != 0 && searchDataListRequest_count <= Integer.parseInt(props.getProperty("searchf")) && searchDataRequest_count != 0 && searchDataRequest_count <= Integer
.parseInt(props.getProperty("viewf")) && ftpRequest_count <= Integer.parseInt(props.getProperty("downloadf"))) {
String sessionURL = props.getProperty("SessionPort") + props.getProperty("SessionUrl") + "?sessionid=" + sessionId + "&sessionType=" + outputType + "&requestType=" + inputType;
session_count = 1;
IndexRequest ir = new IndexRequest(logIndex, outputType).source(
jsonBuilder().startObject().field("SessionID", sessionId).field("SessionURL", sessionURL).field("Duration", duration).field("Number of Keywords", keywords_num).field("Time", min)
.field("End_time", max).field("searchDataListRequest_count", searchDataListRequest_count).field("searchDataListRequest_byKeywords_count", searchDataListRequest_byKeywords_count)
.field("searchDataRequest_count", searchDataRequest_count).field("keywords", es.customAnalyzing(logIndex, keywords)).field("views", views).field("downloads", downloads)
.field("request_rate", request_rate).field("Comments", "").field("Validation", 0).field("Produceby", 0).field("Correlation", 0).field("IP", IP).endObject());
es.getBulkProcessor().add(ir);
}
return session_count;
}
@Override
public Object execute(Object o) {
return null;
}
}
| |
/*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.hint;
import com.intellij.codeInsight.lookup.Lookup;
import com.intellij.codeInsight.lookup.LookupManager;
import com.intellij.codeInsight.lookup.impl.LookupImpl;
import com.intellij.lang.parameterInfo.*;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.RangeMarker;
import com.intellij.openapi.editor.ScrollType;
import com.intellij.openapi.editor.event.*;
import com.intellij.openapi.editor.impl.EditorImpl;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.Pair;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.ui.LightweightHint;
import com.intellij.util.Alarm;
import com.intellij.util.ArrayUtil;
import com.intellij.util.text.CharArrayUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.awt.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.List;
public class ParameterInfoController implements Disposable {
private final Project myProject;
@NotNull private final Editor myEditor;
private final RangeMarker myLbraceMarker;
private final LightweightHint myHint;
private final ParameterInfoComponent myComponent;
private final CaretListener myEditorCaretListener;
@NotNull private final ParameterInfoHandler<Object, Object> myHandler;
private final ShowParameterInfoHandler.BestLocationPointProvider myProvider;
private final Alarm myAlarm = new Alarm();
private static final int DELAY = 200;
private boolean myDisposed = false;
/**
* Keeps Vector of ParameterInfoController's in Editor
*/
private static final Key<List<ParameterInfoController>> ALL_CONTROLLERS_KEY = Key.create("ParameterInfoController.ALL_CONTROLLERS_KEY");
public static ParameterInfoController findControllerAtOffset(Editor editor, int offset) {
List<ParameterInfoController> allControllers = getAllControllers(editor);
for (int i = 0; i < allControllers.size(); ++i) {
ParameterInfoController controller = allControllers.get(i);
if (controller.myLbraceMarker.getStartOffset() == offset) {
if (controller.myHint.isVisible()) return controller;
Disposer.dispose(controller);
--i;
}
}
return null;
}
public Object[] getSelectedElements() {
ParameterInfoContext context = new ParameterInfoContext() {
@Override
public Project getProject() {
return myProject;
}
@Override
public PsiFile getFile() {
return myComponent.getParameterOwner().getContainingFile();
}
@Override
public int getOffset() {
return myEditor.getCaretModel().getOffset();
}
@Override
@NotNull
public Editor getEditor() {
return myEditor;
}
};
if (!myHandler.tracksParameterIndex()) {
return myHandler.getParametersForDocumentation(myComponent.getObjects()[0],context);
}
final Object[] objects = myComponent.getObjects();
int selectedParameterIndex = myComponent.getCurrentParameterIndex();
List<Object> params = new ArrayList<Object>(objects.length);
final Object highlighted = myComponent.getHighlighted();
for(Object o:objects) {
if (highlighted != null && !o.equals(highlighted)) continue;
collectParams(context, selectedParameterIndex, params, o);
}
//choose anything when highlighted is not applicable
if (highlighted != null && params.isEmpty()) {
for (Object o : objects) {
collectParams(context, selectedParameterIndex, params, o);
}
}
return ArrayUtil.toObjectArray(params);
}
private void collectParams(ParameterInfoContext context, int selectedParameterIndex, List<Object> params, Object o) {
final Object[] availableParams = myHandler.getParametersForDocumentation(o, context);
if (availableParams != null &&
selectedParameterIndex < availableParams.length &&
selectedParameterIndex >= 0
) {
params.add(availableParams[selectedParameterIndex]);
}
}
private static List<ParameterInfoController> getAllControllers(@NotNull Editor editor) {
List<ParameterInfoController> array = editor.getUserData(ALL_CONTROLLERS_KEY);
if (array == null){
array = new ArrayList<ParameterInfoController>();
editor.putUserData(ALL_CONTROLLERS_KEY, array);
}
return array;
}
public static boolean isAlreadyShown(Editor editor, int lbraceOffset) {
return findControllerAtOffset(editor, lbraceOffset) != null;
}
public ParameterInfoController(@NotNull Project project,
@NotNull Editor editor,
int lbraceOffset,
@NotNull LightweightHint hint,
@NotNull ParameterInfoHandler handler,
@NotNull ShowParameterInfoHandler.BestLocationPointProvider provider) {
myProject = project;
myEditor = editor;
myHandler = handler;
myProvider = provider;
myLbraceMarker = editor.getDocument().createRangeMarker(lbraceOffset, lbraceOffset);
myHint = hint;
myComponent = (ParameterInfoComponent)myHint.getComponent();
List<ParameterInfoController> allControllers = getAllControllers(myEditor);
allControllers.add(this);
myEditorCaretListener = new CaretAdapter(){
@Override
public void caretPositionChanged(CaretEvent e) {
myAlarm.cancelAllRequests();
addAlarmRequest();
}
};
myEditor.getCaretModel().addCaretListener(myEditorCaretListener);
myEditor.getDocument().addDocumentListener(new DocumentAdapter() {
@Override
public void documentChanged(DocumentEvent e) {
myAlarm.cancelAllRequests();
addAlarmRequest();
}
}, this);
PropertyChangeListener lookupListener = new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (LookupManager.PROP_ACTIVE_LOOKUP.equals(evt.getPropertyName())) {
final LookupImpl lookup = (LookupImpl)evt.getNewValue();
if (lookup != null && lookup.isShown()) {
adjustPositionForLookup(lookup);
}
}
}
};
LookupManager.getInstance(project).addPropertyChangeListener(lookupListener, this);
updateComponent();
if (myEditor instanceof EditorImpl) {
Disposer.register(((EditorImpl)myEditor).getDisposable(), this);
}
}
@Override
public void dispose(){
if (myDisposed) return;
myDisposed = true;
List<ParameterInfoController> allControllers = getAllControllers(myEditor);
allControllers.remove(this);
myEditor.getCaretModel().removeCaretListener(myEditorCaretListener);
}
private void adjustPositionForLookup(@NotNull Lookup lookup) {
if (!myHint.isVisible() || myEditor.isDisposed()) {
Disposer.dispose(this);
return;
}
HintManagerImpl hintManager = HintManagerImpl.getInstanceImpl();
short constraint = lookup.isPositionedAboveCaret() ? HintManager.UNDER : HintManager.ABOVE;
Point p = hintManager.getHintPosition(myHint, myEditor, constraint);
//Dimension hintSize = myHint.getComponent().getPreferredSize();
//JLayeredPane layeredPane = myEditor.getComponent().getRootPane().getLayeredPane();
//p.x = Math.min(p.x, layeredPane.getWidth() - hintSize.width);
//p.x = Math.max(p.x, 0);
myHint.pack();
myHint.updateLocation(p.x, p.y);
}
private void addAlarmRequest(){
Runnable request = new Runnable(){
@Override
public void run(){
if (!myDisposed && !myProject.isDisposed()) {
DumbService.getInstance(myProject).withAlternativeResolveEnabled(new Runnable() {
@Override
public void run() {
updateComponent();
}
});
}
}
};
myAlarm.addRequest(request, DELAY, ModalityState.stateForComponent(myEditor.getComponent()));
}
private void updateComponent(){
if (!myHint.isVisible()){
Disposer.dispose(this);
return;
}
PsiDocumentManager.getInstance(myProject).commitAllDocuments();
final PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(myEditor.getDocument());
CharSequence chars = myEditor.getDocument().getCharsSequence();
final int offset = CharArrayUtil.shiftBackward(chars, myEditor.getCaretModel().getOffset() - 1, " \t") + 1;
final UpdateParameterInfoContext context = new MyUpdateParameterInfoContext(offset, file);
final Object elementForUpdating = myHandler.findElementForUpdatingParameterInfo(context);
if (elementForUpdating != null) {
myHandler.updateParameterInfo(elementForUpdating, context);
if (!myDisposed && myHint.isVisible() && myEditor.getComponent().getRootPane() != null) {
myComponent.update();
Pair<Point,Short> pos = myProvider.getBestPointPosition(myHint, (PsiElement)elementForUpdating, offset, true, HintManager.UNDER);
HintManagerImpl.adjustEditorHintPosition(myHint, myEditor, pos.getFirst(), pos.getSecond());
}
}
else {
context.removeHint();
}
}
public static boolean hasPrevOrNextParameter(Editor editor, int lbraceOffset, boolean isNext) {
ParameterInfoController controller = findControllerAtOffset(editor, lbraceOffset);
return controller != null && controller.getPrevOrNextParameterOffset(isNext) != -1;
}
public static void prevOrNextParameter(Editor editor, int lbraceOffset, boolean isNext) {
ParameterInfoController controller = findControllerAtOffset(editor, lbraceOffset);
int newOffset = controller != null ? controller.getPrevOrNextParameterOffset(isNext) : -1;
if (newOffset != -1) {
controller.moveToParameterAtOffset(newOffset);
}
}
private void moveToParameterAtOffset(int offset) {
PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(myEditor.getDocument());
PsiElement argsList = findArgumentList(file, offset, -1);
if (argsList == null) return;
myEditor.getCaretModel().moveToOffset(offset);
myEditor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
myEditor.getSelectionModel().removeSelection();
myHandler.updateParameterInfo(argsList, new MyUpdateParameterInfoContext(offset, file));
}
private int getPrevOrNextParameterOffset(boolean isNext) {
if (!(myHandler instanceof ParameterInfoHandlerWithTabActionSupport)) return -1;
int offset = CharArrayUtil.shiftBackward(myEditor.getDocument().getCharsSequence(), myEditor.getCaretModel().getOffset() - 1, " \t") + 1;
int lbraceOffset = myLbraceMarker.getStartOffset();
PsiFile file = PsiDocumentManager.getInstance(myProject).getPsiFile(myEditor.getDocument());
PsiElement argList = lbraceOffset < offset ? findArgumentList(file, offset, lbraceOffset) : null;
if (argList == null) return -1;
ParameterInfoHandlerWithTabActionSupport handler = (ParameterInfoHandlerWithTabActionSupport)myHandler;
int currentParameterIndex = ParameterInfoUtils.getCurrentParameterIndex(argList.getNode(), offset, handler.getActualParameterDelimiterType());
if (currentParameterIndex == -1) return -1;
@SuppressWarnings("unchecked") PsiElement[] parameters = handler.getActualParameters(argList);
int prevOrNextParameterIndex = isNext && currentParameterIndex < parameters.length - 1 ? currentParameterIndex + 1 :
!isNext && currentParameterIndex > 0 ? currentParameterIndex - 1 : -1;
return prevOrNextParameterIndex != -1 ? parameters[prevOrNextParameterIndex].getTextRange().getStartOffset() : -1;
}
@Nullable
public static <E extends PsiElement> E findArgumentList(PsiFile file, int offset, int lbraceOffset){
if (file == null) return null;
ParameterInfoHandler[] handlers = ShowParameterInfoHandler.getHandlers(file.getProject(), PsiUtilCore.getLanguageAtOffset(file, offset), file.getViewProvider().getBaseLanguage());
if (handlers != null) {
for(ParameterInfoHandler handler:handlers) {
if (handler instanceof ParameterInfoHandlerWithTabActionSupport) {
final ParameterInfoHandlerWithTabActionSupport parameterInfoHandler2 = (ParameterInfoHandlerWithTabActionSupport)handler;
// please don't remove typecast in the following line; it's required to compile the code under old JDK 6 versions
final E e = (E) ParameterInfoUtils.findArgumentList(file, offset, lbraceOffset, parameterInfoHandler2);
if (e != null) return e;
}
}
}
return null;
}
private class MyUpdateParameterInfoContext implements UpdateParameterInfoContext {
private final int myOffset;
private final PsiFile myFile;
public MyUpdateParameterInfoContext(final int offset, final PsiFile file) {
myOffset = offset;
myFile = file;
}
@Override
public int getParameterListStart() {
return myLbraceMarker.getStartOffset();
}
@Override
public int getOffset() {
return myOffset;
}
@Override
public Project getProject() {
return myProject;
}
@Override
public PsiFile getFile() {
return myFile;
}
@Override
@NotNull
public Editor getEditor() {
return myEditor;
}
@Override
public void removeHint() {
myHint.hide();
Disposer.dispose(ParameterInfoController.this);
}
@Override
public void setParameterOwner(final PsiElement o) {
myComponent.setParameterOwner(o);
}
@Override
public PsiElement getParameterOwner() {
return myComponent.getParameterOwner();
}
@Override
public void setHighlightedParameter(final Object method) {
myComponent.setHighlightedParameter(method);
}
@Override
public void setCurrentParameter(final int index) {
myComponent.setCurrentParameterIndex(index);
}
@Override
public boolean isUIComponentEnabled(int index) {
return myComponent.isEnabled(index);
}
@Override
public void setUIComponentEnabled(int index, boolean b) {
myComponent.setEnabled(index, b);
}
@Override
public Object[] getObjectsToView() {
return myComponent.getObjects();
}
}
}
| |
package org.docksidestage.hangar.dbflute.dtomapper.bs;
import java.io.Serializable;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import org.dbflute.Entity;
import org.dbflute.dbmeta.DBMeta;
import org.dbflute.dbmeta.InstanceKeyEntity;
import org.dbflute.dbmeta.dtomap.DtoMapper;
import org.dbflute.dbmeta.dtomap.InstanceKeyDto;
import org.dbflute.helper.beans.DfBeanDesc;
import org.dbflute.helper.beans.DfPropertyDesc;
import org.dbflute.helper.beans.factory.DfBeanDescFactory;
import org.dbflute.jdbc.Classification;
import org.docksidestage.hangar.dbflute.exentity.*;
import org.docksidestage.hangar.simpleflute.dto.*;
import org.docksidestage.hangar.dbflute.dtomapper.*;
/**
* The DTO mapper of WHITE_DATE_TERM as TABLE. <br>
* <pre>
* [primary-key]
* DATE_TERM_ID
*
* [column]
* DATE_TERM_ID, DATE_TERM_VALUE, BEGIN_DATE, END_DATE
*
* [sequence]
*
*
* [identity]
*
*
* [version-no]
*
*
* [foreign-table]
*
*
* [referrer-table]
*
*
* [foreign-property]
*
*
* [referrer-property]
*
* </pre>
* @author DBFlute(AutoGenerator)
*/
public abstract class BsWhiteDateTermDtoMapper implements DtoMapper<WhiteDateTerm, WhiteDateTermDto>, Serializable {
// ===================================================================================
// Definition
// ==========
/** The serial version UID for object serialization. (Default) */
private static final long serialVersionUID = 1L;
// ===================================================================================
// Attribute
// =========
protected final Map<Entity, Object> _relationDtoMap;
protected final Map<Object, Entity> _relationEntityMap;
protected boolean _exceptCommonColumn;
protected boolean _reverseReference; // default: one-way reference
protected boolean _instanceCache = true; // default: cached
// ===================================================================================
// Constructor
// ===========
public BsWhiteDateTermDtoMapper() {
_relationDtoMap = new HashMap<Entity, Object>();
_relationEntityMap = new HashMap<Object, Entity>();
}
public BsWhiteDateTermDtoMapper(Map<Entity, Object> relationDtoMap, Map<Object, Entity> relationEntityMap) {
_relationDtoMap = relationDtoMap;
_relationEntityMap = relationEntityMap;
}
// ===================================================================================
// Mapping
// =======
// -----------------------------------------------------
// to DTO
// ------
/**
* {@inheritDoc}
*/
public WhiteDateTermDto mappingToDto(WhiteDateTerm entity) {
if (entity == null) {
return null;
}
WhiteDateTermDto dto = new WhiteDateTermDto();
dto.setDateTermId(entity.getDateTermId());
dto.setDateTermValue(entity.getDateTermValue());
dto.setBeginDate(entity.getBeginDate());
dto.setEndDate(entity.getEndDate());
reflectDerivedProperty(entity, dto, true);
return dto;
}
/**
* {@inheritDoc}
*/
public List<WhiteDateTermDto> mappingToDtoList(List<WhiteDateTerm> entityList) {
if (entityList == null) {
throw new IllegalArgumentException("The argument 'entityList' should not be null.");
}
List<WhiteDateTermDto> dtoList = new ArrayList<WhiteDateTermDto>();
for (WhiteDateTerm entity : entityList) {
WhiteDateTermDto dto = mappingToDto(entity);
if (dto != null) {
dtoList.add(dto);
} else {
if (isAcceptNullElementOnList()) {
dtoList.add(null);
}
}
}
return dtoList;
}
// -----------------------------------------------------
// to Entity
// ---------
/**
* {@inheritDoc}
*/
public WhiteDateTerm mappingToEntity(WhiteDateTermDto dto) {
if (dto == null) {
return null;
}
WhiteDateTerm entity = new WhiteDateTerm();
if (needsMapping(dto, dto.getDateTermId(), "dateTermId")) {
entity.setDateTermId(dto.getDateTermId());
}
if (needsMapping(dto, dto.getDateTermValue(), "dateTermValue")) {
entity.setDateTermValue(dto.getDateTermValue());
}
if (needsMapping(dto, dto.getBeginDate(), "beginDate")) {
entity.setBeginDate(dto.getBeginDate());
}
if (needsMapping(dto, dto.getEndDate(), "endDate")) {
entity.setEndDate(dto.getEndDate());
}
reflectDerivedProperty(entity, dto, false);
return entity;
}
/**
* Does the property need to be mapped to an entity? <br>
* If modified info of DTO has at least one property, only modified properties are mapped.
* And if no property is modified, all properties are mapped (but the other option exists).
* @param dto The instance of DTO. (NotNull)
* @param value The value of DTO's property. (NotNull)
* @param propName The property name of DTO. (NotNull)
* @return The determination, true or false.
*/
protected boolean needsMapping(WhiteDateTermDto dto, Object value, String propName) {
Set<String> modifiedProperties = dto.mymodifiedProperties();
if (modifiedProperties.isEmpty()) {
return isMappingToEntityContainsNull() || value != null;
}
return modifiedProperties.contains(propName);
}
/**
* Does the mapping to an entity contain null values? (when no property is modified) <br>
* Default is true that means a setter is called if the value is null.
* But this method is valid only when no property is modified.
* @return The determination, true or false.
*/
protected boolean isMappingToEntityContainsNull() { // for extension
return true; // as default
}
/**
* {@inheritDoc}
*/
public List<WhiteDateTerm> mappingToEntityList(List<WhiteDateTermDto> dtoList) {
if (dtoList == null) {
throw new IllegalArgumentException("The argument 'dtoList' should not be null.");
}
List<WhiteDateTerm> entityList = new ArrayList<WhiteDateTerm>();
for (WhiteDateTermDto dto : dtoList) {
WhiteDateTerm entity = mappingToEntity(dto);
if (entity != null) {
entityList.add(entity);
} else {
if (isAcceptNullElementOnList()) {
entityList.add(null);
}
}
}
return entityList;
}
protected boolean isAcceptNullElementOnList() {
return true; // as default
}
// -----------------------------------------------------
// Instance Key
// ------------
protected Object createInstanceKeyDto(final Object dto, final int instanceHash) {
return new InstanceKeyDto(dto, instanceHash);
}
protected InstanceKeyEntity createInstanceKeyEntity(Entity entity) {
return new InstanceKeyEntity(entity);
}
public void disableInstanceCache() { // internal option
_instanceCache = false;
}
// -----------------------------------------------------
// Derived Property
// ----------------
protected void reflectDerivedProperty(Entity entity, Object dto, boolean toDto) {
DfBeanDesc entityDesc = DfBeanDescFactory.getBeanDesc(entity.getClass());
DfBeanDesc dtoDesc = DfBeanDescFactory.getBeanDesc(dto.getClass());
DBMeta dbmeta = entity.asDBMeta();
for (String propertyName : entityDesc.getProppertyNameList()) {
if (isOutOfDerivedPropertyName(entity, dto, toDto, dbmeta, entityDesc, dtoDesc, propertyName)) {
continue;
}
DfPropertyDesc entityProp = entityDesc.getPropertyDesc(propertyName);
Class<?> propertyType = entityProp.getPropertyType();
if (isOutOfDerivedPropertyType(entity, dto, toDto, propertyName, propertyType)) {
continue;
}
if (entityProp.isReadable() && entityProp.isWritable()) {
DfPropertyDesc dtoProp = dtoDesc.getPropertyDesc(propertyName);
if (dtoProp.isReadable() && dtoProp.isWritable()) {
if (toDto) {
dtoProp.setValue(dto, entityProp.getValue(entity));
} else {
entityProp.setValue(entity, dtoProp.getValue(dto));
}
}
}
}
}
protected boolean isOutOfDerivedPropertyName(Entity entity, Object dto, boolean toDto
, DBMeta dbmeta, DfBeanDesc entityDesc, DfBeanDesc dtoDesc
, String propertyName) {
return dbmeta.hasColumn(propertyName)
|| dbmeta.hasForeign(propertyName) || dbmeta.hasReferrer(propertyName)
|| !dtoDesc.hasPropertyDesc(propertyName);
}
protected boolean isOutOfDerivedPropertyType(Entity entity, Object dto, boolean toDto
, String propertyName, Class<?> propertyType) {
return List.class.isAssignableFrom(propertyType)
|| Entity.class.isAssignableFrom(propertyType)
|| Classification.class.isAssignableFrom(propertyType);
}
// ===================================================================================
// Suppress Relation
// =================
// (basically) to suppress infinity loop
protected void doSuppressAll() { // internal
}
protected void doSuppressClear() { // internal
}
// ===================================================================================
// Mapping Option
// ==============
/**
* {@inheritDoc}
*/
public void setBaseOnlyMapping(boolean baseOnlyMapping) {
if (baseOnlyMapping) {
doSuppressAll();
} else {
doSuppressClear();
}
}
protected boolean isExceptCommonColumn() {
return _exceptCommonColumn;
}
/**
* {@inheritDoc}
*/
public void setExceptCommonColumn(boolean exceptCommonColumn) {
_exceptCommonColumn = exceptCommonColumn;
}
protected boolean isReverseReference() {
return _reverseReference;
}
/**
* {@inheritDoc}
*/
public void setReverseReference(boolean reverseReference) {
_reverseReference = reverseReference;
}
// -----------------------------------------------------
// Easy-to-Use
// -----------
/**
* Enable base-only mapping that means the mapping ignores all references.
* @return this. (NotNull)
*/
public WhiteDateTermDtoMapper baseOnlyMapping() {
setBaseOnlyMapping(true);
return (WhiteDateTermDtoMapper)this;
}
/**
* Enable except common column that means the mapping excepts common column.
* @return this. (NotNull)
*/
public WhiteDateTermDtoMapper exceptCommonColumn() {
setExceptCommonColumn(true);
return (WhiteDateTermDtoMapper)this;
}
/**
* Enable reverse reference that means the mapping contains reverse references.
* @return this. (NotNull)
*/
public WhiteDateTermDtoMapper reverseReference() {
setReverseReference(true);
return (WhiteDateTermDtoMapper)this;
}
}
| |
/*
* Copyright 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.ui.impl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.eclipse.jetty.websocket.WebSocket;
import org.onlab.osgi.ServiceDirectory;
import org.onlab.osgi.ServiceNotFoundException;
import org.onosproject.cluster.ClusterService;
import org.onosproject.cluster.ControllerNode;
import org.onosproject.ui.UiConnection;
import org.onosproject.ui.UiExtensionService;
import org.onosproject.ui.UiMessageHandlerFactory;
import org.onosproject.ui.UiMessageHandler;
import org.onosproject.ui.UiTopoOverlayFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
* Web socket capable of interacting with the GUI.
*/
public class UiWebSocket
implements UiConnection, WebSocket.OnTextMessage, WebSocket.OnControl {
private static final Logger log = LoggerFactory.getLogger(UiWebSocket.class);
private static final long MAX_AGE_MS = 30_000;
private static final byte PING = 0x9;
private static final byte PONG = 0xA;
private static final byte[] PING_DATA = new byte[]{(byte) 0xde, (byte) 0xad};
private final ServiceDirectory directory;
private Connection connection;
private FrameConnection control;
private final ObjectMapper mapper = new ObjectMapper();
private long lastActive = System.currentTimeMillis();
private Map<String, UiMessageHandler> handlers;
private TopoOverlayCache overlayCache;
/**
* Creates a new web-socket for serving data to GUI.
*
* @param directory service directory
*/
public UiWebSocket(ServiceDirectory directory) {
this.directory = directory;
}
/**
* Issues a close on the connection.
*/
synchronized void close() {
destroyHandlersAndOverlays();
if (connection.isOpen()) {
connection.close();
}
}
/**
* Indicates if this connection is idle.
*
* @return true if idle or closed
*/
synchronized boolean isIdle() {
long quietFor = System.currentTimeMillis() - lastActive;
boolean idle = quietFor > MAX_AGE_MS;
if (idle || (connection != null && !connection.isOpen())) {
log.debug("IDLE (or closed) websocket [{} ms]", quietFor);
return true;
} else if (connection != null) {
try {
control.sendControl(PING, PING_DATA, 0, PING_DATA.length);
} catch (IOException e) {
log.warn("Unable to send ping message due to: ", e);
}
}
return false;
}
@Override
public void onOpen(Connection connection) {
this.connection = connection;
this.control = (FrameConnection) connection;
try {
createHandlersAndOverlays();
sendInstanceData();
log.info("GUI client connected");
} catch (ServiceNotFoundException e) {
log.warn("Unable to open GUI connection; services have been shut-down", e);
this.connection.close();
this.connection = null;
this.control = null;
}
}
@Override
public synchronized void onClose(int closeCode, String message) {
destroyHandlersAndOverlays();
log.info("GUI client disconnected [close-code={}, message={}]",
closeCode, message);
}
@Override
public boolean onControl(byte controlCode, byte[] data, int offset, int length) {
lastActive = System.currentTimeMillis();
return true;
}
@Override
public void onMessage(String data) {
log.debug("onMessage: {}", data);
lastActive = System.currentTimeMillis();
try {
ObjectNode message = (ObjectNode) mapper.reader().readTree(data);
String type = message.path("event").asText("unknown");
UiMessageHandler handler = handlers.get(type);
if (handler != null) {
handler.process(message);
} else {
log.warn("No GUI message handler for type {}", type);
}
} catch (Exception e) {
log.warn("Unable to parse GUI message {} due to {}", data, e);
log.debug("Boom!!!", e);
}
}
@Override
public synchronized void sendMessage(ObjectNode message) {
try {
if (connection.isOpen()) {
connection.sendMessage(message.toString());
}
} catch (IOException e) {
log.warn("Unable to send message {} to GUI due to {}", message, e);
log.debug("Boom!!!", e);
}
}
@Override
public synchronized void sendMessage(String type, long sid, ObjectNode payload) {
ObjectNode message = mapper.createObjectNode();
message.put("event", type);
if (sid > 0) {
message.put("sid", sid);
}
message.set("payload", payload);
sendMessage(message);
}
// Creates new message handlers.
private synchronized void createHandlersAndOverlays() {
log.debug("creating handlers and overlays...");
handlers = new HashMap<>();
overlayCache = new TopoOverlayCache();
UiExtensionService service = directory.get(UiExtensionService.class);
service.getExtensions().forEach(ext -> {
UiMessageHandlerFactory factory = ext.messageHandlerFactory();
if (factory != null) {
factory.newHandlers().forEach(handler -> {
handler.init(this, directory);
handler.messageTypes().forEach(type -> handlers.put(type, handler));
// need to inject the overlay cache into topology message handler
if (handler instanceof TopologyViewMessageHandler) {
((TopologyViewMessageHandler) handler).setOverlayCache(overlayCache);
}
});
}
UiTopoOverlayFactory overlayFactory = ext.topoOverlayFactory();
if (overlayFactory != null) {
overlayFactory.newOverlays().forEach(overlayCache::add);
}
});
log.debug("#handlers = {}, #overlays = {}", handlers.size(),
overlayCache.size());
}
// Destroys message handlers.
private synchronized void destroyHandlersAndOverlays() {
log.debug("destroying handlers and overlays...");
handlers.forEach((type, handler) -> handler.destroy());
handlers.clear();
if (overlayCache != null) {
overlayCache.destroy();
overlayCache = null;
}
}
// Sends cluster node/instance information to allow GUI to fail-over.
private void sendInstanceData() {
ClusterService service = directory.get(ClusterService.class);
ArrayNode instances = mapper.createArrayNode();
for (ControllerNode node : service.getNodes()) {
ObjectNode instance = mapper.createObjectNode()
.put("id", node.id().toString())
.put("ip", node.ip().toString())
.put("uiAttached", node.equals(service.getLocalNode()));
instances.add(instance);
}
ObjectNode payload = mapper.createObjectNode();
payload.set("clusterNodes", instances);
sendMessage("bootstrap", 0, payload);
}
}
| |
/*
* Copyright 2013 Zakhar Prykhoda
*
* 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.midao.jdbc.core.db;
import org.midao.jdbc.core.handlers.model.CallResults;
import org.midao.jdbc.core.handlers.model.QueryParameters;
import org.midao.jdbc.core.handlers.output.lazy.MapLazyOutputHandler;
import org.midao.jdbc.core.service.QueryRunnerService;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
public class DBCall extends BaseDB {
public static void callQueryParameters(QueryStructure structure, QueryRunnerService runner) throws SQLException {
QueryParameters result = null;
try {
structure.create(runner);
structure.execute(runner);
result = (QueryParameters) structure.values.get("result");
assertEquals("John", result.getValue("name"));
assertEquals("DOE", result.getValue("surname"));
assertEquals("John DOE", result.getValue("fullname"));
} finally {
structure.drop(runner);
}
}
public static void callProcedure(QueryStructure structure, QueryRunnerService runner) throws SQLException {
/*
runner.update(CREATE_STUDENT_TABLE);
runner.update(new MapInputHandler(INSERT_NAMED_STUDENT_TABLE, new HashMap<String, Object>() {{
put("studentName", "John");
}}), new RowCountHandler<Integer>());
runner.update(new MapInputHandler(INSERT_NAMED_STUDENT_TABLE, new HashMap<String, Object>() {{
put("studentName", "Doe");}}), new RowCountHandler<Integer>());
if (dbName.equals(derby) == true) {
runner.update(DERBY_PROCEDURE_IN);
}
QueryParameters parameters = new QueryParameters();
parameters.set("id", 2, MjdbcTypes.INTEGER, QueryParameters.Direction.IN);
parameters.set("rs", null, QueryParameters.Direction.OUT);
QueryInputHandler input = new QueryInputHandler(CALL_PROCEDURE_IN, parameters);
QueryParameters result = null;
result = runner.call(input);
System.out.println(result);
runner.update(DROP_STUDENT_TABLE);
*/
}
public static void callFunction(QueryStructure structure, QueryRunnerService runner) throws SQLException {
QueryParameters result = null;
try {
structure.create(runner);
structure.execute(runner);
result = (QueryParameters) structure.values.get("result1");
assertEquals("Doe", result.getValue("name"));
result = (QueryParameters) structure.values.get("result2");
assertEquals("John", result.getValue("name"));
} finally {
structure.drop(runner);
}
}
public static void callOutputHandlerMap(QueryStructure structure, QueryRunnerService runner) throws SQLException {
CallResults<QueryParameters, Map<String, Object>> result = null;
try {
structure.create(runner);
structure.execute(runner);
result = (CallResults<QueryParameters, Map<String, Object>>) structure.values.get("result");
assertEquals("Doe", result.getCallOutput().get("name"));
} finally {
structure.drop(runner);
}
}
public static void callLazyOutputHandlerMap(QueryStructure structure, QueryRunnerService runner) throws SQLException {
CallResults<QueryParameters, MapLazyOutputHandler> result = null;
try {
structure.create(runner);
structure.execute(runner);
result = (CallResults<QueryParameters, MapLazyOutputHandler>) structure.values.get("result");
assertEquals("Doe", result.getCallOutput().getNext().get("name"));
result.getCallOutput().close();
} finally {
structure.drop(runner);
}
}
public static void callOutputHandlerListMap(QueryStructure structure, QueryRunnerService runner) throws SQLException {
CallResults<QueryParameters, List<Map<String, Object>>> result = null;
try {
structure.create(runner);
structure.execute(runner);
result = (CallResults<QueryParameters, List<Map<String, Object>>>) structure.values.get("result");
assertEquals("Doe", result.getCallOutput().get(0).get("name"));
assertEquals("John", result.getCallOutput().get(1).get("name"));
} finally {
structure.drop(runner);
}
}
public static void callOutputHandlerBean(QueryStructure structure, QueryRunnerService runner) throws SQLException {
CallResults<QueryParameters, Student> result = null;
try {
structure.create(runner);
structure.execute(runner);
result = (CallResults<QueryParameters, Student>) structure.values.get("result");
assertEquals("Doe", result.getCallOutput().getName());
} finally {
structure.drop(runner);
}
}
public static void callOutputHandlerListBean(QueryStructure structure, QueryRunnerService runner) throws SQLException {
CallResults<QueryParameters, List<Student>> result = null;
try {
structure.create(runner);
structure.execute(runner);
result = (CallResults<QueryParameters, List<Student>>) structure.values.get("result");
assertEquals("Doe", result.getCallOutput().get(0).getName());
assertEquals("John", result.getCallOutput().get(1).getName());
} finally {
structure.drop(runner);
}
}
public static void callNamedInputHandler(QueryStructure structure, QueryRunnerService runner) {
}
public static void callLargeParameters(QueryStructure structure, QueryRunnerService runner) throws SQLException {
CallResults<QueryParameters, Map<String, Object>> result = null;
try {
structure.create(runner);
structure.execute(runner);
result = (CallResults<QueryParameters, Map<String, Object>>) structure.values.get("result");
String clobOut = (String) result.getCallInput().getValue("clobOut");
Object blobOut = result.getCallInput().getValue("blobOut");
assertEquals("Hello John", clobOut);
if (blobOut instanceof byte[]) {
assertEquals("Hi Doe", new String((byte[]) blobOut));
} else if (blobOut instanceof String) {
assertEquals("Hi Doe", blobOut);
} else {
fail();
}
} finally {
structure.drop(runner);
}
}
public static void callNamedHandler(QueryStructure structure, QueryRunnerService runner) throws SQLException {
Student result = null;
try {
structure.create(runner);
structure.execute(runner);
result = (Student) structure.values.get("result1");
assertEquals("Doe", result.getName());
result = (Student) structure.values.get("result2");
assertEquals("John", result.getName());
} finally {
structure.drop(runner);
}
}
public static void callXMLParameters(QueryStructure structure, QueryRunnerService runner) {
}
}
| |
/**
* Copyright 2014 Atos
* Contact: Atos <roman.sosa@atos.net>
*
* 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 eu.atos.sla.evaluation.guarantee;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import eu.atos.sla.datamodel.IAgreement;
import eu.atos.sla.datamodel.IBreach;
import eu.atos.sla.datamodel.IGuaranteeTerm;
import eu.atos.sla.datamodel.IPolicy;
import eu.atos.sla.datamodel.IViolation;
import eu.atos.sla.datamodel.bean.Breach;
import eu.atos.sla.datamodel.bean.Policy;
import eu.atos.sla.datamodel.bean.Violation;
import eu.atos.sla.evaluation.constraint.IConstraintEvaluator;
import eu.atos.sla.monitoring.IMonitoringMetric;
/**
* Implements a ServiceLevelEvaluator that takes into account Policies.
*
* <p>In a policy, a non-fulfilled service level by a metric is considered a breach. A policy specifies how many
* breaches in a interval of time must occur to raise a violation.</p>
*
* <p>If no policies are defined for the guarantee term, each breach is a violation. Otherwise, only a violation
* will be raised (if applicable) in each execution. Therefore, to avoid having breaches not considered as
* violations, the policy interval should be greater than the evaluation interval.</p>
*
* <p>The breaches management (load, store) is totally performed in this class, and therefore, can be considered
* as a side effect. The advantage is that this way, the interface for upper levels is cleaner
* (GuaranteeTermEvaluator and AgreementEvaluator do not know about breaches).</p>
*
* Usage:
* <pre>
* PoliciedServiceLevelEvaluator pe = new PoliciedServiceLevelEvaluator();
* pe.setConstraintEvaluator(...);
* pe.setBreachRepository(...);
*
* pe.evaluate(...):
* </pre>
*
* @see IBreachRepository
* @see IConstraintEvaluator
* @author rsosa
*
*/
public class PoliciedServiceLevelEvaluator implements IServiceLevelEvaluator {
private static Logger logger = LoggerFactory.getLogger(PoliciedServiceLevelEvaluator.class);
private static IPolicy defaultPolicy = new Policy(1, new Date(0));
private IConstraintEvaluator constraintEval;
private IBreachRepository breachRepository;
private PoliciedServiceLevelEvaluator.ActualValueBuilder actualValueBuilder = new ActualValueBuilder();
private PoliciedServiceLevelEvaluator.BreachesFromMetricsBuilder breachesFromMetricsBuilder = new BreachesFromMetricsBuilder();
@Override
public List<IViolation> evaluate(
IAgreement agreement, IGuaranteeTerm term, List<IMonitoringMetric> metrics, Date now) {
logger.debug("evaluate(agreement={}, term={}, servicelevel={})",
agreement.getAgreementId(), term.getKpiName(), term.getServiceLevel());
/*
* throws NullPointerException if not property initialized
*/
checkInitialized();
List<IViolation> newViolations = new ArrayList<IViolation>();
String kpiName = term.getKpiName();
String constraint = term.getServiceLevel();
/*
* Calculate with new metrics are breaches
*/
List<IMonitoringMetric> newBreachMetrics = constraintEval.evaluate(kpiName, constraint, metrics);
logger.debug("Found {} breaches in new metrics", newBreachMetrics.size());
List<IPolicy> policies = getPoliciesOrDefault(term);
boolean withPolicies = !isDefaultPolicy(policies);
List<IBreach> newBreaches = null; /* only to use with policies */
if (withPolicies) {
newBreaches = breachesFromMetricsBuilder.build(newBreachMetrics, agreement, kpiName);
saveBreaches(newBreaches);
}
/*
* Evaluate each policy
*/
for (IPolicy policy : policies) {
Date breachesBegin = new Date(now.getTime() - policy.getTimeInterval().getTime());
logger.debug("Evaluating policy({},{}s) in interval({}, {})",
policy.getCount(), policy.getTimeInterval().getTime() / 1000, breachesBegin, now);
List<IBreach> oldBreaches;
if (withPolicies) {
/*
* TODO rsosa: oldBreaches should start from last violation, if any; otherwise, as is.
*/
oldBreaches = breachRepository.getBreachesByTimeRange(agreement, kpiName, breachesBegin, now);
logger.debug("Found {} breaches", oldBreaches.size());
List<IBreach> breaches = new PoliciedServiceLevelEvaluator.CompositeList<IBreach>(
oldBreaches, newBreaches);
if (evaluatePolicy(policy, oldBreaches, newBreaches)) {
IViolation violation = newViolation(agreement, term, policy, kpiName, breaches, now);
newViolations.add(violation);
violation.setBreaches(breaches);
logger.debug("Violation raised");
}
}
else {
oldBreaches = Collections.emptyList();
for (IMonitoringMetric breach : newBreachMetrics) {
IViolation violation = newViolation(agreement, term, kpiName, breach);
newViolations.add(violation);
logger.debug("Violation raised");
}
}
}
return newViolations;
}
private void checkInitialized() {
if (breachRepository == null) {
throw new NullPointerException("breachRepository is not set");
}
if (constraintEval == null) {
throw new NullPointerException("constraintEval is not set");
}
}
private void saveBreaches(List<IBreach> breaches) {
breachRepository.saveBreaches(breaches);
}
/**
* Builds a Violation from a list of breaches (for the case when the term has policies)
*/
private IViolation newViolation(final IAgreement agreement, final IGuaranteeTerm term,
final IPolicy policy, final String kpiName, final List<IBreach> breaches, final Date timestamp) {
String actualValue = actualValueBuilder.fromBreaches(breaches);
String expectedValue = null;
IViolation v = newViolation(
agreement, term, policy, kpiName, actualValue, expectedValue, timestamp);
return v;
}
/**
* Builds a Violation from metric breach (for the case when the term does not have policies)
*/
private IViolation newViolation(final IAgreement agreement, final IGuaranteeTerm term,
final String kpiName, IMonitoringMetric breach) {
String actualValue = breach.getMetricValue();
String expectedValue = null;
/*
* The policy is null, as the term has the default policy.
*/
IViolation v = newViolation(
agreement, term, null, kpiName, actualValue, expectedValue, breach.getDate());
return v;
}
private Violation newViolation(final IAgreement contract, final IGuaranteeTerm term,
final IPolicy policy, final String kpiName, final String actualValue,
final String expectedValue, final Date timestamp) {
Violation result = new Violation();
result.setUuid(UUID.randomUUID().toString());
result.setContractUuid(contract.getAgreementId());
result.setKpiName(kpiName);
result.setDatetime(timestamp);
result.setExpectedValue(expectedValue);
result.setActualValue(actualValue);
result.setServiceName(term.getServiceName());
result.setServiceScope(term.getServiceScope());
result.setContractUuid(contract.getAgreementId());
result.setPolicy(policy);
return result;
}
private boolean evaluatePolicy(
IPolicy policy,
List<IBreach> oldBreaches,
List<IBreach> newBreaches) {
return oldBreaches.size() + newBreaches.size() >= policy.getCount();
}
/**
* Return policies of the term if any, or the default policy.
*/
private List<IPolicy> getPoliciesOrDefault(final IGuaranteeTerm term) {
if (term.getPolicies() != null && term.getPolicies().size() > 0) {
return term.getPolicies();
}
return Collections.singletonList(defaultPolicy);
}
/**
* Checks if a list of breaches is only the default policy.
*/
private boolean isDefaultPolicy(List<IPolicy> policies) {
return policies.size() == 1 && isDefaultPolicy(policies.get(0));
}
private boolean isDefaultPolicy(IPolicy policy) {
return policy.getCount() == 1;
}
public IConstraintEvaluator getConstraintEvaluator() {
return constraintEval;
}
public void setConstraintEvaluator(IConstraintEvaluator constraintEval) {
this.constraintEval = constraintEval;
}
public IBreachRepository getBreachRepository() {
return breachRepository;
}
public void setBreachRepository(IBreachRepository breachRepository) {
this.breachRepository = breachRepository;
}
/**
* Unmodifiable List wrapper over 2 lists.
*
* There is no such wrapper in jdk.
* @see http://stackoverflow.com/a/13868352
*/
public static class CompositeList<E> extends AbstractList<E> {
private final List<E> list1;
private final List<E> list2;
public CompositeList(List<E> list1, List<E> list2) {
this.list1 = list1;
this.list2 = list2;
}
@Override
public E get(int index) {
if (index < list1.size()) {
return list1.get(index);
}
return list2.get(index-list1.size());
}
@Override
public int size() {
return list1.size() + list2.size();
}
}
/**
* Constructs a list of Breach entities from a list of metrics that are considered breaches.
*/
public static class BreachesFromMetricsBuilder {
public List<IBreach> build(
final List<IMonitoringMetric> metrics,
final IAgreement agreement,
final String kpiName) {
List<IBreach> result = new ArrayList<IBreach>();
for (IMonitoringMetric metric : metrics) {
result.add(newBreach(agreement, metric, kpiName));
}
return result;
}
private IBreach newBreach(
final IAgreement contract,
final IMonitoringMetric metric,
final String kpiName) {
Breach breach = new Breach();
breach.setDatetime(metric.getDate());
breach.setKpiName(kpiName);
breach.setValue(metric.getMetricValue());
breach.setAgreementUuid(contract.getAgreementId());
return breach;
}
}
/**
* Calculates the actual value of a breach. This value is not expected to be read by a computer, but by a human,
* as it can be truncated.
*
* This builder builds a comma separated list of the first three breach values.
*/
public static class ActualValueBuilder {
private static final int MAX_ACTUAL_VALUES = 3;
private PoliciedServiceLevelEvaluator.BreachesFromMetricsBuilder breachesFromMetricsBuilder = new BreachesFromMetricsBuilder();
public String fromBreaches(final List<IBreach> breaches) {
StringBuilder str = new StringBuilder();
String sep = "";
for (int i = 0; i < breaches.size() && i < MAX_ACTUAL_VALUES; i++) {
IBreach breach = breaches.get(i);
str.append(sep);
str.append(breach.getValue());
sep = ",";
}
if (breaches.size() > MAX_ACTUAL_VALUES) {
str.append("...");
}
return str.toString();
}
public String fromMetrics(
final List<IMonitoringMetric> breachMetrics, IAgreement agreement, String kpiName) {
List<IBreach> breaches = breachesFromMetricsBuilder.build(breachMetrics, agreement, kpiName);
String result = fromBreaches(breaches);
return result;
}
}
}
| |
package com.instructure.canvasapi.api;
import com.instructure.canvasapi.model.CanvasContext;
import com.instructure.canvasapi.model.Quiz;
import com.instructure.canvasapi.model.QuizQuestion;
import com.instructure.canvasapi.model.QuizSubmission;
import com.instructure.canvasapi.model.QuizSubmissionQuestionResponse;
import com.instructure.canvasapi.model.QuizSubmissionResponse;
import com.instructure.canvasapi.model.QuizSubmissionTime;
import com.instructure.canvasapi.utilities.APIHelpers;
import com.instructure.canvasapi.utilities.CanvasCallback;
import com.instructure.canvasapi.utilities.CanvasRestAdapter;
import java.util.ArrayList;
import retrofit.Callback;
import retrofit.RestAdapter;
import retrofit.client.Response;
import retrofit.http.GET;
import retrofit.http.POST;
import retrofit.http.PUT;
import retrofit.http.Path;
import retrofit.http.Query;
/**
* Created by Josh Ruesch on 8/9/13.
*
* Copyright (c) 2014 Instructure. All rights reserved.
*/
public class QuizAPI {
private static final String QUIZ_SUBMISSION_SESSION_STARTED = "android_session_started";
public static String getFirstPageQuizzesCacheFilename(CanvasContext canvasContext){
return canvasContext.toAPIString() + "/quizzes";
}
public static String getDetailedQuizCacheFilename(CanvasContext canvasContext, long quizID){
return canvasContext.toAPIString() + "/quizzes/" + quizID;
}
public static String getFirstPageQuizQuestionsCacheFilename(CanvasContext canvasContext, long quizID) {
return canvasContext.toAPIString() + "/quizzes/" + quizID + "/questions";
}
public static String getFirstPageQuizSubmissionsCacheFilename(CanvasContext canvasContext, long quizID) {
return canvasContext.toAPIString() + "/quizzes/" + quizID + "/submissions";
}
public static String getFirstPageSubmissionQuestionsCacheFilename(long quizSubmissionID) {
return "/quizSubmissions/" + quizSubmissionID + "/questions";
}
interface QuizzesInterface {
@GET("/{context_id}/quizzes")
void getFirstPageQuizzesList(@Path("context_id") long context_id, Callback<Quiz[]> callback);
@GET("/{next}")
void getNextPageQuizzesList(@Path(value = "next", encode = false) String nextURL, Callback<Quiz[]> callback);
@GET("/{context_id}/quizzes/{quizid}")
void getDetailedQuiz(@Path("context_id") long context_id, @Path("quizid") long quizid, Callback<Quiz> callback);
@GET("/{next}")
void getDetailedQuizFromURL(@Path(value = "next", encode = false) String quizURL, Callback<Quiz> callback);
@GET("/{context_id}/quizzes/{quizid}/questions")
void getFirstPageQuizQuestions(@Path("context_id") long context_id, @Path("quizid") long quizid, Callback<QuizQuestion[]> callback);
@GET("/{next}")
void getNextPageQuizQuestions(@Path(value = "next", encode = false) String nextURL, Callback<QuizQuestion[]> callback);
@POST("/{context_id}/quizzes/{quizid}/submissions")
void startQuiz(@Path("context_id") long context_id, @Path("quizid") long quizid, Callback<Response> callback);
@GET("/{context_id}/quizzes/{quizid}/submissions")
void getFirstPageQuizSubmissions(@Path("context_id") long context_id, @Path("quizid") long quizid, Callback<QuizSubmissionResponse> callback);
@GET("/{next}")
void getNextPageQuizSubmissions(@Path(value = "next", encode = false) String nextURL, Callback<QuizSubmissionResponse> callback);
@GET("/quiz_submissions/{quiz_submission_id}/questions")
void getFirstPageSubmissionQuestions(@Path("quiz_submission_id") long quizSubmissionId, Callback<QuizSubmissionQuestionResponse> callback);
@GET("/{next}")
void getNextPageSubmissionQuestions(@Path(value = "next", encode = false) String nextURL, Callback<QuizSubmissionQuestionResponse> callback);
@POST("/quiz_submissions/{quiz_submission_id}/questions")
void postQuizQuestionMultiChoice(@Path("quiz_submission_id") long quizSubmissionId, @Query("attempt") int attempt, @Query("validation_token") String token, @Query("quiz_questions[][id]") long questionId, @Query("quiz_questions[][answer]") long answer, Callback<QuizSubmissionQuestionResponse> callback);
@PUT("/quiz_submissions/{quiz_submission_id}/questions/{question_id}/flag")
void putFlagQuizQuestion(@Path("quiz_submission_id") long quizSubmissionId, @Path("question_id") long questionId, @Query("attempt") int attempt, @Query("validation_token") String token, CanvasCallback<Response> callback);
@PUT("/quiz_submissions/{quiz_submission_id}/questions/{question_id}/unflag")
void putUnflagQuizQuestion(@Path("quiz_submission_id") long quizSubmissionId, @Path("question_id") long questionId, @Query("attempt") int attempt, @Query("validation_token") String token, CanvasCallback<Response> callback);
@POST("/quiz_submissions/{quiz_submission_id}/questions")
void postQuizQuestionEssay(@Path("quiz_submission_id") long quizSubmissionId, @Query("attempt") int attempt, @Query("validation_token") String token, @Query("quiz_questions[][id]") long questionId, @Query("quiz_questions[][answer]") String answer, Callback<QuizSubmissionQuestionResponse> callback);
@POST("/{context_id}/quizzes/{quiz_id}/submissions/{submission_id}/complete")
void postQuizSubmit(@Path("context_id") long context_id, @Path("quiz_id") long quizId, @Path("submission_id") long submissionId, @Query("attempt") int attempt, @Query("validation_token") String token, Callback<QuizSubmissionResponse> callback);
@POST("/{context_id}/quizzes/{quiz_id}/submissions/{submission_id}/events")
void postQuizStartedEvent(@Path("context_id") long context_id, @Path("quiz_id") long quizId, @Path("submission_id") long submissionId, @Query("quiz_submission_events[][event_type]") String sessionStartedString, @Query("quiz_submission_events[][event_data][user_agent]") String userAgentString, CanvasCallback<Response> callback);
@GET("/{context_id}/quizzes/{quiz_id}/submissions/{submission_id}/time")
void getQuizSubmissionTime(@Path("context_id") long context_id, @Path("quiz_id") long quizId, @Path("submission_id") long submissionId, CanvasCallback<QuizSubmissionTime> callback);
@POST("/quiz_submissions/{quiz_submission_id}/questions{query_params}")
void postQuizQuestionMultiAnswers(@Path("quiz_submission_id") long quizSubmissionId, @Path(value = "query_params", encode = false) String queryParams, Callback<QuizSubmissionQuestionResponse> callback);
}
/////////////////////////////////////////////////////////////////////////
// Build Interface Helpers
/////////////////////////////////////////////////////////////////////////
private static QuizzesInterface buildInterface(CanvasCallback<?> callback, CanvasContext canvasContext) {
RestAdapter restAdapter = CanvasRestAdapter.buildAdapter(callback, canvasContext);
return restAdapter.create(QuizzesInterface.class);
}
private static QuizzesInterface buildInterfaceNoPerPage(CanvasCallback<?> callback, CanvasContext canvasContext) {
RestAdapter restAdapter = CanvasRestAdapter.buildAdapter(callback, canvasContext, false);
return restAdapter.create(QuizzesInterface.class);
}
/////////////////////////////////////////////////////////////////////////
// API Calls
/////////////////////////////////////////////////////////////////////////
public static void getFirstPageQuizzes(CanvasContext canvasContext, CanvasCallback<Quiz[]> callback) {
if (APIHelpers.paramIsNull(callback, canvasContext)) { return; }
callback.readFromCache(getFirstPageQuizzesCacheFilename(canvasContext));
buildInterface(callback, canvasContext).getFirstPageQuizzesList(canvasContext.getId(), callback);
}
public static void getNextPageQuizzes(String nextURL, CanvasCallback<Quiz[]> callback){
if (APIHelpers.paramIsNull(callback, nextURL)) { return; }
callback.setIsNextPage(true);
buildInterface(callback, null).getNextPageQuizzesList(nextURL, callback);
}
public static void getDetailedQuiz(CanvasContext canvasContext, long quiz_id, CanvasCallback<Quiz> callback) {
if (APIHelpers.paramIsNull(callback, canvasContext)) { return; }
callback.readFromCache(getDetailedQuizCacheFilename(canvasContext,quiz_id));
buildInterface(callback, canvasContext).getDetailedQuiz(canvasContext.getId(), quiz_id, callback);
}
public static void getDetailedQuizFromURL(String url, CanvasCallback<Quiz> callback) {
if (APIHelpers.paramIsNull(callback,url)) { return; }
callback.readFromCache(url);
buildInterface(callback, null).getDetailedQuizFromURL(url,callback);
}
public static void getFirstPageQuizQuestions(CanvasContext canvasContext, long quiz_id, CanvasCallback<QuizQuestion[]> callback) {
if (APIHelpers.paramIsNull(callback, canvasContext)) { return; }
callback.readFromCache(getFirstPageQuizQuestionsCacheFilename(canvasContext, quiz_id));
buildInterface(callback, canvasContext).getFirstPageQuizQuestions(canvasContext.getId(), quiz_id, callback);
}
public static void getNextPageQuizQuestions(String nextURL, CanvasCallback<QuizQuestion[]> callback){
if (APIHelpers.paramIsNull(callback, nextURL)) { return; }
callback.setIsNextPage(true);
buildInterface(callback, null).getNextPageQuizQuestions(nextURL, callback);
}
public static void startQuiz(CanvasContext canvasContext, long quiz_id, CanvasCallback<Response> callback) {
if (APIHelpers.paramIsNull(callback, canvasContext)) { return; }
buildInterface(callback, canvasContext).startQuiz(canvasContext.getId(), quiz_id, callback);
}
public static void getFirstPageQuizSubmissions(CanvasContext canvasContext, long quiz_id, CanvasCallback<QuizSubmissionResponse> callback) {
if (APIHelpers.paramIsNull(callback, canvasContext)) { return; }
callback.readFromCache(getFirstPageQuizSubmissionsCacheFilename(canvasContext, quiz_id));
buildInterface(callback, canvasContext).getFirstPageQuizSubmissions(canvasContext.getId(), quiz_id, callback);
}
public static void getNextPageQuizSubmissions(String nextURL, CanvasCallback<QuizSubmissionResponse> callback){
if (APIHelpers.paramIsNull(callback, nextURL)) { return; }
callback.setIsNextPage(true);
buildInterface(callback, null).getNextPageQuizSubmissions(nextURL, callback);
}
public static void getFirstPageSubmissionQuestions(long quizSubmissionId, CanvasCallback<QuizSubmissionQuestionResponse> callback) {
if (APIHelpers.paramIsNull(callback)) { return; }
callback.readFromCache(getFirstPageSubmissionQuestionsCacheFilename(quizSubmissionId));
buildInterface(callback, null).getFirstPageSubmissionQuestions(quizSubmissionId, callback);
}
public static void getNextPageSubmissionQuestions(String nextURL, CanvasCallback<QuizSubmissionQuestionResponse> callback){
if (APIHelpers.paramIsNull(callback, nextURL)) { return; }
callback.setIsNextPage(true);
buildInterface(callback, null).getNextPageSubmissionQuestions(nextURL, callback);
}
public static void postQuizQuestionMultiChoice(QuizSubmission quizSubmission, long answerId, long questionId, CanvasCallback<QuizSubmissionQuestionResponse> callback){
if (APIHelpers.paramIsNull(callback, quizSubmission, quizSubmission.getSubmissionId(), quizSubmission.getValidationToken())) { return; }
buildInterface(callback, null).postQuizQuestionMultiChoice(quizSubmission.getId(), quizSubmission.getAttempt(), quizSubmission.getValidationToken(), questionId, answerId, callback);
}
public static void putFlagQuizQuestion(QuizSubmission quizSubmission, long quizQuestionId, boolean shouldFlag, CanvasCallback<Response> callback) {
if (APIHelpers.paramIsNull(callback, quizSubmission, quizSubmission.getSubmissionId(), quizSubmission.getValidationToken())) { return; }
if(shouldFlag) {
buildInterface(callback, null).putFlagQuizQuestion(quizSubmission.getId(), quizQuestionId, quizSubmission.getAttempt(), quizSubmission.getValidationToken(), callback);
} else {
buildInterface(callback, null).putUnflagQuizQuestion(quizSubmission.getId(), quizQuestionId, quizSubmission.getAttempt(), quizSubmission.getValidationToken(), callback);
}
}
public static void postQuizQuestionEssay(QuizSubmission quizSubmission, String answer, long questionId, CanvasCallback<QuizSubmissionQuestionResponse> callback){
if (APIHelpers.paramIsNull(callback, quizSubmission, quizSubmission.getSubmissionId(), quizSubmission.getValidationToken())) { return; }
buildInterface(callback, null).postQuizQuestionEssay(quizSubmission.getId(), quizSubmission.getAttempt(), quizSubmission.getValidationToken(), questionId, answer, callback);
}
public static void postQuizSubmit(CanvasContext canvasContext, QuizSubmission quizSubmission, CanvasCallback<QuizSubmissionResponse> callback) {
if (APIHelpers.paramIsNull(canvasContext, callback, quizSubmission, quizSubmission.getSubmissionId(), quizSubmission.getValidationToken())) { return; }
buildInterface(callback, canvasContext).postQuizSubmit(canvasContext.getId(), quizSubmission.getQuizId(), quizSubmission.getId(), quizSubmission.getAttempt(), quizSubmission.getValidationToken(), callback);
}
public static void postQuizStartedEvent(CanvasContext canvasContext, QuizSubmission quizSubmission, String userAgentString, CanvasCallback<Response> callback) {
if (APIHelpers.paramIsNull(canvasContext, callback, quizSubmission, quizSubmission.getSubmissionId())) { return; }
buildInterface(callback, canvasContext).postQuizStartedEvent(canvasContext.getId(), quizSubmission.getQuizId(), quizSubmission.getId(), QUIZ_SUBMISSION_SESSION_STARTED, userAgentString, callback);
}
public static void getQuizSubmissionTime(CanvasContext canvasContext, QuizSubmission quizSubmission, CanvasCallback<QuizSubmissionTime> callback) {
if(APIHelpers.paramIsNull(canvasContext, callback, quizSubmission)) { return; }
buildInterface(callback, canvasContext).getQuizSubmissionTime(canvasContext.getId(), quizSubmission.getQuizId(), quizSubmission.getId(), callback);
}
public static void postQuizQuestionMultiAnswer(QuizSubmission quizSubmission, long questionId, ArrayList<Integer> answers, CanvasCallback<QuizSubmissionQuestionResponse> callback){
if (APIHelpers.paramIsNull(callback, quizSubmission, quizSubmission.getSubmissionId(), quizSubmission.getValidationToken())) { return; }
//we don't to append the per_page parameter because we're building the query parameters ourselves, so use the different interface
buildInterfaceNoPerPage(callback, null).postQuizQuestionMultiAnswers(quizSubmission.getId(), buildMultiAnswerList(quizSubmission.getAttempt(), quizSubmission.getValidationToken(), questionId, answers), callback);
}
private static String buildMultiAnswerList(int attempt, String validationToken, long questionId, ArrayList<Integer> answers) {
// build the query params because we'll have an unknown amount of answers. It will end up looking like:
// ?attempt={attempt}&validation_token={validation_token}&quiz_questions[][id]={question_id}&quiz_questions[][answer][]={answer_id}...
StringBuilder builder = new StringBuilder();
builder.append("?");
builder.append("attempt=");
builder.append(Integer.toString(attempt));
builder.append("&");
builder.append("validation_token=");
builder.append(validationToken);
builder.append("&");
builder.append("quiz_questions[][id]=");
builder.append(Long.toString(questionId));
builder.append("&");
for(Integer answer : answers) {
builder.append("quiz_questions[][answer][]");
builder.append("=");
builder.append(Integer.toString(answer));
builder.append("&");
}
String answerString = builder.toString();
if(answerString.endsWith("&")) {
answerString = answerString.substring(0, answerString.length() - 1);
}
return answerString;
}
}
| |
/*
* Copyright (C) 2014 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.strata.basics.index;
import static com.opengamma.strata.basics.currency.Currency.CAD;
import static com.opengamma.strata.basics.currency.Currency.COP;
import static com.opengamma.strata.basics.currency.Currency.EUR;
import static com.opengamma.strata.basics.currency.Currency.GBP;
import static com.opengamma.strata.basics.currency.Currency.USD;
import static com.opengamma.strata.basics.date.HolidayCalendarIds.EUTA;
import static com.opengamma.strata.basics.date.HolidayCalendarIds.GBLO;
import static com.opengamma.strata.basics.date.HolidayCalendarIds.NO_HOLIDAYS;
import static com.opengamma.strata.basics.index.FxIndices.EUR_CHF_ECB;
import static com.opengamma.strata.collect.TestHelper.assertJodaConvert;
import static com.opengamma.strata.collect.TestHelper.assertSerialization;
import static com.opengamma.strata.collect.TestHelper.coverImmutableBean;
import static com.opengamma.strata.collect.TestHelper.coverPrivateConstructor;
import static com.opengamma.strata.collect.TestHelper.date;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import org.joda.beans.ImmutableBean;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import com.google.common.collect.ImmutableMap;
import com.opengamma.strata.basics.ReferenceData;
import com.opengamma.strata.basics.currency.CurrencyPair;
import com.opengamma.strata.basics.date.DaysAdjustment;
import com.opengamma.strata.basics.date.HolidayCalendarId;
/**
* Test {@link FxIndex}.
*/
public class FxIndexTest {
private static final ReferenceData REF_DATA = ReferenceData.standard();
//-------------------------------------------------------------------------
public static Object[][] data_name() {
return new Object[][] {
{FxIndices.EUR_CHF_ECB, "EUR/CHF-ECB"},
{FxIndices.EUR_GBP_ECB, "EUR/GBP-ECB"},
{FxIndices.EUR_JPY_ECB, "EUR/JPY-ECB"},
{FxIndices.EUR_USD_ECB, "EUR/USD-ECB"},
{FxIndices.USD_CHF_WM, "USD/CHF-WM"},
{FxIndices.EUR_USD_WM, "EUR/USD-WM"},
{FxIndices.GBP_USD_WM, "GBP/USD-WM"},
{FxIndices.USD_JPY_WM, "USD/JPY-WM"},
};
}
@ParameterizedTest
@MethodSource("data_name")
public void test_name(FxIndex convention, String name) {
assertThat(convention.getName()).isEqualTo(name);
}
@ParameterizedTest
@MethodSource("data_name")
public void test_toString(FxIndex convention, String name) {
assertThat(convention.toString()).isEqualTo(name);
}
@ParameterizedTest
@MethodSource("data_name")
public void test_of_lookup(FxIndex convention, String name) {
assertThat(FxIndex.of(name)).isEqualTo(convention);
}
@ParameterizedTest
@MethodSource("data_name")
public void test_extendedEnum(FxIndex convention, String name) {
ImmutableMap<String, FxIndex> map = FxIndex.extendedEnum().lookupAll();
assertThat(map.get(name)).isEqualTo(convention);
}
@Test
public void test_of_lookup_notFound() {
assertThatIllegalArgumentException().isThrownBy(() -> FxIndex.of("Rubbish"));
}
@Test
public void test_of_lookup_null() {
assertThatIllegalArgumentException().isThrownBy(() -> FxIndex.of((String) null));
}
@Test
public void test_of_lookup_parse_currency() {
CurrencyPair usdCad = CurrencyPair.of(USD, CAD);
HolidayCalendarId calendarId = HolidayCalendarId.defaultByCurrencyPair(usdCad);
ImmutableFxIndex fxIndex = ImmutableFxIndex.builder()
.name(usdCad.toString())
.currencyPair(usdCad)
.fixingCalendar(calendarId)
.maturityDateOffset(DaysAdjustment.ofBusinessDays(2, calendarId))
.build();
assertThat(FxIndex.of(usdCad.toString())).usingRecursiveComparison().isEqualTo(fxIndex);
}
@Test
public void test_of_lookup_currency_pair_from_extendedEnum() {
ImmutableFxIndex fxIndex = ImmutableFxIndex.builder()
.name("USD/COP-TRM-COP02")
.currencyPair(CurrencyPair.of(USD, COP))
.fixingCalendar(HolidayCalendarId.of("COBO"))
.maturityDateOffset(DaysAdjustment.ofBusinessDays(0, HolidayCalendarId.of("COBO")))
.build();
assertThat(FxIndex.of(CurrencyPair.of(USD, COP))).usingRecursiveComparison()
.isEqualTo(fxIndex);
}
//-------------------------------------------------------------------------
@Test
public void test_ecb_eur_gbp_dates() {
FxIndex test = FxIndices.EUR_GBP_ECB;
assertThat(test.getFixingDateOffset())
.isEqualTo(DaysAdjustment.ofBusinessDays(-2, EUTA.combinedWith(GBLO)));
assertThat(test.getMaturityDateOffset())
.isEqualTo(DaysAdjustment.ofBusinessDays(2, EUTA.combinedWith(GBLO)));
assertThat(test.calculateMaturityFromFixing(date(2014, 10, 13), REF_DATA)).isEqualTo(date(2014, 10, 15));
assertThat(test.calculateFixingFromMaturity(date(2014, 10, 15), REF_DATA)).isEqualTo(date(2014, 10, 13));
// weekend
assertThat(test.calculateMaturityFromFixing(date(2014, 10, 16), REF_DATA)).isEqualTo(date(2014, 10, 20));
assertThat(test.calculateFixingFromMaturity(date(2014, 10, 20), REF_DATA)).isEqualTo(date(2014, 10, 16));
assertThat(test.calculateMaturityFromFixing(date(2014, 10, 17), REF_DATA)).isEqualTo(date(2014, 10, 21));
assertThat(test.calculateFixingFromMaturity(date(2014, 10, 21), REF_DATA)).isEqualTo(date(2014, 10, 17));
// input date is Sunday
assertThat(test.calculateMaturityFromFixing(date(2014, 10, 19), REF_DATA)).isEqualTo(date(2014, 10, 22));
assertThat(test.calculateFixingFromMaturity(date(2014, 10, 19), REF_DATA)).isEqualTo(date(2014, 10, 16));
// skip maturity over EUR (1st May) and GBP (5th May) holiday
assertThat(test.calculateMaturityFromFixing(date(2014, 4, 30), REF_DATA)).isEqualTo(date(2014, 5, 6));
assertThat(test.calculateFixingFromMaturity(date(2014, 5, 6), REF_DATA)).isEqualTo(date(2014, 4, 30));
// resolve
assertThat(test.resolve(REF_DATA).apply(date(2014, 5, 6)))
.isEqualTo(FxIndexObservation.of(test, date(2014, 5, 6), REF_DATA));
}
@Test
public void test_dates() {
FxIndex test = ImmutableFxIndex.builder()
.name("Test")
.currencyPair(CurrencyPair.of(EUR, GBP))
.fixingCalendar(NO_HOLIDAYS)
.maturityDateOffset(DaysAdjustment.ofCalendarDays(2))
.build();
assertThat(test.calculateMaturityFromFixing(date(2014, 10, 13), REF_DATA)).isEqualTo(date(2014, 10, 15));
assertThat(test.calculateFixingFromMaturity(date(2014, 10, 15), REF_DATA)).isEqualTo(date(2014, 10, 13));
// weekend
assertThat(test.calculateMaturityFromFixing(date(2014, 10, 16), REF_DATA)).isEqualTo(date(2014, 10, 18));
assertThat(test.calculateFixingFromMaturity(date(2014, 10, 18), REF_DATA)).isEqualTo(date(2014, 10, 16));
assertThat(test.calculateMaturityFromFixing(date(2014, 10, 17), REF_DATA)).isEqualTo(date(2014, 10, 19));
assertThat(test.calculateFixingFromMaturity(date(2014, 10, 19), REF_DATA)).isEqualTo(date(2014, 10, 17));
// input date is Sunday
assertThat(test.calculateMaturityFromFixing(date(2014, 10, 19), REF_DATA)).isEqualTo(date(2014, 10, 21));
assertThat(test.calculateFixingFromMaturity(date(2014, 10, 19), REF_DATA)).isEqualTo(date(2014, 10, 17));
}
@Test
public void test_cny() {
FxIndex test = FxIndex.of("USD/CNY-SAEC-CNY01");
assertThat(test.getName()).isEqualTo("USD/CNY-SAEC-CNY01");
}
@Test
public void test_inr() {
FxIndex test = FxIndex.of("USD/INR-FBIL-INR01");
assertThat(test.getName()).isEqualTo("USD/INR-FBIL-INR01");
}
//-------------------------------------------------------------------------
@Test
public void test_equals() {
ImmutableFxIndex a = ImmutableFxIndex.builder()
.name("GBP-EUR")
.currencyPair(CurrencyPair.of(GBP, EUR))
.fixingCalendar(GBLO)
.maturityDateOffset(DaysAdjustment.ofBusinessDays(2, GBLO))
.build();
ImmutableFxIndex b = a.toBuilder().name("EUR-GBP").build();
assertThat(a.equals(b)).isEqualTo(false);
}
//-------------------------------------------------------------------------
@Test
public void coverage() {
coverPrivateConstructor(FxIndices.class);
coverImmutableBean((ImmutableBean) EUR_CHF_ECB);
}
@Test
public void test_jodaConvert() {
assertJodaConvert(FxIndex.class, EUR_CHF_ECB);
}
@Test
public void test_serialization() {
assertSerialization(EUR_CHF_ECB);
}
}
| |
/*
* JBoss, Home of Professional Open Source.
* Copyright 2016 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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.keycloak.adapters.elytron;
import java.util.function.Consumer;
import javax.security.auth.callback.CallbackHandler;
import org.jboss.logging.Logger;
import org.keycloak.KeycloakPrincipal;
import org.keycloak.KeycloakSecurityContext;
import org.keycloak.adapters.AdapterTokenStore;
import org.keycloak.adapters.AdapterUtils;
import org.keycloak.adapters.KeycloakDeployment;
import org.keycloak.adapters.OidcKeycloakAccount;
import org.keycloak.adapters.RefreshableKeycloakSecurityContext;
import org.keycloak.adapters.RequestAuthenticator;
import org.wildfly.security.http.HttpScope;
import org.wildfly.security.http.HttpScopeNotification;
import org.wildfly.security.http.Scope;
/**
* @author <a href="mailto:psilva@redhat.com">Pedro Igor</a>
*/
public class ElytronSessionTokenStore implements ElytronTokeStore {
private static Logger log = Logger.getLogger(ElytronSessionTokenStore.class);
private final ElytronHttpFacade httpFacade;
private final CallbackHandler callbackHandler;
public ElytronSessionTokenStore(ElytronHttpFacade httpFacade, CallbackHandler callbackHandler) {
this.httpFacade = httpFacade;
this.callbackHandler = callbackHandler;
}
@Override
public void checkCurrentToken() {
HttpScope session = httpFacade.getScope(Scope.SESSION);
if (!session.exists()) return;
RefreshableKeycloakSecurityContext securityContext = (RefreshableKeycloakSecurityContext) session.getAttachment(KeycloakSecurityContext.class.getName());
if (securityContext == null) return;
// just in case session got serialized
if (securityContext.getDeployment() == null) securityContext.setCurrentRequestInfo(httpFacade.getDeployment(), this);
if (securityContext.isActive() && !securityContext.getDeployment().isAlwaysRefreshToken()) return;
// FYI: A refresh requires same scope, so same roles will be set. Otherwise, refresh will fail and token will
// not be updated
boolean success = securityContext.refreshExpiredToken(false);
if (success && securityContext.isActive()) return;
// Refresh failed, so user is already logged out from keycloak. Cleanup and expire our session
session.setAttachment(KeycloakSecurityContext.class.getName(), null);
session.invalidate();
}
@Override
public boolean isCached(RequestAuthenticator authenticator) {
HttpScope session = this.httpFacade.getScope(Scope.SESSION);
if (session == null || !session.supportsAttachments()) {
log.debug("session was null, returning null");
return false;
}
ElytronAccount account;
try {
account = (ElytronAccount) session.getAttachment(ElytronAccount.class.getName());
} catch (IllegalStateException e) {
log.debug("session was invalidated. Return false.");
return false;
}
if (account == null) {
log.debug("Account was not in session, returning null");
return false;
}
KeycloakDeployment deployment = httpFacade.getDeployment();
if (!deployment.getRealm().equals(account.getKeycloakSecurityContext().getRealm())) {
log.debug("Account in session belongs to a different realm than for this request.");
return false;
}
boolean active = account.checkActive();
if (!active) {
active = account.tryRefresh(this.callbackHandler);
}
if (active) {
log.debug("Cached account found");
restoreRequest();
httpFacade.authenticationComplete(account, true);
return true;
} else {
log.debug("Refresh failed. Account was not active. Returning null and invalidating Http session");
try {
session.setAttachment(KeycloakSecurityContext.class.getName(), null);
session.setAttachment(ElytronAccount.class.getName(), null);
session.invalidate();
} catch (Exception e) {
log.debug("Failed to invalidate session, might already be invalidated");
}
return false;
}
}
@Override
public void saveAccountInfo(OidcKeycloakAccount account) {
HttpScope session = this.httpFacade.getScope(Scope.SESSION);
if (!session.exists()) {
session.create();
}
session.setAttachment(ElytronAccount.class.getName(), account);
session.setAttachment(KeycloakSecurityContext.class.getName(), account.getKeycloakSecurityContext());
session.registerForNotification(httpScopeNotification -> {
if (!httpScopeNotification.isOfType(HttpScopeNotification.SessionNotificationType.UNDEPLOY)) {
logout();
}
});
HttpScope scope = this.httpFacade.getScope(Scope.EXCHANGE);
scope.setAttachment(KeycloakSecurityContext.class.getName(), account.getKeycloakSecurityContext());
}
@Override
public void logout() {
logout(false);
}
@Override
public void refreshCallback(RefreshableKeycloakSecurityContext securityContext) {
KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal = new KeycloakPrincipal<RefreshableKeycloakSecurityContext>(AdapterUtils.getPrincipalName(this.httpFacade.getDeployment(), securityContext.getToken()), securityContext);
saveAccountInfo(new ElytronAccount(principal));
}
@Override
public void saveRequest() {
this.httpFacade.suspendRequest();
}
@Override
public boolean restoreRequest() {
return this.httpFacade.restoreRequest();
}
@Override
public void logout(boolean glo) {
HttpScope session = this.httpFacade.getScope(Scope.SESSION);
if (!session.exists()) {
return;
}
try {
if (glo) {
KeycloakSecurityContext ksc = (KeycloakSecurityContext) session.getAttachment(KeycloakSecurityContext.class.getName());
if (ksc == null) {
return;
}
KeycloakDeployment deployment = httpFacade.getDeployment();
if (!deployment.isBearerOnly() && ksc != null && ksc instanceof RefreshableKeycloakSecurityContext) {
((RefreshableKeycloakSecurityContext) ksc).logout(deployment);
}
}
session.setAttachment(KeycloakSecurityContext.class.getName(), null);
session.setAttachment(ElytronAccount.class.getName(), null);
session.invalidate();
} catch (IllegalStateException ise) {
// Session may be already logged-out in case that app has adminUrl
log.debugf("Session %s logged-out already", session.getID());
}
}
}
| |
package com.codelv.enamlnative;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Build;
import android.content.Intent;
import android.os.Handler;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.util.Log;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class EnamlActivity extends AppCompatActivity {
public static final String TAG = "EnamlActivity";
// Reference to the activity so it can be accessed from the python interpreter
public static EnamlActivity mActivity = null;
// Save layout elements to display a fade in animation
// When the view is loaded from python
FrameLayout mContentView;
View mPythonView;
View mLoadingView;
Bridge mBridge;
boolean mLoadingDone = false;
int mShortAnimationDuration = 300;
final List<EnamlPackage> mEnamlPackages = new ArrayList<EnamlPackage>();
PermissionResultListener mPermissionResultListener;
final List<ActivityResultListener> mActivityResultListeners = new ArrayList<ActivityResultListener>();
final List<ActivityLifecycleListener> mActivityLifecycleListeners = new ArrayList<ActivityLifecycleListener>();
final List<BackPressedListener> mBackPressedListeners = new ArrayList<BackPressedListener>();
final List<ConfigurationChangedListener> mConfigurationChangedListeners = new ArrayList<ConfigurationChangedListener>();
final HashMap<String, Long> mProfilers = new HashMap<>();
final Handler mHandler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Save reference so python can access it
mActivity = this;
// Initialize the packages
EnamlApplication app = (EnamlApplication) getApplication();
mEnamlPackages.addAll(app.getPackages());
prepareLoadingScreen();
// Create
for (EnamlPackage pkg: getPackages()) {
Log.d(TAG, "Creating "+pkg);
pkg.onCreate(this);
}
// Now notify any listeners
for (ActivityLifecycleListener listener:mActivityLifecycleListeners) {
listener.onActivityLifecycleChanged("created");
}
}
public List<EnamlPackage> getPackages() {
return mEnamlPackages;
}
/**
* Show the loading screen. Can be overridden if necessary.
*/
protected void prepareLoadingScreen() {
// Show loading screen
setContentView(R.layout.activity_main);
// Save views for animation when loading is complete
mContentView = (FrameLayout) findViewById(R.id.contentView);
mLoadingView = getLoadingScreen();
}
/**
* Get the loading screen. This must contain a TextView for displaying
* error messages. It will be swapped in and out when
* @return
*/
protected View getLoadingScreen() {
return findViewById(R.id.loadingView);
}
/**
* Get the text view from the loading screen that will be used
* to display error messages and reloading status.
*
* @return
*/
public TextView getMessageTextView() {
return findViewById(R.id.textView);
}
/**
* Set the bridge implementation
* @param bridge
*/
public void setBridge(Bridge bridge) {
mBridge = bridge;
}
/**
* Should debug messages be used.
* @return
*/
public boolean showDebugMessages() {
return ((EnamlApplication)getApplication()).showDebugMessages();
}
/**
* Set error message text in loading view.
* @param message: Message to display
*/
public void showErrorMessage(String message) {
if (!showDebugMessages()) {
// Crash on release
throw new RuntimeException(message);
}
Log.e(TAG,message);
// Push to end of handler stack as this can occur during the view change animation
mHandler.post(()->{
// Move to top of screen
TextView textView = (TextView) getMessageTextView();
textView.setHorizontallyScrolling(true);
((ViewGroup.MarginLayoutParams) textView.getLayoutParams()).setMargins(10, 10, 10, 10);
textView.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START);
textView.setTextColor(Color.RED);
textView.setText(message);
// Hide progress bar
//View progressBar = findViewById(R.id.progressBar);
//progressBar.setVisibility(View.INVISIBLE);
// If error occured after view was loaded, animate the error back in
if (mLoadingDone) {
// Swap the views back
animateView(mLoadingView, mPythonView);
}
});
}
/**
* Set error message text in loading view from an exception
* @param e: Exception to display.
*/
public void showErrorMessage(Exception e) {
// do something for a debug build
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
showErrorMessage(sw.toString());
}
/**
* Set the content view and fade out the loading view
* @param view
*/
public void setView(View view) {
Log.i(TAG, "View loaded!");
// Support reloading the view
if (mPythonView!=null) {
mContentView.removeView(mPythonView);
mContentView.forceLayout();
mLoadingView.setVisibility(View.VISIBLE);
}
mPythonView = view;
mContentView.addView(view);
animateView(view, mLoadingView);
mLoadingDone = true;
}
/**
* Show the loading screen again with the given message
*/
public void showLoading(String message) {
// Set the message
TextView textView = (TextView) getMessageTextView();
float dp = getResources().getDisplayMetrics().density;
((ViewGroup.MarginLayoutParams) textView.getLayoutParams()).setMargins(10, Math.round(200*dp), 10, 10);
textView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
textView.setTextColor(Color.GRAY);
textView.setText(message);
// Show progress bar
//View progressBar = findViewById(R.id.progressBar);
//progressBar.setVisibility(View.VISIBLE);
if (mPythonView!=null && mLoadingView!=mPythonView) {
// Swap the views back
animateView(mLoadingView, mPythonView);
}
}
protected void animateView(View in, View out) {
// Set the content view to 0% opacity but visible, so that it is visible
// (but fully transparent) during the animation.
in.setAlpha(0f);
in.setVisibility(View.VISIBLE);
// Animate the content view to 100% opacity, and clear any animation
// listener set on the view.
in.animate()
.alpha(1f)
.setDuration(mShortAnimationDuration)
.setListener(null);
// Animate the loading view to 0% opacity. After the animation ends,
// set its visibility to GONE as an optimization step (it won't
// participate in layout passes, etc.)
out.animate()
.alpha(0f)
.setDuration(mShortAnimationDuration)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
out.setVisibility(View.GONE);
}
});
}
/**
* Get bridge controller
* @return
*/
public Bridge getBridge() {
return mBridge;
}
@Override
protected void onStart() {
super.onStart();
// Now initialize everything
for (EnamlPackage pkg: getPackages()) {
pkg.onStart();
}
// Now notify any listeners
for (ActivityLifecycleListener listener:mActivityLifecycleListeners) {
listener.onActivityLifecycleChanged("started");
}
}
@Override
protected void onResume() {
super.onResume();
// Initialize the packages
for (EnamlPackage pkg: getPackages()) {
pkg.onResume();
}
// Now notify any listeners
for (ActivityLifecycleListener listener:mActivityLifecycleListeners) {
listener.onActivityLifecycleChanged("resumed");
}
}
@Override
protected void onPause() {
super.onPause();
// Initialize the packages
for (EnamlPackage pkg: getPackages()) {
pkg.onPause();
}
// Now notify any listeners
for (ActivityLifecycleListener listener:mActivityLifecycleListeners) {
listener.onActivityLifecycleChanged("paused");
}
}
/**
* Dispatch the back pressed event to all listeners. If any of them
* return true then skip the default handler.
*/
@Override
public void onBackPressed(){
boolean handled = false;
for (BackPressedListener listener: mBackPressedListeners) {
handled = handled || listener.onBackPressed();
}
if (!handled) {
super.onBackPressed();
}
}
/**
* Dispatch the back pressed event to all listeners.
*/
@Override
public void onConfigurationChanged(Configuration config) {
super.onConfigurationChanged(config);
for (ConfigurationChangedListener listener: mConfigurationChangedListeners) {
listener.onConfigurationChanged(new HashMap<String, Object>() {{
put("width", config.screenWidthDp);
put("height", config.screenHeightDp);
put("orientation", config.orientation);
}});
}
}
@Override
protected void onStop() {
super.onStop();
// Initialize the packages
for (EnamlPackage pkg: getPackages()) {
pkg.onStop();
}
// Now notify any listeners
for (ActivityLifecycleListener listener:mActivityLifecycleListeners) {
listener.onActivityLifecycleChanged("stopped");
}
}
@Override
protected void onDestroy() {
super.onDestroy();
// Initialize the packages
for (EnamlPackage pkg: getPackages()) {
pkg.onDestroy();
}
// Now notify any listeners
for (ActivityLifecycleListener listener:mActivityLifecycleListeners) {
listener.onActivityLifecycleChanged("destroyed");
}
}
/**
* Set the app permission listener to use. Meant to be used from python
* so it can receive events from java.
* @param listener
*/
public void setPermissionResultListener(PermissionResultListener listener) {
mPermissionResultListener = listener;
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (mPermissionResultListener !=null) {
mPermissionResultListener.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
public interface PermissionResultListener{
/**
* Receive permission request results
* @param code
* @param permissions
* @param results
*/
void onRequestPermissionsResult(int code, String[] permissions, int[] results);
}
/**
* Add an app activity result listener to use. Meant to be used from python
* so it can receive events from java.
* @param listener
*/
public void addActivityResultListener(ActivityResultListener listener) {
mActivityResultListeners.add(listener);
}
public void removeActivityResultListener(ActivityResultListener listener) {
mActivityResultListeners.remove(listener);
}
/**
* Let Packages and python handle activity results and break execution
* if needed.
* @param requestCode
* @param resultCode
* @param data
*/
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
boolean handled = false;
for (ActivityResultListener listener: mActivityResultListeners) {
if (listener.onActivityResult(requestCode, resultCode, data)) {
handled = true; // But still execute the rest
}
}
if (!handled) {
super.onActivityResult(requestCode, resultCode, data);
}
}
public interface ActivityResultListener{
/**
* Receive activity request results from Intents
* @param requestCode
* @param resultCode
* @param data
*/
boolean onActivityResult(int requestCode, int resultCode, Intent data);
}
/**
* Add an app activity lifecycle listener to use. Meant to be used from python
* so it can receive events from java when the app state changes.
* @param listener
*/
public void addActivityLifecycleListener(ActivityLifecycleListener listener) {
mActivityLifecycleListeners.add(listener);
}
public void removeActivityLifecycleListener(ActivityLifecycleListener listener) {
mActivityLifecycleListeners.remove(listener);
}
public interface ActivityLifecycleListener{
/**
* Receive activity lifecycle changes
* @param state
*/
void onActivityLifecycleChanged(String state);
}
/**
* Add a back press listener to use. Meant to be used from python
* so it can receive events from java when the back button is pressed.
* @param listener
*/
public void addBackPressedListener(BackPressedListener listener) {
mBackPressedListeners.add(listener);
}
public void removeBackPressedListener(BackPressedListener listener) {
mBackPressedListeners.remove(listener);
}
public interface BackPressedListener {
/**
* Called when the back button is pressed. All listeners will be called. If
* one of them return true the default handler will NOT be invoked.
*
* Handlers must be fast or they will block the UI.
*/
boolean onBackPressed();
}
/**
* Add an configuration change listener. Meant to be used from python
* so it can receive events from java when screen orientation changes.
* @param listener
*/
public void addConfigurationChangedListener(ConfigurationChangedListener listener) {
mConfigurationChangedListeners.add(listener);
}
public void removeConfigurationChangedListener(ConfigurationChangedListener listener) {
mConfigurationChangedListeners.remove(listener);
}
public interface ConfigurationChangedListener {
/**
* Called when screen configuration changes. All listeners will be called.
*
* Handlers must be fast or they will block the UI.
*/
void onConfigurationChanged(HashMap<String, Object> configuration);
}
/**
* Return build info. Called from python at startup to get info like screen density
* and API version.
* @return
*/
public HashMap<String,Object> getBuildInfo() {
DisplayMetrics metrics = getResources().getDisplayMetrics();
return new HashMap<String, Object>() {{
put("BOARD",Build.BOARD);
put("BOOTLOADER", Build.BOOTLOADER);
put("BRAND", Build.BRAND);
put("DISPLAY", Build.DISPLAY);
put("DEVICE", Build.DEVICE);
put("FINGERPRINT", Build.FINGERPRINT);
put("HARDWARE", Build.HARDWARE);
put("HOST", Build.HOST);
put("ID", Build.ID);
put("MANUFACTURER", Build.MANUFACTURER);
put("MODEL", Build.MODEL);
put("TIME", Build.TIME);
put("TAGS", Build.TAGS);
put("PRODUCT", Build.PRODUCT);
put("SERIAL", Build.SERIAL);
put("USER", Build.USER);
put("SDK_INT",Build.VERSION.SDK_INT);
put("RELEASE", Build.VERSION.RELEASE);
put("CODENAME", Build.VERSION.CODENAME);
put("DISPLAY_DENSITY", metrics.density);
put("DISPLAY_WIDTH", metrics.widthPixels/metrics.density);
put("DISPLAY_HEIGHT", metrics.heightPixels/metrics.density);
put("DISPLAY_ORIENTATION", getResources().getConfiguration().orientation);
}};
}
/**
* Utility for measuring how long tasks take.
*/
public void startTrace(String tag) {
Log.i(TAG, "[Trace][" + tag + "] Started ");
mProfilers.put(tag, System.currentTimeMillis());
}
public void stopTrace(String tag) {
Log.i(TAG, "[Trace][" + tag + "] Ended " + (System.currentTimeMillis() - mProfilers.get(tag)) + " (ms)");
}
/**
* Reset stats on the bridge
*/
public void resetBridgeStats() {
mBridge.resetStats();
}
/**
* Reset cached objects on the bridge
*/
public void resetBridgeCache() {
mBridge.clearCache();
}
}
| |
package gov.cdc.epiinfo.statcalc;
import gov.cdc.epiinfo.DeviceManager;
import gov.cdc.epiinfo.R;
import gov.cdc.epiinfo.statcalc.calculators.Cohort;
import gov.cdc.epiinfo.statcalc.etc.CCResult;
import java.text.DecimalFormat;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;
public class CohortActivity extends Activity implements SeekBar.OnSeekBarChangeListener {
Spinner ddlConfidence;
TextView txtPower;
SeekBar skbPower;
EditText txtControlRatio;
TextView txtPercentExposed;
SeekBar skbPercentExposed;
EditText txtOddsRatio;
EditText txtRiskRatio;
TextView txtPercentCasesExposure;
SeekBar skbPercentCasesExposure;
TextView txtKelseyCases;
TextView txtKelseyControls;
TextView txtKelseyTotal;
TextView txtFleissCases;
TextView txtFleissControls;
TextView txtFleissTotal;
TextView txtFleissCCCases;
TextView txtFleissCCControls;
TextView txtFleissCCTotal;
InputMethodManager imm;
Cohort calc;
boolean riskChanging;
boolean oddsChanging;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DeviceManager.SetOrientation(this, false);
this.setTheme(R.style.AppThemeNoBar);
setContentView(R.layout.statcalc_cohort);
riskChanging = false;
oddsChanging = false;
calc = new Cohort();
imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
ddlConfidence = findViewById(R.id.ddlConfidence);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,R.array.confidence_levels, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
ddlConfidence.setAdapter(adapter);
ddlConfidence.setOnItemSelectedListener(
new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
Calculate();
}
public void onNothingSelected(AdapterView<?> parent)
{
// do nothing
}
}
);
txtPower = findViewById(R.id.txtPower);
skbPower = findViewById(R.id.skbPower);
skbPower.setOnSeekBarChangeListener(this);
txtControlRatio = findViewById(R.id.txtControlRatio);
txtControlRatio.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (txtControlRatio.getText().toString().length() > 0)
{
Calculate();
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
txtPercentExposed = findViewById(R.id.txtPercentExposed);
skbPercentExposed = findViewById(R.id.skbPercentExposed);
skbPercentExposed.setOnSeekBarChangeListener(this);
txtRiskRatio = findViewById(R.id.txtRiskRatio);
txtRiskRatio.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (txtRiskRatio.getText().toString().length() > 0)
{
double riskRatioRaw = Double.parseDouble(txtRiskRatio.getText().toString());
double percentExposed = ((skbPercentExposed.getProgress() / 10) / 10.0)/100.0;
double oddsRatioRaw = calc.RiskToOdds(riskRatioRaw, percentExposed);
if (!oddsChanging)
{
if (oddsRatioRaw < 999)
{
txtOddsRatio.setText(new DecimalFormat("#.##").format(oddsRatioRaw));
}
else
{
txtOddsRatio.setText(new DecimalFormat("#").format(oddsRatioRaw));
}
}
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
riskChanging = true;
}
@Override
public void afterTextChanged(Editable s) {
riskChanging = false;
}
});
txtOddsRatio = findViewById(R.id.txtOddsRatio);
txtOddsRatio.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (txtOddsRatio.getText().toString().length() > 0)
{
double oddsRatioRaw = Double.parseDouble(txtOddsRatio.getText().toString());
double percentExposed = ((skbPercentExposed.getProgress() / 10) / 10.0)/100.0;
double percentCases = calc.OddsToPercentCases(oddsRatioRaw, percentExposed);
double riskRatioRaw = calc.OddsToRisk(oddsRatioRaw, percentExposed);
if (!riskChanging)
{
if (riskRatioRaw < 999)
{
txtRiskRatio.setText(new DecimalFormat("#.##").format(riskRatioRaw));
}
else
{
txtRiskRatio.setText(new DecimalFormat("#").format(riskRatioRaw));
}
}
skbPercentCasesExposure.setProgress((int)Math.round(percentCases * 100.0));
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
oddsChanging = true;
}
@Override
public void afterTextChanged(Editable s) {
oddsChanging = false;
}
});
txtPercentCasesExposure = findViewById(R.id.txtPercentCasesExposure);
skbPercentCasesExposure = findViewById(R.id.skbPercentCasesExposure);
skbPercentCasesExposure.setOnSeekBarChangeListener(this);
txtKelseyCases = findViewById(R.id.txtKelseyCases);
txtKelseyControls = findViewById(R.id.txtKelseyControls);
txtKelseyTotal = findViewById(R.id.txtKelseyTotal);
txtFleissCases = findViewById(R.id.txtFleissCases);
txtFleissControls = findViewById(R.id.txtFleissControls);
txtFleissTotal = findViewById(R.id.txtFleissTotal);
txtFleissCCCases = findViewById(R.id.txtFleissCCCases);
txtFleissCCControls = findViewById(R.id.txtFleissCCControls);
txtFleissCCTotal = findViewById(R.id.txtFleissCCTotal);
Calculate();
imm.hideSoftInputFromWindow(txtControlRatio.getWindowToken(), 0);
}
private void Calculate()
{
calc = new Cohort();
String confidenceRaw = ddlConfidence.getSelectedItem().toString().split("%")[0];
double confidence = (100.0 - Double.parseDouble(confidenceRaw)) / 100.0;
double power = (skbPower.getProgress() / 100.0) / 100.0;
double controlRatio = 1;
if (txtControlRatio.getText().toString().length() > 0)
{
controlRatio = Double.parseDouble(txtControlRatio.getText().toString());
}
else
{
txtControlRatio.setText("1");
}
double percentExposed = (skbPercentExposed.getProgress() / 100.0) / 100.0;
double oddsRatio = 3;
if (txtOddsRatio.getText().toString().length() > 0)
{
oddsRatio = Double.parseDouble(txtOddsRatio.getText().toString());
}
else
{
txtOddsRatio.setText("3");
}
double percentCasesExposure = (skbPercentCasesExposure.getProgress() / 100.0) / 100.0;
CCResult results = calc.CalculateUnmatchedCaseControl(confidence, power, controlRatio, percentExposed, oddsRatio, percentCasesExposure);
txtKelseyCases.setText(results.GetKelseyCases() + "");
txtKelseyControls.setText(results.GetKelseyControls() + "");
txtKelseyTotal.setText((results.GetKelseyCases() + results.GetKelseyControls()) + "");
txtFleissCases.setText(results.GetFleissCases() + "");
txtFleissControls.setText(results.GetFleissControls() + "");
txtFleissTotal.setText((results.GetFleissCases() + results.GetFleissControls()) + "");
txtFleissCCCases.setText(results.GetFleissCCCases() + "");
txtFleissCCControls.setText(results.GetFleissCCControls() + "");
txtFleissCCTotal.setText((results.GetFleissCCCases() + results.GetFleissCCControls()) + "");
//scroller.fullScroll(ScrollView.FOCUS_DOWN);
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
if (seekBar.getId() == R.id.skbPower)
{
txtPower.setText(((progress / 10) / 10.0) + "%");
}
else if (seekBar.getId() == R.id.skbPercentExposed)
{
double percentExposedRaw = (progress / 10) / 10.0;
double percentExposed = percentExposedRaw / 100.0;
double percentCases = ((skbPercentCasesExposure.getProgress() / 10) / 10.0)/100.0;
double oddsRatioRaw = calc.PercentCasesToOdds(percentCases, percentExposed);
txtPercentExposed.setText(percentExposedRaw + "%");
if (oddsRatioRaw < 999)
{
txtOddsRatio.setText(new DecimalFormat("#.##").format(oddsRatioRaw));
}
else
{
txtOddsRatio.setText(new DecimalFormat("#").format(oddsRatioRaw));
}
}
else
{
double percentCasesRaw = (progress / 10) / 10.0;
double percentCases = percentCasesRaw / 100.0;
double percentExposed = ((skbPercentExposed.getProgress() / 10) / 10.0)/100.0;
double oddsRatioRaw = calc.PercentCasesToOdds(percentCases, percentExposed);
txtPercentCasesExposure.setText(percentCasesRaw + "%");
if (fromUser)
{
if (oddsRatioRaw < 999)
{
txtOddsRatio.setText(new DecimalFormat("#.##").format(oddsRatioRaw));
}
else
{
txtOddsRatio.setText(new DecimalFormat("#").format(oddsRatioRaw));
}
}
}
if (fromUser)
{
imm.hideSoftInputFromWindow(txtOddsRatio.getWindowToken(), 0);
}
Calculate();
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}
| |
/**
* Copyright (C) 2012-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mangoo.maven;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.apache.maven.project.MavenProject;
import io.mangoo.build.Minification;
import io.mangoo.build.Runner;
import io.mangoo.build.Trigger;
import io.mangoo.build.Watcher;
import io.mangoo.core.Application;
import io.mangoo.utils.MangooUtils;
/**
* This is a refactored version of
* NinjaRunMojo.java from the Ninja Web Framework
*
* Original source code can be found here:
* https://github.com/ninjaframework/ninja/blob/develop/ninja-maven-plugin/src/main/java/ninja/maven/NinjaRunMojo.java
*
* @author svenkubiak
*
*/
@Mojo(name = "run",
requiresDependencyResolution = ResolutionScope.COMPILE_PLUS_RUNTIME,
defaultPhase = LifecyclePhase.NONE,
threadSafe = true)
public class MangooMojo extends AbstractMojo {
private static final String [] DEFAULT_EXCLUDE_PATTERNS = {
"(.*)" + Pattern.quote(File.separator) + "templates" + Pattern.quote(File.separator) + "(.*)ftl",
"(.*)less",
"(.*)sass",
"(.*)" + Pattern.quote(File.separator) + "assets" + Pattern.quote(File.separator) + "(.*)"
};
@Parameter(defaultValue = "${project}", readonly = true)
protected MavenProject project;
@Parameter(property = "mangoo.skip", defaultValue="false", required = true)
private boolean skip;
@Parameter(property = "mangoo.jpdaPort", defaultValue="0", required = true)
private int jpdaPort;
@Parameter(property = "mangoo.jvmArgs", required = false)
private String jvmArgs;
@Parameter(property = "mangoo.outputDirectory", defaultValue = "${project.build.outputDirectory}", required = true)
private String buildOutputDirectory;
@Parameter(property = "mangoo.watchDirs", required = false)
private File[] watchDirs;
@Parameter(property = "mangoo.watchAllClassPathDirs", defaultValue = "false", required = true)
private boolean watchAllClassPathDirs;
@Parameter(property = "mangoo.watchAllClassPathJars", defaultValue = "false", required = true)
private boolean watchAllClassPathJars;
@Parameter(property = "mangoo.includes", required = false)
protected List<String> includes;
@Parameter(property = "mangoo.excludes", required = false)
private List<String> excludes;
@Parameter(property = "mangoo.useDefaultExcludes", defaultValue = "true", required = true)
protected boolean useDefaultExcludes;
@Parameter(property = "mangoo.settleDownMillis", defaultValue="500", required = false)
private Long settleDownMillis;
@Override
public void execute() throws MojoExecutionException {
if (skip) {
getLog().info("Skip flag is on. Will not execute.");
return;
}
initMojo();
checkClasses(buildOutputDirectory);
Minification.setBasePath(project.getBasedir().getAbsolutePath());
List<String> classpathItems = new ArrayList<>();
classpathItems.add(buildOutputDirectory);
for (Artifact artifact: project.getArtifacts()) {
classpathItems.add(artifact.getFile().toString()); //NOSONAR
}
Set<String> includesSet = new LinkedHashSet<>(includes);
Set<String> excludesSet = new LinkedHashSet<>(excludes);
Set<Path> watchDirectories = new LinkedHashSet<>();
var fileSystem = FileSystems.getDefault();
watchDirectories.add(fileSystem.getPath(buildOutputDirectory).toAbsolutePath());
if (this.watchDirs != null) {
for (File watchDir: this.watchDirs) {
watchDirectories.add(watchDir.toPath().toAbsolutePath());
}
}
getArtifacts(includesSet, excludesSet, watchDirectories);
startRunner(classpathItems, includesSet, excludesSet, watchDirectories);
MangooUtils.closeQuietly(fileSystem);
}
private void startRunner(List<String> classpathItems, Set<String> includesSet, Set<String> excludesSet, Set<Path> watchDirectories) {
try {
var machine = new Runner(
Application.class.getName(),
StringUtils.join(classpathItems, File.pathSeparator),
project.getBasedir(),
jpdaPort,
jvmArgs);
var restartTrigger = new Trigger(machine);
restartTrigger.setSettleDownMillis(settleDownMillis);
restartTrigger.start();
var watcher = new Watcher(
watchDirectories,
includesSet,
excludesSet,
restartTrigger);
machine.restart();
watcher.run(); //NOSONAR
} catch (IOException e) {
getLog().error(e);
}
}
private void getArtifacts(Set<String> includesSet, Set<String> excludesSet, Set<Path> watchDirectories) {
for (Artifact artifact : project.getArtifacts()) {
File file = artifact.getFile();
if (this.watchAllClassPathDirs && file.isDirectory()) {
watchDirectories.add(file.toPath().toAbsolutePath());
} else if (file.getName().endsWith(".jar") && this.watchAllClassPathJars) {
var parentDir = file.getParentFile();
var parentPath = parentDir.toPath().toAbsolutePath();
String rulePrefix = parentDir.getAbsolutePath() + File.separator;
rulePrefix = rulePrefix.replace("\\", "\\\\");
if (!watchDirectories.contains(parentPath)) {
excludesSet.add(rulePrefix + "(.*)$");
}
includesSet.add(rulePrefix + file.getName() + "$");
watchDirectories.add(parentPath);
} else {
// Ignore anything else
}
}
}
private void initMojo() {
if (useDefaultExcludes) {
excludes.addAll(List.of(DEFAULT_EXCLUDE_PATTERNS));
}
}
@SuppressWarnings("all")
public void checkClasses(String classesDirectory) {
if (!new File(classesDirectory).exists()) { //NOSONAR
getLog().error("Directory with classes does not exist: " + classesDirectory);
System.exit(1); //NOSONAR
}
}
}
| |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.action.search.type;
import com.carrotsearch.hppc.IntArrayList;
import org.apache.lucene.search.ScoreDoc;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.ActionRunnable;
import org.elasticsearch.action.search.ReduceSearchPhaseException;
import org.elasticsearch.action.search.SearchPhaseExecutionException;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.ActionFilters;
import org.elasticsearch.cluster.ClusterService;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.util.concurrent.AtomicArray;
import org.elasticsearch.search.SearchShardTarget;
import org.elasticsearch.search.action.SearchServiceTransportAction;
import org.elasticsearch.search.controller.SearchPhaseController;
import org.elasticsearch.search.dfs.AggregatedDfs;
import org.elasticsearch.search.dfs.DfsSearchResult;
import org.elasticsearch.search.fetch.ShardFetchSearchRequest;
import org.elasticsearch.search.fetch.FetchSearchResult;
import org.elasticsearch.search.internal.InternalSearchResponse;
import org.elasticsearch.search.internal.ShardSearchTransportRequest;
import org.elasticsearch.search.query.QuerySearchRequest;
import org.elasticsearch.search.query.QuerySearchResult;
import org.elasticsearch.threadpool.ThreadPool;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;
/**
*
*/
public class TransportSearchDfsQueryThenFetchAction extends TransportSearchTypeAction {
@Inject
public TransportSearchDfsQueryThenFetchAction(Settings settings, ThreadPool threadPool, ClusterService clusterService,
SearchServiceTransportAction searchService, SearchPhaseController searchPhaseController, ActionFilters actionFilters) {
super(settings, threadPool, clusterService, searchService, searchPhaseController, actionFilters);
}
@Override
protected void doExecute(SearchRequest searchRequest, ActionListener<SearchResponse> listener) {
new AsyncAction(searchRequest, listener).start();
}
private class AsyncAction extends BaseAsyncAction<DfsSearchResult> {
final AtomicArray<QuerySearchResult> queryResults;
final AtomicArray<FetchSearchResult> fetchResults;
final AtomicArray<IntArrayList> docIdsToLoad;
private AsyncAction(SearchRequest request, ActionListener<SearchResponse> listener) {
super(request, listener);
queryResults = new AtomicArray<>(firstResults.length());
fetchResults = new AtomicArray<>(firstResults.length());
docIdsToLoad = new AtomicArray<>(firstResults.length());
}
@Override
protected String firstPhaseName() {
return "dfs";
}
@Override
protected void sendExecuteFirstPhase(DiscoveryNode node, ShardSearchTransportRequest request, ActionListener<DfsSearchResult> listener) {
searchService.sendExecuteDfs(node, request, listener);
}
@Override
protected void moveToSecondPhase() {
final AggregatedDfs dfs = searchPhaseController.aggregateDfs(firstResults);
final AtomicInteger counter = new AtomicInteger(firstResults.asList().size());
for (final AtomicArray.Entry<DfsSearchResult> entry : firstResults.asList()) {
DfsSearchResult dfsResult = entry.value;
DiscoveryNode node = nodes.get(dfsResult.shardTarget().nodeId());
QuerySearchRequest querySearchRequest = new QuerySearchRequest(request, dfsResult.id(), dfs);
executeQuery(entry.index, dfsResult, counter, querySearchRequest, node);
}
}
void executeQuery(final int shardIndex, final DfsSearchResult dfsResult, final AtomicInteger counter, final QuerySearchRequest querySearchRequest, DiscoveryNode node) {
searchService.sendExecuteQuery(node, querySearchRequest, new ActionListener<QuerySearchResult>() {
@Override
public void onResponse(QuerySearchResult result) {
result.shardTarget(dfsResult.shardTarget());
queryResults.set(shardIndex, result);
if (counter.decrementAndGet() == 0) {
executeFetchPhase();
}
}
@Override
public void onFailure(Throwable t) {
onQueryFailure(t, querySearchRequest, shardIndex, dfsResult, counter);
}
});
}
void onQueryFailure(Throwable t, QuerySearchRequest querySearchRequest, int shardIndex, DfsSearchResult dfsResult, AtomicInteger counter) {
if (logger.isDebugEnabled()) {
logger.debug("[{}] Failed to execute query phase", t, querySearchRequest.id());
}
this.addShardFailure(shardIndex, dfsResult.shardTarget(), t);
successfulOps.decrementAndGet();
if (counter.decrementAndGet() == 0) {
if (successfulOps.get() == 0) {
listener.onFailure(new SearchPhaseExecutionException("query", "all shards failed", buildShardFailures()));
} else {
executeFetchPhase();
}
}
}
void executeFetchPhase() {
try {
innerExecuteFetchPhase();
} catch (Throwable e) {
listener.onFailure(new ReduceSearchPhaseException("query", "", e, buildShardFailures()));
}
}
void innerExecuteFetchPhase() throws Exception {
boolean useScroll = request.scroll() != null;
sortedShardList = searchPhaseController.sortDocs(useScroll, queryResults);
searchPhaseController.fillDocIdsToLoad(docIdsToLoad, sortedShardList);
if (docIdsToLoad.asList().isEmpty()) {
finishHim();
return;
}
final ScoreDoc[] lastEmittedDocPerShard = searchPhaseController.getLastEmittedDocPerShard(
request, sortedShardList, firstResults.length()
);
final AtomicInteger counter = new AtomicInteger(docIdsToLoad.asList().size());
for (final AtomicArray.Entry<IntArrayList> entry : docIdsToLoad.asList()) {
QuerySearchResult queryResult = queryResults.get(entry.index);
DiscoveryNode node = nodes.get(queryResult.shardTarget().nodeId());
ShardFetchSearchRequest fetchSearchRequest = createFetchRequest(queryResult, entry, lastEmittedDocPerShard);
executeFetch(entry.index, queryResult.shardTarget(), counter, fetchSearchRequest, node);
}
}
void executeFetch(final int shardIndex, final SearchShardTarget shardTarget, final AtomicInteger counter, final ShardFetchSearchRequest fetchSearchRequest, DiscoveryNode node) {
searchService.sendExecuteFetch(node, fetchSearchRequest, new ActionListener<FetchSearchResult>() {
@Override
public void onResponse(FetchSearchResult result) {
result.shardTarget(shardTarget);
fetchResults.set(shardIndex, result);
if (counter.decrementAndGet() == 0) {
finishHim();
}
}
@Override
public void onFailure(Throwable t) {
onFetchFailure(t, fetchSearchRequest, shardIndex, shardTarget, counter);
}
});
}
void onFetchFailure(Throwable t, ShardFetchSearchRequest fetchSearchRequest, int shardIndex, SearchShardTarget shardTarget, AtomicInteger counter) {
if (logger.isDebugEnabled()) {
logger.debug("[{}] Failed to execute fetch phase", t, fetchSearchRequest.id());
}
this.addShardFailure(shardIndex, shardTarget, t);
successfulOps.decrementAndGet();
if (counter.decrementAndGet() == 0) {
finishHim();
}
}
private void finishHim() {
threadPool.executor(ThreadPool.Names.SEARCH).execute(new ActionRunnable<SearchResponse>(listener) {
@Override
public void doRun() throws IOException {
final InternalSearchResponse internalResponse = searchPhaseController.merge(sortedShardList, queryResults, fetchResults);
String scrollId = null;
if (request.scroll() != null) {
scrollId = TransportSearchHelper.buildScrollId(request.searchType(), firstResults, null);
}
listener.onResponse(new SearchResponse(internalResponse, scrollId, expectedSuccessfulOps, successfulOps.get(), buildTookInMillis(), buildShardFailures()));
releaseIrrelevantSearchContexts(queryResults, docIdsToLoad);
}
@Override
public void onFailure(Throwable t) {
try {
ReduceSearchPhaseException failure = new ReduceSearchPhaseException("merge", "", t, buildShardFailures());
if (logger.isDebugEnabled()) {
logger.debug("failed to reduce search", failure);
}
super.onFailure(failure);
} finally {
releaseIrrelevantSearchContexts(queryResults, docIdsToLoad);
}
}
});
}
}
}
| |
/**
* Copyright 2010 - 2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.exodus.core.execution;
import jetbrains.exodus.core.dataStructures.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
public abstract class JobProcessorQueueAdapter extends JobProcessorAdapter {
public static final String CONCURRENT_QUEUE_PROPERTY = "jetbrains.exodus.core.execution.concurrentQueue";
private final PriorityQueue<Priority, Job> queue;
private final PriorityQueue<Long, Job> timeQueue;
private volatile int outdatedJobsCount;
private volatile Job currentJob;
protected final Semaphore awake;
@SuppressWarnings("unchecked")
protected JobProcessorQueueAdapter() {
queue = createQueue();
timeQueue = createQueue();
awake = new Semaphore(0);
}
@Override
protected boolean queueLowest(@NotNull Job job) {
if (isFinished()) return false;
if (job.getProcessor() == null) {
job.setProcessor(this);
}
queue.lock();
try {
final Pair<Priority, Job> pair = queue.floorPair();
final Priority priority = pair == null ? Priority.highest : pair.getFirst();
if (queue.push(priority, job) != null) {
return false;
}
} finally {
queue.unlock();
}
awake.release();
return true;
}
@Override
protected boolean push(final Job job, final Priority priority) {
if (isFinished()) return false;
if (job.getProcessor() == null) {
job.setProcessor(this);
}
queue.lock();
try {
if (queue.push(priority, job) != null) {
return false;
}
} finally {
queue.unlock();
}
awake.release();
return true;
}
@Override
protected Job pushAt(final Job job, final long millis) {
if (isFinished()) {
return null;
}
if (job.getProcessor() == null) {
job.setProcessor(this);
}
Job oldJob;
final Pair<Long, Job> pair;
final long priority = Long.MAX_VALUE - millis;
timeQueue.lock();
try {
oldJob = timeQueue.push(priority, job);
pair = timeQueue.peekPair();
} finally {
timeQueue.unlock();
}
if (pair != null && pair.getFirst() != priority) {
return oldJob;
}
awake.release();
return oldJob;
}
@Override
protected boolean queueLowestTimed(@NotNull final Job job) {
if (isFinished()) {
return false;
}
if (job.getProcessor() == null) {
job.setProcessor(this);
}
timeQueue.lock();
try {
final Pair<Long, Job> pair = timeQueue.floorPair();
final long priority = pair == null ? Long.MAX_VALUE - System.currentTimeMillis() : pair.getFirst();
if (timeQueue.push(priority, job) != null) {
return false;
}
} finally {
timeQueue.unlock();
}
awake.release();
return true;
}
@Override
public int pendingJobs() {
return queue.size() + (currentJob == null ? 0 : 1);
}
@Override
public int pendingTimedJobs() {
return timeQueue.size() + outdatedJobsCount;
}
@Nullable
@Override
public Job getCurrentJob() {
return currentJob;
}
@NotNull
@Override
public Iterable<Job> getPendingJobs() {
return queue;
}
protected void doJobs() {
final boolean jobsQueued;
try {
jobsQueued = waitForJobs();
} catch (InterruptedException e) {
return;
}
if (!isFinished()) {
if (jobsQueued) {
final Job job;
queue.lock();
try {
job = queue.pop();
} finally {
queue.unlock();
}
doExecuteJob(job);
} else {
doTimedJobs();
}
}
}
protected void clearQueues() {
queue.clear();
timeQueue.clear();
}
protected void doTimedJobs() {
final Collection<Job> outdatedJobs = new ArrayList<>();
final long currentTimePriority = Long.MAX_VALUE - System.currentTimeMillis();
final int count;
timeQueue.lock();
try {
Pair<Long, Job> pair = timeQueue.peekPair();
while (pair != null && pair.getFirst() >= currentTimePriority) {
outdatedJobs.add(timeQueue.pop());
pair = timeQueue.peekPair();
}
count = outdatedJobs.size();
} finally {
timeQueue.unlock();
}
// outdatedJobsCount is updated in single thread, so we won't bother with synchronization on its update
outdatedJobsCount = count;
for (final Job job : outdatedJobs) {
executeImmediateJobsIfAny();
if (isFinished()) {
break;
}
doExecuteJob(job);
--outdatedJobsCount;
}
}
private void executeImmediateJobsIfAny() {
//noinspection StatementWithEmptyBody
while (!isFinished() && executeImmediateJobIfAny() != null) ;
}
/**
* @return executed job or null if it was nothing to execute.
*/
private Job executeImmediateJobIfAny() {
Job urgentImmediateJob = null;
queue.lock();
try {
final Pair<Priority, Job> peekPair = queue.peekPair();
if (peekPair != null && peekPair.getFirst() == Priority.highest) {
urgentImmediateJob = queue.pop();
}
} finally {
queue.unlock();
}
if (urgentImmediateJob != null) {
doExecuteJob(urgentImmediateJob);
}
return urgentImmediateJob;
}
// returns true if a job was queued within a timeout
protected boolean waitForJobs() throws InterruptedException {
final Pair<Long, Job> peekPair;
timeQueue.lock();
try {
peekPair = timeQueue.peekPair();
} finally {
timeQueue.unlock();
}
if (peekPair == null) {
awake.acquire();
return true;
}
final long timeout = Long.MAX_VALUE - peekPair.getFirst() - System.currentTimeMillis();
if (timeout < 0) {
return false;
}
return awake.tryAcquire(timeout, TimeUnit.MILLISECONDS);
}
private void doExecuteJob(final Job job) {
currentJob = job;
try {
executeJob(job);
} finally {
currentJob = null;
}
}
@SuppressWarnings("rawtypes")
private static PriorityQueue createQueue() {
final String concurrentQueueProperty = System.getProperty(CONCURRENT_QUEUE_PROPERTY);
if (concurrentQueueProperty != null && "false".equalsIgnoreCase(concurrentQueueProperty)) {
return new StablePriorityQueue();
}
return new ConcurrentStablePriorityQueue();
}
}
| |
/*
* Copyright 2000-2014 Vaadin 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 com.vaadin.ui;
import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import com.vaadin.server.VaadinSession;
import com.vaadin.server.communication.AtmospherePushConnection;
import com.vaadin.shared.communication.PushMode;
import com.vaadin.shared.ui.ui.Transport;
import com.vaadin.shared.ui.ui.UIState.PushConfigurationState;
/**
* Provides method for configuring the push channel.
*
* @since 7.1
* @author Vaadin Ltd
*/
public interface PushConfiguration extends Serializable {
/**
* Returns the mode of bidirectional ("push") communication that is used.
*
* @return The push mode.
*/
public PushMode getPushMode();
/**
* Sets the mode of bidirectional ("push") communication that should be
* used.
* <p>
* Add-on developers should note that this method is only meant for the
* application developer. An add-on should not set the push mode directly,
* rather instruct the user to set it.
* </p>
*
* @param pushMode
* The push mode to use.
*
* @throws IllegalArgumentException
* if the argument is null.
* @throws IllegalStateException
* if push support is not available.
*/
public void setPushMode(PushMode pushMode);
/**
* Returns the primary transport type for push.
* <p>
* Note that if you set the transport type using
* {@link #setParameter(String, String)} to an unsupported type this method
* will return null. Supported types are defined by {@link Transport}.
*
* @return The primary transport type
*/
public Transport getTransport();
/**
* Sets the primary transport type for push.
* <p>
* Note that the new transport type will not be used until the push channel
* is disconnected and reconnected if already active.
*
* @param transport
* The primary transport type
*/
public void setTransport(Transport transport);
/**
* Returns the fallback transport type for push.
* <p>
* Note that if you set the transport type using
* {@link #setParameter(String, String)} to an unsupported type this method
* will return null. Supported types are defined by {@link Transport}.
*
* @return The fallback transport type
*/
public Transport getFallbackTransport();
/**
* Sets the fallback transport type for push.
* <p>
* Note that the new transport type will not be used until the push channel
* is disconnected and reconnected if already active.
*
* @param fallbackTransport
* The fallback transport type
*/
public void setFallbackTransport(Transport fallbackTransport);
/**
* Returns the given parameter, if set.
* <p>
* This method provides low level access to push parameters and is typically
* not needed for normal application development.
*
* @since 7.1
* @param parameter
* The parameter name
* @return The parameter value or null if not set
*/
public String getParameter(String parameter);
/**
* Returns the parameters which have been defined.
*
* @since 7.1
* @return A collection of parameter names
*/
public Collection<String> getParameterNames();
/**
* Sets the given parameter.
* <p>
* This method provides low level access to push parameters and is typically
* not needed for normal application development.
*
* @since 7.1
* @param parameter
* The parameter name
* @param value
* The value
*/
public void setParameter(String parameter, String value);
/**
* Sets the URL to use for push requests.
* <p>
* This is only used when overriding the URL to use. Setting this to null
* (the default) will use the default URL.
*
* @since
* @param pushUrl
* The push URL to use
*/
public void setPushUrl(String pushUrl);
/**
* Returns the URL to use for push requests.
* <p>
* This is only used when overriding the URL to use. Returns null (the
* default) when the default URL is used.
*
* @since
* @return the URL to use for push requests, or null to use to default
*/
public String getPushUrl();
}
class PushConfigurationImpl implements PushConfiguration {
private UI ui;
public PushConfigurationImpl(UI ui) {
this.ui = ui;
}
/*
* (non-Javadoc)
*
* @see com.vaadin.ui.PushConfiguration#getPushMode()
*/
@Override
public PushMode getPushMode() {
return getState(false).mode;
}
/*
* (non-Javadoc)
*
* @see
* com.vaadin.ui.PushConfiguration#setPushMode(com.vaadin.shared.communication
* .PushMode)
*/
@Override
public void setPushMode(PushMode pushMode) {
if (pushMode == null) {
throw new IllegalArgumentException("Push mode cannot be null");
}
VaadinSession session = ui.getSession();
if (session == null) {
throw new UIDetachedException(
"Cannot set the push mode for a detached UI");
}
assert session.hasLock();
if (pushMode.isEnabled() && !session.getService().ensurePushAvailable()) {
throw new IllegalStateException(
"Push is not available. See previous log messages for more information.");
}
PushMode oldMode = getState().mode;
if (oldMode != pushMode) {
getState().mode = pushMode;
if (!oldMode.isEnabled() && pushMode.isEnabled()) {
// The push connection is initially in a disconnected state;
// the client will establish the connection
ui.setPushConnection(new AtmospherePushConnection(ui));
}
// Nothing to do here if disabling push;
// the client will close the connection
}
}
@Override
public void setPushUrl(String pushUrl) {
getState().pushUrl = pushUrl;
}
@Override
public String getPushUrl() {
return getState(false).pushUrl;
}
/*
* (non-Javadoc)
*
* @see com.vaadin.ui.PushConfiguration#getTransport()
*/
@Override
public Transport getTransport() {
try {
Transport tr = Transport
.getByIdentifier(getParameter(PushConfigurationState.TRANSPORT_PARAM));
if (tr == Transport.WEBSOCKET
&& getState(false).alwaysUseXhrForServerRequests) {
return Transport.WEBSOCKET_XHR;
} else {
return tr;
}
} catch (IllegalArgumentException e) {
return null;
}
}
/*
* (non-Javadoc)
*
* @see
* com.vaadin.ui.PushConfiguration#setTransport(com.vaadin.shared.ui.ui.
* Transport)
*/
@Override
public void setTransport(Transport transport) {
if (transport == Transport.WEBSOCKET_XHR) {
getState().alwaysUseXhrForServerRequests = true;
// Atmosphere knows only about "websocket"
setParameter(PushConfigurationState.TRANSPORT_PARAM,
Transport.WEBSOCKET.getIdentifier());
} else {
getState().alwaysUseXhrForServerRequests = false;
setParameter(PushConfigurationState.TRANSPORT_PARAM,
transport.getIdentifier());
}
}
/*
* (non-Javadoc)
*
* @see com.vaadin.ui.PushConfiguration#getFallbackTransport()
*/
@Override
public Transport getFallbackTransport() {
try {
return Transport
.valueOf(getParameter(PushConfigurationState.FALLBACK_TRANSPORT_PARAM));
} catch (IllegalArgumentException e) {
return null;
}
}
/*
* (non-Javadoc)
*
* @see
* com.vaadin.ui.PushConfiguration#setFallbackTransport(com.vaadin.shared
* .ui.ui.Transport)
*/
@Override
public void setFallbackTransport(Transport fallbackTransport) {
if (fallbackTransport == Transport.WEBSOCKET_XHR) {
throw new IllegalArgumentException(
"WEBSOCKET_XHR can only be used as primary transport");
}
setParameter(PushConfigurationState.FALLBACK_TRANSPORT_PARAM,
fallbackTransport.getIdentifier());
}
/*
* (non-Javadoc)
*
* @see com.vaadin.ui.PushConfiguration#getParameter(java.lang.String)
*/
@Override
public String getParameter(String parameter) {
return getState(false).parameters.get(parameter);
}
/*
* (non-Javadoc)
*
* @see com.vaadin.ui.PushConfiguration#setParameter(java.lang.String,
* java.lang.String)
*/
@Override
public void setParameter(String parameter, String value) {
getState().parameters.put(parameter, value);
}
private PushConfigurationState getState() {
return ui.getState().pushConfiguration;
}
private PushConfigurationState getState(boolean markAsDirty) {
return ui.getState(markAsDirty).pushConfiguration;
}
@Override
public Collection<String> getParameterNames() {
return Collections.unmodifiableCollection(getState(false).parameters
.keySet());
}
}
| |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.index.mapper;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.compress.CompressedXContent;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.test.ESSingleNodeTestCase;
import java.io.IOException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
public class DocumentMapperTests extends ESSingleNodeTestCase {
public void test1Merge() throws Exception {
String stage1Mapping = Strings.toString(XContentFactory.jsonBuilder().startObject().startObject("person").startObject("properties")
.startObject("name").field("type", "text").endObject()
.endObject().endObject().endObject());
DocumentMapperParser parser = createIndex("test").mapperService().documentMapperParser();
DocumentMapper stage1 = parser.parse("person", new CompressedXContent(stage1Mapping));
String stage2Mapping = Strings.toString(XContentFactory.jsonBuilder().startObject().startObject("person").startObject("properties")
.startObject("name").field("type", "text").endObject()
.startObject("age").field("type", "integer").endObject()
.startObject("obj1").startObject("properties").startObject("prop1").field("type", "integer").endObject().endObject()
.endObject()
.endObject().endObject().endObject());
DocumentMapper stage2 = parser.parse("person", new CompressedXContent(stage2Mapping));
DocumentMapper merged = stage1.merge(stage2.mapping());
// stage1 mapping should not have been modified
assertThat(stage1.mappers().getMapper("age"), nullValue());
assertThat(stage1.mappers().getMapper("obj1.prop1"), nullValue());
// but merged should
assertThat(merged.mappers().getMapper("age"), notNullValue());
assertThat(merged.mappers().getMapper("obj1.prop1"), notNullValue());
}
public void testMergeObjectDynamic() throws Exception {
DocumentMapperParser parser = createIndex("test").mapperService().documentMapperParser();
String objectMapping = Strings.toString(XContentFactory.jsonBuilder().startObject().startObject("type1").endObject().endObject());
DocumentMapper mapper = parser.parse("type1", new CompressedXContent(objectMapping));
assertNull(mapper.root().dynamic());
String withDynamicMapping = Strings.toString(
XContentFactory.jsonBuilder().startObject().startObject("type1").field("dynamic", "false").endObject().endObject());
DocumentMapper withDynamicMapper = parser.parse("type1", new CompressedXContent(withDynamicMapping));
assertThat(withDynamicMapper.root().dynamic(), equalTo(ObjectMapper.Dynamic.FALSE));
DocumentMapper merged = mapper.merge(withDynamicMapper.mapping());
assertThat(merged.root().dynamic(), equalTo(ObjectMapper.Dynamic.FALSE));
}
public void testMergeObjectAndNested() throws Exception {
DocumentMapperParser parser = createIndex("test").mapperService().documentMapperParser();
String objectMapping = Strings.toString(XContentFactory.jsonBuilder().startObject().startObject("type1").startObject("properties")
.startObject("obj").field("type", "object").endObject()
.endObject().endObject().endObject());
DocumentMapper objectMapper = parser.parse("type1", new CompressedXContent(objectMapping));
String nestedMapping = Strings.toString(XContentFactory.jsonBuilder().startObject().startObject("type1").startObject("properties")
.startObject("obj").field("type", "nested").endObject()
.endObject().endObject().endObject());
DocumentMapper nestedMapper = parser.parse("type1", new CompressedXContent(nestedMapping));
try {
objectMapper.merge(nestedMapper.mapping());
fail();
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), containsString("object mapping [obj] can't be changed from non-nested to nested"));
}
try {
nestedMapper.merge(objectMapper.mapping());
fail();
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), containsString("object mapping [obj] can't be changed from nested to non-nested"));
}
}
public void testMergeSearchAnalyzer() throws Exception {
XContentBuilder mapping1 = XContentFactory.jsonBuilder().startObject().startObject("type")
.startObject("properties").startObject("field")
.field("type", "text")
.field("analyzer", "standard")
.field("search_analyzer", "whitespace")
.endObject().endObject()
.endObject().endObject();
MapperService mapperService = createIndex("test", Settings.EMPTY, "type", mapping1).mapperService();
assertThat(mapperService.fullName("field").searchAnalyzer().name(), equalTo("whitespace"));
String mapping2 = Strings.toString(XContentFactory.jsonBuilder().startObject().startObject("type")
.startObject("properties").startObject("field")
.field("type", "text")
.field("analyzer", "standard")
.field("search_analyzer", "keyword")
.endObject().endObject()
.endObject().endObject());
mapperService.merge("type", new CompressedXContent(mapping2), MapperService.MergeReason.MAPPING_UPDATE);
assertThat(mapperService.fullName("field").searchAnalyzer().name(), equalTo("keyword"));
}
public void testChangeSearchAnalyzerToDefault() throws Exception {
XContentBuilder mapping1 = XContentFactory.jsonBuilder().startObject().startObject("type")
.startObject("properties").startObject("field")
.field("type", "text")
.field("analyzer", "standard")
.field("search_analyzer", "whitespace")
.endObject().endObject()
.endObject().endObject();
MapperService mapperService = createIndex("test", Settings.EMPTY, "type", mapping1).mapperService();
assertThat(mapperService.fullName("field").searchAnalyzer().name(), equalTo("whitespace"));
String mapping2 = Strings.toString(XContentFactory.jsonBuilder().startObject().startObject("type")
.startObject("properties").startObject("field")
.field("type", "text")
.field("analyzer", "standard")
.endObject().endObject()
.endObject().endObject());
mapperService.merge("type", new CompressedXContent(mapping2), MapperService.MergeReason.MAPPING_UPDATE);
assertThat(mapperService.fullName("field").searchAnalyzer().name(), equalTo("standard"));
}
public void testConcurrentMergeTest() throws Throwable {
final MapperService mapperService = createIndex("test").mapperService();
mapperService.merge("test", new CompressedXContent("{\"test\":{}}"), MapperService.MergeReason.MAPPING_UPDATE);
final DocumentMapper documentMapper = mapperService.documentMapper("test");
DocumentFieldMappers dfm = documentMapper.mappers();
try {
assertNotNull(dfm.indexAnalyzer().tokenStream("non_existing_field", "foo"));
fail();
} catch (IllegalArgumentException e) {
// ok that's expected
}
final AtomicBoolean stopped = new AtomicBoolean(false);
final CyclicBarrier barrier = new CyclicBarrier(2);
final AtomicReference<String> lastIntroducedFieldName = new AtomicReference<>();
final AtomicReference<Exception> error = new AtomicReference<>();
final Thread updater = new Thread() {
@Override
public void run() {
try {
barrier.await();
for (int i = 0; i < 200 && stopped.get() == false; i++) {
final String fieldName = Integer.toString(i);
ParsedDocument doc = documentMapper.parse(new SourceToParse("test",
"test",
fieldName,
new BytesArray("{ \"" + fieldName + "\" : \"test\" }"),
XContentType.JSON));
Mapping update = doc.dynamicMappingsUpdate();
assert update != null;
lastIntroducedFieldName.set(fieldName);
mapperService.merge("test", new CompressedXContent(update.toString()), MapperService.MergeReason.MAPPING_UPDATE);
}
} catch (Exception e) {
error.set(e);
} finally {
stopped.set(true);
}
}
};
updater.start();
try {
barrier.await();
while(stopped.get() == false) {
final String fieldName = lastIntroducedFieldName.get();
final BytesReference source = new BytesArray("{ \"" + fieldName + "\" : \"test\" }");
ParsedDocument parsedDoc = documentMapper.parse(new SourceToParse("test",
"test",
"random",
source,
XContentType.JSON));
if (parsedDoc.dynamicMappingsUpdate() != null) {
// not in the mapping yet, try again
continue;
}
dfm = documentMapper.mappers();
assertNotNull(dfm.indexAnalyzer().tokenStream(fieldName, "foo"));
}
} finally {
stopped.set(true);
updater.join();
}
if (error.get() != null) {
throw error.get();
}
}
public void testDoNotRepeatOriginalMapping() throws IOException {
CompressedXContent mapping = new CompressedXContent(BytesReference.bytes(XContentFactory.jsonBuilder().startObject()
.startObject("type")
.startObject("_source")
.field("enabled", false)
.endObject()
.endObject().endObject()));
MapperService mapperService = createIndex("test").mapperService();
mapperService.merge("type", mapping, MapperService.MergeReason.MAPPING_UPDATE);
CompressedXContent update = new CompressedXContent(BytesReference.bytes(XContentFactory.jsonBuilder().startObject()
.startObject("type")
.startObject("properties")
.startObject("foo")
.field("type", "text")
.endObject()
.endObject()
.endObject().endObject()));
DocumentMapper mapper = mapperService.merge("type", update, MapperService.MergeReason.MAPPING_UPDATE);
assertNotNull(mapper.mappers().getMapper("foo"));
assertFalse(mapper.sourceMapper().enabled());
}
public void testMergeMeta() throws IOException {
DocumentMapperParser parser = createIndex("test").mapperService().documentMapperParser();
String initMapping = Strings
.toString(XContentFactory.jsonBuilder()
.startObject()
.startObject("test")
.startObject("_meta")
.field("foo").value("bar")
.endObject()
.endObject()
.endObject());
DocumentMapper initMapper = parser.parse("test", new CompressedXContent(initMapping));
assertThat(initMapper.meta().get("foo"), equalTo("bar"));
String updateMapping = Strings
.toString(XContentFactory.jsonBuilder()
.startObject()
.startObject("test")
.startObject("properties")
.startObject("name").field("type", "text").endObject()
.endObject()
.endObject()
.endObject());
DocumentMapper updatedMapper = parser.parse("test", new CompressedXContent(updateMapping));
assertThat(initMapper.merge(updatedMapper.mapping()).meta().get("foo"), equalTo("bar"));
updateMapping = Strings
.toString(XContentFactory.jsonBuilder()
.startObject()
.startObject("test")
.startObject("_meta")
.field("foo").value("new_bar")
.endObject()
.endObject()
.endObject());
updatedMapper = parser.parse("test", new CompressedXContent(updateMapping));
assertThat(initMapper.merge(updatedMapper.mapping()).meta().get("foo"), equalTo("new_bar"));
}
}
| |
package net.metadata.dataspace.data.model.version;
import net.metadata.dataspace.data.model.Record;
import net.metadata.dataspace.data.model.UnknownTypeException;
import net.metadata.dataspace.data.model.Version;
import net.metadata.dataspace.data.model.context.Source;
import net.metadata.dataspace.data.model.context.SourceAuthor;
import net.metadata.dataspace.data.model.record.AbstractRecordEntity;
import net.metadata.dataspace.util.DaoHelper;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.Calendar;
import java.util.Collections;
import java.util.Enumeration;
import java.util.GregorianCalendar;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.MappedSuperclass;
import javax.persistence.Temporal;
/**
* Author: alabri
* Date: 01/11/2010
* Time: 11:40:11 AM
*/
@MappedSuperclass
public abstract class AbstractVersionEntity<R extends Record<?>> implements Serializable, Comparable<Version<R>>, Version<R> {
/**
*
*/
private static final long serialVersionUID = -7632183952742865428L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotNull
@Column(name="atomicnumber", insertable=true, updatable=false)
private Integer atomicNumber;
private boolean isActive;
@NotNull
private String title; //name
@NotNull
@Column(length = 4096)
private String description;
@NotNull
@javax.persistence.Version
@Temporal(javax.persistence.TemporalType.TIMESTAMP)
private Calendar updated;
@NotNull
@Temporal(javax.persistence.TemporalType.TIMESTAMP)
@Column(insertable=true,updatable=false,nullable=false)
private Calendar created;
@ElementCollection(fetch = FetchType.LAZY)
private Set<SourceAuthor> descriptionAuthors = new HashSet<SourceAuthor>();
@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private Source source;
@ManyToOne
@JoinColumn(name="parent_id")
private R parent;
public AbstractVersionEntity() {
this.isActive = true;
setCreated(Calendar.getInstance());
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Override
public String getUriKey() {
return DaoHelper.fromDecimalToOtherBase(31, getAtomicNumber());
}
@Override
public Integer getAtomicNumber() {
Enumeration<?> e = Collections.enumeration(getParent().getVersions());
@SuppressWarnings("unchecked")
List<Version<R>> list = (List<Version<R>>) Collections.list(e);
Collections.reverse(list);
this.atomicNumber = list.indexOf(this)+1;
return atomicNumber;
}
public boolean isActive() {
return isActive;
}
public void setActive(boolean active) {
isActive = active;
}
@Override
public String getTitle() {
return title;
}
@Override
public void setTitle(String title) {
this.title = title;
}
@Override
public String getDescription() {
return description;
}
@Override
public void setDescription(String description) {
this.description = description;
}
@Override
public Calendar getUpdated() {
return updated;
}
protected void setUpdated(Calendar updated) {
this.updated = updated;
}
@Override
public int compareTo(Version<R> version) {
if (this.getCreated().equals(version.getCreated())) {
return this.getAtomicNumber().compareTo(version.getAtomicNumber());
}
if (this.getCreated().before(version.getCreated())) {
return 1;
}
if (this.getCreated().after(version.getCreated())) {
return -1;
}
return 0;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof AbstractRecordEntity)) {
return false;
}
@SuppressWarnings("unchecked")
AbstractVersionEntity<R> other = (AbstractVersionEntity<R>) obj;
return getId().equals(other.getId());
}
@Override
public Calendar getCreated() {
return created;
}
public void setCreated(Calendar created) {
this.created = created;
}
@Override
public Set<SourceAuthor> getDescriptionAuthors() {
return descriptionAuthors;
}
@Override
public void setDescriptionAuthors(Set<SourceAuthor> descriptionAuthors) {
this.descriptionAuthors = descriptionAuthors;
}
@Override
public Source getSource() {
return source;
}
@Override
public void setSource(Source source) {
this.source = source;
}
@Override
public R getParent() {
return parent;
}
@Override
public void setParent(R parent) {
this.parent = parent;
}
public abstract void setType(String type) throws UnknownTypeException;
}
| |
/*
* Copyright (c) 2008, WSO2 Inc. (http://www.wso2.org) 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.wso2.carbon.governance.api.test;
import org.apache.axiom.om.OMElement;
import org.wso2.carbon.governance.api.common.dataobjects.GovernanceArtifact;
import org.wso2.carbon.governance.api.endpoints.EndpointManager;
import org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint;
import org.wso2.carbon.governance.api.exception.GovernanceException;
import org.wso2.carbon.governance.api.services.ServiceManager;
import org.wso2.carbon.governance.api.services.dataobjects.Service;
import org.wso2.carbon.governance.api.test.utils.BaseTestCase;
import org.wso2.carbon.governance.api.util.GovernanceUtils;
import org.wso2.carbon.governance.api.wsdls.WsdlManager;
import org.wso2.carbon.governance.api.wsdls.dataobjects.Wsdl;
import org.wso2.carbon.registry.extensions.utils.CommonConstants;
import javax.xml.namespace.QName;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
public class EndpointTest extends BaseTestCase {
public void testAddEndpoint() throws Exception {
// first add an endpoint, get it delete it, simply stuff like that.
EndpointManager endpointManager = new EndpointManager(registry);
Endpoint endpoint1 = endpointManager.newEndpoint("http://localhost/papapa/booom");
endpoint1.addAttribute("status", "QA");
endpointManager.addEndpoint(endpoint1);
assertEquals("/endpoints/localhost/papapa/ep-booom", endpoint1.getPath());
// now get the endpoint back.
Endpoint endpoint2 = endpointManager.getEndpoint(endpoint1.getId());
assertEquals("http://localhost/papapa/booom", endpoint2.getUrl());
assertEquals("QA", endpoint1.getAttribute("status"));
// so we will be deleting the endpoint
endpointManager.removeEndpoint(endpoint2.getId());
assertTrue(true);
endpoint2 = endpointManager.getEndpoint(endpoint2.getId());
assertNull(endpoint2);
}
public void testAddWsdlWithEndpoints() throws Exception {
WsdlManager wsdlManager = new WsdlManager(registry);
Wsdl wsdl = wsdlManager.newWsdl("http://svn.wso2.org/repos/wso2/carbon/platform/trunk/components/governance/org.wso2.carbon.governance.api/src/test/resources/test-resources/wsdl/BizService.wsdl");
wsdlManager.addWsdl(wsdl);
Endpoint[] endpoints = wsdl.getAttachedEndpoints();
assertEquals(1, endpoints.length);
assertEquals("http://localhost:8080/axis2/services/BizService", endpoints[0].getUrl());
assertEquals(1, endpoints[0].getAttributeKeys().length);
assertEquals("true", endpoints[0].getAttribute(CommonConstants.SOAP11_ENDPOINT_ATTRIBUTE));
// now we are trying to remove the endpoint
EndpointManager endpointManager = new EndpointManager(registry);
try {
endpointManager.removeEndpoint(endpoints[0].getId());
assertTrue(false);
} catch (Exception e) {
assertTrue(true);
}
GovernanceArtifact[] artifacts = wsdl.getDependents();
// delete the wsdl
wsdlManager.removeWsdl(wsdl.getId());
ServiceManager serviceManager = new ServiceManager(registry);
for (GovernanceArtifact artifact: artifacts) {
if (artifact instanceof Service) {
// getting the service.
Service service2 = (Service)artifact;
serviceManager.removeService(service2.getId());
}
}
// now try to remove the endpoint
endpointManager.removeEndpoint(endpoints[0].getId());
assertTrue(true);
}
public void testAddServiceWithEndpoints() throws Exception {
ServiceManager serviceManager = new ServiceManager(registry);
Service service = serviceManager.newService(new QName("http://wso2.com/test/xxx", "myService"));
service.addAttribute("endpoints_entry", ":http://endpoint1");
service.addAttribute("endpoints_entry", "QA:http://endpoint2");
serviceManager.addService(service);
Endpoint[] endpoints = service.getAttachedEndpoints();
assertEquals(2, endpoints.length);
assertEquals("http://endpoint1", endpoints[0].getUrl());
assertEquals(0, endpoints[0].getAttributeKeys().length);
assertEquals("http://endpoint2", endpoints[1].getUrl());
assertEquals(1, endpoints[1].getAttributeKeys().length);
assertEquals("QA", endpoints[1].getAttribute(CommonConstants.ENDPOINT_ENVIRONMENT_ATTR));
// now update the endpoints in the service
service.setAttributes("endpoints_entry", new String[] {
"Dev:http://endpoint3",
"Production:http://endpoint4",
"QA:http://endpoint2",
});
serviceManager.updateService(service);
endpoints = getAttachedEndpointsFromService(service);
// endpoints = service.getAttachedEndpoints();
assertEquals(3, endpoints.length);
assertEquals("http://endpoint3", endpoints[0].getUrl());
assertEquals(1, endpoints[0].getAttributeKeys().length);
assertEquals("Dev", endpoints[0].getAttribute(CommonConstants.ENDPOINT_ENVIRONMENT_ATTR));
assertEquals("http://endpoint4", endpoints[1].getUrl());
assertEquals(1, endpoints[1].getAttributeKeys().length);
assertEquals("Production", endpoints[1].getAttribute(CommonConstants.ENDPOINT_ENVIRONMENT_ATTR));
assertEquals("http://endpoint2", endpoints[2].getUrl());
assertEquals(1, endpoints[2].getAttributeKeys().length);
assertEquals("QA", endpoints[2].getAttribute(CommonConstants.ENDPOINT_ENVIRONMENT_ATTR));
}
// add endpoints as attachments
public void testAttachEndpointsToService() throws Exception {
ServiceManager serviceManager = new ServiceManager(registry);
Service service = serviceManager.newService(new QName("http://wso2.com/test234/xxxxx", "myServicxcde"));
serviceManager.addService(service);
EndpointManager endpointManager = new EndpointManager(registry);
Endpoint ep1 = endpointManager.newEndpoint("http://endpoint1xx");
endpointManager.addEndpoint(ep1);
Endpoint ep2 = endpointManager.newEndpoint("http://endpoint2xx");
ep2.setAttribute(CommonConstants.ENDPOINT_ENVIRONMENT_ATTR, "QA");
endpointManager.addEndpoint(ep2);
service.attachEndpoint(ep1);
service.attachEndpoint(ep2);
Endpoint[] endpoints = service.getAttachedEndpoints();
assertEquals(2, endpoints.length);
assertEquals("http://endpoint1xx", endpoints[0].getUrl());
assertEquals(0, endpoints[0].getAttributeKeys().length);
assertEquals("http://endpoint2xx", endpoints[1].getUrl());
assertEquals(1, endpoints[1].getAttributeKeys().length);
assertEquals("QA", endpoints[1].getAttribute(CommonConstants.ENDPOINT_ENVIRONMENT_ATTR));
service.detachEndpoint(ep1.getId());
endpoints = service.getAttachedEndpoints();
assertEquals(1, endpoints.length);
assertEquals("http://endpoint2xx", endpoints[0].getUrl());
assertEquals(1, endpoints[0].getAttributeKeys().length);
assertEquals("QA", endpoints[0].getAttribute(CommonConstants.ENDPOINT_ENVIRONMENT_ATTR));
// now update the endpoints in the service
service.setAttributes("endpoints_entry", new String[] {
"Dev:http://endpoint3",
"Production:http://endpoint4",
"QA:http://endpoint2xx",
});
serviceManager.updateService(service);
endpoints = getAttachedEndpointsFromService(service);
// endpoints = service.getAttachedEndpoints();
assertEquals(3, endpoints.length);
assertEquals("http://endpoint3", endpoints[0].getUrl());
assertEquals(1, endpoints[0].getAttributeKeys().length);
assertEquals("Dev", endpoints[0].getAttribute(CommonConstants.ENDPOINT_ENVIRONMENT_ATTR));
assertEquals("http://endpoint4", endpoints[1].getUrl());
assertEquals(1, endpoints[1].getAttributeKeys().length);
assertEquals("Production", endpoints[1].getAttribute(CommonConstants.ENDPOINT_ENVIRONMENT_ATTR));
assertEquals("http://endpoint2xx", endpoints[2].getUrl());
assertEquals(1, endpoints[2].getAttributeKeys().length);
assertEquals("QA", endpoints[2].getAttribute(CommonConstants.ENDPOINT_ENVIRONMENT_ATTR));
Endpoint ep5 = endpointManager.getEndpointByUrl("http://endpoint2");
assertEquals("QA", ep5.getAttribute(CommonConstants.ENDPOINT_ENVIRONMENT_ATTR));
}
public void testAssociatingEndpoints() throws Exception {
ServiceManager serviceManager = new ServiceManager(registry);
Service service = serviceManager.newService(new QName("http://done.ding/dong/doodo", "bangService343"));
serviceManager.addService(service);
EndpointManager endpointManager = new EndpointManager(registry);
Endpoint endpoint = endpointManager.newEndpoint("http://dos.dis/doos/safdsf/ppeekk");
endpointManager.addEndpoint(endpoint);
service.attachEndpoint(endpoint);
// retrieve the service
Service service2 = serviceManager.getService(service.getId());
Endpoint[] endpoints = service2.getAttachedEndpoints();
assertEquals(1, endpoints.length);
assertEquals(":" + endpoints[0].getUrl(), service2.getAttribute("endpoints_entry"));
}
public void testServiceAddingEndpointsWithWsdl() throws Exception {
File file = new File("src/test/resources/service.metadata.xml");
FileInputStream fileInputStream = new FileInputStream(file);
byte[] fileContents = new byte[(int)file.length()];
fileInputStream.read(fileContents);
OMElement contentElement = GovernanceUtils.buildOMElement(fileContents);
ServiceManager serviceManager = new ServiceManager(registry);
Service service = serviceManager.newService(contentElement);
service.addAttribute("custom-attribute", "custom-value");
serviceManager.addService(service);
// so retrieve it back
String serviceId = service.getId();
Service newService = serviceManager.getService(serviceId);
assertEquals(newService.getAttribute("custom-attribute"), "custom-value");
assertEquals(newService.getAttribute("endpoints_entry"),
":http://localhost:8080/axis2/services/BizService");
// now we just add an endpoints
WsdlManager wsdlManager = new WsdlManager(registry);
Wsdl wsdl = wsdlManager.newWsdl("http://svn.wso2.org/repos/wso2/carbon/platform/trunk/components/governance/org.wso2.carbon.governance.api/src/test/resources/test-resources/wsdl/MyChangedBizService.wsdl");
wsdl.addAttribute("boom", "hahahaha");
wsdlManager.addWsdl(wsdl);
GovernanceArtifact[] artifacts = wsdl.getDependents();
for (GovernanceArtifact artifact: artifacts) {
if (artifact instanceof Service) {
// getting the service.
Service service2 = (Service)artifact;
Endpoint[] endpoints = service2.getAttachedEndpoints();
assertEquals(1, endpoints.length);
assertEquals("http://localhost:8080/axis2/services/BizService-my-changes", endpoints[0].getUrl());
}
}
}
// detach endpoints
public void testDetachEndpointsToService() throws Exception {
ServiceManager serviceManager = new ServiceManager(registry);
Service service = serviceManager.newService(new QName("http://wso2.com/test234/xxxxxx", "_myServicxcde"));
serviceManager.addService(service);
EndpointManager endpointManager = new EndpointManager(registry);
Endpoint ep1 = endpointManager.newEndpoint("http://endpoint1");
endpointManager.addEndpoint(ep1);
Endpoint ep2 = endpointManager.newEndpoint("http://endpoint2");
ep2.setAttribute(CommonConstants.ENDPOINT_ENVIRONMENT_ATTR, "QA");
endpointManager.addEndpoint(ep2);
service.attachEndpoint(ep1);
service.attachEndpoint(ep2);
Endpoint[] endpoints = service.getAttachedEndpoints();
assertEquals(2, endpoints.length);
// get the updated service endpoints
service = serviceManager.getService(service.getId());
String[] endpointValues = service.getAttributes("endpoints_entry");
assertEquals(2, endpointValues.length);
}
// add non http endpoints as attachments
public void testNonHttpEndpointsToService() throws Exception {
ServiceManager serviceManager = new ServiceManager(registry);
Service service = serviceManager.newService(new QName("http://wso2.com/doadf/spidf", "myServisdfcxcde"));
serviceManager.addService(service);
EndpointManager endpointManager = new EndpointManager(registry);
Endpoint ep1 = endpointManager.newEndpoint("jms:/Service1");
endpointManager.addEndpoint(ep1);
Endpoint ep2 = endpointManager.newEndpoint("jms:/Service2");
ep2.setAttribute(CommonConstants.ENDPOINT_ENVIRONMENT_ATTR, "QA");
endpointManager.addEndpoint(ep2);
service.attachEndpoint(ep1);
service.attachEndpoint(ep2);
Endpoint[] endpoints = service.getAttachedEndpoints();
assertEquals(2, endpoints.length);
// get the updated service endpoints
service = serviceManager.getService(service.getId());
String[] endpointValues = service.getAttributes("endpoints_entry");
assertEquals(2, endpointValues.length);
}
private Endpoint[] getAttachedEndpointsFromService(Service service) throws GovernanceException {
List<Endpoint> endpoints =new ArrayList<Endpoint>();
try {
String[] endpointValues = service.getAttributes("endpoints_entry");
EndpointManager endpointManager = new EndpointManager(registry);
for(String ep:endpointValues) {
endpoints.add(endpointManager.getEndpointByUrl(getFilteredEPURL(ep)));
}
} catch (GovernanceException e) {
throw new GovernanceException("Exception occurred while geting endpoints ");
}
return endpoints.toArray(new Endpoint[endpoints.size()]);
}
private String getFilteredEPURL(String ep){
// Dev:http://endpoint3
if(!ep.startsWith("http")){
return ep.substring(ep.indexOf(":") + 1, ep.length());
} else {
return ep;
}
}
}
| |
/*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.exoplayer.dash.mpd;
import com.google.android.exoplayer.ParserException;
import com.google.android.exoplayer.chunk.Format;
import com.google.android.exoplayer.dash.mpd.SegmentBase.SegmentList;
import com.google.android.exoplayer.dash.mpd.SegmentBase.SegmentTemplate;
import com.google.android.exoplayer.dash.mpd.SegmentBase.SegmentTimelineElement;
import com.google.android.exoplayer.dash.mpd.SegmentBase.SingleSegmentBase;
import com.google.android.exoplayer.drm.DrmInitData.SchemeInitData;
import com.google.android.exoplayer.extractor.mp4.PsshAtomUtil;
import com.google.android.exoplayer.upstream.UriLoadable;
import com.google.android.exoplayer.util.Assertions;
import com.google.android.exoplayer.util.MimeTypes;
import com.google.android.exoplayer.util.ParserUtil;
import com.google.android.exoplayer.util.UriUtil;
import com.google.android.exoplayer.util.Util;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.util.Pair;
import org.xml.sax.helpers.DefaultHandler;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* A parser of media presentation description files.
*/
public class MediaPresentationDescriptionParser extends DefaultHandler
implements UriLoadable.Parser<MediaPresentationDescription> {
private static final String TAG = "MediaPresentationDescriptionParser";
private static final Pattern FRAME_RATE_PATTERN = Pattern.compile("(\\d+)(?:/(\\d+))?");
private final String contentId;
private final XmlPullParserFactory xmlParserFactory;
/**
* Equivalent to calling {@code new MediaPresentationDescriptionParser(null)}.
*/
public MediaPresentationDescriptionParser() {
this(null);
}
/**
* @param contentId An optional content identifier to include in the parsed manifest.
*/
// TODO: Remove the need to inject a content identifier here, by not including it in the parsed
// manifest. Instead, it should be injected directly where needed (i.e. DashChunkSource).
public MediaPresentationDescriptionParser(String contentId) {
this.contentId = contentId;
try {
xmlParserFactory = XmlPullParserFactory.newInstance();
} catch (XmlPullParserException e) {
throw new RuntimeException("Couldn't create XmlPullParserFactory instance", e);
}
}
// MPD parsing.
@Override
public MediaPresentationDescription parse(String connectionUrl, InputStream inputStream)
throws IOException, ParserException {
try {
XmlPullParser xpp = xmlParserFactory.newPullParser();
xpp.setInput(inputStream, null);
int eventType = xpp.next();
if (eventType != XmlPullParser.START_TAG || !"MPD".equals(xpp.getName())) {
throw new ParserException(
"inputStream does not contain a valid media presentation description");
}
return parseMediaPresentationDescription(xpp, connectionUrl);
} catch (XmlPullParserException e) {
throw new ParserException(e);
} catch (ParseException e) {
throw new ParserException(e);
}
}
protected MediaPresentationDescription parseMediaPresentationDescription(XmlPullParser xpp,
String baseUrl) throws XmlPullParserException, IOException, ParseException {
long availabilityStartTime = parseDateTime(xpp, "availabilityStartTime", -1);
long durationMs = parseDuration(xpp, "mediaPresentationDuration", -1);
long minBufferTimeMs = parseDuration(xpp, "minBufferTime", -1);
String typeString = xpp.getAttributeValue(null, "type");
boolean dynamic = (typeString != null) ? typeString.equals("dynamic") : false;
long minUpdateTimeMs = (dynamic) ? parseDuration(xpp, "minimumUpdatePeriod", -1) : -1;
long timeShiftBufferDepthMs = (dynamic) ? parseDuration(xpp, "timeShiftBufferDepth", -1) : -1;
UtcTimingElement utcTiming = null;
String location = null;
List<Period> periods = new ArrayList<>();
long nextPeriodStartMs = dynamic ? -1 : 0;
boolean seenEarlyAccessPeriod = false;
boolean seenFirstBaseUrl = false;
do {
xpp.next();
if (ParserUtil.isStartTag(xpp, "BaseURL")) {
if (!seenFirstBaseUrl) {
baseUrl = parseBaseUrl(xpp, baseUrl);
seenFirstBaseUrl = true;
}
} else if (ParserUtil.isStartTag(xpp, "UTCTiming")) {
utcTiming = parseUtcTiming(xpp);
} else if (ParserUtil.isStartTag(xpp, "Location")) {
location = xpp.nextText();
} else if (ParserUtil.isStartTag(xpp, "Period") && !seenEarlyAccessPeriod) {
Pair<Period, Long> periodWithDurationMs = parsePeriod(xpp, baseUrl, nextPeriodStartMs);
Period period = periodWithDurationMs.first;
if (period.startMs == -1) {
if (dynamic) {
// This is an early access period. Ignore it. All subsequent periods must also be
// early access.
seenEarlyAccessPeriod = true;
} else {
throw new ParserException("Unable to determine start of period " + periods.size());
}
} else {
long periodDurationMs = periodWithDurationMs.second;
nextPeriodStartMs = periodDurationMs == -1 ? -1 : period.startMs + periodDurationMs;
periods.add(period);
}
}
} while (!ParserUtil.isEndTag(xpp, "MPD"));
if (durationMs == -1) {
if (nextPeriodStartMs != -1) {
// If we know the end time of the final period, we can use it as the duration.
durationMs = nextPeriodStartMs;
} else if (!dynamic) {
throw new ParserException("Unable to determine duration of static manifest.");
}
}
if (periods.isEmpty()) {
throw new ParserException("No periods found.");
}
return buildMediaPresentationDescription(availabilityStartTime, durationMs, minBufferTimeMs,
dynamic, minUpdateTimeMs, timeShiftBufferDepthMs, utcTiming, location, periods);
}
protected MediaPresentationDescription buildMediaPresentationDescription(
long availabilityStartTime, long durationMs, long minBufferTimeMs, boolean dynamic,
long minUpdateTimeMs, long timeShiftBufferDepthMs, UtcTimingElement utcTiming,
String location, List<Period> periods) {
return new MediaPresentationDescription(availabilityStartTime, durationMs, minBufferTimeMs,
dynamic, minUpdateTimeMs, timeShiftBufferDepthMs, utcTiming, location, periods);
}
protected UtcTimingElement parseUtcTiming(XmlPullParser xpp) {
String schemeIdUri = xpp.getAttributeValue(null, "schemeIdUri");
String value = xpp.getAttributeValue(null, "value");
return buildUtcTimingElement(schemeIdUri, value);
}
protected UtcTimingElement buildUtcTimingElement(String schemeIdUri, String value) {
return new UtcTimingElement(schemeIdUri, value);
}
protected Pair<Period, Long> parsePeriod(XmlPullParser xpp, String baseUrl, long defaultStartMs)
throws XmlPullParserException, IOException {
String id = xpp.getAttributeValue(null, "id");
long startMs = parseDuration(xpp, "start", defaultStartMs);
long durationMs = parseDuration(xpp, "duration", -1);
SegmentBase segmentBase = null;
List<AdaptationSet> adaptationSets = new ArrayList<>();
boolean seenFirstBaseUrl = false;
do {
xpp.next();
if (ParserUtil.isStartTag(xpp, "BaseURL")) {
if (!seenFirstBaseUrl) {
baseUrl = parseBaseUrl(xpp, baseUrl);
seenFirstBaseUrl = true;
}
} else if (ParserUtil.isStartTag(xpp, "AdaptationSet")) {
adaptationSets.add(parseAdaptationSet(xpp, baseUrl, segmentBase));
} else if (ParserUtil.isStartTag(xpp, "SegmentBase")) {
segmentBase = parseSegmentBase(xpp, baseUrl, null);
} else if (ParserUtil.isStartTag(xpp, "SegmentList")) {
segmentBase = parseSegmentList(xpp, baseUrl, null);
} else if (ParserUtil.isStartTag(xpp, "SegmentTemplate")) {
segmentBase = parseSegmentTemplate(xpp, baseUrl, null);
}
} while (!ParserUtil.isEndTag(xpp, "Period"));
return Pair.create(buildPeriod(id, startMs, adaptationSets), durationMs);
}
protected Period buildPeriod(String id, long startMs, List<AdaptationSet> adaptationSets) {
return new Period(id, startMs, adaptationSets);
}
// AdaptationSet parsing.
protected AdaptationSet parseAdaptationSet(XmlPullParser xpp, String baseUrl,
SegmentBase segmentBase) throws XmlPullParserException, IOException {
int id = parseInt(xpp, "id", -1);
int contentType = parseContentType(xpp);
String mimeType = xpp.getAttributeValue(null, "mimeType");
String codecs = xpp.getAttributeValue(null, "codecs");
int width = parseInt(xpp, "width", -1);
int height = parseInt(xpp, "height", -1);
float frameRate = parseFrameRate(xpp, -1);
int audioChannels = -1;
int audioSamplingRate = parseInt(xpp, "audioSamplingRate", -1);
String language = xpp.getAttributeValue(null, "lang");
ContentProtectionsBuilder contentProtectionsBuilder = new ContentProtectionsBuilder();
List<Representation> representations = new ArrayList<>();
boolean seenFirstBaseUrl = false;
do {
xpp.next();
if (ParserUtil.isStartTag(xpp, "BaseURL")) {
if (!seenFirstBaseUrl) {
baseUrl = parseBaseUrl(xpp, baseUrl);
seenFirstBaseUrl = true;
}
} else if (ParserUtil.isStartTag(xpp, "ContentProtection")) {
ContentProtection contentProtection = parseContentProtection(xpp);
if (contentProtection != null) {
contentProtectionsBuilder.addAdaptationSetProtection(contentProtection);
}
} else if (ParserUtil.isStartTag(xpp, "ContentComponent")) {
language = checkLanguageConsistency(language, xpp.getAttributeValue(null, "lang"));
contentType = checkContentTypeConsistency(contentType, parseContentType(xpp));
} else if (ParserUtil.isStartTag(xpp, "Representation")) {
Representation representation = parseRepresentation(xpp, baseUrl, mimeType, codecs, width,
height, frameRate, audioChannels, audioSamplingRate, language, segmentBase,
contentProtectionsBuilder);
Log.d("LLEEJ, MPD","MPDParser parseAdaptationSet() : " + representation.getFormat().width +","+representation.getFormat().height);
contentProtectionsBuilder.endRepresentation();
contentType = checkContentTypeConsistency(contentType, getContentType(representation));
representations.add(representation);
} else if (ParserUtil.isStartTag(xpp, "AudioChannelConfiguration")) {
audioChannels = parseAudioChannelConfiguration(xpp);
} else if (ParserUtil.isStartTag(xpp, "SegmentBase")) {
segmentBase = parseSegmentBase(xpp, baseUrl, (SingleSegmentBase) segmentBase);
} else if (ParserUtil.isStartTag(xpp, "SegmentList")) {
segmentBase = parseSegmentList(xpp, baseUrl, (SegmentList) segmentBase);
} else if (ParserUtil.isStartTag(xpp, "SegmentTemplate")) {
segmentBase = parseSegmentTemplate(xpp, baseUrl, (SegmentTemplate) segmentBase);
} else if (ParserUtil.isStartTag(xpp)) {
parseAdaptationSetChild(xpp);
}
} while (!ParserUtil.isEndTag(xpp, "AdaptationSet"));
return buildAdaptationSet(id, contentType, representations, contentProtectionsBuilder.build());
}
protected AdaptationSet buildAdaptationSet(int id, int contentType,
List<Representation> representations, List<ContentProtection> contentProtections) {
return new AdaptationSet(id, contentType, representations, contentProtections);
}
protected int parseContentType(XmlPullParser xpp) {
String contentType = xpp.getAttributeValue(null, "contentType");
return TextUtils.isEmpty(contentType) ? AdaptationSet.TYPE_UNKNOWN
: MimeTypes.BASE_TYPE_AUDIO.equals(contentType) ? AdaptationSet.TYPE_AUDIO
: MimeTypes.BASE_TYPE_VIDEO.equals(contentType) ? AdaptationSet.TYPE_VIDEO
: MimeTypes.BASE_TYPE_TEXT.equals(contentType) ? AdaptationSet.TYPE_TEXT
: AdaptationSet.TYPE_UNKNOWN;
}
protected int getContentType(Representation representation) {
String mimeType = representation.format.mimeType;
if (TextUtils.isEmpty(mimeType)) {
return AdaptationSet.TYPE_UNKNOWN;
} else if (MimeTypes.isVideo(mimeType)) {
return AdaptationSet.TYPE_VIDEO;
} else if (MimeTypes.isAudio(mimeType)) {
return AdaptationSet.TYPE_AUDIO;
} else if (MimeTypes.isText(mimeType) || MimeTypes.APPLICATION_TTML.equals(mimeType)) {
return AdaptationSet.TYPE_TEXT;
} else if (MimeTypes.APPLICATION_MP4.equals(mimeType)) {
// The representation uses mp4 but does not contain video or audio. Use codecs to determine
// whether the container holds text.
String codecs = representation.format.codecs;
if ("stpp".equals(codecs) || "wvtt".equals(codecs)) {
return AdaptationSet.TYPE_TEXT;
}
}
return AdaptationSet.TYPE_UNKNOWN;
}
/**
* Parses a {@link ContentProtection} element.
*
* @throws XmlPullParserException If an error occurs parsing the element.
* @throws IOException If an error occurs reading the element.
* @return The parsed {@link ContentProtection} element, or null if the element is unsupported.
**/
protected ContentProtection parseContentProtection(XmlPullParser xpp)
throws XmlPullParserException, IOException {
String schemeIdUri = xpp.getAttributeValue(null, "schemeIdUri");
UUID uuid = null;
SchemeInitData data = null;
boolean seenPsshElement = false;
do {
xpp.next();
// The cenc:pssh element is defined in 23001-7:2015.
if (ParserUtil.isStartTag(xpp, "cenc:pssh") && xpp.next() == XmlPullParser.TEXT) {
seenPsshElement = true;
data = new SchemeInitData(MimeTypes.VIDEO_MP4,
Base64.decode(xpp.getText(), Base64.DEFAULT));
uuid = PsshAtomUtil.parseUuid(data.data);
}
} while (!ParserUtil.isEndTag(xpp, "ContentProtection"));
if (seenPsshElement && uuid == null) {
Log.w(TAG, "Skipped unsupported ContentProtection element");
return null;
}
return buildContentProtection(schemeIdUri, uuid, data);
}
protected ContentProtection buildContentProtection(String schemeIdUri, UUID uuid,
SchemeInitData data) {
return new ContentProtection(schemeIdUri, uuid, data);
}
/**
* Parses children of AdaptationSet elements not specifically parsed elsewhere.
*
* @param xpp The XmpPullParser from which the AdaptationSet child should be parsed.
* @throws XmlPullParserException If an error occurs parsing the element.
* @throws IOException If an error occurs reading the element.
**/
protected void parseAdaptationSetChild(XmlPullParser xpp)
throws XmlPullParserException, IOException {
// pass
}
// Representation parsing.
protected Representation parseRepresentation(XmlPullParser xpp, String baseUrl,
String adaptationSetMimeType, String adaptationSetCodecs, int adaptationSetWidth,
int adaptationSetHeight, float adaptationSetFrameRate, int adaptationSetAudioChannels,
int adaptationSetAudioSamplingRate, String adaptationSetLanguage, SegmentBase segmentBase,
ContentProtectionsBuilder contentProtectionsBuilder)
throws XmlPullParserException, IOException {
String id = xpp.getAttributeValue(null, "id");
int bandwidth = parseInt(xpp, "bandwidth");
String mimeType = parseString(xpp, "mimeType", adaptationSetMimeType);
String codecs = parseString(xpp, "codecs", adaptationSetCodecs);
int width = parseInt(xpp, "width", adaptationSetWidth);
int height = parseInt(xpp, "height", adaptationSetHeight);
float frameRate = parseFrameRate(xpp, adaptationSetFrameRate);
int audioChannels = adaptationSetAudioChannels;
int audioSamplingRate = parseInt(xpp, "audioSamplingRate", adaptationSetAudioSamplingRate);
String language = adaptationSetLanguage;
boolean seenFirstBaseUrl = false;
do {
xpp.next();
if (ParserUtil.isStartTag(xpp, "BaseURL")) {
if (!seenFirstBaseUrl) {
baseUrl = parseBaseUrl(xpp, baseUrl);
seenFirstBaseUrl = true;
}
} else if (ParserUtil.isStartTag(xpp, "AudioChannelConfiguration")) {
audioChannels = parseAudioChannelConfiguration(xpp);
} else if (ParserUtil.isStartTag(xpp, "SegmentBase")) {
segmentBase = parseSegmentBase(xpp, baseUrl, (SingleSegmentBase) segmentBase);
} else if (ParserUtil.isStartTag(xpp, "SegmentList")) {
segmentBase = parseSegmentList(xpp, baseUrl, (SegmentList) segmentBase);
} else if (ParserUtil.isStartTag(xpp, "SegmentTemplate")) {
segmentBase = parseSegmentTemplate(xpp, baseUrl, (SegmentTemplate) segmentBase);
} else if (ParserUtil.isStartTag(xpp, "ContentProtection")) {
ContentProtection contentProtection = parseContentProtection(xpp);
if (contentProtection != null) {
contentProtectionsBuilder.addAdaptationSetProtection(contentProtection);
}
}
} while (!ParserUtil.isEndTag(xpp, "Representation"));
Format format = buildFormat(id, mimeType, width, height, frameRate, audioChannels,
audioSamplingRate, bandwidth, language, codecs);
return buildRepresentation(contentId, -1, format,
segmentBase != null ? segmentBase : new SingleSegmentBase(baseUrl));
}
protected Format buildFormat(String id, String mimeType, int width, int height, float frameRate,
int audioChannels, int audioSamplingRate, int bandwidth, String language, String codecs) {
return new Format(id, mimeType, width, height, frameRate, audioChannels, audioSamplingRate,
bandwidth, language, codecs);
}
protected Representation buildRepresentation(String contentId, int revisionId, Format format,
SegmentBase segmentBase) {
return Representation.newInstance(contentId, revisionId, format, segmentBase);
}
// SegmentBase, SegmentList and SegmentTemplate parsing.
protected SingleSegmentBase parseSegmentBase(XmlPullParser xpp, String baseUrl,
SingleSegmentBase parent) throws XmlPullParserException, IOException {
long timescale = parseLong(xpp, "timescale", parent != null ? parent.timescale : 1);
long presentationTimeOffset = parseLong(xpp, "presentationTimeOffset",
parent != null ? parent.presentationTimeOffset : 0);
long indexStart = parent != null ? parent.indexStart : 0;
long indexLength = parent != null ? parent.indexLength : -1;
String indexRangeText = xpp.getAttributeValue(null, "indexRange");
if (indexRangeText != null) {
String[] indexRange = indexRangeText.split("-");
indexStart = Long.parseLong(indexRange[0]);
indexLength = Long.parseLong(indexRange[1]) - indexStart + 1;
}
RangedUri initialization = parent != null ? parent.initialization : null;
do {
xpp.next();
if (ParserUtil.isStartTag(xpp, "Initialization")) {
initialization = parseInitialization(xpp, baseUrl);
}
} while (!ParserUtil.isEndTag(xpp, "SegmentBase"));
return buildSingleSegmentBase(initialization, timescale, presentationTimeOffset, baseUrl,
indexStart, indexLength);
}
protected SingleSegmentBase buildSingleSegmentBase(RangedUri initialization, long timescale,
long presentationTimeOffset, String baseUrl, long indexStart, long indexLength) {
return new SingleSegmentBase(initialization, timescale, presentationTimeOffset, baseUrl,
indexStart, indexLength);
}
protected SegmentList parseSegmentList(XmlPullParser xpp, String baseUrl, SegmentList parent)
throws XmlPullParserException, IOException {
long timescale = parseLong(xpp, "timescale", parent != null ? parent.timescale : 1);
long presentationTimeOffset = parseLong(xpp, "presentationTimeOffset",
parent != null ? parent.presentationTimeOffset : 0);
long duration = parseLong(xpp, "duration", parent != null ? parent.duration : -1);
int startNumber = parseInt(xpp, "startNumber", parent != null ? parent.startNumber : 1);
RangedUri initialization = null;
List<SegmentTimelineElement> timeline = null;
List<RangedUri> segments = null;
do {
xpp.next();
if (ParserUtil.isStartTag(xpp, "Initialization")) {
initialization = parseInitialization(xpp, baseUrl);
} else if (ParserUtil.isStartTag(xpp, "SegmentTimeline")) {
timeline = parseSegmentTimeline(xpp);
} else if (ParserUtil.isStartTag(xpp, "SegmentURL")) {
if (segments == null) {
segments = new ArrayList<>();
}
segments.add(parseSegmentUrl(xpp, baseUrl));
}
} while (!ParserUtil.isEndTag(xpp, "SegmentList"));
if (parent != null) {
initialization = initialization != null ? initialization : parent.initialization;
timeline = timeline != null ? timeline : parent.segmentTimeline;
segments = segments != null ? segments : parent.mediaSegments;
}
return buildSegmentList(initialization, timescale, presentationTimeOffset,
startNumber, duration, timeline, segments);
}
protected SegmentList buildSegmentList(RangedUri initialization, long timescale,
long presentationTimeOffset, int startNumber, long duration,
List<SegmentTimelineElement> timeline, List<RangedUri> segments) {
return new SegmentList(initialization, timescale, presentationTimeOffset,
startNumber, duration, timeline, segments);
}
protected SegmentTemplate parseSegmentTemplate(XmlPullParser xpp, String baseUrl,
SegmentTemplate parent) throws XmlPullParserException, IOException {
long timescale = parseLong(xpp, "timescale", parent != null ? parent.timescale : 1);
long presentationTimeOffset = parseLong(xpp, "presentationTimeOffset",
parent != null ? parent.presentationTimeOffset : 0);
long duration = parseLong(xpp, "duration", parent != null ? parent.duration : -1);
int startNumber = parseInt(xpp, "startNumber", parent != null ? parent.startNumber : 1);
UrlTemplate mediaTemplate = parseUrlTemplate(xpp, "media",
parent != null ? parent.mediaTemplate : null);
UrlTemplate initializationTemplate = parseUrlTemplate(xpp, "initialization",
parent != null ? parent.initializationTemplate : null);
RangedUri initialization = null;
List<SegmentTimelineElement> timeline = null;
do {
xpp.next();
if (ParserUtil.isStartTag(xpp, "Initialization")) {
initialization = parseInitialization(xpp, baseUrl);
} else if (ParserUtil.isStartTag(xpp, "SegmentTimeline")) {
timeline = parseSegmentTimeline(xpp);
}
} while (!ParserUtil.isEndTag(xpp, "SegmentTemplate"));
if (parent != null) {
initialization = initialization != null ? initialization : parent.initialization;
timeline = timeline != null ? timeline : parent.segmentTimeline;
}
return buildSegmentTemplate(initialization, timescale, presentationTimeOffset,
startNumber, duration, timeline, initializationTemplate, mediaTemplate, baseUrl);
}
protected SegmentTemplate buildSegmentTemplate(RangedUri initialization, long timescale,
long presentationTimeOffset, int startNumber, long duration,
List<SegmentTimelineElement> timeline, UrlTemplate initializationTemplate,
UrlTemplate mediaTemplate, String baseUrl) {
return new SegmentTemplate(initialization, timescale, presentationTimeOffset,
startNumber, duration, timeline, initializationTemplate, mediaTemplate, baseUrl);
}
protected List<SegmentTimelineElement> parseSegmentTimeline(XmlPullParser xpp)
throws XmlPullParserException, IOException {
List<SegmentTimelineElement> segmentTimeline = new ArrayList<>();
long elapsedTime = 0;
do {
xpp.next();
if (ParserUtil.isStartTag(xpp, "S")) {
elapsedTime = parseLong(xpp, "t", elapsedTime);
long duration = parseLong(xpp, "d");
int count = 1 + parseInt(xpp, "r", 0);
for (int i = 0; i < count; i++) {
segmentTimeline.add(buildSegmentTimelineElement(elapsedTime, duration));
elapsedTime += duration;
}
}
} while (!ParserUtil.isEndTag(xpp, "SegmentTimeline"));
return segmentTimeline;
}
protected SegmentTimelineElement buildSegmentTimelineElement(long elapsedTime, long duration) {
return new SegmentTimelineElement(elapsedTime, duration);
}
protected UrlTemplate parseUrlTemplate(XmlPullParser xpp, String name,
UrlTemplate defaultValue) {
String valueString = xpp.getAttributeValue(null, name);
if (valueString != null) {
return UrlTemplate.compile(valueString);
}
return defaultValue;
}
protected RangedUri parseInitialization(XmlPullParser xpp, String baseUrl) {
return parseRangedUrl(xpp, baseUrl, "sourceURL", "range");
}
protected RangedUri parseSegmentUrl(XmlPullParser xpp, String baseUrl) {
return parseRangedUrl(xpp, baseUrl, "media", "mediaRange");
}
protected RangedUri parseRangedUrl(XmlPullParser xpp, String baseUrl, String urlAttribute,
String rangeAttribute) {
String urlText = xpp.getAttributeValue(null, urlAttribute);
long rangeStart = 0;
long rangeLength = -1;
String rangeText = xpp.getAttributeValue(null, rangeAttribute);
if (rangeText != null) {
String[] rangeTextArray = rangeText.split("-");
rangeStart = Long.parseLong(rangeTextArray[0]);
if (rangeTextArray.length == 2) {
rangeLength = Long.parseLong(rangeTextArray[1]) - rangeStart + 1;
}
}
return buildRangedUri(baseUrl, urlText, rangeStart, rangeLength);
}
protected RangedUri buildRangedUri(String baseUrl, String urlText, long rangeStart,
long rangeLength) {
return new RangedUri(baseUrl, urlText, rangeStart, rangeLength);
}
// AudioChannelConfiguration parsing.
protected int parseAudioChannelConfiguration(XmlPullParser xpp)
throws XmlPullParserException, IOException {
int audioChannels;
String schemeIdUri = parseString(xpp, "schemeIdUri", null);
if ("urn:mpeg:dash:23003:3:audio_channel_configuration:2011".equals(schemeIdUri)) {
audioChannels = parseInt(xpp, "value");
} else {
audioChannels = -1;
}
do {
xpp.next();
} while (!ParserUtil.isEndTag(xpp, "AudioChannelConfiguration"));
return audioChannels;
}
// Utility methods.
/**
* Checks two languages for consistency, returning the consistent language, or throwing an
* {@link IllegalStateException} if the languages are inconsistent.
* <p>
* Two languages are consistent if they are equal, or if one is null.
*
* @param firstLanguage The first language.
* @param secondLanguage The second language.
* @return The consistent language.
*/
private static String checkLanguageConsistency(String firstLanguage, String secondLanguage) {
if (firstLanguage == null) {
return secondLanguage;
} else if (secondLanguage == null) {
return firstLanguage;
} else {
Assertions.checkState(firstLanguage.equals(secondLanguage));
return firstLanguage;
}
}
/**
* Checks two adaptation set content types for consistency, returning the consistent type, or
* throwing an {@link IllegalStateException} if the types are inconsistent.
* <p>
* Two types are consistent if they are equal, or if one is {@link AdaptationSet#TYPE_UNKNOWN}.
* Where one of the types is {@link AdaptationSet#TYPE_UNKNOWN}, the other is returned.
*
* @param firstType The first type.
* @param secondType The second type.
* @return The consistent type.
*/
private static int checkContentTypeConsistency(int firstType, int secondType) {
if (firstType == AdaptationSet.TYPE_UNKNOWN) {
return secondType;
} else if (secondType == AdaptationSet.TYPE_UNKNOWN) {
return firstType;
} else {
Assertions.checkState(firstType == secondType);
return firstType;
}
}
protected static float parseFrameRate(XmlPullParser xpp, float defaultValue) {
float frameRate = defaultValue;
String frameRateAttribute = xpp.getAttributeValue(null, "frameRate");
if (frameRateAttribute != null) {
Matcher frameRateMatcher = FRAME_RATE_PATTERN.matcher(frameRateAttribute);
if (frameRateMatcher.matches()) {
int numerator = Integer.parseInt(frameRateMatcher.group(1));
String denominatorString = frameRateMatcher.group(2);
if (!TextUtils.isEmpty(denominatorString)) {
frameRate = (float) numerator / Integer.parseInt(denominatorString);
} else {
frameRate = numerator;
}
}
}
return frameRate;
}
protected static long parseDuration(XmlPullParser xpp, String name, long defaultValue) {
String value = xpp.getAttributeValue(null, name);
if (value == null) {
return defaultValue;
} else {
return Util.parseXsDuration(value);
}
}
protected static long parseDateTime(XmlPullParser xpp, String name, long defaultValue)
throws ParseException {
String value = xpp.getAttributeValue(null, name);
if (value == null) {
return defaultValue;
} else {
return Util.parseXsDateTime(value);
}
}
protected static String parseBaseUrl(XmlPullParser xpp, String parentBaseUrl)
throws XmlPullParserException, IOException {
xpp.next();
return UriUtil.resolve(parentBaseUrl, xpp.getText());
}
protected static int parseInt(XmlPullParser xpp, String name) {
return parseInt(xpp, name, -1);
}
protected static int parseInt(XmlPullParser xpp, String name, int defaultValue) {
String value = xpp.getAttributeValue(null, name);
return value == null ? defaultValue : Integer.parseInt(value);
}
protected static long parseLong(XmlPullParser xpp, String name) {
return parseLong(xpp, name, -1);
}
protected static long parseLong(XmlPullParser xpp, String name, long defaultValue) {
String value = xpp.getAttributeValue(null, name);
return value == null ? defaultValue : Long.parseLong(value);
}
protected static String parseString(XmlPullParser xpp, String name, String defaultValue) {
String value = xpp.getAttributeValue(null, name);
return value == null ? defaultValue : value;
}
/**
* Builds a list of {@link ContentProtection} elements for an {@link AdaptationSet}.
* <p>
* If child Representation elements contain ContentProtection elements, then it is required that
* they all define the same ones. If they do, the ContentProtection elements are bubbled up to the
* AdaptationSet. Child Representation elements defining different ContentProtection elements is
* considered an error.
*/
protected static final class ContentProtectionsBuilder implements Comparator<ContentProtection> {
private ArrayList<ContentProtection> adaptationSetProtections;
private ArrayList<ContentProtection> representationProtections;
private ArrayList<ContentProtection> currentRepresentationProtections;
private boolean representationProtectionsSet;
/**
* Adds a {@link ContentProtection} found in the AdaptationSet element.
*
* @param contentProtection The {@link ContentProtection} to add.
*/
public void addAdaptationSetProtection(ContentProtection contentProtection) {
if (adaptationSetProtections == null) {
adaptationSetProtections = new ArrayList<>();
}
maybeAddContentProtection(adaptationSetProtections, contentProtection);
}
/**
* Adds a {@link ContentProtection} found in a child Representation element.
*
* @param contentProtection The {@link ContentProtection} to add.
*/
public void addRepresentationProtection(ContentProtection contentProtection) {
if (currentRepresentationProtections == null) {
currentRepresentationProtections = new ArrayList<>();
}
maybeAddContentProtection(currentRepresentationProtections, contentProtection);
}
/**
* Should be invoked after processing each child Representation element, in order to apply
* consistency checks.
*/
public void endRepresentation() {
if (!representationProtectionsSet) {
if (currentRepresentationProtections != null) {
Collections.sort(currentRepresentationProtections, this);
}
representationProtections = currentRepresentationProtections;
representationProtectionsSet = true;
} else {
// Assert that each Representation element defines the same ContentProtection elements.
if (currentRepresentationProtections == null) {
Assertions.checkState(representationProtections == null);
} else {
Collections.sort(currentRepresentationProtections, this);
Assertions.checkState(currentRepresentationProtections.equals(representationProtections));
}
}
currentRepresentationProtections = null;
}
/**
* Returns the final list of consistent {@link ContentProtection} elements.
*/
public ArrayList<ContentProtection> build() {
if (adaptationSetProtections == null) {
return representationProtections;
} else if (representationProtections == null) {
return adaptationSetProtections;
} else {
// Bubble up ContentProtection elements found in the child Representation elements.
for (int i = 0; i < representationProtections.size(); i++) {
maybeAddContentProtection(adaptationSetProtections, representationProtections.get(i));
}
return adaptationSetProtections;
}
}
/**
* Checks a ContentProtection for consistency with the given list, adding it if necessary.
* <ul>
* <li>If the new ContentProtection matches another in the list, it's consistent and is not
* added to the list.
* <li>If the new ContentProtection has the same schemeUriId as another ContentProtection in the
* list, but its other attributes do not match, then it's inconsistent and an
* {@link IllegalStateException} is thrown.
* <li>Else the new ContentProtection has a unique schemeUriId, it's consistent and is added.
* </ul>
*
* @param contentProtections The list of ContentProtection elements currently known.
* @param contentProtection The ContentProtection to add.
*/
private void maybeAddContentProtection(List<ContentProtection> contentProtections,
ContentProtection contentProtection) {
if (!contentProtections.contains(contentProtection)) {
for (int i = 0; i < contentProtections.size(); i++) {
// If contains returned false (no complete match), but find a matching schemeUriId, then
// the MPD contains inconsistent ContentProtection data.
Assertions.checkState(
!contentProtections.get(i).schemeUriId.equals(contentProtection.schemeUriId));
}
contentProtections.add(contentProtection);
}
}
// Comparator implementation.
@Override
public int compare(ContentProtection first, ContentProtection second) {
return first.schemeUriId.compareTo(second.schemeUriId);
}
}
}
| |
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package net.opengis.gml.impl;
import net.opengis.gml.CompositeSolidPropertyType;
import net.opengis.gml.CompositeSolidType;
import net.opengis.gml.GmlPackage;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.EObjectImpl;
import org.w3._1999.xlink.ActuateType;
import org.w3._1999.xlink.ShowType;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Composite Solid Property Type</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link net.opengis.gml.impl.CompositeSolidPropertyTypeImpl#getCompositeSolid <em>Composite Solid</em>}</li>
* <li>{@link net.opengis.gml.impl.CompositeSolidPropertyTypeImpl#getActuate <em>Actuate</em>}</li>
* <li>{@link net.opengis.gml.impl.CompositeSolidPropertyTypeImpl#getArcrole <em>Arcrole</em>}</li>
* <li>{@link net.opengis.gml.impl.CompositeSolidPropertyTypeImpl#getHref <em>Href</em>}</li>
* <li>{@link net.opengis.gml.impl.CompositeSolidPropertyTypeImpl#getRemoteSchema <em>Remote Schema</em>}</li>
* <li>{@link net.opengis.gml.impl.CompositeSolidPropertyTypeImpl#getRole <em>Role</em>}</li>
* <li>{@link net.opengis.gml.impl.CompositeSolidPropertyTypeImpl#getShow <em>Show</em>}</li>
* <li>{@link net.opengis.gml.impl.CompositeSolidPropertyTypeImpl#getTitle <em>Title</em>}</li>
* <li>{@link net.opengis.gml.impl.CompositeSolidPropertyTypeImpl#getType <em>Type</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class CompositeSolidPropertyTypeImpl extends EObjectImpl implements CompositeSolidPropertyType {
/**
* The cached value of the '{@link #getCompositeSolid() <em>Composite Solid</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getCompositeSolid()
* @generated
* @ordered
*/
protected CompositeSolidType compositeSolid;
/**
* The default value of the '{@link #getActuate() <em>Actuate</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getActuate()
* @generated
* @ordered
*/
protected static final ActuateType ACTUATE_EDEFAULT = ActuateType.ON_LOAD;
/**
* The cached value of the '{@link #getActuate() <em>Actuate</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getActuate()
* @generated
* @ordered
*/
protected ActuateType actuate = ACTUATE_EDEFAULT;
/**
* This is true if the Actuate attribute has been set.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
protected boolean actuateESet;
/**
* The default value of the '{@link #getArcrole() <em>Arcrole</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getArcrole()
* @generated
* @ordered
*/
protected static final String ARCROLE_EDEFAULT = null;
/**
* The cached value of the '{@link #getArcrole() <em>Arcrole</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getArcrole()
* @generated
* @ordered
*/
protected String arcrole = ARCROLE_EDEFAULT;
/**
* The default value of the '{@link #getHref() <em>Href</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getHref()
* @generated
* @ordered
*/
protected static final String HREF_EDEFAULT = null;
/**
* The cached value of the '{@link #getHref() <em>Href</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getHref()
* @generated
* @ordered
*/
protected String href = HREF_EDEFAULT;
/**
* The default value of the '{@link #getRemoteSchema() <em>Remote Schema</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getRemoteSchema()
* @generated
* @ordered
*/
protected static final String REMOTE_SCHEMA_EDEFAULT = null;
/**
* The cached value of the '{@link #getRemoteSchema() <em>Remote Schema</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getRemoteSchema()
* @generated
* @ordered
*/
protected String remoteSchema = REMOTE_SCHEMA_EDEFAULT;
/**
* The default value of the '{@link #getRole() <em>Role</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getRole()
* @generated
* @ordered
*/
protected static final String ROLE_EDEFAULT = null;
/**
* The cached value of the '{@link #getRole() <em>Role</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getRole()
* @generated
* @ordered
*/
protected String role = ROLE_EDEFAULT;
/**
* The default value of the '{@link #getShow() <em>Show</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getShow()
* @generated
* @ordered
*/
protected static final ShowType SHOW_EDEFAULT = ShowType.NEW;
/**
* The cached value of the '{@link #getShow() <em>Show</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getShow()
* @generated
* @ordered
*/
protected ShowType show = SHOW_EDEFAULT;
/**
* This is true if the Show attribute has been set.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
protected boolean showESet;
/**
* The default value of the '{@link #getTitle() <em>Title</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getTitle()
* @generated
* @ordered
*/
protected static final String TITLE_EDEFAULT = null;
/**
* The cached value of the '{@link #getTitle() <em>Title</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getTitle()
* @generated
* @ordered
*/
protected String title = TITLE_EDEFAULT;
/**
* The default value of the '{@link #getType() <em>Type</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getType()
* @generated
* @ordered
*/
protected static final String TYPE_EDEFAULT = "simple";
/**
* The cached value of the '{@link #getType() <em>Type</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getType()
* @generated
* @ordered
*/
protected String type = TYPE_EDEFAULT;
/**
* This is true if the Type attribute has been set.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
protected boolean typeESet;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected CompositeSolidPropertyTypeImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return GmlPackage.eINSTANCE.getCompositeSolidPropertyType();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public CompositeSolidType getCompositeSolid() {
return compositeSolid;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetCompositeSolid(CompositeSolidType newCompositeSolid, NotificationChain msgs) {
CompositeSolidType oldCompositeSolid = compositeSolid;
compositeSolid = newCompositeSolid;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, GmlPackage.COMPOSITE_SOLID_PROPERTY_TYPE__COMPOSITE_SOLID, oldCompositeSolid, newCompositeSolid);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setCompositeSolid(CompositeSolidType newCompositeSolid) {
if (newCompositeSolid != compositeSolid) {
NotificationChain msgs = null;
if (compositeSolid != null)
msgs = ((InternalEObject)compositeSolid).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - GmlPackage.COMPOSITE_SOLID_PROPERTY_TYPE__COMPOSITE_SOLID, null, msgs);
if (newCompositeSolid != null)
msgs = ((InternalEObject)newCompositeSolid).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - GmlPackage.COMPOSITE_SOLID_PROPERTY_TYPE__COMPOSITE_SOLID, null, msgs);
msgs = basicSetCompositeSolid(newCompositeSolid, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, GmlPackage.COMPOSITE_SOLID_PROPERTY_TYPE__COMPOSITE_SOLID, newCompositeSolid, newCompositeSolid));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ActuateType getActuate() {
return actuate;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setActuate(ActuateType newActuate) {
ActuateType oldActuate = actuate;
actuate = newActuate == null ? ACTUATE_EDEFAULT : newActuate;
boolean oldActuateESet = actuateESet;
actuateESet = true;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, GmlPackage.COMPOSITE_SOLID_PROPERTY_TYPE__ACTUATE, oldActuate, actuate, !oldActuateESet));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void unsetActuate() {
ActuateType oldActuate = actuate;
boolean oldActuateESet = actuateESet;
actuate = ACTUATE_EDEFAULT;
actuateESet = false;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.UNSET, GmlPackage.COMPOSITE_SOLID_PROPERTY_TYPE__ACTUATE, oldActuate, ACTUATE_EDEFAULT, oldActuateESet));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean isSetActuate() {
return actuateESet;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getArcrole() {
return arcrole;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setArcrole(String newArcrole) {
String oldArcrole = arcrole;
arcrole = newArcrole;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, GmlPackage.COMPOSITE_SOLID_PROPERTY_TYPE__ARCROLE, oldArcrole, arcrole));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getHref() {
return href;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setHref(String newHref) {
String oldHref = href;
href = newHref;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, GmlPackage.COMPOSITE_SOLID_PROPERTY_TYPE__HREF, oldHref, href));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getRemoteSchema() {
return remoteSchema;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setRemoteSchema(String newRemoteSchema) {
String oldRemoteSchema = remoteSchema;
remoteSchema = newRemoteSchema;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, GmlPackage.COMPOSITE_SOLID_PROPERTY_TYPE__REMOTE_SCHEMA, oldRemoteSchema, remoteSchema));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getRole() {
return role;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setRole(String newRole) {
String oldRole = role;
role = newRole;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, GmlPackage.COMPOSITE_SOLID_PROPERTY_TYPE__ROLE, oldRole, role));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ShowType getShow() {
return show;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setShow(ShowType newShow) {
ShowType oldShow = show;
show = newShow == null ? SHOW_EDEFAULT : newShow;
boolean oldShowESet = showESet;
showESet = true;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, GmlPackage.COMPOSITE_SOLID_PROPERTY_TYPE__SHOW, oldShow, show, !oldShowESet));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void unsetShow() {
ShowType oldShow = show;
boolean oldShowESet = showESet;
show = SHOW_EDEFAULT;
showESet = false;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.UNSET, GmlPackage.COMPOSITE_SOLID_PROPERTY_TYPE__SHOW, oldShow, SHOW_EDEFAULT, oldShowESet));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean isSetShow() {
return showESet;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getTitle() {
return title;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setTitle(String newTitle) {
String oldTitle = title;
title = newTitle;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, GmlPackage.COMPOSITE_SOLID_PROPERTY_TYPE__TITLE, oldTitle, title));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getType() {
return type;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setType(String newType) {
String oldType = type;
type = newType;
boolean oldTypeESet = typeESet;
typeESet = true;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, GmlPackage.COMPOSITE_SOLID_PROPERTY_TYPE__TYPE, oldType, type, !oldTypeESet));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void unsetType() {
String oldType = type;
boolean oldTypeESet = typeESet;
type = TYPE_EDEFAULT;
typeESet = false;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.UNSET, GmlPackage.COMPOSITE_SOLID_PROPERTY_TYPE__TYPE, oldType, TYPE_EDEFAULT, oldTypeESet));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean isSetType() {
return typeESet;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case GmlPackage.COMPOSITE_SOLID_PROPERTY_TYPE__COMPOSITE_SOLID:
return basicSetCompositeSolid(null, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case GmlPackage.COMPOSITE_SOLID_PROPERTY_TYPE__COMPOSITE_SOLID:
return getCompositeSolid();
case GmlPackage.COMPOSITE_SOLID_PROPERTY_TYPE__ACTUATE:
return getActuate();
case GmlPackage.COMPOSITE_SOLID_PROPERTY_TYPE__ARCROLE:
return getArcrole();
case GmlPackage.COMPOSITE_SOLID_PROPERTY_TYPE__HREF:
return getHref();
case GmlPackage.COMPOSITE_SOLID_PROPERTY_TYPE__REMOTE_SCHEMA:
return getRemoteSchema();
case GmlPackage.COMPOSITE_SOLID_PROPERTY_TYPE__ROLE:
return getRole();
case GmlPackage.COMPOSITE_SOLID_PROPERTY_TYPE__SHOW:
return getShow();
case GmlPackage.COMPOSITE_SOLID_PROPERTY_TYPE__TITLE:
return getTitle();
case GmlPackage.COMPOSITE_SOLID_PROPERTY_TYPE__TYPE:
return getType();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case GmlPackage.COMPOSITE_SOLID_PROPERTY_TYPE__COMPOSITE_SOLID:
setCompositeSolid((CompositeSolidType)newValue);
return;
case GmlPackage.COMPOSITE_SOLID_PROPERTY_TYPE__ACTUATE:
setActuate((ActuateType)newValue);
return;
case GmlPackage.COMPOSITE_SOLID_PROPERTY_TYPE__ARCROLE:
setArcrole((String)newValue);
return;
case GmlPackage.COMPOSITE_SOLID_PROPERTY_TYPE__HREF:
setHref((String)newValue);
return;
case GmlPackage.COMPOSITE_SOLID_PROPERTY_TYPE__REMOTE_SCHEMA:
setRemoteSchema((String)newValue);
return;
case GmlPackage.COMPOSITE_SOLID_PROPERTY_TYPE__ROLE:
setRole((String)newValue);
return;
case GmlPackage.COMPOSITE_SOLID_PROPERTY_TYPE__SHOW:
setShow((ShowType)newValue);
return;
case GmlPackage.COMPOSITE_SOLID_PROPERTY_TYPE__TITLE:
setTitle((String)newValue);
return;
case GmlPackage.COMPOSITE_SOLID_PROPERTY_TYPE__TYPE:
setType((String)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case GmlPackage.COMPOSITE_SOLID_PROPERTY_TYPE__COMPOSITE_SOLID:
setCompositeSolid((CompositeSolidType)null);
return;
case GmlPackage.COMPOSITE_SOLID_PROPERTY_TYPE__ACTUATE:
unsetActuate();
return;
case GmlPackage.COMPOSITE_SOLID_PROPERTY_TYPE__ARCROLE:
setArcrole(ARCROLE_EDEFAULT);
return;
case GmlPackage.COMPOSITE_SOLID_PROPERTY_TYPE__HREF:
setHref(HREF_EDEFAULT);
return;
case GmlPackage.COMPOSITE_SOLID_PROPERTY_TYPE__REMOTE_SCHEMA:
setRemoteSchema(REMOTE_SCHEMA_EDEFAULT);
return;
case GmlPackage.COMPOSITE_SOLID_PROPERTY_TYPE__ROLE:
setRole(ROLE_EDEFAULT);
return;
case GmlPackage.COMPOSITE_SOLID_PROPERTY_TYPE__SHOW:
unsetShow();
return;
case GmlPackage.COMPOSITE_SOLID_PROPERTY_TYPE__TITLE:
setTitle(TITLE_EDEFAULT);
return;
case GmlPackage.COMPOSITE_SOLID_PROPERTY_TYPE__TYPE:
unsetType();
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case GmlPackage.COMPOSITE_SOLID_PROPERTY_TYPE__COMPOSITE_SOLID:
return compositeSolid != null;
case GmlPackage.COMPOSITE_SOLID_PROPERTY_TYPE__ACTUATE:
return isSetActuate();
case GmlPackage.COMPOSITE_SOLID_PROPERTY_TYPE__ARCROLE:
return ARCROLE_EDEFAULT == null ? arcrole != null : !ARCROLE_EDEFAULT.equals(arcrole);
case GmlPackage.COMPOSITE_SOLID_PROPERTY_TYPE__HREF:
return HREF_EDEFAULT == null ? href != null : !HREF_EDEFAULT.equals(href);
case GmlPackage.COMPOSITE_SOLID_PROPERTY_TYPE__REMOTE_SCHEMA:
return REMOTE_SCHEMA_EDEFAULT == null ? remoteSchema != null : !REMOTE_SCHEMA_EDEFAULT.equals(remoteSchema);
case GmlPackage.COMPOSITE_SOLID_PROPERTY_TYPE__ROLE:
return ROLE_EDEFAULT == null ? role != null : !ROLE_EDEFAULT.equals(role);
case GmlPackage.COMPOSITE_SOLID_PROPERTY_TYPE__SHOW:
return isSetShow();
case GmlPackage.COMPOSITE_SOLID_PROPERTY_TYPE__TITLE:
return TITLE_EDEFAULT == null ? title != null : !TITLE_EDEFAULT.equals(title);
case GmlPackage.COMPOSITE_SOLID_PROPERTY_TYPE__TYPE:
return isSetType();
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (actuate: ");
if (actuateESet) result.append(actuate); else result.append("<unset>");
result.append(", arcrole: ");
result.append(arcrole);
result.append(", href: ");
result.append(href);
result.append(", remoteSchema: ");
result.append(remoteSchema);
result.append(", role: ");
result.append(role);
result.append(", show: ");
if (showESet) result.append(show); else result.append("<unset>");
result.append(", title: ");
result.append(title);
result.append(", type: ");
if (typeESet) result.append(type); else result.append("<unset>");
result.append(')');
return result.toString();
}
} //CompositeSolidPropertyTypeImpl
| |
/**
* Copyright 2005-2016 Red Hat, Inc.
*
* Red Hat 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 io.fabric8.cxf;
import org.apache.cxf.common.logging.LogUtils;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.endpoint.Endpoint;
import org.apache.cxf.endpoint.Retryable;
import org.apache.cxf.helpers.CastUtils;
import org.apache.cxf.message.Exchange;
import org.apache.cxf.message.Message;
import org.apache.cxf.service.model.BindingOperationInfo;
import org.apache.cxf.transport.Conduit;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
public class FailOverTargetSelector extends LoadBalanceTargetSelector {
private static final Logger LOG =
LogUtils.getL7dLogger(FailOverTargetSelector.class);
protected Map<InvocationKey, InvocationContext> inProgress;
protected List<Class> exceptionClasses;
public FailOverTargetSelector(List<Class> exceptions) {
this(null, exceptions);
}
public FailOverTargetSelector(Conduit c, List<Class> exceptions) {
super(c);
inProgress = new ConcurrentHashMap<InvocationKey, InvocationContext>();
if (exceptions != null) {
exceptionClasses = exceptions;
} else {
exceptionClasses = new ArrayList<Class>();
}
// FailOver the IOException by default
if (!exceptionClasses.contains(IOException.class)) {
exceptionClasses.add(IOException.class);
}
}
@Override
protected Logger getLogger() {
return LOG;
}
public synchronized void prepare(Message message) {
Exchange exchange = message.getExchange();
InvocationKey key = new InvocationKey(exchange);
if (!inProgress.containsKey(key)) {
Endpoint endpoint = exchange.get(Endpoint.class);
BindingOperationInfo bindingOperationInfo =
exchange.getBindingOperationInfo();
Object[] params = message.getContent(List.class).toArray();
Map<String, Object> context =
CastUtils.cast((Map) message.get(Message.INVOCATION_CONTEXT));
InvocationContext invocation =
new InvocationContext(endpoint,
bindingOperationInfo,
params,
context);
inProgress.put(key, invocation);
}
}
public void complete(Exchange exchange) {
InvocationKey key = new InvocationKey(exchange);
InvocationContext invocation = null;
invocation = inProgress.get(key);
boolean failOver = false;
if (requiresFailOver(exchange)) {
Endpoint failOverTarget = getFailOverTarget(exchange, invocation);
if (failOverTarget != null) {
setEndpoint(failOverTarget);
selectedConduit.close();
selectedConduit = null;
Exception prevExchangeFault =
(Exception)exchange.remove(Exception.class.getName());
Message outMessage = exchange.getOutMessage();
Exception prevOutMessageFault =
outMessage.getContent(Exception.class);
Message inFaultMessage = exchange.getInFaultMessage();
Exception prevInFaultMessageFault = null;
if (inFaultMessage != null) {
prevInFaultMessageFault =
inFaultMessage.getContent(Exception.class);
inFaultMessage.setContent(Exception.class, null);
}
outMessage.setContent(Exception.class, null);
overrideAddressProperty(invocation.getContext());
Retryable retry = exchange.get(Retryable.class);
exchange.clear();
if (retry != null) {
try {
failOver = true;
retry.invoke(invocation.getBindingOperationInfo(),
invocation.getParams(),
invocation.getContext(),
exchange);
} catch (Exception e) {
if (exchange.get(Exception.class) != null) {
exchange.put(Exception.class, prevExchangeFault);
}
if (outMessage.getContent(Exception.class) != null) {
outMessage.setContent(Exception.class,
prevOutMessageFault);
}
if (inFaultMessage!= null && inFaultMessage.getContent(Exception.class) != null) {
inFaultMessage.setContent(Exception.class,
prevInFaultMessageFault);
}
}
}
} else {
setEndpoint(invocation.retrieveOriginalEndpoint(endpoint));
}
}
if (!failOver) {
getLogger().info("FailOver is not required.");
inProgress.remove(key);
super.complete(exchange);
}
}
// Now we just fail over on the exceptions
protected boolean requiresFailOver(Exchange exchange) {
Exception ex = null;
if (exchange.getOutMessage().getContent(Exception.class) != null) {
ex = exchange.getOutMessage().getContent(Exception.class);
} else if (exchange.get(Exception.class) != null) {
ex = exchange.get(Exception.class);
} else if (exchange.getInFaultMessage() != null) {
ex = exchange.getInFaultMessage().getContent(Exception.class);
}
getLogger().log(Level.FINE,
"Check last invoke failed " + ex);
Throwable curr = ex;
boolean failOver = false;
while (curr != null && !failOver) {
failOver = checkExceptionClasses(curr);
curr = curr.getCause();
}
getLogger().log(Level.INFO, "Check failure in transport " + ex + ", failOver is " + failOver);
return failOver;
}
protected boolean checkExceptionClasses(Throwable current) {
for (Class<?> exceptionClass : exceptionClasses) {
if (exceptionClass.isInstance(current)) {
return true;
}
}
return false;
}
protected Endpoint getFailOverTarget(Exchange exchange,
InvocationContext invocation) {
Endpoint failOverTarget = null;
if (invocation.getAlternateAddresses() == null) {
invocation.setAlternateAddresses(getLoadBalanceStrategy().getAlternateAddressList());
// Remove the first one as it is used
invocation.getAlternateAddresses().remove(0);
}
String alternateAddress = null;
if (invocation.getAlternateAddresses().size() > 0) {
alternateAddress = invocation.getAlternateAddresses().remove(0);
}
if (alternateAddress != null) {
// reuse the endpointInfo
failOverTarget = getEndpoint();
failOverTarget.getEndpointInfo().setAddress(alternateAddress);
}
return failOverTarget;
}
protected void overrideAddressProperty(Map<String, Object> context) {
Map<String, Object> requestContext =
CastUtils.cast((Map)context.get(Client.REQUEST_CONTEXT));
if (requestContext != null) {
requestContext.put(Message.ENDPOINT_ADDRESS,
getEndpoint().getEndpointInfo().getAddress());
requestContext.put("javax.xml.ws.service.endpoint.address",
getEndpoint().getEndpointInfo().getAddress());
// We should not replace the Address this time as the address is already override
requestContext.put(LoadBalanceTargetSelector.OVERRIDE_ADDRESS, "false");
}
}
protected static class InvocationKey {
private Exchange exchange;
InvocationKey(Exchange ex) {
exchange = ex;
}
@Override
public int hashCode() {
return System.identityHashCode(this.exchange);
}
@Override
public boolean equals(Object o) {
return o instanceof InvocationKey
&& exchange == ((InvocationKey)o).exchange;
}
}
/**
* Records the context of an invocation.
*/
protected class InvocationContext {
private Endpoint originalEndpoint;
private String originalAddress;
private BindingOperationInfo bindingOperationInfo;
private Object[] params;
private Map<String, Object> context;
private List<String> alternateAddresses;
InvocationContext(Endpoint endpoint,
BindingOperationInfo boi,
Object[] prms,
Map<String, Object> ctx) {
originalEndpoint = endpoint;
originalAddress = endpoint.getEndpointInfo().getAddress();
bindingOperationInfo = boi;
params = prms;
context = ctx;
}
Endpoint retrieveOriginalEndpoint(Endpoint endpoint) {
if (endpoint != originalEndpoint) {
getLogger().log(Level.INFO,
"Revert to original target " +
endpoint.getEndpointInfo().getName());
}
if (!endpoint.getEndpointInfo().getAddress().equals(originalAddress)) {
endpoint.getEndpointInfo().setAddress(originalAddress);
getLogger().log(Level.INFO,
"Revert to original address ",
endpoint.getEndpointInfo().getAddress());
}
return originalEndpoint;
}
BindingOperationInfo getBindingOperationInfo() {
return bindingOperationInfo;
}
Object[] getParams() {
return params;
}
Map<String, Object> getContext() {
return context;
}
void setAlternateAddresses(List<String> alternates) {
alternateAddresses = alternates;
}
List<String> getAlternateAddresses() {
return alternateAddresses;
}
}
}
| |
/*
* Copyright (c) 2010-2015 Evolveum
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.evolveum.midpoint.repo.common.expression;
import java.util.ArrayList;
import java.util.Collection;
import javax.xml.namespace.QName;
import com.evolveum.midpoint.prism.*;
import com.evolveum.midpoint.prism.delta.ContainerDelta;
import com.evolveum.midpoint.prism.delta.ItemDelta;
import com.evolveum.midpoint.prism.delta.PrismValueDeltaSetTriple;
import com.evolveum.midpoint.prism.delta.PropertyDelta;
import com.evolveum.midpoint.prism.path.ItemPath;
import com.evolveum.midpoint.prism.path.ItemPath.CompareResult;
import com.evolveum.midpoint.util.DebugDumpable;
import com.evolveum.midpoint.util.DebugUtil;
import com.evolveum.midpoint.util.exception.SchemaException;
/**
* @author semancik
*
*/
public class ItemDeltaItem<V extends PrismValue,D extends ItemDefinition> implements DebugDumpable {
Item<V,D> itemOld;
ItemDelta<V,D> delta;
Item<V,D> itemNew;
ItemPath resolvePath = ItemPath.EMPTY_PATH;
ItemPath residualPath = null;
// The deltas in sub-items. E.g. if this object represents "ContainerDeltaContainer"
// this property contains property deltas that may exist inside the container.
Collection<? extends ItemDelta<?,?>> subItemDeltas;
public ItemDeltaItem() { }
public ItemDeltaItem(Item<V,D> itemOld, ItemDelta<V,D> delta, Item<V,D> itemNew) {
super();
this.itemOld = itemOld;
this.delta = delta;
this.itemNew = itemNew;
}
public ItemDeltaItem(ItemDeltaItem<V,D> idi) {
super();
this.itemOld = idi.getItemOld();
this.itemNew = idi.getItemNew();
this.delta = idi.getDelta();
}
public ItemDeltaItem(Item<V,D> item) {
super();
this.itemOld = item;
this.itemNew = item;
this.delta = null;
}
public Item<V,D> getItemOld() {
return itemOld;
}
public void setItemOld(Item<V,D> itemOld) {
this.itemOld = itemOld;
}
public ItemDelta<V,D> getDelta() {
return delta;
}
public void setDelta(ItemDelta<V,D> delta) {
this.delta = delta;
}
public Item<V,D> getItemNew() {
return itemNew;
}
public void setItemNew(Item<V,D> itemNew) {
this.itemNew = itemNew;
}
public Item<V,D> getAnyItem() {
if (itemOld != null) {
return itemOld;
}
return itemNew;
}
public ItemPath getResidualPath() {
return residualPath;
}
public void setResidualPath(ItemPath residualPath) {
this.residualPath = residualPath;
}
public ItemPath getResolvePath() {
return resolvePath;
}
public void setResolvePath(ItemPath resolvePath) {
this.resolvePath = resolvePath;
}
public Collection<? extends ItemDelta<?,?>> getSubItemDeltas() {
return subItemDeltas;
}
public void setSubItemDeltas(Collection<? extends ItemDelta<?,?>> subItemDeltas) {
this.subItemDeltas = subItemDeltas;
}
public boolean isNull() {
return itemOld == null && itemNew == null && delta == null && subItemDeltas == null;
}
public QName getElementName() {
Item<V,D> anyItem = getAnyItem();
if (anyItem != null) {
return anyItem.getElementName();
}
if (delta != null) {
return delta.getElementName();
}
return null;
}
public ItemDefinition getDefinition() {
Item<V,D> anyItem = getAnyItem();
if (anyItem != null) {
return anyItem.getDefinition();
}
if (delta != null) {
return delta.getDefinition();
}
return null;
}
public void recompute() throws SchemaException {
if (delta != null) {
itemNew = delta.getItemNewMatchingPath(itemOld);
} else {
itemNew = itemOld;
}
if (subItemDeltas != null && !subItemDeltas.isEmpty()) {
if (itemNew == null) {
throw new SchemaException("Cannot apply subitem delta to null new item");
}
for (ItemDelta<?,?> subItemDelta: subItemDeltas) {
itemNew = (Item<V,D>) subItemDelta.getItemNew((Item) itemNew);
}
}
}
public <IV extends PrismValue, ID extends ItemDefinition> ItemDeltaItem<IV,ID> findIdi(ItemPath path) {
if (path.isEmpty()) {
return (ItemDeltaItem<IV,ID>) this;
}
Item<IV,ID> subItemOld = null;
ItemPath subResidualPath = null;
ItemPath newResolvePath = resolvePath.subPath(path);
if (itemOld != null) {
PartiallyResolvedItem<IV,ID> partialItemOld = itemOld.findPartial(path);
if (partialItemOld != null) {
subItemOld = partialItemOld.getItem();
subResidualPath = partialItemOld.getResidualPath();
}
}
Item<IV,ID> subItemNew = null;
if (itemNew != null) {
PartiallyResolvedItem<IV,ID> partialItemNew = itemNew.findPartial(path);
if (partialItemNew != null) {
subItemNew = partialItemNew.getItem();
if (subResidualPath == null) {
subResidualPath = partialItemNew.getResidualPath();
}
}
}
ItemDelta<IV,ID> subDelta= null;
if (delta != null) {
if (delta instanceof ContainerDelta<?>) {
subDelta = (ItemDelta<IV,ID>) ((ContainerDelta<?>)delta).getSubDelta(path);
} else {
CompareResult compareComplex = delta.getPath().compareComplex(newResolvePath);
if (compareComplex == CompareResult.EQUIVALENT || compareComplex == CompareResult.SUBPATH) {
subDelta = (ItemDelta<IV,ID>) delta;
}
}
}
ItemDeltaItem<IV,ID> subIdi = new ItemDeltaItem<IV,ID>(subItemOld, subDelta, subItemNew);
subIdi.setResidualPath(subResidualPath);
subIdi.resolvePath = newResolvePath;
if (subItemDeltas != null) {
Item<IV,ID> subAnyItem = subIdi.getAnyItem();
Collection<ItemDelta<?,?>> subSubItemDeltas = new ArrayList<>();
for (ItemDelta<?,?> subItemDelta: subItemDeltas) {
CompareResult compareComplex = subItemDelta.getPath().compareComplex(subAnyItem.getPath());
if (compareComplex == CompareResult.EQUIVALENT || compareComplex == CompareResult.SUBPATH) {
subSubItemDeltas.add(subItemDelta);
}
}
if (!subSubItemDeltas.isEmpty()) {
// Niceness optimization
if (subDelta == null && subSubItemDeltas.size() == 1) {
ItemDelta<?,?> subSubItemDelta = subSubItemDeltas.iterator().next();
if (subSubItemDelta.isApplicableTo(subAnyItem)) {
subDelta = (ItemDelta<IV,ID>) subSubItemDelta;
subIdi.setDelta(subDelta);
} else {
subIdi.setSubItemDeltas(subSubItemDeltas);
}
} else {
subIdi.setSubItemDeltas(subSubItemDeltas);
}
}
}
return subIdi;
}
public PrismValueDeltaSetTriple<V> toDeltaSetTriple() {
return ItemDelta.toDeltaSetTriple(itemOld, delta);
}
public boolean isContainer() {
Item<V,D> item = getAnyItem();
if (item != null) {
return item instanceof PrismContainer<?>;
}
if (getDelta() != null) {
return getDelta() instanceof ContainerDelta<?>;
}
return false;
}
public boolean isProperty() {
Item<V,D> item = getAnyItem();
if (item != null) {
return item instanceof PrismProperty<?>;
}
if (getDelta() != null) {
return getDelta() instanceof PropertyDelta<?>;
}
return false;
}
/**
* @return
*/
public boolean isStructuredProperty() {
if (!isProperty()) {
return false;
}
PrismProperty<?> property = (PrismProperty<?>) getAnyItem();
Object realValue = property.getAnyRealValue();
if (realValue != null) {
return realValue instanceof Structured;
}
PropertyDelta<?> delta = (PropertyDelta<?>) getDelta();
realValue = delta.getAnyRealValue();
if (realValue != null) {
return realValue instanceof Structured;
}
return false;
}
// Assumes that this IDI represents structured property
public <X> ItemDeltaItem<PrismPropertyValue<X>,PrismPropertyDefinition<X>> resolveStructuredProperty(ItemPath resolvePath, PrismPropertyDefinition outputDefinition, ItemPath outputPath) {
ItemDeltaItem<PrismPropertyValue<Structured>,PrismPropertyDefinition<Structured>> thisIdi = (ItemDeltaItem<PrismPropertyValue<Structured>,PrismPropertyDefinition<Structured>>)this;
PrismProperty<X> outputPropertyNew = resolveStructuredPropertyItem((PrismProperty<Structured>) thisIdi.getItemNew(), resolvePath, outputDefinition);
PrismProperty<X> outputPropertyOld = resolveStructuredPropertyItem((PrismProperty<Structured>) thisIdi.getItemOld(), resolvePath, outputDefinition);
PropertyDelta<X> outputDelta = resolveStructuredPropertyDelta((PropertyDelta<Structured>) thisIdi.getDelta(), resolvePath, outputDefinition, outputPath);
return new ItemDeltaItem<PrismPropertyValue<X>,PrismPropertyDefinition<X>>(outputPropertyOld, outputDelta, outputPropertyNew);
}
private <X> PrismProperty<X> resolveStructuredPropertyItem(PrismProperty<Structured> sourceProperty, ItemPath resolvePath, PrismPropertyDefinition outputDefinition) {
if (sourceProperty == null) {
return null;
}
PrismProperty<X> outputProperty = outputDefinition.instantiate();
for (Structured sourceRealValue: sourceProperty.getRealValues()) {
X outputRealValue = (X) sourceRealValue.resolve(resolvePath);
outputProperty.addRealValue(outputRealValue);
}
return outputProperty;
}
private <X> PropertyDelta<X> resolveStructuredPropertyDelta(PropertyDelta<Structured> sourceDelta, ItemPath resolvePath, PrismPropertyDefinition outputDefinition, ItemPath outputPath) {
if (sourceDelta == null) {
return null;
}
PropertyDelta<X> outputDelta = (PropertyDelta<X>) outputDefinition.createEmptyDelta(outputPath);
Collection<PrismPropertyValue<X>> outputValuesToAdd = resolveStructuredDeltaSet(sourceDelta.getValuesToAdd(), resolvePath);
if (outputValuesToAdd != null) {
outputDelta.addValuesToAdd(outputValuesToAdd);
}
Collection<PrismPropertyValue<X>> outputValuesToDelete = resolveStructuredDeltaSet(sourceDelta.getValuesToDelete(), resolvePath);
if (outputValuesToDelete != null) {
outputDelta.addValuesToDelete(outputValuesToDelete);
}
Collection<PrismPropertyValue<X>> outputValuesToReplace = resolveStructuredDeltaSet(sourceDelta.getValuesToReplace(), resolvePath);
if (outputValuesToReplace != null) {
outputDelta.setValuesToReplace(outputValuesToReplace);
}
return outputDelta;
}
private <X> Collection<PrismPropertyValue<X>> resolveStructuredDeltaSet(Collection<PrismPropertyValue<Structured>> set, ItemPath resolvePath) {
if (set == null) {
return null;
}
Collection<PrismPropertyValue<X>> outputSet = new ArrayList<PrismPropertyValue<X>>(set.size());
for (PrismPropertyValue<Structured> structuredPVal: set) {
Structured structured = structuredPVal.getValue();
X outputRval = (X) structured.resolve(resolvePath);
outputSet.add(new PrismPropertyValue<X>(outputRval));
}
return outputSet;
}
public void applyDefinition(D def, boolean force) throws SchemaException {
if (itemNew != null) {
itemNew.applyDefinition(def, force);
}
if (itemOld != null) {
itemOld.applyDefinition(def, force);
}
if (delta != null) {
delta.applyDefinition(def, force);
}
}
public ItemDeltaItem<V,D> clone() {
ItemDeltaItem<V,D> clone = new ItemDeltaItem<>();
copyValues(clone);
return clone;
}
protected void copyValues(ItemDeltaItem<V,D> clone) {
if (this.itemNew != null) {
clone.itemNew = this.itemNew.clone();
}
if (this.delta != null) {
clone.delta = this.delta.clone();
}
if (this.itemOld != null) {
clone.itemOld = this.itemOld.clone();
}
clone.residualPath = this.residualPath;
clone.resolvePath = this.resolvePath;
if (this.subItemDeltas != null) {
clone.subItemDeltas = ItemDelta.cloneCollection(this.subItemDeltas);
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((delta == null) ? 0 : delta.hashCode());
result = prime * result + ((itemNew == null) ? 0 : itemNew.hashCode());
result = prime * result + ((itemOld == null) ? 0 : itemOld.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ItemDeltaItem other = (ItemDeltaItem) obj;
if (delta == null) {
if (other.delta != null)
return false;
} else if (!delta.equals(other.delta))
return false;
if (itemNew == null) {
if (other.itemNew != null)
return false;
} else if (!itemNew.equals(other.itemNew))
return false;
if (itemOld == null) {
if (other.itemOld != null)
return false;
} else if (!itemOld.equals(other.itemOld))
return false;
return true;
}
@Override
public String toString() {
return "IDI(old=" + itemOld + ", delta=" + delta + ", new=" + itemNew + ")";
}
@Override
public String debugDump(int indent) {
StringBuilder sb = new StringBuilder();
DebugUtil.debugDumpLabelLn(sb, "ItemDeltaItem", indent);
DebugUtil.debugDumpWithLabelLn(sb, "itemOld", itemOld, indent + 1);
DebugUtil.debugDumpWithLabelLn(sb, "delta", delta, indent + 1);
DebugUtil.debugDumpWithLabelLn(sb, "itemNew", itemNew, indent + 1);
DebugUtil.debugDumpWithLabelToStringLn(sb, "resolvePath", resolvePath, indent + 1);
DebugUtil.debugDumpWithLabelToString(sb, "residualPath", residualPath, indent + 1);
return sb.toString();
}
private V getSingleValue(Item<V, D> item) {
if (item == null || item.isEmpty()) {
return null;
} else if (item.size() == 1) {
return item.getValue(0);
} else {
throw new IllegalStateException("Multiple values where single one was expected: " + item);
}
}
public V getSingleValue(boolean evaluateOld) {
return getSingleValue(evaluateOld ? itemOld : itemNew);
}
}
| |
/*
* Copyright (c) 2012, Gerrit Grunwald
* 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.
* The names of its contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package eu.hansolo.steelseries.tools;
import java.awt.Color;
import java.awt.Paint;
import java.awt.PaintContext;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.Transparency;
import java.awt.image.ColorModel;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;
import java.util.HashMap;
import java.util.Map;
/**
* @author Gerrit Grunwald <han.solo at muenster.de>
*/
public class EllipticGradientPaint implements Paint {
private final Point2D CENTER;
private final Point2D RADIUS_X_Y;
private final float[] FRACTIONS;
private final Color[] COLORS;
private final GradientWrapper COLOR_LOOKUP;
public EllipticGradientPaint(final Point2D GIVEN_CENTER, Point2D GIVEN_RADIUS_X_Y, final float[] GIVEN_FRACTIONS, final Color[] GIVEN_COLORS) {
if (GIVEN_RADIUS_X_Y.distance(0, 0) <= 0) {
throw new IllegalArgumentException("Radius must be greater than 0.");
}
// Check that fractions and colors are of the same size
if (GIVEN_FRACTIONS.length != GIVEN_COLORS.length) {
throw new IllegalArgumentException("Fractions and colors must be equal in size");
}
CENTER = GIVEN_CENTER;
RADIUS_X_Y = GIVEN_RADIUS_X_Y;
FRACTIONS = GIVEN_FRACTIONS.clone();
COLORS = GIVEN_COLORS.clone();
COLOR_LOOKUP = new GradientWrapper(new Point2D.Double(0, 0), new Point2D.Double(100, 0), FRACTIONS, COLORS);
}
@Override
public java.awt.PaintContext createContext(final ColorModel COLOR_MODEL,
final Rectangle DEVICE_BOUNDS,
final Rectangle2D USER_BOUNDS,
final AffineTransform TRANSFORM,
final RenderingHints RENDERING_HINTS) {
final Point2D TRANSFORMED_CENTER = TRANSFORM.transform(CENTER, null);
final Point2D TRANSFORMED_RADIUS_XY = TRANSFORM.deltaTransform(RADIUS_X_Y, null);
return new OvalGradientContext(TRANSFORMED_CENTER, TRANSFORMED_RADIUS_XY, FRACTIONS, COLORS);
}
@Override
public int getTransparency() {
return Transparency.TRANSLUCENT;
}
private final class OvalGradientContext implements PaintContext {
private final Point2D CENTER;
private final Ellipse2D.Double ELLIPSE;
private final Line2D.Double LINE;
private Map<Double, Double> lookup;
private double R;
public OvalGradientContext(final Point2D CENTER, final Point2D RADIUS_X_Y, final float[] FRACTIONS, final Color[] COLORS) {
this.CENTER = CENTER;
final double X = CENTER.getX() - RADIUS_X_Y.getX();
final double Y = CENTER.getY() - RADIUS_X_Y.getY();
final double WIDTH = 2 * RADIUS_X_Y.getX();
final double HEIGHT = 2 * RADIUS_X_Y.getY();
ELLIPSE = new Ellipse2D.Double(X, Y, WIDTH, HEIGHT);
LINE = new Line2D.Double();
R = Point2D.distance(0, 0, RADIUS_X_Y.getX(), RADIUS_X_Y.getY());
initLookup();
}
@Override
public void dispose() {
}
@Override
public ColorModel getColorModel() {
return ColorModel.getRGBdefault();
}
@Override
public Raster getRaster(final int X, final int Y, final int TILE_WIDTH, final int TILE_HEIGHT) {
final WritableRaster RASTER = getColorModel().createCompatibleWritableRaster(TILE_WIDTH, TILE_HEIGHT);
int[] data = new int[TILE_WIDTH * TILE_HEIGHT * 4];
double distance;
double dx;
double dy;
double alpha;
double roundDegrees;
double radius;
float ratio;
for (int tileY = 0; tileY < TILE_HEIGHT; tileY++) {
for (int tileX = 0; tileX < TILE_WIDTH; tileX++) {
distance = CENTER.distance(X + tileX, Y + tileY);
dy = Y + tileY - CENTER.getY();
dx = X + tileX - CENTER.getX();
alpha = Math.atan2(dy, dx);
roundDegrees = Math.round(Math.toDegrees(alpha));
radius = lookup.get(roundDegrees);
ratio = (float) (distance / radius);
if (Float.compare(ratio, 1.0f) > 0) {
ratio = 1.0f;
}
final int BASE = (tileY * TILE_WIDTH + tileX) * 4;
data[BASE + 0] = (COLOR_LOOKUP.getColorAt(ratio).getRed());
data[BASE + 1] = (COLOR_LOOKUP.getColorAt(ratio).getGreen());
data[BASE + 2] = (COLOR_LOOKUP.getColorAt(ratio).getBlue());
data[BASE + 3] = (COLOR_LOOKUP.getColorAt(ratio).getAlpha());
}
}
RASTER.setPixels(0, 0, TILE_WIDTH, TILE_HEIGHT, data);
return RASTER;
}
private void initLookup() {
lookup = new HashMap<Double, Double>(360);
double alpha;
double xp;
double yp;
for (int angle = -180; angle <= 180; angle++) {
Double key = Double.valueOf(angle);
alpha = Math.toRadians(angle);
xp = CENTER.getX() + R * Math.cos(alpha);
yp = CENTER.getY() + R * Math.sin(alpha);
LINE.setLine(CENTER.getX(), CENTER.getY(), xp, yp);
Double value = Double.valueOf(getRadius());
lookup.put(key, value);
}
lookup.put(0.0, getRadius());
}
private double getRadius() {
final double[] COORDINATES = new double[6];
final Point2D.Double P = new Point2D.Double();
double minDistance = Double.MAX_VALUE;
final double FLATNESS = 0.005;
final java.awt.geom.PathIterator PATH_ITERATOR = ELLIPSE.getPathIterator(null, FLATNESS);
while (!PATH_ITERATOR.isDone()) {
int segment = PATH_ITERATOR.currentSegment(COORDINATES);
switch (segment) {
case java.awt.geom.PathIterator.SEG_CLOSE:
case java.awt.geom.PathIterator.SEG_MOVETO:
case java.awt.geom.PathIterator.SEG_LINETO:
break;
default:
break;
}
final double DISTANCE = LINE.ptSegDist(COORDINATES[0], COORDINATES[1]);
if (DISTANCE < minDistance) {
minDistance = DISTANCE;
P.x = COORDINATES[0];
P.y = COORDINATES[1];
}
PATH_ITERATOR.next();
}
return CENTER.distance(P);
}
}
}
| |
// Copyright 2017 The Nomulus Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package google.registry.model.tmch;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.ImmutableMap.toImmutableMap;
import static google.registry.persistence.transaction.QueryComposer.Comparator.EQ;
import static google.registry.persistence.transaction.TransactionManagerFactory.jpaTm;
import com.google.common.collect.ImmutableMap;
import google.registry.model.CreateAutoTimestamp;
import google.registry.model.ImmutableObject;
import google.registry.model.replay.SqlOnlyEntity;
import google.registry.model.tld.label.ReservedList.ReservedListEntry;
import java.util.Map;
import java.util.Optional;
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.PostPersist;
import javax.persistence.PostUpdate;
import javax.persistence.PreRemove;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.joda.time.DateTime;
/**
* A list of TMCH claims labels and their associated claims keys.
*
* <p>Note that the primary key of this entity is {@link #revisionId}, which is auto-generated by
* the database. So, if a retry of insertion happens after the previous attempt unexpectedly
* succeeds, we will end up with having two exact same claims list with only different {@link
* #revisionId}. However, this is not an actual problem because we only use the claims list with
* highest {@link #revisionId}.
*/
@Entity(name = "ClaimsList")
@Table
public class ClaimsList extends ImmutableObject implements SqlOnlyEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Long revisionId;
@AttributeOverrides({
@AttributeOverride(
name = "creationTime",
column = @Column(name = "creationTimestamp", nullable = false))
})
CreateAutoTimestamp creationTimestamp = CreateAutoTimestamp.create(null);
/**
* When the claims list was last updated.
*
* <p>Note that the value of this field is parsed from the claims list file(See this <a
* href="https://tools.ietf.org/html/draft-lozano-tmch-func-spec-08#section-6.1">RFC</>), it is
* the DNL List creation datetime from the rfc. Since this field has been used by Datastore, we
* cannot change its name until we finish the migration.
*
* <p>TODO(b/177567432): Rename this field to tmdbGenerationTime.
*/
@Column(name = "tmdb_generation_time", nullable = false)
DateTime creationTime;
/**
* A map from labels to claims keys.
*
* <p>This field requires special treatment since we want to lazy load it. We have to remove it
* from the immutability contract so we can modify it after construction and we have to handle the
* database processing on our own so we can detach it after load.
*/
@Insignificant @Transient ImmutableMap<String, String> labelsToKeys;
@PreRemove
void preRemove() {
jpaTm()
.query("DELETE FROM ClaimsEntry WHERE revision_id = :revisionId")
.setParameter("revisionId", revisionId)
.executeUpdate();
}
/**
* Hibernate hook called on the insert of a new ReservedList. Stores the associated {@link
* ReservedListEntry}'s.
*
* <p>We need to persist the list entries, but only on the initial insert (not on update) since
* the entries themselves never get changed, so we only annotate it with {@link PostPersist}, not
* {@link PostUpdate}.
*/
@PostPersist
void postPersist() {
if (labelsToKeys != null) {
labelsToKeys.entrySet().stream()
.forEach(
entry ->
jpaTm().insert(new ClaimsEntry(revisionId, entry.getKey(), entry.getValue())));
}
}
/** Returns the revision id of this claims list, or throws exception if it is null. */
public Long getRevisionId() {
checkState(
revisionId != null, "revisionId is null because it is not persisted in the database");
return revisionId;
}
/**
* Returns the time when the external TMDB service generated this revision of the claims list.
*
* @see <a href="https://tools.ietf.org/html/draft-lozano-tmch-func-spec-08#section-6.1">DNL List
* creation datetime</a>
*/
public DateTime getTmdbGenerationTime() {
return creationTime;
}
/** Returns the creation time of this claims list. */
public DateTime getCreationTimestamp() {
return creationTimestamp.getTimestamp();
}
/**
* Returns the claim key for a given domain if there is one, empty otherwise.
*
* <p>Note that this may do a database query. For checking multiple keys against the claims list
* it may be more efficient to use {@link #getLabelsToKeys()} first, as this will prefetch all
* entries and cache them locally.
*/
public Optional<String> getClaimKey(String label) {
if (labelsToKeys != null) {
return Optional.ofNullable(labelsToKeys.get(label));
}
return jpaTm()
.transact(
() ->
jpaTm()
.createQueryComposer(ClaimsEntry.class)
.where("revisionId", EQ, revisionId)
.where("domainLabel", EQ, label)
.first()
.map(ClaimsEntry::getClaimKey));
}
/**
* Returns an {@link Map} mapping domain label to its lookup key.
*
* <p>Note that this involves a database fetch of a potentially large number of elements and
* should be avoided unless necessary.
*/
public ImmutableMap<String, String> getLabelsToKeys() {
if (labelsToKeys == null) {
labelsToKeys =
jpaTm()
.transact(
() ->
jpaTm()
.createQueryComposer(ClaimsEntry.class)
.where("revisionId", EQ, revisionId)
.stream()
.collect(
toImmutableMap(
ClaimsEntry::getDomainLabel, ClaimsEntry::getClaimKey)));
}
return labelsToKeys;
}
/**
* Returns the number of claims.
*
* <p>Note that this will perform a database "count" query if the label to key map has not been
* previously cached by calling {@link #getLabelsToKeys()}.
*/
public long size() {
if (labelsToKeys == null) {
return jpaTm()
.createQueryComposer(ClaimsEntry.class)
.where("revisionId", EQ, revisionId)
.count();
}
return labelsToKeys.size();
}
public static ClaimsList create(
DateTime tmdbGenerationTime, ImmutableMap<String, String> labelsToKeys) {
ClaimsList instance = new ClaimsList();
instance.creationTime = checkNotNull(tmdbGenerationTime);
instance.labelsToKeys = checkNotNull(labelsToKeys);
return instance;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.