gt
stringclasses 1
value | context
stringlengths 2.05k
161k
|
---|---|
package asis.ini_asis;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
import lev.Ln;
import skyproc.FormID;
import skyproc.ModListing;
/**
*
* @author Dres Croffgrin and Plutoman
*/
public class INI_asis {
public INI_asis(String fileName) throws IOException {
//Creates a BufferedReader to allow for reding of the ini file that the object represents
//Will throw IOException of the ini sent does not exist or is corrupt
iniReader = new BufferedReader(new FileReader(fileName));
this.fileName = fileName;
}//close constructor INI(String filename)
public INI_asis(String fileName, Collection<IniSectionHead> sectionsToAdd) throws IOException {
iniReader = new BufferedReader(new FileReader(fileName));
this.fileName = fileName;
addSection(sectionsToAdd);
}
//Reads the INI file and stores the contents in a Map
public void readData() throws IOException {
String currentLine; //Will store the string with the entire current line
IniSectionHead currentSection = null; //The current INI section being processed
if (iniReader == null) {
iniReader = new BufferedReader(new FileReader(fileName));
}
boolean foundType = false; //A boolean indicating if there is an ini section being parsed
//Loops through each line of the ini file and processes the contents
while ((currentLine = iniReader.readLine()) != null) {
//Removes all whitespace from the current line
//and removes all text in a line that comes after a ';'
currentLine = Ln.cleanLine(currentLine, commentMarkingString);
//execute if current line is the header for a new section
if (containsHeader(currentLine)) {
currentSection = getHeaderFrom(currentLine);
foundType = true;
iniMap.put(currentSection, new ArrayList<IniData>());
} //execute if current line contains data.
else if (foundType && !currentLine.equalsIgnoreCase("") && currentLine != null) {
// if the data is single-entry
if (currentSection.getFormat().equals(IniDataFormat.VALUE)) {
IniData value = getVALUEDataFrom(currentLine);
iniMap.get(currentSection).add(value);
} // if the data is KEY:VALUE
else if (currentSection.getFormat().equals(IniDataFormat.KEY_VALUE)) {
IniData value = getKEY_VALUEDataFrom(currentLine);
iniMap.get(currentSection).add(value);
}
}
}// Close while
iniReader.close();
iniReader = null;
loadIniMaps();
}// close method readData()
//Returns an ArrayList with the String representations of the sections
// in the INI file
public Collection<String> getIniSections() {
ArrayList<String> iniSectionsToReturn = new ArrayList<>();
//Gathers the INI Sections from the map
Set iniSectionTypes = iniMap.keySet();
Iterator iniIterator = iniSectionTypes.iterator();
//Adds the INI Sections to an ArrayList
while (iniIterator.hasNext()) {
iniSectionsToReturn.add((String) iniIterator.next());
}
return iniSectionsToReturn;
}// Close method getIniSections
//Returns the KEY:VALUE map with the header specified by the String
public Collection<IniData> getSectionData(IniSectionHead mapToGet) {
return iniMap.get(mapToGet);
}
public Map<String, String> getMap(IniSectionHead sectionToChoose) {
if (!sectionToChoose.getFormat().equals(IniDataFormat.KEY_VALUE)) {
return new HashMap<>(0);
}
String name = sectionToChoose.getName();
if (keyValueData.get(name) == null) {
return new HashMap<>(0);
} else {
return keyValueData.get(name);
}
}
public Map<Integer, String> getMapIntStr(IniSectionHead sectionToChoose) {
if (!sectionToChoose.getFormat().equals(IniDataFormat.KEY_VALUE)) {
return new HashMap<>(0);
}
String name = sectionToChoose.getName();
HashMap<Integer, String> intStrMap = new HashMap<>();
int key;
String value;
for (Map.Entry<String, String> entry : keyValueData.get(name).entrySet()) {
key = Integer.parseInt(entry.getKey());
value = entry.getValue();
intStrMap.put(key, value);
}
return intStrMap;
}
public Map<String, ArrayList<Integer>> getMapStrIntArrayList(IniSectionHead sectionToChoose) {
if (!sectionToChoose.getFormat().equals(IniDataFormat.KEY_VALUE)) {
return new HashMap<>(0);
}
String name = sectionToChoose.getName();
HashMap<String, ArrayList<Integer>> intArrayStrMap = new HashMap<>();
String key;
String valueTemp;
ArrayList<Integer> value = new ArrayList<>();
for (Map.Entry<String, String> entry : keyValueData.get(name).entrySet()) {
key = entry.getKey();
valueTemp = entry.getValue();
Scanner s = new Scanner(valueTemp);
s.useDelimiter(" ");
while (s.hasNext()) {
value.add(Integer.parseInt(s.next()));
}
try {
intArrayStrMap.put(key, value);
} catch (NullPointerException e) {
//Continue on.
}
s.close();
}
return intArrayStrMap;
}
public Collection<String> getCollection(IniSectionHead sectionToChoose) {
if (!sectionToChoose.getFormat().equals(IniDataFormat.VALUE)) {
return new ArrayList<>(0);
}
String name = sectionToChoose.getName();
if (valueData.get(name) == null) {
return new ArrayList<>(0);
} else {
return valueData.get(name);
}
}
public Collection<FormID> getCollectionForms(IniSectionHead sectionToChoose) {
if (!sectionToChoose.getFormat().equals(IniDataFormat.VALUE)) {
return new ArrayList<>(0);
}
String name = sectionToChoose.getName();
Collection<FormID> forms = new ArrayList<>();
ArrayList<String> temp = (ArrayList) valueData.get(name);
for (int i = 0; i < valueData.get(name).size(); i++) {
forms.add(new FormID(temp.get(i), new ModListing("Skyrim", true)));
}
return forms;
}
/*
* Prerequisites: - readData() has been run
*
* Returns: - A Map of all IniSectionHeads from the parameter that are valid
* sections for this ini mapped to a Collection of IniData objects for that
* head. The Collection is implemented as an ArrayList.
*/
public Map<IniSectionHead, Collection<IniData>> getSectionData(Collection<IniSectionHead> mapsToGet) {
Map<IniSectionHead, Collection<IniData>> dataToReturn = new TreeMap<>();
// loops through the sections in the parameter, and adds all of the valid data associated with those
// keys to the map to return.
for (IniSectionHead currentSection : mapsToGet) {
if (iniMap.containsKey(currentSection)) {
dataToReturn.put(currentSection, getSectionData(currentSection));
}
}
return dataToReturn;
}
//Returns the full map for the INI
public Map<IniSectionHead, Collection<IniData>> getData() {
return iniMap;
}
public void setCommentMarkingString(String markerToSet) {
commentMarkingString = markerToSet;
}
public void setKeyValueDelimiter(String delim) {
keyValueDelimiter = delim;
}
public final void addSection(IniSectionHead section) {
sections.add(section);
}
public final void addSection(Collection<IniSectionHead> sections) {
for (IniSectionHead currentSection : sections) {
this.sections.add(currentSection);
}
}
private boolean hasSection(String sectionName) {
boolean hasSection = false;
for (IniSectionHead currentHead : sections) {
if (currentHead.getName().equalsIgnoreCase(sectionName)) {
hasSection = true;
}
}
return hasSection;
}
private boolean containsHeader(String line) {
if (!(line.contains("[") && line.contains("]"))) {
return false;
}
//ensures that there is a string between the brackets to be used as a header
if (line.indexOf("[") + 1 >= line.indexOf("]")) {
return false;
}
String headerValue = getHeaderStringFrom(line);
return hasSection(headerValue);
}
private String getHeaderStringFrom(String line) {
return line.substring(line.indexOf("[") + 1, line.indexOf("]"));
}
private IniSectionHead getHeaderFrom(String line) {
for (IniSectionHead currentHead : sections) {
if (currentHead.getName().equalsIgnoreCase(getHeaderStringFrom(line))) {
return currentHead;
}
}
return null;
}
private IniData getVALUEDataFrom(String line) {
return new IniData(IniDataFormat.VALUE, line);
}
private IniData getKEY_VALUEDataFrom(String line) {
Scanner lineParser = new Scanner(line);
lineParser.useDelimiter(keyValueDelimiter);
String key = lineParser.next();
String value = lineParser.next();
lineParser.close();
return new IniData(IniDataFormat.KEY_VALUE, key, value);
}
private Map<String, Map<String, String>> keyValueData() {
Map<String, Map<String, String>> dataToReturn = new TreeMap<>();
for (IniSectionHead currentSection : iniMap.keySet()) {
if (currentSection.getFormat().equals(IniDataFormat.KEY_VALUE)) {
dataToReturn.put(currentSection.getName(), new TreeMap<String, String>());
Map<String, String> currentDataMap = dataToReturn.get(currentSection.getName());
for (IniData currentData : iniMap.get(currentSection)) {
currentDataMap.put(currentData.getKey(), currentData.getValue());
}
}
}
return dataToReturn;
}
private Map<String, Collection<String>> valueData() {
Map<String, Collection<String>> dataToReturn = new TreeMap<>();
for (IniSectionHead currentSection : iniMap.keySet()) {
if (currentSection.getFormat().equals(IniDataFormat.VALUE)) {
dataToReturn.put(currentSection.getName(), new ArrayList<String>());
Collection<String> currentDataCollection = dataToReturn.get(currentSection.getName());
for (IniData currentData : iniMap.get(currentSection)) {
currentDataCollection.add(currentData.getValue());
}
}
}
return dataToReturn;
}
private void loadIniMaps() {
keyValueData = keyValueData();
valueData = valueData();
}
public Map<String, Map<String, String>> getKeyValueMap() {
return keyValueData;
}
public Map<String, Collection<String>> getValueMap() {
return valueData;
}
// The Reader to read the ini.
private BufferedReader iniReader;
private String fileName;
private String commentMarkingString = ";";
private String keyValueDelimiter = "[:[=]]";
// The map to store all of the INIs data
private Map<IniSectionHead, Collection<IniData>> iniMap = new TreeMap<>();
private Collection<IniSectionHead> sections = new ArrayList<>();
private Map<String, Map<String, String>> keyValueData = null;
private Map<String, Collection<String>> valueData = null;
public static class IniSectionHead implements Comparable<IniSectionHead> {
public IniSectionHead(String name, IniDataFormat format) {
this.name = name;
this.format = format;
}
public String getName() {
return name;
}
public IniDataFormat getFormat() {
return format;
}
public boolean equals(IniSectionHead other) {
return ((other.getName().equalsIgnoreCase(getName())) && (other.getFormat().equals(getFormat())));
}
@Override
public boolean equals(Object otherObject) {
try {
IniSectionHead other = (IniSectionHead) otherObject;
return ((other.getName().equalsIgnoreCase(getName())) && (other.getFormat().equals(getFormat())));
} catch (ClassCastException e) {
return false;
}
}
@Override
public int compareTo(IniSectionHead other) {
if (this.equals(other)) {
return 0;
} else {
return (this.getName().compareTo(other.getName()));
}
}
@Override
public int hashCode() {
int hash = 5;
hash = 43 * hash + (this.name != null ? this.name.hashCode() : 0);
hash = 43 * hash + (this.format != null ? this.format.hashCode() : 0);
return hash;
}
private String name;
private IniDataFormat format;
}
public static class IniData {
public IniData(IniDataFormat format) {
this.format = format;
}
public IniData(IniDataFormat format, String value) {
this.format = format;
this.value = value;
}
public IniData(IniDataFormat format, String key, String value) {
this.format = format;
this.key = key;
this.value = value;
}
public IniDataFormat getFormat() {
return format;
}
public String getKey() {
return key;
}
public String getValue() {
return value;
}
public boolean equals(IniData other) {
if (!other.getFormat().equals(getFormat())) {
return false;
}
if (!other.getKey().equals(getKey())) {
return false;
}
return (other.getValue().equals(getValue()));
}
private IniDataFormat format;
private String key = null;
private String value;
}
public enum IniDataFormat {
KEY_VALUE,
VALUE;
}
}
|
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.beam.runners.core;
import static com.google.common.base.Preconditions.checkArgument;
import com.google.auto.service.AutoService;
import com.google.common.collect.Collections2;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.Multimap;
import com.google.protobuf.ByteString;
import com.google.protobuf.BytesValue;
import com.google.protobuf.InvalidProtocolBufferException;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Supplier;
import org.apache.beam.fn.harness.data.BeamFnDataClient;
import org.apache.beam.fn.harness.fn.ThrowingConsumer;
import org.apache.beam.fn.harness.fn.ThrowingRunnable;
import org.apache.beam.runners.core.construction.ParDoTranslation;
import org.apache.beam.runners.dataflow.util.DoFnInfo;
import org.apache.beam.sdk.common.runner.v1.RunnerApi;
import org.apache.beam.sdk.options.PipelineOptions;
import org.apache.beam.sdk.state.State;
import org.apache.beam.sdk.state.TimeDomain;
import org.apache.beam.sdk.state.Timer;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.DoFn.OnTimerContext;
import org.apache.beam.sdk.transforms.DoFn.ProcessContext;
import org.apache.beam.sdk.transforms.reflect.DoFnInvoker;
import org.apache.beam.sdk.transforms.reflect.DoFnInvokers;
import org.apache.beam.sdk.transforms.splittabledofn.RestrictionTracker;
import org.apache.beam.sdk.transforms.windowing.BoundedWindow;
import org.apache.beam.sdk.transforms.windowing.PaneInfo;
import org.apache.beam.sdk.util.SerializableUtils;
import org.apache.beam.sdk.util.UserCodeException;
import org.apache.beam.sdk.util.WindowedValue;
import org.apache.beam.sdk.values.PCollectionView;
import org.apache.beam.sdk.values.TupleTag;
import org.apache.beam.sdk.values.WindowingStrategy;
import org.joda.time.Instant;
/**
* A {@link DoFnRunner} specific to integrating with the Fn Api. This is to remove the layers
* of abstraction caused by StateInternals/TimerInternals since they model state and timer
* concepts differently.
*/
public class FnApiDoFnRunner<InputT, OutputT> implements DoFnRunner<InputT, OutputT> {
/**
* A registrar which provides a factory to handle Java {@link DoFn}s.
*/
@AutoService(PTransformRunnerFactory.Registrar.class)
public static class Registrar implements
PTransformRunnerFactory.Registrar {
@Override
public Map<String, PTransformRunnerFactory> getPTransformRunnerFactories() {
return ImmutableMap.of(ParDoTranslation.CUSTOM_JAVA_DO_FN_URN, new Factory());
}
}
/** A factory for {@link FnApiDoFnRunner}. */
static class Factory<InputT, OutputT>
implements PTransformRunnerFactory<DoFnRunner<InputT, OutputT>> {
@Override
public DoFnRunner<InputT, OutputT> createRunnerForPTransform(
PipelineOptions pipelineOptions,
BeamFnDataClient beamFnDataClient,
String pTransformId,
RunnerApi.PTransform pTransform,
Supplier<String> processBundleInstructionId,
Map<String, RunnerApi.PCollection> pCollections,
Map<String, RunnerApi.Coder> coders,
Multimap<String, ThrowingConsumer<WindowedValue<?>>> pCollectionIdsToConsumers,
Consumer<ThrowingRunnable> addStartFunction,
Consumer<ThrowingRunnable> addFinishFunction) {
// For every output PCollection, create a map from output name to Consumer
ImmutableMap.Builder<String, Collection<ThrowingConsumer<WindowedValue<?>>>>
outputMapBuilder = ImmutableMap.builder();
for (Map.Entry<String, String> entry : pTransform.getOutputsMap().entrySet()) {
outputMapBuilder.put(
entry.getKey(),
pCollectionIdsToConsumers.get(entry.getValue()));
}
ImmutableMap<String, Collection<ThrowingConsumer<WindowedValue<?>>>> outputMap =
outputMapBuilder.build();
// Get the DoFnInfo from the serialized blob.
ByteString serializedFn;
try {
serializedFn = pTransform.getSpec().getParameter().unpack(BytesValue.class).getValue();
} catch (InvalidProtocolBufferException e) {
throw new IllegalArgumentException(
String.format("Unable to unwrap DoFn %s", pTransform.getSpec()), e);
}
@SuppressWarnings({"unchecked", "rawtypes"})
DoFnInfo<InputT, OutputT> doFnInfo = (DoFnInfo) SerializableUtils.deserializeFromByteArray(
serializedFn.toByteArray(), "DoFnInfo");
// Verify that the DoFnInfo tag to output map matches the output map on the PTransform.
checkArgument(
Objects.equals(
new HashSet<>(Collections2.transform(outputMap.keySet(), Long::parseLong)),
doFnInfo.getOutputMap().keySet()),
"Unexpected mismatch between transform output map %s and DoFnInfo output map %s.",
outputMap.keySet(),
doFnInfo.getOutputMap());
ImmutableMultimap.Builder<TupleTag<?>,
ThrowingConsumer<WindowedValue<?>>> tagToOutputMapBuilder =
ImmutableMultimap.builder();
for (Map.Entry<Long, TupleTag<?>> entry : doFnInfo.getOutputMap().entrySet()) {
@SuppressWarnings({"unchecked", "rawtypes"})
Collection<ThrowingConsumer<WindowedValue<?>>> consumers =
outputMap.get(Long.toString(entry.getKey()));
tagToOutputMapBuilder.putAll(entry.getValue(), consumers);
}
ImmutableMultimap<TupleTag<?>, ThrowingConsumer<WindowedValue<?>>> tagToOutputMap =
tagToOutputMapBuilder.build();
@SuppressWarnings({"unchecked", "rawtypes"})
DoFnRunner<InputT, OutputT> runner = new FnApiDoFnRunner<>(
pipelineOptions,
doFnInfo.getDoFn(),
(Collection<ThrowingConsumer<WindowedValue<OutputT>>>) (Collection)
tagToOutputMap.get(doFnInfo.getOutputMap().get(doFnInfo.getMainOutput())),
tagToOutputMap,
doFnInfo.getWindowingStrategy());
// Register the appropriate handlers.
addStartFunction.accept(runner::startBundle);
for (String pcollectionId : pTransform.getInputsMap().values()) {
pCollectionIdsToConsumers.put(
pcollectionId,
(ThrowingConsumer) (ThrowingConsumer<WindowedValue<InputT>>) runner::processElement);
}
addFinishFunction.accept(runner::finishBundle);
return runner;
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////
private final PipelineOptions pipelineOptions;
private final DoFn<InputT, OutputT> doFn;
private final Collection<ThrowingConsumer<WindowedValue<OutputT>>> mainOutputConsumers;
private final Multimap<TupleTag<?>, ThrowingConsumer<WindowedValue<?>>> outputMap;
private final DoFnInvoker<InputT, OutputT> doFnInvoker;
private final StartBundleContext startBundleContext;
private final ProcessBundleContext processBundleContext;
private final FinishBundleContext finishBundleContext;
/**
* The lifetime of this member is only valid during {@link #processElement(WindowedValue)}.
*/
private WindowedValue<InputT> currentElement;
/**
* The lifetime of this member is only valid during {@link #processElement(WindowedValue)}.
*/
private BoundedWindow currentWindow;
FnApiDoFnRunner(
PipelineOptions pipelineOptions,
DoFn<InputT, OutputT> doFn,
Collection<ThrowingConsumer<WindowedValue<OutputT>>> mainOutputConsumers,
Multimap<TupleTag<?>, ThrowingConsumer<WindowedValue<?>>> outputMap,
WindowingStrategy windowingStrategy) {
this.pipelineOptions = pipelineOptions;
this.doFn = doFn;
this.mainOutputConsumers = mainOutputConsumers;
this.outputMap = outputMap;
this.doFnInvoker = DoFnInvokers.invokerFor(doFn);
this.startBundleContext = new StartBundleContext();
this.processBundleContext = new ProcessBundleContext();
this.finishBundleContext = new FinishBundleContext();
}
@Override
public void startBundle() {
doFnInvoker.invokeStartBundle(startBundleContext);
}
@Override
public void processElement(WindowedValue<InputT> elem) {
currentElement = elem;
try {
Iterator<BoundedWindow> windowIterator =
(Iterator<BoundedWindow>) elem.getWindows().iterator();
while (windowIterator.hasNext()) {
currentWindow = windowIterator.next();
doFnInvoker.invokeProcessElement(processBundleContext);
}
} finally {
currentElement = null;
currentWindow = null;
}
}
@Override
public void onTimer(
String timerId,
BoundedWindow window,
Instant timestamp,
TimeDomain timeDomain) {
throw new UnsupportedOperationException("TODO: Add support for timers");
}
@Override
public void finishBundle() {
doFnInvoker.invokeFinishBundle(finishBundleContext);
}
/**
* Outputs the given element to the specified set of consumers wrapping any exceptions.
*/
private <T> void outputTo(
Collection<ThrowingConsumer<WindowedValue<T>>> consumers,
WindowedValue<T> output) {
Iterator<ThrowingConsumer<WindowedValue<T>>> consumerIterator;
try {
for (ThrowingConsumer<WindowedValue<T>> consumer : consumers) {
consumer.accept(output);
}
} catch (Throwable t) {
throw UserCodeException.wrap(t);
}
}
/**
* Provides arguments for a {@link DoFnInvoker} for {@link DoFn.StartBundle @StartBundle}.
*/
private class StartBundleContext
extends DoFn<InputT, OutputT>.StartBundleContext
implements DoFnInvoker.ArgumentProvider<InputT, OutputT> {
private StartBundleContext() {
doFn.super();
}
@Override
public PipelineOptions getPipelineOptions() {
return pipelineOptions;
}
@Override
public PipelineOptions pipelineOptions() {
return pipelineOptions;
}
@Override
public BoundedWindow window() {
throw new UnsupportedOperationException(
"Cannot access window outside of @ProcessElement and @OnTimer methods.");
}
@Override
public DoFn<InputT, OutputT>.StartBundleContext startBundleContext(
DoFn<InputT, OutputT> doFn) {
return this;
}
@Override
public DoFn<InputT, OutputT>.FinishBundleContext finishBundleContext(
DoFn<InputT, OutputT> doFn) {
throw new UnsupportedOperationException(
"Cannot access FinishBundleContext outside of @FinishBundle method.");
}
@Override
public DoFn<InputT, OutputT>.ProcessContext processContext(DoFn<InputT, OutputT> doFn) {
throw new UnsupportedOperationException(
"Cannot access ProcessContext outside of @ProcessElement method.");
}
@Override
public DoFn<InputT, OutputT>.OnTimerContext onTimerContext(DoFn<InputT, OutputT> doFn) {
throw new UnsupportedOperationException(
"Cannot access OnTimerContext outside of @OnTimer methods.");
}
@Override
public RestrictionTracker<?> restrictionTracker() {
throw new UnsupportedOperationException(
"Cannot access RestrictionTracker outside of @ProcessElement method.");
}
@Override
public State state(String stateId) {
throw new UnsupportedOperationException(
"Cannot access state outside of @ProcessElement and @OnTimer methods.");
}
@Override
public Timer timer(String timerId) {
throw new UnsupportedOperationException(
"Cannot access timers outside of @ProcessElement and @OnTimer methods.");
}
}
/**
* Provides arguments for a {@link DoFnInvoker} for {@link DoFn.ProcessElement @ProcessElement}.
*/
private class ProcessBundleContext
extends DoFn<InputT, OutputT>.ProcessContext
implements DoFnInvoker.ArgumentProvider<InputT, OutputT> {
private ProcessBundleContext() {
doFn.super();
}
@Override
public BoundedWindow window() {
return currentWindow;
}
@Override
public DoFn.StartBundleContext startBundleContext(DoFn<InputT, OutputT> doFn) {
throw new UnsupportedOperationException(
"Cannot access StartBundleContext outside of @StartBundle method.");
}
@Override
public DoFn.FinishBundleContext finishBundleContext(DoFn<InputT, OutputT> doFn) {
throw new UnsupportedOperationException(
"Cannot access FinishBundleContext outside of @FinishBundle method.");
}
@Override
public ProcessContext processContext(DoFn<InputT, OutputT> doFn) {
return this;
}
@Override
public OnTimerContext onTimerContext(DoFn<InputT, OutputT> doFn) {
throw new UnsupportedOperationException("TODO: Add support for timers");
}
@Override
public RestrictionTracker<?> restrictionTracker() {
throw new UnsupportedOperationException("TODO: Add support for SplittableDoFn");
}
@Override
public State state(String stateId) {
throw new UnsupportedOperationException("TODO: Add support for state");
}
@Override
public Timer timer(String timerId) {
throw new UnsupportedOperationException("TODO: Add support for timers");
}
@Override
public PipelineOptions getPipelineOptions() {
return pipelineOptions;
}
@Override
public PipelineOptions pipelineOptions() {
return pipelineOptions;
}
@Override
public void output(OutputT output) {
outputTo(mainOutputConsumers,
WindowedValue.of(
output,
currentElement.getTimestamp(),
currentWindow,
currentElement.getPane()));
}
@Override
public void outputWithTimestamp(OutputT output, Instant timestamp) {
outputTo(mainOutputConsumers,
WindowedValue.of(
output,
timestamp,
currentWindow,
currentElement.getPane()));
}
@Override
public <T> void output(TupleTag<T> tag, T output) {
Collection<ThrowingConsumer<WindowedValue<T>>> consumers = (Collection) outputMap.get(tag);
if (consumers == null) {
throw new IllegalArgumentException(String.format("Unknown output tag %s", tag));
}
outputTo(consumers,
WindowedValue.of(
output,
currentElement.getTimestamp(),
currentWindow,
currentElement.getPane()));
}
@Override
public <T> void outputWithTimestamp(TupleTag<T> tag, T output, Instant timestamp) {
Collection<ThrowingConsumer<WindowedValue<T>>> consumers = (Collection) outputMap.get(tag);
if (consumers == null) {
throw new IllegalArgumentException(String.format("Unknown output tag %s", tag));
}
outputTo(consumers,
WindowedValue.of(
output,
timestamp,
currentWindow,
currentElement.getPane()));
}
@Override
public InputT element() {
return currentElement.getValue();
}
@Override
public <T> T sideInput(PCollectionView<T> view) {
throw new UnsupportedOperationException("TODO: Support side inputs");
}
@Override
public Instant timestamp() {
return currentElement.getTimestamp();
}
@Override
public PaneInfo pane() {
return currentElement.getPane();
}
@Override
public void updateWatermark(Instant watermark) {
throw new UnsupportedOperationException("TODO: Add support for SplittableDoFn");
}
}
/**
* Provides arguments for a {@link DoFnInvoker} for {@link DoFn.FinishBundle @FinishBundle}.
*/
private class FinishBundleContext
extends DoFn<InputT, OutputT>.FinishBundleContext
implements DoFnInvoker.ArgumentProvider<InputT, OutputT> {
private FinishBundleContext() {
doFn.super();
}
@Override
public PipelineOptions getPipelineOptions() {
return pipelineOptions;
}
@Override
public PipelineOptions pipelineOptions() {
return pipelineOptions;
}
@Override
public BoundedWindow window() {
throw new UnsupportedOperationException(
"Cannot access window outside of @ProcessElement and @OnTimer methods.");
}
@Override
public DoFn<InputT, OutputT>.StartBundleContext startBundleContext(
DoFn<InputT, OutputT> doFn) {
throw new UnsupportedOperationException(
"Cannot access StartBundleContext outside of @StartBundle method.");
}
@Override
public DoFn<InputT, OutputT>.FinishBundleContext finishBundleContext(
DoFn<InputT, OutputT> doFn) {
return this;
}
@Override
public DoFn<InputT, OutputT>.ProcessContext processContext(DoFn<InputT, OutputT> doFn) {
throw new UnsupportedOperationException(
"Cannot access ProcessContext outside of @ProcessElement method.");
}
@Override
public DoFn<InputT, OutputT>.OnTimerContext onTimerContext(DoFn<InputT, OutputT> doFn) {
throw new UnsupportedOperationException(
"Cannot access OnTimerContext outside of @OnTimer methods.");
}
@Override
public RestrictionTracker<?> restrictionTracker() {
throw new UnsupportedOperationException(
"Cannot access RestrictionTracker outside of @ProcessElement method.");
}
@Override
public State state(String stateId) {
throw new UnsupportedOperationException(
"Cannot access state outside of @ProcessElement and @OnTimer methods.");
}
@Override
public Timer timer(String timerId) {
throw new UnsupportedOperationException(
"Cannot access timers outside of @ProcessElement and @OnTimer methods.");
}
@Override
public void output(OutputT output, Instant timestamp, BoundedWindow window) {
outputTo(mainOutputConsumers,
WindowedValue.of(output, timestamp, window, PaneInfo.NO_FIRING));
}
@Override
public <T> void output(TupleTag<T> tag, T output, Instant timestamp, BoundedWindow window) {
Collection<ThrowingConsumer<WindowedValue<T>>> consumers = (Collection) outputMap.get(tag);
if (consumers == null) {
throw new IllegalArgumentException(String.format("Unknown output tag %s", tag));
}
outputTo(consumers,
WindowedValue.of(output, timestamp, window, PaneInfo.NO_FIRING));
}
}
}
|
|
/*
* Copyright (C) 2009 Klaus Reimer <[email protected]>
* See LICENSE.txt file for licensing information.
*/
package de.ailis.gramath;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertThat;
import org.junit.Test;
/**
* Tests the ImmutableVector2f class.
*
* @author Klaus Reimer ([email protected])
*/
public class ImmutableVector2fTest
{
/**
* Tests the value constructor.
*/
@Test
public void testValueConstructor()
{
final Vector2f v = new ImmutableVector2f(1, 2);
assertEquals(1, v.x, 0.001f);
assertEquals(2, v.y, 0.001f);
}
/**
* Tests the constructor with a Point2d argument.
*/
@Test
public void testPoint2dConstructor()
{
final Vector2f v = new ImmutableVector2f(new MutablePoint2d(3, 2));
assertEquals(3, v.x, 0.001f);
assertEquals(2, v.y, 0.001f);
}
/**
* Tests the constructor with a Point2f argument.
*/
@Test
public void testPoint2fConstructor()
{
final Vector2f v = new ImmutableVector2f(new MutablePoint2f(3, 2));
assertEquals(3, v.x, 0.001f);
assertEquals(2, v.y, 0.001f);
}
/**
* Tests the constructor with a Point3d argument.
*/
@Test
public void testPoint3dConstructor()
{
final Vector2f v = new ImmutableVector2f(new MutablePoint3d(3, 2, 1));
assertEquals(3, v.x, 0.001f);
assertEquals(2, v.y, 0.001f);
}
/**
* Tests the constructor with a Point3f argument.
*/
@Test
public void testPoint3fConstructor()
{
final Vector2f v = new ImmutableVector2f(new MutablePoint3f(3, 2, 1));
assertEquals(3, v.x, 0.001f);
assertEquals(2, v.y, 0.001f);
}
/**
* Tests the constructor with a Vector2d argument.
*/
@Test
public void testVector2dConstructor()
{
final Vector2f v = new ImmutableVector2f(new MutableVector2d(3, 2));
assertEquals(3, v.x, 0.001f);
assertEquals(2, v.y, 0.001f);
}
/**
* Tests the constructor with a Vector2f argument.
*/
@Test
public void testVector2fConstructor()
{
final Vector2f v = new ImmutableVector2f(new MutableVector2f(3, 2));
assertEquals(3, v.x, 0.001f);
assertEquals(2, v.y, 0.001f);
}
/**
* Tests the constructor with a Vector3f argument.
*/
@Test
public void testVector3fConstructor()
{
final Vector2f v = new ImmutableVector2f(new MutableVector3f(3, 2, 1));
assertEquals(3, v.x, 0.001f);
assertEquals(2, v.y, 0.001f);
}
/**
* Tests the constructor with a Vector3d argument.
*/
@Test
public void testVector3dConstructor()
{
final Vector2f v = new ImmutableVector2f(new MutableVector3d(3, 2, 1));
assertEquals(3, v.x, 0.001f);
assertEquals(2, v.y, 0.001f);
}
/**
* Tests access to the vector components
*/
@Test
public void testToString()
{
assertEquals("[ 1.0, 2.0 ]", new ImmutableVector2f(1, 2).toString());
}
/**
* Tests the dot product of two Vectors.
*/
@Test
public void testDot()
{
assertEquals(1 * 2 + 2 * 3, new ImmutableVector2f(1, 2)
.dot(new ImmutableVector2f(2, 3)), 0.01);
}
/**
* Tests calculating the vector length.
*/
@Test
public void testLength()
{
assertEquals(Math.sqrt(1 + 2 * 2), new ImmutableVector2f(
1, 2).getLength(), 0.001f);
assertEquals(0, new ImmutableVector2f(0, 0).getLength(), 0.001f);
assertEquals(1, new ImmutableVector2f(-1, 0).getLength(), 0.001f);
}
/**
* Tests conversion to the unit vector.
*/
@Test
public void testGetNormalization()
{
assertEquals(new ImmutableVector2f(1, 0), new ImmutableVector2f(123,
0).getNormalization());
assertEquals(new ImmutableVector2f(0, 1), new ImmutableVector2f(0,
234).getNormalization());
assertEquals(new ImmutableVector2f(-1, 0), new ImmutableVector2f(
-123, 0).getNormalization());
assertEquals(new ImmutableVector2f(0, -1), new ImmutableVector2f(0,
-234).getNormalization());
assertEquals(new ImmutableVector2f(0, 0), new ImmutableVector2f(0,
0).getNormalization());
}
/**
* Tests calculating the angle between two vectors
*/
@Test
public void testAngle()
{
assertEquals(Math.toRadians(45), new ImmutableVector2f(0, 123)
.angle(new ImmutableVector2f(50, 50)), 0.01);
assertEquals(Math.toRadians(45), new ImmutableVector2f(1, 1)
.angle(new ImmutableVector2f(0, 1)), 0.01);
}
/**
* Tests the clone method.
*/
@Test
public void testClone()
{
final ImmutableVector2f v = new ImmutableVector2f(1, 2);
final ImmutableVector2f v2 = v.clone();
assertNotSame(v, v2);
assertEquals(v, v2);
}
/**
* Tests the newInstance method.
*/
@Test
public void testNewInstance()
{
final ImmutableVector2f v = new ImmutableVector2f(1, 2);
final ImmutableVector2f v2 = v.newInstance();
assertNotSame(v, v2);
assertThat(v, not(equalTo(v2)));
}
}
|
|
/*
* 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.geode.distributed.internal;
import static org.apache.geode.test.awaitility.GeodeAwaitility.await;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.apache.geode.CancelCriterion;
import org.apache.geode.distributed.internal.locks.ElderState;
import org.apache.geode.distributed.internal.membership.InternalDistributedMember;
import org.apache.geode.distributed.internal.membership.MembershipManager;
import org.apache.geode.test.junit.rules.ConcurrencyRule;
public class ClusterElderManagerTest {
private MembershipManager memberManager;
private CancelCriterion systemCancelCriterion;
private InternalDistributedSystem system;
private CancelCriterion cancelCriterion;
private ClusterDistributionManager clusterDistributionManager;
private InternalDistributedMember member0;
private final InternalDistributedMember member1 = mock(InternalDistributedMember.class);
private final InternalDistributedMember member2 = mock(InternalDistributedMember.class);
@Rule
public ConcurrencyRule concurrencyRule = new ConcurrencyRule();
@Before
public void before() {
member0 = mock(InternalDistributedMember.class);
clusterDistributionManager = mock(ClusterDistributionManager.class);
cancelCriterion = mock(CancelCriterion.class);
system = mock(InternalDistributedSystem.class);
systemCancelCriterion = mock(CancelCriterion.class);
memberManager = mock(MembershipManager.class);
when(clusterDistributionManager.getCancelCriterion()).thenReturn(cancelCriterion);
when(clusterDistributionManager.getSystem()).thenReturn(system);
when(system.getCancelCriterion()).thenReturn(systemCancelCriterion);
when(clusterDistributionManager.getMembershipManager()).thenReturn(memberManager);
}
@Test
public void getElderIdReturnsOldestMember() {
ClusterElderManager clusterElderManager = new ClusterElderManager(clusterDistributionManager);
when(clusterDistributionManager.getViewMembers()).thenReturn(Arrays.asList(member1, member2));
assertThat(clusterElderManager.getElderId()).isEqualTo(member1);
}
@Test
public void getElderIdWithNoMembers() {
ClusterElderManager clusterElderManager = new ClusterElderManager(clusterDistributionManager);
when(clusterDistributionManager.getViewMembers()).thenReturn(Arrays.asList());
assertThat(clusterElderManager.getElderId()).isNull();
}
@Test
public void getElderIdIgnoresAdminMembers() {
ClusterElderManager clusterElderManager = new ClusterElderManager(clusterDistributionManager);
when(member1.getVmKind()).thenReturn(ClusterDistributionManager.ADMIN_ONLY_DM_TYPE);
when(clusterDistributionManager.getViewMembers()).thenReturn(Arrays.asList(member1, member2));
assertThat(clusterElderManager.getElderId()).isEqualTo(member2);
}
@Test
public void getElderIdIgnoresSurpriseMembers() {
ClusterElderManager clusterElderManager = new ClusterElderManager(clusterDistributionManager);
when(memberManager.isSurpriseMember(eq(member1))).thenReturn(true);
when(clusterDistributionManager.getViewMembers()).thenReturn(Arrays.asList(member1, member2));
assertThat(clusterElderManager.getElderId()).isEqualTo(member2);
}
@Test
public void isElderIfOldestMember() {
ClusterElderManager clusterElderManager = new ClusterElderManager(clusterDistributionManager);
when(clusterDistributionManager.getViewMembers()).thenReturn(Arrays.asList(member0, member1));
when(clusterDistributionManager.getId()).thenReturn(member0);
assertThat(clusterElderManager.isElder()).isTrue();
}
@Test
public void isNotElderIfOldestMember() {
ClusterElderManager clusterElderManager = new ClusterElderManager(clusterDistributionManager);
when(clusterDistributionManager.getViewMembers()).thenReturn(Arrays.asList(member1, member0));
when(clusterDistributionManager.getId()).thenReturn(member0);
assertThat(clusterElderManager.isElder()).isFalse();
}
@Test
public void waitForElderReturnsTrueIfAnotherMemberIsElder() {
ClusterElderManager clusterElderManager = new ClusterElderManager(clusterDistributionManager);
when(clusterDistributionManager.getId()).thenReturn(member0);
when(clusterDistributionManager.getViewMembers()).thenReturn(Arrays.asList(member1, member0));
assertThat(clusterElderManager.waitForElder(member1)).isTrue();
}
@Test
public void waitForElderReturnsFalseIfWeAreElder() {
ClusterElderManager clusterElderManager = new ClusterElderManager(clusterDistributionManager);
when(clusterDistributionManager.getId()).thenReturn(member0);
when(clusterDistributionManager.isCurrentMember(eq(member1))).thenReturn(true);
when(clusterDistributionManager.getViewMembers()).thenReturn(Arrays.asList(member0, member1));
assertThat(clusterElderManager.waitForElder(member1)).isFalse();
}
@Test
public void waitForElderReturnsFalseIfDesiredElderIsNotACurrentMember() {
ClusterElderManager clusterElderManager = new ClusterElderManager(clusterDistributionManager);
when(clusterDistributionManager.getId()).thenReturn(member0);
when(clusterDistributionManager.getViewMembers())
.thenReturn(Arrays.asList(member2, member0, member1));
assertThat(clusterElderManager.waitForElder(member1)).isFalse();
}
@Test
public void waitForElderWaits() {
ClusterElderManager clusterElderManager = new ClusterElderManager(clusterDistributionManager);
when(clusterDistributionManager.getId()).thenReturn(member0);
when(clusterDistributionManager.getViewMembers()).thenReturn(Arrays.asList(member1, member0));
when(clusterDistributionManager.isCurrentMember(eq(member0))).thenReturn(true);
assertThatRunnableWaits(() -> clusterElderManager.waitForElder(member0));
}
@Test
public void waitForElderStopsWaitingWhenUpdated() {
ClusterElderManager clusterElderManager = new ClusterElderManager(clusterDistributionManager);
when(clusterDistributionManager.getId()).thenReturn(member0);
when(clusterDistributionManager.isCurrentMember(eq(member0))).thenReturn(true);
AtomicReference<List<InternalDistributedMember>> currentMembers =
new AtomicReference<>(Arrays.asList(member1, member0));
when(clusterDistributionManager.getViewMembers()).then(invocation -> currentMembers.get());
AtomicReference<MembershipListener> membershipListener = new AtomicReference<>();
doAnswer(invocation -> {
membershipListener.set(invocation.getArgument(0));
return null;
}).when(clusterDistributionManager).addMembershipListener(any());
Callable<Boolean> waitForElder = () -> clusterElderManager.waitForElder(member0);
Callable<Void> updateMembershipView = () -> {
// Wait for membership listener to be added
await().until(() -> membershipListener.get() != null);
currentMembers.set(Arrays.asList(member0));
membershipListener.get().memberDeparted(clusterDistributionManager, member1, true);
return null;
};
concurrencyRule.add(waitForElder).expectValue(true);
concurrencyRule.add(updateMembershipView);
concurrencyRule.executeInParallel();
assertThat(clusterElderManager.getElderId()).isEqualTo(member0);
}
@Test
public void getElderStateAsElder() {
Supplier<ElderState> elderStateSupplier = mock(Supplier.class);
ElderState elderState = mock(ElderState.class);
when(elderStateSupplier.get()).thenReturn(elderState);
ClusterElderManager clusterElderManager =
new ClusterElderManager(clusterDistributionManager, elderStateSupplier);
when(clusterDistributionManager.getId()).thenReturn(member0);
when(clusterDistributionManager.getViewMembers()).thenReturn(Arrays.asList(member0, member1));
assertThat(clusterElderManager.getElderState(false)).isEqualTo(elderState);
verify(elderStateSupplier, times(1)).get();
}
@Test
public void getElderStateGetsBuiltOnceAsElder() {
Supplier<ElderState> elderStateSupplier = mock(Supplier.class);
ElderState elderState = mock(ElderState.class);
when(elderStateSupplier.get()).thenReturn(elderState);
ClusterElderManager clusterElderManager =
new ClusterElderManager(clusterDistributionManager, elderStateSupplier);
when(clusterDistributionManager.getId()).thenReturn(member0);
when(clusterDistributionManager.getViewMembers()).thenReturn(Arrays.asList(member0, member1));
assertThat(clusterElderManager.getElderState(false)).isEqualTo(elderState);
assertThat(clusterElderManager.getElderState(false)).isEqualTo(elderState);
// Make sure that we only create the elder state once
verify(elderStateSupplier, times(1)).get();
}
@Test
public void getElderStateFromMultipleThreadsAsElder() {
Supplier<ElderState> elderStateSupplier = mock(Supplier.class);
ElderState elderState = mock(ElderState.class);
when(elderStateSupplier.get()).thenReturn(elderState);
ClusterElderManager clusterElderManager =
new ClusterElderManager(clusterDistributionManager, elderStateSupplier);
when(clusterDistributionManager.getId()).thenReturn(member0);
when(clusterDistributionManager.getViewMembers()).thenReturn(Arrays.asList(member0, member1));
Callable<ElderState> callable = () -> clusterElderManager.getElderState(false);
concurrencyRule.add(callable).expectValue(elderState);
concurrencyRule.add(callable).expectValue(elderState);
concurrencyRule.executeInParallel();
// Make sure that we only create the elder state once
verify(elderStateSupplier, times(1)).get();
}
@Test
public void getElderStateNotAsElder() {
Supplier<ElderState> elderStateSupplier = mock(Supplier.class);
ClusterElderManager clusterElderManager =
new ClusterElderManager(clusterDistributionManager, elderStateSupplier);
when(clusterDistributionManager.getId()).thenReturn(member0);
when(clusterDistributionManager.getViewMembers()).thenReturn(Arrays.asList(member1, member0));
assertThat(clusterElderManager.getElderState(false)).isEqualTo(null);
verify(elderStateSupplier, times(0)).get();
}
@Test
public void getElderStateWaitsToBecomeElder() {
Supplier<ElderState> elderStateSupplier = mock(Supplier.class);
ClusterElderManager clusterElderManager =
new ClusterElderManager(clusterDistributionManager, elderStateSupplier);
when(clusterDistributionManager.getId()).thenReturn(member0);
when(clusterDistributionManager.getViewMembers()).thenReturn(Arrays.asList(member1, member0));
when(clusterDistributionManager.isCurrentMember(eq(member0))).thenReturn(true);
assertThatRunnableWaits(() -> clusterElderManager.getElderState(true));
verify(elderStateSupplier, times(0)).get();
}
private void assertThatRunnableWaits(Runnable runnable) {
Thread waitThread = new Thread(runnable);
waitThread.start();
EnumSet<Thread.State> waitingStates =
EnumSet.of(Thread.State.WAITING, Thread.State.TIMED_WAITING);
try {
await()
.until(() -> waitingStates.contains(waitThread.getState()));
} finally {
waitThread.interrupt();
}
}
}
|
|
// Copyright 2016 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.analysis.util;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.devtools.build.lib.analysis.ConfiguredTarget;
import com.google.devtools.build.lib.analysis.config.BuildConfigurationValue;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.testutil.Scratch;
import java.io.IOException;
import java.util.Arrays;
/**
* A writer for a scratch build target and associated source files. Can be parameterized with a rule
* type for which to write a mock target.
*
* <p>For example, the snippet:
*
* <pre>{@code
* new ScratchAttributeWriter(testCase, "cc_library", "//x:x")
* .setList("srcs", "a.cc", "b.cc")
* .setList("hdrs", "hdr.h")
* .write();
* }</pre>
*
* <p>Would create the BUILD file "x/BUILD" with contents:
*
* <pre>{@code
* cc_library(
* name = 'x',
* srcs = ['a.cc', 'b.cc'],
* hdrs = ['hdr.h'],
* )
* }</pre>
*/
public class ScratchAttributeWriter {
private abstract static class ScratchAttribute<T> {
protected String attributeName;
protected T attributeValue;
abstract StringBuilder appendLine(StringBuilder builder);
}
/** A plain string attribute. */
private static class StringAttribute extends ScratchAttribute<String> {
public StringAttribute(String attributeName, String attributeValue) {
this.attributeName = attributeName;
this.attributeValue = attributeValue;
}
@Override
StringBuilder appendLine(StringBuilder builder) {
return builder.append(String.format("%s=%s,", attributeName, attributeValue));
}
}
/** An integer attribute, such as "alwayslink" */
private static class IntegerAttribute extends ScratchAttribute<Integer> {
public IntegerAttribute(String attributeName, Integer attributeValue) {
this.attributeName = attributeName;
this.attributeValue = attributeValue;
}
@Override
StringBuilder appendLine(StringBuilder builder) {
return builder.append(String.format("%s=%d,", attributeName, attributeValue));
}
}
/** A list attribute, such as "srcs" */
private static class StringListAttribute extends ScratchAttribute<Iterable<String>> {
public StringListAttribute(String attributeName, Iterable<String> attributeValue) {
this.attributeName = attributeName;
this.attributeValue = attributeValue;
}
@Override
StringBuilder appendLine(StringBuilder builder) {
builder.append(String.format("%s=[", attributeName));
for (String value : attributeValue) {
builder.append(String.format("'%s',", value));
}
builder.append("],");
return builder;
}
}
/** The name of the package. */
private final String packageName;
/** The name of the target. */
private final String targetName;
/** The test case for which to write this target. */
private final BuildViewTestCase testCase;
/** The name of the rule for this target */
private final String ruleName;
/** An ordered list of the attributes to be written for this scratch target */
StringBuilder buildString;
/**
* Creates a ScratchAttributeWriter for a given test case, package name, and target name. The
* provided rule name will determine the type of the target written.
*/
private ScratchAttributeWriter(
BuildViewTestCase testCase, String ruleName, String packageName, String targetName) {
this.testCase = checkNotNull(testCase);
this.ruleName = checkNotNull(ruleName);
this.packageName = checkNotNull(packageName);
this.targetName = checkNotNull(targetName);
this.buildString =
new StringBuilder()
.append(String.format("%s(", this.ruleName))
.append(String.format("name='%s',", this.targetName));
}
/**
* Creates a ScratchAttributeWriter for a given test case and label. The provided rule name will
* determine the type of the target written.
*/
public static ScratchAttributeWriter fromLabel(
BuildViewTestCase testCase, String ruleName, Label label) {
return new ScratchAttributeWriter(testCase, ruleName, label.getPackageName(), label.getName());
}
/**
* Creates a ScratchAttributeWriter for a given test case and label string. The provided rule name
* will determine the type of the target written.
*/
public static ScratchAttributeWriter fromLabelString(
BuildViewTestCase testCase, String ruleName, String labelString) {
return fromLabel(testCase, ruleName, Label.parseAbsoluteUnchecked(labelString));
}
/**
* Writes this scratch target to this ScratchAttributeWriter's Scratch instance, and returns the
* target in the given configuration.
*/
public ConfiguredTarget write(BuildConfigurationValue config) throws Exception {
Scratch scratch = testCase.getScratch();
buildString.append(")");
scratch.file(String.format("%s/BUILD", packageName), buildString.toString());
return testCase.getConfiguredTarget(String.format("//%s:%s", packageName, targetName), config);
}
/**
* Writes this scratch target to this ScratchAttributeWriter's Scratch instance, and returns the
* target in the target configuration.
*/
public ConfiguredTarget write() throws Exception {
return write(testCase.getTargetConfiguration());
}
private void createSource(String source) throws IOException {
testCase.getScratch().file(String.format("%s/%s", packageName, source));
}
/** Sets a string attribute (like ios_application.app_icon) for this target. */
public ScratchAttributeWriter set(String name, String value) {
new StringAttribute(name, value).appendLine(this.buildString);
return this;
}
/** Sets an integer attribute (like cc_binary.linkstatic) for this target. */
public ScratchAttributeWriter set(String name, int value) {
new IntegerAttribute(name, value).appendLine(this.buildString);
return this;
}
/** Sets a list attribute (like cc_library.srcs) for this target. */
public ScratchAttributeWriter setList(String name, Iterable<String> value) {
new StringListAttribute(name, value).appendLine(this.buildString);
return this;
}
/** Sets a list attribute (like cc_library.srcs) for this target */
public ScratchAttributeWriter setList(String name, String... value) {
return setList(name, Arrays.asList(value));
}
/**
* Sets a list attribute (link cc_library.srcs) for this target. For each string in 'value',
* writes an empty file to this writer's package with that name.
*
* <p>Usually, an analysis-time should not require that referenced files actually be written, in
* which case ScratchAttributeWriter#set should be used instead.
*/
public ScratchAttributeWriter setAndCreateFiles(String name, Iterable<String> value)
throws IOException {
for (String source : value) {
createSource(source);
}
return setList(name, value);
}
/**
* Sets a list attribute (link cc_library.srcs) for this target. For each string in 'value',
* writes an empty file to this writer's package with that name.
*
* <p>Usually, an analysis-time should not require that referenced files actually be written, in
* which case ScratchAttributeWriter#set should be used instead.
*/
public ScratchAttributeWriter setAndCreateFiles(String name, String... value) throws IOException {
return setAndCreateFiles(name, Arrays.asList(value));
}
}
|
|
package agersant.polaris.features.queue;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import java.util.Random;
import agersant.polaris.PlaybackQueue;
import agersant.polaris.PolarisApplication;
import agersant.polaris.PolarisPlayer;
import agersant.polaris.PolarisState;
import agersant.polaris.R;
import agersant.polaris.api.local.OfflineCache;
import agersant.polaris.api.remote.DownloadQueue;
import agersant.polaris.databinding.FragmentQueueBinding;
import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
public class QueueFragment extends Fragment {
private QueueAdapter adapter;
private BroadcastReceiver receiver;
private View tutorial;
private RecyclerView recyclerView;
private Toolbar toolbar;
private PlaybackQueue playbackQueue;
private PolarisPlayer player;
private OfflineCache offlineCache;
private DownloadQueue downloadQueue;
private Boolean initialCreation = true;
private void subscribeToEvents() {
IntentFilter filter = new IntentFilter();
filter.addAction(PlaybackQueue.REMOVED_ITEM);
filter.addAction(PlaybackQueue.REMOVED_ITEMS);
filter.addAction(PlaybackQueue.QUEUED_ITEMS);
filter.addAction(PolarisPlayer.OPENING_TRACK);
filter.addAction(PolarisPlayer.PLAYING_TRACK);
filter.addAction(OfflineCache.AUDIO_CACHED);
filter.addAction(DownloadQueue.WORKLOAD_CHANGED);
filter.addAction(OfflineCache.AUDIO_REMOVED_FROM_CACHE);
receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent == null || intent.getAction() == null) {
return;
}
switch (intent.getAction()) {
case PlaybackQueue.REMOVED_ITEM:
case PlaybackQueue.REMOVED_ITEMS:
updateTutorial();
break;
case PlaybackQueue.QUEUED_ITEMS:
case PlaybackQueue.OVERWROTE_QUEUE:
adapter.notifyDataSetChanged();
updateTutorial();
break;
case PolarisPlayer.OPENING_TRACK:
case PolarisPlayer.PLAYING_TRACK:
case OfflineCache.AUDIO_CACHED:
case OfflineCache.AUDIO_REMOVED_FROM_CACHE:
case DownloadQueue.WORKLOAD_CHANGED:
adapter.notifyItemRangeChanged(0, adapter.getItemCount());
break;
}
}
};
requireActivity().registerReceiver(receiver, filter);
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
setHasOptionsMenu(true);
PolarisState state = PolarisApplication.getState();
playbackQueue = state.playbackQueue;
player = state.player;
offlineCache = state.offlineCache;
downloadQueue = state.downloadQueue;
FragmentQueueBinding binding = FragmentQueueBinding.inflate(inflater);
recyclerView = binding.queueRecyclerView;
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(requireContext()));
DefaultItemAnimator animator = new DefaultItemAnimator() {
@Override
public boolean animateRemove(RecyclerView.ViewHolder holder) {
holder.itemView.setAlpha(0.f);
return false;
}
@Override
public boolean canReuseUpdatedViewHolder(@NonNull RecyclerView.ViewHolder viewHolder) {
return true;
}
};
recyclerView.setItemAnimator(animator);
tutorial = binding.queueTutorial;
toolbar = requireActivity().findViewById(R.id.toolbar);
populate();
updateTutorial();
return binding.getRoot();
}
private void updateTutorial() {
boolean empty = adapter.getItemCount() == 0;
if (empty) {
tutorial.setVisibility(View.VISIBLE);
} else {
tutorial.setVisibility(View.GONE);
}
}
@Override
public void onStart() {
super.onStart();
subscribeToEvents();
updateTutorial();
if (!initialCreation) {
adapter.notifyDataSetChanged();
} else {
initialCreation = false;
}
}
@Override
public void onStop() {
super.onStop();
requireActivity().unregisterReceiver(receiver);
receiver = null;
}
@Override
public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
inflater.inflate(R.menu.queue, menu);
updateOrderingIcon();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_clear:
clear();
return true;
case R.id.action_shuffle:
shuffle();
return true;
case R.id.action_ordering_sequence:
case R.id.action_ordering_repeat_one:
case R.id.action_ordering_repeat_all:
setOrdering(item);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void populate() {
adapter = new QueueAdapter(playbackQueue, player, offlineCache, downloadQueue);
ItemTouchHelper.Callback callback = new QueueTouchCallback(adapter);
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(callback);
itemTouchHelper.attachToRecyclerView(recyclerView);
recyclerView.setAdapter(adapter);
}
private void clear() {
int oldCount = adapter.getItemCount();
playbackQueue.clear();
adapter.notifyItemRangeRemoved(0, oldCount);
}
private void shuffle() {
Random rng = new Random();
int count = adapter.getItemCount();
for (int i = 0; i <= count - 2; i++) {
int j = i + rng.nextInt(count - i);
playbackQueue.move(i, j);
adapter.notifyItemMoved(i, j);
}
}
private void setOrdering(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_ordering_sequence:
playbackQueue.setOrdering(PlaybackQueue.Ordering.SEQUENCE);
break;
case R.id.action_ordering_repeat_one:
playbackQueue.setOrdering(PlaybackQueue.Ordering.REPEAT_ONE);
break;
case R.id.action_ordering_repeat_all:
playbackQueue.setOrdering(PlaybackQueue.Ordering.REPEAT_ALL);
break;
}
updateOrderingIcon();
}
private int getIconForOrdering(PlaybackQueue.Ordering ordering) {
switch (ordering) {
case REPEAT_ONE:
return R.drawable.ic_repeat_one_24;
case REPEAT_ALL:
return R.drawable.ic_repeat_24;
case SEQUENCE:
default:
return R.drawable.ic_reorder_24;
}
}
private void updateOrderingIcon() {
int icon = getIconForOrdering(playbackQueue.getOrdering());
MenuItem orderingItem = toolbar.getMenu().findItem(R.id.action_ordering);
if (orderingItem != null) {
orderingItem.setIcon(icon);
}
}
}
|
|
/**
*
* Copyright 2017 Florian Erhard
*
* 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 gedi.diskintervaltree;
import gedi.core.reference.ReferenceSequence;
import gedi.core.region.GenomicRegion;
import gedi.core.region.GenomicRegionStorage;
import gedi.util.datastructure.collections.intcollections.IntArrayList;
import gedi.util.datastructure.collections.longcollections.LongArrayList;
import gedi.util.datastructure.tree.redblacktree.Interval;
import gedi.util.datastructure.tree.redblacktree.IntervalComparator;
import gedi.util.datastructure.tree.redblacktree.IntervalTree;
import gedi.util.io.randomaccess.BinaryReader;
import gedi.util.io.randomaccess.BinaryWriter;
import gedi.util.io.randomaccess.PageFile;
import gedi.util.io.randomaccess.PageFileWriter;
import gedi.util.io.randomaccess.serialization.BinarySerializable;
import java.io.File;
import java.io.IOException;
import java.util.AbstractCollection;
import java.util.AbstractSet;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.NavigableSet;
import java.util.NoSuchElementException;
import java.util.SortedSet;
import java.util.Spliterators;
import java.util.Stack;
import java.util.function.BiFunction;
import java.util.function.BinaryOperator;
public class DiskIntervalTree<T extends BinarySerializable> extends AbstractSet<GenomicRegion> implements NavigableSet<GenomicRegion>, Interval {
/**
* The number of entries in the tree
*/
private int size = 0;
private String info;
private static final int OFFSET_min = 0;
private static final int OFFSET_max = 4;
private static final int OFFSET_start = 8;
private static final int OFFSET_stop = 12;
private static final int OFFSET_parent = 16;
private static final int OFFSET_mask = 24;
private static final int OFFSET_children = 25;
private static final int SIZE_ptr = 8;
private static class BinIndex implements BinarySerializable {
private int binsize;
private int min;
private int max;
private long[] offsets; // deepest node that fully contains the given bin
public void set(int binsize, int min, int max) {
this.binsize = binsize;
this.min = min;
this.max = max;
this.offsets = new long[(int)Math.ceil((max-min)/(double)binsize)];
}
@Override
public void serialize(BinaryWriter out) throws IOException {
out.putInt(binsize);
out.putInt(min);
out.putInt(max);
for (int i=0; i<offsets.length; i++)
out.putLong(offsets[i]);
}
@Override
public void deserialize(BinaryReader in) throws IOException {
set(in.getInt(),in.getInt(),in.getInt());
for (int i=0; i<offsets.length; i++)
offsets[i] = in.getLong();
}
public int getBin(int start, int stop) {
int a = getBin(start);
int b = getBin(stop);
return a==b?a:-1;
}
public int getBin(int index) {
int re = (index-min)/binsize;
if (re>offsets.length) return -1;
return re;
}
public long getOffset(int index) {
int re = (index-min)/binsize;
if (re>offsets.length) return -1;
return offsets[re];
}
}
public static <T extends BinarySerializable> void create(String info,
GenomicRegionStorage<?> storage, ReferenceSequence reference, BiFunction<ReferenceSequence,GenomicRegion,T> datagetter, long size,
String path, Class<T> cls, BinaryOperator<? super T> aggregator, int...binsizes) throws IOException {
if (size>Integer.MAX_VALUE) throw new RuntimeException();
int s = (int) size;
int[] min = new int[s];
int[] max = new int[s];
Object[] agg = new Object[s];
// build tree structure data in memory
Stack<int[]> stack = new Stack<int[]>();
stack.add(new int[] {0,s,-1});// left, right, parentindex
int root = s/2;
int[] parent = new int[s];
while (!stack.isEmpty()) {
int[] in = stack.pop();
int m = (in[0]+in[1])/2;
parent[m] = in[2];
if (m-in[0]>0) stack.push(new int[] {in[0],m,m});
if (in[1]-m-1>0) stack.push(new int[] {m+1,in[1],m});
}
int[] left = new int[s];
int[] right = new int[s];
Arrays.fill(left, -1);
Arrays.fill(right, -1);
for (int i=0; i<parent.length; i++) {
if (parent[i]==-1) continue;
if (parent[i]<i) right[parent[i]]=i;
else left[parent[i]]=i;
}
// determine min/max/agg
Iterator<? extends GenomicRegion> it = Spliterators.iterator(storage.iterateGenomicRegions(reference));
int di=0;
while (it.hasNext()) {
GenomicRegion d = it.next();
min[di] = d.getStart();
max[di] = d.getStop();
agg[di] = datagetter.apply(reference, d);
di++;
}
IntArrayList dfs = new IntArrayList();
dfs.add(-root-1);
while (!dfs.isEmpty()) {
int n = dfs.removeLast();
if (n<0) { // walking down
n = -n-1;
dfs.add(n);
if (left[n]>-1) dfs.add(-left[n]-1);
if (left[n]>-1) dfs.add(-right[n]-1);
}
else { // walking up
int l = left[n];
int r = right[n];
min[n] = Math.min(min[n],Math.min(l>-1?min[l]:min[n],r>-1?min[r]:min[n]));
max[n] = Math.max(max[n],Math.max(l>-1?max[l]:max[n],r>-1?max[r]:max[n]));
min[n] = Math.min(min[n],Math.min(l>-1?min[l]:min[n],r>-1?min[r]:min[n]));
if (l>-1)
agg[n] = aggregator.apply((T)agg[n],(T)agg[l]);
if (r>-1)
agg[n] = aggregator.apply((T)agg[n],(T)agg[r]);
}
}
File file = new File(path);
file.getParentFile().mkdirs();
PageFileWriter out = new PageFileWriter(path);
// Header
out.putInt(info.length());
out.putChars(info);
out.putInt(s);
out.putInt(cls.getName().length());
out.putChars(cls.getName());
long rootOffsetOffset = out.position();
out.putLong(-1L); // root offset
// Bin indices
out.putInt(binsizes.length);
long binOffset = out.position();
BinIndex[] binInd = new BinIndex[binsizes.length];
for (int i=0; i<binInd.length; i++) {
binInd[i] = new BinIndex();
binInd[i].set(binsizes[i], min[root], max[root]);
binInd[i].serialize(out);
}
// tree
long treeOffset = out.position();
long[] offsets = new long[s];
it = Spliterators.iterator(storage.iterateGenomicRegions(reference));
di=0;
while (it.hasNext()) {
GenomicRegion d = it.next();
offsets[di] = out.position();
int l = left[di];
int r = right[di];
int p = parent[di];
out.putInt(min[di]);
out.putInt(max[di]);
out.putInt(d.getStart());
out.putInt(d.getStop());
out.putLong(-1);
int mask = set(SPLICE,set(LEFT,set(RIGHT,set(DATA,set(AGGREGATED,0,datagetter.apply(reference, d)!=agg[di]),datagetter.apply(reference, d)!=null),r!=-1),l!=-1),!d.isSingleton());
out.putByte(mask);
if (l!=-1) out.putLong(-1);
if (r!=-1) out.putLong(-1);
if (!d.isSingleton()) {
out.putInt(d.getNumParts());
for (int c=1; c<d.getNumBoundaries()-1; c++)
out.putInt(d.getBoundary(c));
}
T da = datagetter.apply(reference, d);
if (da!=null) da.serialize(out);
if (da!=agg[di]) ((T)agg[di]).serialize(out);
di++;
}
out.position(rootOffsetOffset);
out.putLong(offsets[root]);
out.position(treeOffset);
for (di=0; di<s; di++){
out.position(offsets[di]+OFFSET_parent);
int l = left[di];
int r = right[di];
int p = parent[di];
// System.out.printf("%d/%d %d -> %d\n",di,data.size(),p==-1?-1:offsets[p],out.getFilePointer());
out.putLong(p==-1?-1:offsets[p]);
out.relativePosition(1);
if (l!=-1) out.putLong(offsets[l]);
if (r!=-1) out.putLong(offsets[r]);
}
// Bin indices
out.position(binOffset);
for (int i=0; i<binInd.length; i++) {
Arrays.fill(binInd[i].offsets,-1);
dfs.clear();
dfs.add(root);
while (!dfs.isEmpty()) {
int n = dfs.removeLast();
int bin = binInd[i].getBin(min[n],max[n]);
if (bin!=-1)
binInd[i].offsets[bin] = offsets[n];
else {
if (left[n]>-1) dfs.add(left[n]);
if (right[n]>-1) dfs.add(right[n]);
}
}
binInd[i].serialize(out);
}
out.close();
}
private static final int LEFT = 0;
private static final int RIGHT = 1;
private static final int SPLICE = 2;
private static final int DATA = 3;
private static final int AGGREGATED = 4;
private static boolean has(int pos, int mask) {
return (mask>>pos & 1) ==1;
}
private static int set(int pos, int mask, boolean val) {
if (val) return mask | 1<<pos;
else return mask & ~(1<<pos);
}
private long parent(long offset) throws IOException {
file.position(offset+OFFSET_parent);
return file.getLong();
}
private long left(long offset) throws IOException {
file.position(offset+OFFSET_mask);
int mask = file.getByte();
if (!has(LEFT,mask)) return -1;
return file.getLong();
}
private long right(long offset) throws IOException {
file.position(offset+OFFSET_mask);
int mask = file.getByte();
if (!has(RIGHT,mask)) return -1;
if (has(LEFT,mask)) file.relativePosition(SIZE_ptr);
return file.getLong();
}
private int readMin(long index) throws IOException {
file.position(index+OFFSET_min);
return file.getInt();
}
private int readMax(long index) throws IOException {
file.position(index+OFFSET_max);
return file.getInt();
}
private int readStart(long index) throws IOException {
file.position(index+OFFSET_start);
return file.getInt();
}
private int readStop(long index) throws IOException {
file.position(index+OFFSET_stop);
return file.getInt();
}
private DiskIntervalGenomicRegion<T> readRecord(long index) throws IOException {
file.position(index+4+4);
int start = file.getInt();
int stop = file.getInt();
file.relativePosition(SIZE_ptr); // parent ptr
int mask = file.getByte();
if (has(LEFT,mask))
file.relativePosition(SIZE_ptr);
if (has(RIGHT,mask))
file.relativePosition(SIZE_ptr);
int[] coord = null;
if (has(SPLICE,mask)) {
coord = new int[file.getInt()*2];
coord[0] = start;
coord[coord.length-1] = stop+1;
for (int i=1; i<coord.length-1; i++)
coord[i] = file.getInt();
}
T data = null;
if (has(DATA,mask)) {
try {
data = cls.newInstance();
} catch (Exception e) {
throw new RuntimeException("Could not instantiate interval class!",e);
}
data.deserialize(file);
}
if (has(AGGREGATED,mask)) {
try {
T agg= cls.newInstance();
agg.deserialize(file);
} catch (Exception e) {
throw new RuntimeException("Could not instantiate interval class!",e);
}
}
return coord==null?new DiskIntervalGenomicRegion<T>(start, stop+1, data):new DiskIntervalGenomicRegion<T>(coord, data);
}
private DiskIntervalGenomicRegion<T> readAggregatedRecord(long index) throws IOException {
file.position(index);
int start = file.getInt();
int stop = file.getInt();
file.relativePosition(4+4+SIZE_ptr); // start, stop, parent ptr
int mask = file.getByte();
if (has(LEFT,mask))
file.relativePosition(SIZE_ptr);
if (has(RIGHT,mask))
file.relativePosition(SIZE_ptr);
if (has(SPLICE,mask)) {
int size = file.getInt()*2;
file.relativePosition(4*(size-2));
}
T data = null;
if (has(DATA,mask)) {
try {
data = cls.newInstance();
} catch (Exception e) {
throw new RuntimeException("Could not instantiate interval class!",e);
}
data.deserialize(file);
}
if (has(AGGREGATED,mask)) {
try {
data = cls.newInstance();
data.deserialize(file);
} catch (Exception e) {
throw new RuntimeException("Could not instantiate interval class!",e);
}
}
return new DiskIntervalGenomicRegion<T>(start, stop+1, data);
}
private PageFile file;
private BinIndex[] binIndices;
private Class<T> cls;
public Class<T> getType() {
return cls;
}
private long root;
public DiskIntervalTree(String path) throws IOException, ClassNotFoundException {
file=new PageFile(path);
char[] str = new char[file.getInt()];
for (int i=0; i<str.length; i++)
str[i] = file.getChar();
this.info = new String(str);
size = file.getInt();
str = new char[file.getInt()];
for (int i=0; i<str.length; i++)
str[i] = file.getChar();
cls = (Class<T>) Class.forName(new String(str));
root = file.getLong();
binIndices = new BinIndex[file.getInt()];
for (int i=0; i<binIndices.length; i++) {
binIndices[i] = new BinIndex();
binIndices[i].deserialize(file);
}
}
public Collection<DiskIntervalGenomicRegion<T>> getIntervals() {
return new DiskOrderingCollection();
}
private class DiskOrderingCollection extends AbstractCollection<DiskIntervalGenomicRegion<T>> {
@Override
public Iterator<DiskIntervalGenomicRegion<T>> iterator() {
return new DiskOrderingIterator();
}
@Override
public int size() {
return size;
}
}
private class DiskOrderingIterator implements Iterator<DiskIntervalGenomicRegion<T>> {
private long expectedOffset;
private long length;
public DiskOrderingIterator() {
try {
expectedOffset = getFirstOffset();
file.position(expectedOffset);
length = file.size();
} catch (IOException e) {
throw new RuntimeException("Cannot iterate!",e);
}
}
@Override
public boolean hasNext() {
checkConcurrentOperation();
return expectedOffset<length;
}
@Override
public DiskIntervalGenomicRegion<T> next() {
try {
checkConcurrentOperation();
DiskIntervalGenomicRegion<T> rec = readRecord(expectedOffset);
expectedOffset = file.position();
return rec;
} catch (IOException e) {
throw new RuntimeException("Cannot iterate!",e);
}
}
private void checkConcurrentOperation() {
if (file.position()!=expectedOffset)
throw new ConcurrentModificationException();
}
@Override
public void remove() {
}
}
public void close() throws IOException {
file.close();
}
public String getInfo() {
return info;
}
public void checkIntegrity() throws IOException {
long length = file.size();
file.position(getFirstOffset());
int entry = 0;
while (file.position()<length) {
long offset = file.position();
DiskIntervalGenomicRegion<T> rec = readRecord(offset);
System.out.printf("Entry %d\t%s",entry++,rec);
long nextoffset = file.position();
if (left(offset)==-1)
System.out.printf("\t-");
else if (parent(left(offset))!=offset)
System.out.printf("\tleft parent pointer wrong (%d != %d; %d) ",parent(left(offset)), offset, left(offset));
else
System.out.printf("\tok");
if (right(offset)==-1)
System.out.printf("\t-");
else if (parent(right(offset))!=offset)
System.out.printf("\tright parent pointer wrong (%d != %d; %d) ",parent(right(offset)), offset, right(offset));
else
System.out.printf("\tok");
file.position(nextoffset);
System.out.println();
}
}
private long getFirstOffset() throws IOException {
long p = root;
if (p != -1)
while (left(p) != -1) {
p = left(p);
}
return p;
}
private long getLastOffset() throws IOException {
long p = root;
if (p != -1)
while (right(p) != -1) {
p = right(p);
}
return p;
}
private long getOffset(GenomicRegion k) throws IOException {
long p = root;
while (p != -1) {
int cmp = compareOffsets(k, p);
if (cmp < 0)
p = left(p);
else if (cmp > 0)
p = right(p);
else
return p;
}
return -1;
}
private long getLowerOffset(GenomicRegion k) throws IOException {
long p = root;
while (p != -1) {
int cmp = compareOffsets(k, p);
if (cmp > 0) {
long r = right(p);
if (r != -1)
p = r;
else
return p;
} else {
long l = left(p);
if (l != -1) {
p = l;
} else {
long parent = parent(p);
long ch = p;
while (parent != -1 && ch == left(parent)) {
ch = parent;
parent = parent(parent);
}
return parent;
}
}
}
return -1;
}
private long getHigherOffset(GenomicRegion k) throws IOException {
long p = root;
while (p != -1) {
int cmp = compareOffsets(k, p);
if (cmp < 0) {
long l = left(p);
if (l != -1)
p = l;
else
return p;
} else {
long r = right(p);
if (r != -1) {
p = r;
} else {
long parent = parent(p);
long ch = p;
while (parent != -1 && ch == right(parent)) {
ch = parent;
parent = parent(parent);
}
return parent;
}
}
}
return -1;
}
private long getCeilingOffset(GenomicRegion k) throws IOException {
long p = root;
while (p != -1) {
int cmp = compareOffsets(k, p);
if (cmp < 0) {
long l = left(p);
if (l != -1)
p = l;
else
return p;
} else if (cmp > 0){
long r = right(p);
if (r != -1) {
p = r;
} else {
long parent = parent(p);
long ch = p;
while (parent != -1 && ch == right(parent)) {
ch = parent;
parent = parent(parent);
}
return parent;
}
} else return p;
}
return -1;
}
private long getFloorOffset(GenomicRegion k) throws IOException {
long p = root;
while (p != -1) {
int cmp = compareOffsets(k, p);
if (cmp > 0) {
long r = right(p);
if (r != -1)
p = r;
else
return p;
} else if (cmp < 0) {
long l = left(p);
if (l != -1) {
p = l;
} else {
long parent = parent(p);
long ch = p;
while (parent != -1 && ch == left(parent)) {
ch = parent;
parent = parent(parent);
}
return parent;
}
}else
return p;
}
return -1;
}
private int compareOffsets(GenomicRegion o1, long o2) throws IOException {
int re = o1.getStart()-readStart(o2);
if (re==0)
re = o1.getStop()-readStop(o2);
if (re==0) {
GenomicRegion i1 = o1;
DiskIntervalGenomicRegion<T> i2 = readRecord(o2);
re = i1.compareTo(i2);
}
return re;
}
private int compareOffsets(long o1, long o2) throws IOException {
if (o1==o2)
return 0;
int re = readStart(o1)-readStart(o2);
if (re==0)
re = readStop(o1)-readStop(o2);
if (re==0) {
DiskIntervalGenomicRegion<T> i1 = readRecord(o1);
DiskIntervalGenomicRegion<T> i2 = readRecord(o2);
re = i1.compareTo(i2);
}
return re;
}
/**
* Returns the successor of the specified Entry, or null if no such.
* @throws IOException
*/
private long successorOffset(long t) throws IOException {
if (t == -1)
return -1;
else if (right(t) != -1) {
long p = right(t);
while (left(p) != -1)
p = left(p);
return p;
} else {
long p = parent(t);
long ch = t;
while (p != -1 && ch == right(p)) {
ch = p;
p = parent(p);
}
return p;
}
}
/**
* Returns the predecessor of the specified Entry, or null if no such.
* @throws IOException
*/
private long predecessorOffset(long t) throws IOException {
if (t == -1)
return -1;
else if (left(t) != -1) {
long p = left(t);
while (right(p) != -1)
p = right(p);
return p;
} else {
long p = parent(t);
long ch = t;
while (p != -1 && ch == left(p)) {
ch = p;
p = parent(p);
}
return p;
}
}
@Override
public String toString() {
return info+" ("+size+")";
}
public Comparator<? super GenomicRegion> comparator() {
return new IntervalComparator();
}
@Override
public DiskIntervalGenomicRegion<T> first() {
try {
return readRecord(getFirstOffset());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public DiskIntervalGenomicRegion<T> last() {
try {
return readRecord(getLastOffset());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public int size() {
return size;
}
@Override
public boolean isEmpty() {
return size==0;
}
@Override
public boolean contains(Object o) {
if (!(o instanceof GenomicRegion)) return false;
try {
return getOffset((GenomicRegion) o)!=-1;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public DiskIntervalGenomicRegion<T> get(Object o) {
if (!(o instanceof GenomicRegion)) return null;
if (o instanceof DiskIntervalGenomicRegion)
return ((DiskIntervalGenomicRegion<T>)o);
try {
long offset = getOffset((GenomicRegion) o);
if (offset==-1) return null;
return readRecord(offset);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public boolean add(GenomicRegion e) {
throw new RuntimeException("Not implemented!");
}
@Override
public boolean remove(Object o) {
throw new RuntimeException("Not implemented!");
}
@Override
public boolean addAll(Collection<? extends GenomicRegion> c) {
throw new RuntimeException("Not implemented!");
}
@Override
public boolean retainAll(Collection<?> c) {
throw new RuntimeException("Not implemented!");
}
@Override
public boolean removeAll(Collection<?> c) {
throw new RuntimeException("Not implemented!");
}
@Override
public void clear() {
throw new RuntimeException("Not implemented!");
}
@Override
public DiskIntervalGenomicRegion<T> lower(GenomicRegion e) {
try {
return readRecord(getLowerOffset(e));
} catch (IOException e1) {
throw new RuntimeException(e1);
}
}
@Override
public DiskIntervalGenomicRegion<T> floor(GenomicRegion e) {
try {
return readRecord(getFloorOffset(e));
} catch (IOException e1) {
throw new RuntimeException(e1);
}
}
@Override
public DiskIntervalGenomicRegion<T> ceiling(GenomicRegion e) {
try {
return readRecord(getCeilingOffset(e));
} catch (IOException e1) {
throw new RuntimeException(e1);
}
}
@Override
public DiskIntervalGenomicRegion<T> higher(GenomicRegion e) {
try {
return readRecord(getHigherOffset(e));
} catch (IOException e1) {
throw new RuntimeException(e1);
}
}
@Override
public DiskIntervalGenomicRegion<T> pollFirst() {
throw new RuntimeException("Not implemented!");
}
@Override
public DiskIntervalGenomicRegion<T> pollLast() {
throw new RuntimeException("Not implemented!");
}
@Override
public Iterator<GenomicRegion> iterator() {
try {
return new AscendingIterator(getFirstOffset());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Base class for TreeMap Iterators
*/
private abstract class DiskIntervalIterator implements Iterator<GenomicRegion> {
long next;
long lastReturned;
DiskIntervalIterator(long first) {
lastReturned = -1;
next = first;
}
public final boolean hasNext() {
return next != -1;
}
final long nextOffset() throws IOException {
long e = next;
if (e == -1)
throw new NoSuchElementException();
next = successorOffset(e);
lastReturned = e;
return e;
}
final long prevOffset() throws IOException {
long e = next;
if (e == -1)
throw new NoSuchElementException();
next = predecessorOffset(e);
lastReturned = e;
return e;
}
public void remove() {
throw new RuntimeException("Not implemented!");
}
}
private class AscendingIterator extends DiskIntervalIterator {
AscendingIterator(long first) {
super(first);
}
public DiskIntervalGenomicRegion<T> next() {
try {
return readRecord(nextOffset());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
final class DescendingIterator extends DiskIntervalIterator {
DescendingIterator(long first) {
super(first);
}
public DiskIntervalGenomicRegion<T> next() {
try {
return readRecord(prevOffset());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
@Override
public NavigableSet<GenomicRegion> descendingSet() {
throw new RuntimeException("Not implemented!");
}
@Override
public Iterator<GenomicRegion> descendingIterator() {
try {
return new DescendingIterator(getLastOffset());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public NavigableSet<GenomicRegion> subSet(
GenomicRegion fromElement, boolean fromInclusive,
GenomicRegion toElement, boolean toInclusive) {
throw new RuntimeException("Not implemented!");
}
@Override
public NavigableSet<GenomicRegion> headSet(
GenomicRegion toElement, boolean inclusive) {
throw new RuntimeException("Not implemented!");
}
@Override
public NavigableSet<GenomicRegion> tailSet(
GenomicRegion fromElement, boolean inclusive) {
throw new RuntimeException("Not implemented!");
}
@Override
public SortedSet<GenomicRegion> subSet(GenomicRegion fromElement,
GenomicRegion toElement) {
throw new RuntimeException("Not implemented!");
}
@Override
public SortedSet<GenomicRegion> headSet(GenomicRegion toElement) {
throw new RuntimeException("Not implemented!");
}
@Override
public SortedSet<GenomicRegion> tailSet(GenomicRegion fromElement) {
throw new RuntimeException("Not implemented!");
}
public <C extends Collection<? super DiskIntervalGenomicRegion<T>>> C getIntervalsIntersecting(int start, int stop, C re) {
LongArrayList stack = new LongArrayList();
// for (BinIndex bin : binIndices)
// if (bin.getBin(start, stop)!=-1) {
// stack.add(bin.getOffset(start));
// break;
// }
if (root!=-1 && stack.isEmpty())
stack.add(root);
try{
while (!stack.isEmpty()) {
long n = stack.removeLast();
if (start<=readMax(n)) {
int a = readStart(n);
int b = readStop(n);
if (a<=stop && b>=start)
addChecked(re,start, stop, readRecord(n));
if (left(n)!= -1)
stack.add(left(n));
if (stop>=a && right(n) != -1)
stack.add(right(n));
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return re;
}
public <C extends Collection<? super DiskIntervalGenomicRegion<T>>> C getIntervalsIntersecting(GenomicRegion reg, C re) {
LongArrayList stack = new LongArrayList();
// for (BinIndex bin : binIndices)
// if (bin.getBin(start, stop)!=-1) {
// stack.add(bin.getOffset(start));
// break;
// }
if (root!=-1 && stack.isEmpty())
stack.add(root);
int start = reg.getStart();
int stop = reg.getStop();
try{
while (!stack.isEmpty()) {
long n = stack.removeLast();
if (start<=readMax(n)) {
int a = readStart(n);
int b = readStop(n);
if (a<=stop && b>=start)
addChecked(re,reg, readRecord(n));
if (left(n)!= -1)
stack.add(left(n));
if (stop>=a && right(n) != -1)
stack.add(right(n));
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return re;
}
private <C extends Collection<? super DiskIntervalGenomicRegion<T>>> void addChecked(C coll, int start, int stop, DiskIntervalGenomicRegion<T> co) {
if (co.intersects(start, stop+1))
coll.add(co);
}
private <C extends Collection<? super DiskIntervalGenomicRegion<T>>> void addChecked(C coll, GenomicRegion reg, DiskIntervalGenomicRegion<T> co) {
if (co.intersects(reg))
coll.add(co);
}
public <C extends Collection<? super DiskIntervalGenomicRegion<T>>> C getIntervalsIntersecting(int start, int stop, int resolution, C re) {
LongArrayList stack = new LongArrayList();
//
// for (BinIndex bin : binIndices)
// if (bin.getBin(start, stop)!=-1) {
// stack.add(bin.getOffset(start));
// break;
// }
if (root!=-1 && stack.isEmpty())
stack.add(root);
try{
while (!stack.isEmpty()) {
long n = stack.removeLast();
if (start<=readMax(n)) {
int a = readStart(n);
int b = readStop(n);
if (a<=stop && b>=start) {
int min = readMin(n);
int max = readMax(n);
if (max-min<resolution){
addChecked(re,start, stop, readAggregatedRecord(n));
continue;
}
re.add(readRecord(n));
}
if (left(n)!= -1)
stack.add(left(n));
if (stop>=a && right(n) != -1)
stack.add(right(n));
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return re;
}
@Override
public int getStart() {
return first().getStart();
}
@Override
public int getStop() {
try {
return readMax(root);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Iterates over overlapping groups of intervals
* @return
*/
public Iterator<IntervalTree<DiskIntervalGenomicRegion<T>,T>> groupIterator() {
return groupIterator(0);
}
/**
* Iterates over overlapping groups of intervals; overlap with a tolerance means that two intervals overlap as long as their distance is smaller or equal to the given distance
* @return
*/
public Iterator<IntervalTree<DiskIntervalGenomicRegion<T>,T>> groupIterator(int tolerance) {
return new GroupIterator(tolerance);
}
private class GroupIterator implements Iterator<IntervalTree<DiskIntervalGenomicRegion<T>,T>> {
private AscendingIterator it;
private DiskIntervalGenomicRegion<T> first;
private long firstOffset;
private int intervalMax;
private IntervalTree<DiskIntervalGenomicRegion<T>,T> next;
private int tolerance;
public GroupIterator(int tolerance) {
this.tolerance = tolerance;
try {
it = new AscendingIterator(getFirstOffset());
} catch (IOException e) {
throw new RuntimeException(e);
}
first = it.hasNext()?it.next():null;
firstOffset = it.lastReturned;
intervalMax = first!=null?first.getStop():-1;
}
@Override
public boolean hasNext() {
lookAhead();
return next!=null;
}
@Override
public IntervalTree<DiskIntervalGenomicRegion<T>,T> next() {
lookAhead();
IntervalTree<DiskIntervalGenomicRegion<T>,T> re = next;
next = null;
return re;
}
private void lookAhead() {
if (next==null && first!=null) {
while (it.hasNext()) {
DiskIntervalGenomicRegion<T> current = it.next();
if (intervalMax+tolerance<current.getStart() && !wouldNotSplit(intervalMax,current.getStart())) {// new group
next = new IntervalTree<DiskIntervalGenomicRegion<T>,T>(null);
AscendingIterator cit = new AscendingIterator(firstOffset);
while (cit.hasNext()) {
DiskIntervalGenomicRegion<T> n = cit.next();
if (it.lastReturned==cit.lastReturned) break;
next.add(n);
}
first = current;
firstOffset = it.lastReturned;
intervalMax = Math.max(current.getStop(), intervalMax);
return;
}
intervalMax = Math.max(current.getStop(), intervalMax);
}
next = new IntervalTree<DiskIntervalGenomicRegion<T>,T>(null);
AscendingIterator cit = new AscendingIterator(firstOffset);
while (cit.hasNext()) {
DiskIntervalGenomicRegion<T> n = cit.next();
next.add(n);
}
first = null;
}
}
private boolean wouldNotSplit(int start, int stop) {
return false;
}
@Override
public void remove() {}
}
}
|
|
/*
* 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.physical.impl;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.apache.drill.common.expression.ExpressionPosition;
import org.apache.drill.common.expression.SchemaPath;
import org.apache.drill.common.util.DrillFileUtils;
import org.apache.drill.exec.client.DrillClient;
import org.apache.drill.exec.expr.fn.FunctionImplementationRegistry;
import org.apache.drill.exec.expr.fn.impl.StringFunctionHelpers;
import org.apache.drill.exec.expr.holders.BigIntHolder;
import org.apache.drill.exec.expr.holders.Float4Holder;
import org.apache.drill.exec.expr.holders.Float8Holder;
import org.apache.drill.exec.expr.holders.IntHolder;
import org.apache.drill.exec.expr.holders.VarBinaryHolder;
import org.apache.drill.exec.expr.holders.VarCharHolder;
import org.apache.drill.exec.ops.FragmentContextImpl;
import org.apache.drill.exec.physical.PhysicalPlan;
import org.apache.drill.exec.physical.base.FragmentRoot;
import org.apache.drill.exec.planner.PhysicalPlanReader;
import org.apache.drill.exec.planner.PhysicalPlanReaderTestFactory;
import org.apache.drill.exec.pop.PopUnitTestBase;
import org.apache.drill.exec.proto.BitControl.PlanFragment;
import org.apache.drill.exec.record.RecordBatchLoader;
import org.apache.drill.exec.record.VectorAccessible;
import org.apache.drill.exec.record.VectorWrapper;
import org.apache.drill.exec.rpc.user.QueryDataBatch;
import org.apache.drill.exec.rpc.UserClientConnection;
import org.apache.drill.exec.server.Drillbit;
import org.apache.drill.exec.server.DrillbitContext;
import org.apache.drill.exec.server.RemoteServiceSet;
import org.apache.drill.exec.vector.BigIntVector;
import org.apache.drill.exec.vector.Float4Vector;
import org.apache.drill.exec.vector.Float8Vector;
import org.apache.drill.exec.vector.IntVector;
import org.apache.drill.exec.vector.VarBinaryVector;
import org.apache.drill.exec.vector.VarCharVector;
import org.junit.Test;
import org.apache.drill.shaded.guava.com.google.common.base.Charsets;
import org.apache.drill.shaded.guava.com.google.common.io.Files;
import org.mockito.Mockito;
public class TestCastFunctions extends PopUnitTestBase {
@Test
// cast to bigint.
public void testCastBigInt() throws Throwable {
final DrillbitContext bitContext = mockDrillbitContext();
final UserClientConnection connection = Mockito.mock(UserClientConnection.class);
final PhysicalPlanReader reader = PhysicalPlanReaderTestFactory.defaultPhysicalPlanReader(CONFIG);
final PhysicalPlan plan = reader.readPhysicalPlan(Files.asCharSource(DrillFileUtils.getResourceAsFile("/functions/cast/testCastBigInt.json"), Charsets.UTF_8).read());
final FunctionImplementationRegistry registry = new FunctionImplementationRegistry(CONFIG);
final FragmentContextImpl context = new FragmentContextImpl(bitContext, PlanFragment.getDefaultInstance(), connection, registry);
final SimpleRootExec exec = new SimpleRootExec(ImplCreator.getExec(context, (FragmentRoot) plan.getSortedOperators(false).iterator().next()));
while(exec.next()) {
final BigIntVector c0 = exec.getValueVectorById(new SchemaPath("varchar_cast", ExpressionPosition.UNKNOWN), BigIntVector.class);
final BigIntVector.Accessor a0 = c0.getAccessor();
int count = 0;
for(int i = 0; i < c0.getAccessor().getValueCount(); i++) {
BigIntHolder holder0 = new BigIntHolder();
a0.get(i, holder0);
assertEquals(1256, holder0.value);
++count;
}
assertEquals(5, count);
}
exec.close();
context.close();
if (context.getExecutorState().getFailureCause() != null) {
throw context.getExecutorState().getFailureCause();
}
assertTrue(!context.getExecutorState().isFailed());
}
@Test
//cast to int
public void testCastInt() throws Throwable {
final DrillbitContext bitContext = mockDrillbitContext();
final UserClientConnection connection = Mockito.mock(UserClientConnection.class);
final PhysicalPlanReader reader = PhysicalPlanReaderTestFactory.defaultPhysicalPlanReader(CONFIG);
final PhysicalPlan plan = reader.readPhysicalPlan(Files.asCharSource(DrillFileUtils.getResourceAsFile("/functions/cast/testCastInt.json"), Charsets.UTF_8).read());
final FunctionImplementationRegistry registry = new FunctionImplementationRegistry(CONFIG);
final FragmentContextImpl context = new FragmentContextImpl(bitContext, PlanFragment.getDefaultInstance(), connection, registry);
final SimpleRootExec exec = new SimpleRootExec(ImplCreator.getExec(context, (FragmentRoot) plan.getSortedOperators(false).iterator().next()));
while(exec.next()) {
final IntVector c0 = exec.getValueVectorById(new SchemaPath("varchar_cast", ExpressionPosition.UNKNOWN), IntVector.class);
final IntVector.Accessor a0 = c0.getAccessor();
int count = 0;
for(int i = 0; i < c0.getAccessor().getValueCount(); i++) {
final IntHolder holder0 = new IntHolder();
a0.get(i, holder0);
assertEquals(1256, holder0.value);
++count;
}
assertEquals(5, count);
}
exec.close();
context.close();
if (context.getExecutorState().getFailureCause() != null) {
throw context.getExecutorState().getFailureCause();
}
assertTrue(!context.getExecutorState().isFailed());
}
@Test
//cast to float4
public void testCastFloat4() throws Throwable {
final DrillbitContext bitContext = mockDrillbitContext();
final UserClientConnection connection = Mockito.mock(UserClientConnection.class);
final PhysicalPlanReader reader = PhysicalPlanReaderTestFactory.defaultPhysicalPlanReader(CONFIG);
final PhysicalPlan plan = reader.readPhysicalPlan(Files.asCharSource(DrillFileUtils.getResourceAsFile("/functions/cast/testCastFloat4.json"), Charsets.UTF_8).read());
final FunctionImplementationRegistry registry = new FunctionImplementationRegistry(CONFIG);
final FragmentContextImpl context = new FragmentContextImpl(bitContext, PlanFragment.getDefaultInstance(), connection, registry);
final SimpleRootExec exec = new SimpleRootExec(ImplCreator.getExec(context, (FragmentRoot) plan.getSortedOperators(false).iterator().next()));
while(exec.next()) {
final Float4Vector c0 = exec.getValueVectorById(new SchemaPath("varchar_cast2", ExpressionPosition.UNKNOWN), Float4Vector.class);
final Float4Vector.Accessor a0 = c0.getAccessor();
int count = 0;
for(int i = 0; i < c0.getAccessor().getValueCount(); i++) {
final Float4Holder holder0 = new Float4Holder();
a0.get(i, holder0);
assertEquals(12.56, holder0.value, 0.001);
++count;
}
assertEquals(5, count);
}
exec.close();
context.close();
if (context.getExecutorState().getFailureCause() != null) {
throw context.getExecutorState().getFailureCause();
}
assertTrue(!context.getExecutorState().isFailed());
}
@Test
//cast to float8
public void testCastFloat8() throws Throwable {
final DrillbitContext bitContext = mockDrillbitContext();
final UserClientConnection connection = Mockito.mock(UserClientConnection.class);
final PhysicalPlanReader reader = PhysicalPlanReaderTestFactory.defaultPhysicalPlanReader(CONFIG);
final PhysicalPlan plan = reader.readPhysicalPlan(Files.asCharSource(DrillFileUtils.getResourceAsFile("/functions/cast/testCastFloat8.json"), Charsets.UTF_8).read());
final FunctionImplementationRegistry registry = new FunctionImplementationRegistry(CONFIG);
final FragmentContextImpl context = new FragmentContextImpl(bitContext, PlanFragment.getDefaultInstance(), connection, registry);
final SimpleRootExec exec = new SimpleRootExec(ImplCreator.getExec(context, (FragmentRoot) plan.getSortedOperators(false).iterator().next()));
while(exec.next()) {
final Float8Vector c0 = exec.getValueVectorById(new SchemaPath("varchar_cast2", ExpressionPosition.UNKNOWN), Float8Vector.class);
final Float8Vector.Accessor a0 = c0.getAccessor();
int count = 0;
for(int i = 0; i < c0.getAccessor().getValueCount(); i++){
final Float8Holder holder0 = new Float8Holder();
a0.get(i, holder0);
assertEquals(12.56, holder0.value, 0.001);
++count;
}
assertEquals(5, count);
}
exec.close();
context.close();
if (context.getExecutorState().getFailureCause() != null) {
throw context.getExecutorState().getFailureCause();
}
assertTrue(!context.getExecutorState().isFailed());
}
@Test
//cast to varchar(length)
public void testCastVarChar() throws Throwable {
final DrillbitContext bitContext = mockDrillbitContext();
final UserClientConnection connection = Mockito.mock(UserClientConnection.class);
final PhysicalPlanReader reader = PhysicalPlanReaderTestFactory.defaultPhysicalPlanReader(CONFIG);
final PhysicalPlan plan = reader.readPhysicalPlan(Files.asCharSource(DrillFileUtils.getResourceAsFile("/functions/cast/testCastVarChar.json"), Charsets.UTF_8).read());
final FunctionImplementationRegistry registry = new FunctionImplementationRegistry(CONFIG);
final FragmentContextImpl context = new FragmentContextImpl(bitContext, PlanFragment.getDefaultInstance(), connection, registry);
final SimpleRootExec exec = new SimpleRootExec(ImplCreator.getExec(context, (FragmentRoot) plan.getSortedOperators(false).iterator().next()));
while(exec.next()) {
final VarCharVector c0 = exec.getValueVectorById(new SchemaPath("int_lit_cast", ExpressionPosition.UNKNOWN), VarCharVector.class);
final VarCharVector.Accessor a0 = c0.getAccessor();
int count = 0;
for(int i = 0; i < c0.getAccessor().getValueCount(); i++) {
final VarCharHolder holder0 = new VarCharHolder();
a0.get(i, holder0);
assertEquals("123", StringFunctionHelpers.toStringFromUTF8(holder0.start, holder0.end, holder0.buffer));
++count;
}
assertEquals(5, count);
}
exec.close();
context.close();
if (context.getExecutorState().getFailureCause() != null) {
throw context.getExecutorState().getFailureCause();
}
assertTrue(!context.getExecutorState().isFailed());
}
@Test
//cast to varbinary(length)
public void testCastVarBinary() throws Throwable {
final DrillbitContext bitContext = mockDrillbitContext();
final UserClientConnection connection = Mockito.mock(UserClientConnection.class);
final PhysicalPlanReader reader = PhysicalPlanReaderTestFactory.defaultPhysicalPlanReader(CONFIG);
final PhysicalPlan plan = reader.readPhysicalPlan(Files.asCharSource(DrillFileUtils.getResourceAsFile("/functions/cast/testCastVarBinary.json"), Charsets.UTF_8).read());
final FunctionImplementationRegistry registry = new FunctionImplementationRegistry(CONFIG);
final FragmentContextImpl context = new FragmentContextImpl(bitContext, PlanFragment.getDefaultInstance(), connection, registry);
final SimpleRootExec exec = new SimpleRootExec(ImplCreator.getExec(context, (FragmentRoot) plan.getSortedOperators(false).iterator().next()));
while(exec.next()) {
final VarBinaryVector c0 = exec.getValueVectorById(new SchemaPath("int_lit_cast", ExpressionPosition.UNKNOWN), VarBinaryVector.class);
final VarBinaryVector.Accessor a0 = c0.getAccessor();
int count = 0;
for(int i = 0; i < c0.getAccessor().getValueCount(); i++) {
final VarBinaryHolder holder0 = new VarBinaryHolder();
a0.get(i, holder0);
assertEquals("123", StringFunctionHelpers.toStringFromUTF8(holder0.start, holder0.end, holder0.buffer));
++count;
}
assertEquals(5, count);
}
exec.close();
context.close();
if (context.getExecutorState().getFailureCause() != null) {
throw context.getExecutorState().getFailureCause();
}
assertTrue(!context.getExecutorState().isFailed());
}
@Test
//nested: cast is nested in another cast, or another function.
public void testCastNested() throws Throwable {
final DrillbitContext bitContext = mockDrillbitContext();
final UserClientConnection connection = Mockito.mock(UserClientConnection.class);
final PhysicalPlanReader reader = PhysicalPlanReaderTestFactory.defaultPhysicalPlanReader(CONFIG);
final PhysicalPlan plan = reader.readPhysicalPlan(Files.asCharSource(DrillFileUtils.getResourceAsFile("/functions/cast/testCastNested.json"), Charsets.UTF_8).read());
final FunctionImplementationRegistry registry = new FunctionImplementationRegistry(CONFIG);
final FragmentContextImpl context = new FragmentContextImpl(bitContext, PlanFragment.getDefaultInstance(), connection, registry);
final SimpleRootExec exec = new SimpleRootExec(ImplCreator.getExec(context, (FragmentRoot) plan.getSortedOperators(false).iterator().next()));
while(exec.next()) {
final IntVector c0 = exec.getValueVectorById(new SchemaPath("add_cast", ExpressionPosition.UNKNOWN),IntVector.class);
final IntVector.Accessor a0 = c0.getAccessor();
int count = 0;
for(int i = 0; i < c0.getAccessor().getValueCount(); i++) {
final IntHolder holder0 = new IntHolder();
a0.get(i, holder0);
assertEquals(300, holder0.value);
++count;
}
assertEquals(5, count);
}
exec.close();
context.close();
if (context.getExecutorState().getFailureCause() != null) {
throw context.getExecutorState().getFailureCause();
}
assertTrue(!context.getExecutorState().isFailed());
}
@Test(expected = NumberFormatException.class)
public void testCastNumException() throws Throwable {
final DrillbitContext bitContext = mockDrillbitContext();
final UserClientConnection connection = Mockito.mock(UserClientConnection.class);
final PhysicalPlanReader reader = PhysicalPlanReaderTestFactory.defaultPhysicalPlanReader(CONFIG);
final PhysicalPlan plan = reader.readPhysicalPlan(Files.asCharSource(DrillFileUtils.getResourceAsFile("/functions/cast/testCastNumException.json"), Charsets.UTF_8).read());
final FunctionImplementationRegistry registry = new FunctionImplementationRegistry(CONFIG);
final FragmentContextImpl context = new FragmentContextImpl(bitContext, PlanFragment.getDefaultInstance(), connection, registry);
final SimpleRootExec exec = new SimpleRootExec(ImplCreator.getExec(context, (FragmentRoot) plan.getSortedOperators(false).iterator().next()));
while(exec.next()) {
}
exec.close();
context.close();
assertTrue(context.getExecutorState().isFailed());
if(context.getExecutorState().getFailureCause() != null) {
throw context.getExecutorState().getFailureCause();
}
}
@Test
public void testCastFromNullablCol() throws Throwable {
final RemoteServiceSet serviceSet = RemoteServiceSet.getLocalServiceSet();
try(final Drillbit bit = new Drillbit(CONFIG, serviceSet);
final DrillClient client = new DrillClient(CONFIG, serviceSet.getCoordinator())) {
bit.run();
client.connect();
final List<QueryDataBatch> results = client.runQuery(org.apache.drill.exec.proto.UserBitShared.QueryType.PHYSICAL,
Files.asCharSource(DrillFileUtils.getResourceAsFile("/functions/cast/testCastVarCharNull.json"), Charsets.UTF_8).read().replace("#{TEST_FILE}", "/jsoninput/input1.json"));
final QueryDataBatch batch = results.get(0);
final RecordBatchLoader batchLoader = new RecordBatchLoader(bit.getContext().getAllocator());
batchLoader.load(batch.getHeader().getDef(), batch.getData());
final Object [][] result = getRunResult(batchLoader);
final Object [][] expected = new Object[2][2];
expected[0][0] = new String("2001");
expected[0][1] = new String("1.2");
expected[1][0] = new String("-2002");
expected[1][1] = new String("-1.2");
assertEquals(result.length, expected.length);
assertEquals(result[0].length, expected[0].length);
for (int i = 0; i<result.length; i++ ) {
for (int j = 0; j<result[0].length; j++) {
assertEquals(String.format("Column %s at row %s have wrong result", j, i), result[i][j].toString(), expected[i][j]);
}
}
batchLoader.clear();
for(final QueryDataBatch b : results){
b.release();
}
}
}
private Object[][] getRunResult(VectorAccessible va) {
int size = 0;
for (final VectorWrapper v : va) {
size++;
}
final Object[][] res = new Object [va.getRecordCount()][size];
for (int j = 0; j < va.getRecordCount(); j++) {
int i = 0;
for (final VectorWrapper v : va) {
final Object o = v.getValueVector().getAccessor().getObject(j);
if (o instanceof byte[]) {
res[j][i++] = new String((byte[]) o);
} else {
res[j][i++] = o;
}
}
}
return res;
}
}
|
|
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.application.ex;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.module.impl.ModuleManagerImpl;
import com.intellij.openapi.module.impl.ModulePath;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.JDOMUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.testFramework.Parameterized;
import com.intellij.testFramework.TestRunnerUtil;
import com.intellij.util.containers.ContainerUtil;
import gnu.trove.THashSet;
import junit.framework.TestCase;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.jps.model.serialization.JDomSerializationUtil;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Modifier;
import java.util.*;
import java.util.concurrent.ConcurrentMap;
import static com.intellij.openapi.util.io.FileUtil.toSystemDependentName;
import static java.util.Arrays.asList;
public class PathManagerEx {
/**
* All IDEA project files may be logically divided by the following criteria:
* <ul>
* <li>files that are contained at {@code 'community'} directory;</li>
* <li>all other files;</li>
* </ul>
* <p/>
* File location types implied by criteria mentioned above are enumerated here.
*/
private enum FileSystemLocation {
ULTIMATE, COMMUNITY
}
/**
* Caches test data lookup strategy by class.
*/
private static final ConcurrentMap<Class, TestDataLookupStrategy> CLASS_STRATEGY_CACHE = ContainerUtil.newConcurrentMap();
private static final ConcurrentMap<String, Class> CLASS_CACHE = ContainerUtil.newConcurrentMap();
private static Set<String> ourCommunityModules;
private PathManagerEx() { }
/**
* Enumerates possible strategies of test data lookup.
* <p/>
* Check member-level javadoc for more details.
*/
public enum TestDataLookupStrategy {
/**
* Stands for algorithm that retrieves {@code 'test data'} stored at the {@code 'ultimate'} project level assuming
* that it's used from the test running in context of {@code 'ultimate'} project as well.
* <p/>
* Is assumed to be default strategy for all {@code 'ultimate'} tests.
*/
ULTIMATE,
/**
* Stands for algorithm that retrieves {@code 'test data'} stored at the {@code 'community'} project level assuming
* that it's used from the test running in context of {@code 'community'} project as well.
* <p/>
* Is assumed to be default strategy for all {@code 'community'} tests.
*/
COMMUNITY,
/**
* Stands for algorithm that retrieves {@code 'test data'} stored at the {@code 'community'} project level assuming
* that it's used from the test running in context of {@code 'ultimate'} project.
*/
COMMUNITY_FROM_ULTIMATE
}
/**
* It's assumed that test data location for both {@code community} and {@code ultimate} tests follows the same template:
* <code>'<IDEA_HOME>/<RELATIVE_PATH>'</code>.
* <p/>
* {@code 'IDEA_HOME'} here stands for path to IDEA installation; {@code 'RELATIVE_PATH'} defines a path to
* test data relative to IDEA installation path. That relative path may be different for {@code community}
* and {@code ultimate} tests.
* <p/>
* This collection contains mappings from test group type to relative paths to use, i.e. it's possible to define more than one
* relative path for the single test group. It's assumed that path definition algorithm iterates them and checks if
* resulting absolute path points to existing directory. The one is returned in case of success; last path is returned otherwise.
* <p/>
* Hence, the order of relative paths for the single test group matters.
*/
private static final Map<TestDataLookupStrategy, List<String>> TEST_DATA_RELATIVE_PATHS
= new EnumMap<>(TestDataLookupStrategy.class);
static {
TEST_DATA_RELATIVE_PATHS.put(TestDataLookupStrategy.ULTIMATE, Collections.singletonList(toSystemDependentName("testData")));
TEST_DATA_RELATIVE_PATHS.put(
TestDataLookupStrategy.COMMUNITY,
Collections.singletonList(toSystemDependentName("java/java-tests/testData"))
);
TEST_DATA_RELATIVE_PATHS.put(
TestDataLookupStrategy.COMMUNITY_FROM_ULTIMATE,
Collections.singletonList(toSystemDependentName("community/java/java-tests/testData"))
);
}
/**
* Shorthand for calling {@link #getTestDataPath(TestDataLookupStrategy)} with
* {@link #guessTestDataLookupStrategy() guessed} lookup strategy.
*
* @return test data path with {@link #guessTestDataLookupStrategy() guessed} lookup strategy
* @throws IllegalStateException as defined by {@link #getTestDataPath(TestDataLookupStrategy)}
*/
@NonNls
public static String getTestDataPath() throws IllegalStateException {
TestDataLookupStrategy strategy = guessTestDataLookupStrategy();
return getTestDataPath(strategy);
}
public static String getTestDataPath(String path) throws IllegalStateException {
return getTestDataPath() + path.replace('/', File.separatorChar);
}
/**
* Shorthand for calling {@link #getTestDataPath(TestDataLookupStrategy)} with strategy obtained via call to
* {@link #determineLookupStrategy(Class)} with the given class.
* <p/>
* <b>Note:</b> this method receives explicit class argument in order to solve the following limitation - we analyze calling
* stack trace in order to guess test data lookup strategy ({@link #guessTestDataLookupStrategyOnClassLocation()}). However,
* there is a possible case that super-class method is called on sub-class object. Stack trace shows super-class then.
* There is a possible situation that actual test is {@code 'ultimate'} but its abstract super-class is
* {@code 'community'}, hence, test data lookup is performed incorrectly. So, this method should be called from abstract
* base test class if its concrete sub-classes doesn't explicitly occur at stack trace.
*
*
* @param testClass target test class for which test data should be obtained
* @return base test data directory to use for the given test class
* @throws IllegalStateException as defined by {@link #getTestDataPath(TestDataLookupStrategy)}
*/
public static String getTestDataPath(Class<?> testClass) throws IllegalStateException {
TestDataLookupStrategy strategy = isLocatedInCommunity() ? TestDataLookupStrategy.COMMUNITY : determineLookupStrategy(testClass);
return getTestDataPath(strategy);
}
/**
* @return path to 'community' project home irrespective of current project
*/
@NotNull
public static String getCommunityHomePath() {
String path = PathManager.getHomePath();
return isLocatedInCommunity() ? path : path + File.separator + "community";
}
/**
* @return path to 'community' project home if {@code testClass} is located in the community project and path to 'ultimate' project otherwise
*/
public static String getHomePath(Class<?> testClass) {
TestDataLookupStrategy strategy = isLocatedInCommunity() ? TestDataLookupStrategy.COMMUNITY : determineLookupStrategy(testClass);
return strategy == TestDataLookupStrategy.COMMUNITY_FROM_ULTIMATE ? getCommunityHomePath() : PathManager.getHomePath();
}
/**
* Find file by its path relative to 'community' directory irrespective of current project
* @param relativePath path to file relative to 'community' directory
* @return file under the home directory of 'community' project
*/
public static File findFileUnderCommunityHome(String relativePath) {
File file = new File(getCommunityHomePath(), toSystemDependentName(relativePath));
if (!file.exists()) {
throw new IllegalArgumentException("Cannot find file '" + relativePath + "' under '" + getCommunityHomePath() + "' directory");
}
return file;
}
/**
* Find file by its path relative to project home directory (the 'community' project if {@code testClass} is located
* in the community project, and the 'ultimate' project otherwise)
*/
public static File findFileUnderProjectHome(String relativePath, Class<? extends TestCase> testClass) {
String homePath = getHomePath(testClass);
File file = new File(homePath, toSystemDependentName(relativePath));
if (!file.exists()) {
throw new IllegalArgumentException("Cannot find file '" + relativePath + "' under '" + homePath + "' directory");
}
return file;
}
private static boolean isLocatedInCommunity() {
FileSystemLocation projectLocation = parseProjectLocation();
return projectLocation == FileSystemLocation.COMMUNITY;
// There is no other options then.
}
/**
* Tries to return test data path for the given lookup strategy.
*
* @param strategy lookup strategy to use
* @return test data path for the given strategy
* @throws IllegalStateException if it's not possible to find valid test data path for the given strategy
*/
@NonNls
public static String getTestDataPath(TestDataLookupStrategy strategy) throws IllegalStateException {
String homePath = PathManager.getHomePath();
List<String> relativePaths = TEST_DATA_RELATIVE_PATHS.get(strategy);
if (relativePaths.isEmpty()) {
throw new IllegalStateException(
String.format("Can't determine test data path. Reason: no predefined relative paths are configured for test data "
+ "lookup strategy %s. Configured mappings: %s", strategy, TEST_DATA_RELATIVE_PATHS)
);
}
File candidate = null;
for (String relativePath : relativePaths) {
candidate = new File(homePath, relativePath);
if (candidate.isDirectory()) {
return candidate.getPath();
}
}
if (candidate == null) {
throw new IllegalStateException("Can't determine test data path. Looks like programming error - reached 'if' block that was "
+ "never expected to be executed");
}
return candidate.getPath();
}
/**
* Tries to guess test data lookup strategy for the current execution.
*
* @return guessed lookup strategy for the current execution; defaults to {@link TestDataLookupStrategy#ULTIMATE}
*/
public static TestDataLookupStrategy guessTestDataLookupStrategy() {
TestDataLookupStrategy result = guessTestDataLookupStrategyOnClassLocation();
if (result == null) {
result = guessTestDataLookupStrategyOnDirectoryAvailability();
}
return result;
}
@SuppressWarnings({"ThrowableInstanceNeverThrown"})
@Nullable
private static TestDataLookupStrategy guessTestDataLookupStrategyOnClassLocation() {
if (isLocatedInCommunity()) return TestDataLookupStrategy.COMMUNITY;
// The general idea here is to find test class at the bottom of hierarchy and try to resolve test data lookup strategy
// against it. Rationale is that there is a possible case that, say, 'ultimate' test class extends basic test class
// that remains at 'community'. We want to perform the processing against 'ultimate' test class then.
// About special abstract classes processing - there is a possible case that target test class extends abstract base
// test class and call to this method is rooted from that parent. We need to resolve test data lookup against super
// class then, hence, we keep track of found abstract test class as well and fallback to it if no non-abstract class is found.
Class<?> testClass = null;
Class<?> abstractTestClass = null;
StackTraceElement[] stackTrace = new Exception().getStackTrace();
for (StackTraceElement stackTraceElement : stackTrace) {
String className = stackTraceElement.getClassName();
Class<?> clazz = loadClass(className);
if (clazz == null || TestCase.class == clazz || !isJUnitClass(clazz)) {
continue;
}
if (determineLookupStrategy(clazz) == TestDataLookupStrategy.ULTIMATE) return TestDataLookupStrategy.ULTIMATE;
if ((clazz.getModifiers() & Modifier.ABSTRACT) == 0) {
testClass = clazz;
}
else {
abstractTestClass = clazz;
}
}
Class<?> classToUse = testClass == null ? abstractTestClass : testClass;
return classToUse == null ? null : determineLookupStrategy(classToUse);
}
@Nullable
private static Class<?> loadClass(String className) {
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
Class<?> clazz = CLASS_CACHE.get(className);
if (clazz != null) {
return clazz;
}
ClassLoader definingClassLoader = PathManagerEx.class.getClassLoader();
ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
for (ClassLoader classLoader : asList(contextClassLoader, definingClassLoader, systemClassLoader)) {
clazz = loadClass(className, classLoader);
if (clazz != null) {
CLASS_CACHE.put(className, clazz);
return clazz;
}
}
CLASS_CACHE.put(className, TestCase.class); //dummy
return null;
}
@Nullable
private static Class<?> loadClass(String className, ClassLoader classLoader) {
try {
return Class.forName(className, true, classLoader);
}
catch (NoClassDefFoundError | ClassNotFoundException e) {
return null;
}
}
@SuppressWarnings("TestOnlyProblems")
private static boolean isJUnitClass(Class<?> clazz) {
return TestCase.class.isAssignableFrom(clazz) || TestRunnerUtil.isJUnit4TestClass(clazz) || Parameterized.class.isAssignableFrom(clazz);
}
@Nullable
private static TestDataLookupStrategy determineLookupStrategy(Class<?> clazz) {
// Check if resulting strategy is already cached for the target class.
TestDataLookupStrategy result = CLASS_STRATEGY_CACHE.get(clazz);
if (result != null) {
return result;
}
FileSystemLocation classFileLocation = computeClassLocation(clazz);
// We know that project location is ULTIMATE if control flow reaches this place.
result = classFileLocation == FileSystemLocation.COMMUNITY ? TestDataLookupStrategy.COMMUNITY_FROM_ULTIMATE
: TestDataLookupStrategy.ULTIMATE;
CLASS_STRATEGY_CACHE.put(clazz, result);
return result;
}
public static void replaceLookupStrategy(Class<?> substitutor, Class<?>... initial) {
CLASS_STRATEGY_CACHE.clear();
for (Class<?> aClass : initial) {
CLASS_STRATEGY_CACHE.put(aClass, determineLookupStrategy(substitutor));
}
}
private static FileSystemLocation computeClassLocation(Class<?> clazz) {
String classRootPath = PathManager.getJarPathForClass(clazz);
if (classRootPath == null) {
throw new IllegalStateException("Cannot find root directory for " + clazz);
}
File root = new File(classRootPath);
if (!root.exists()) {
throw new IllegalStateException("Classes root " + root + " doesn't exist");
}
if (!root.isDirectory()) {
//this means that clazz is located in a library, perhaps we should throw exception here
return FileSystemLocation.ULTIMATE;
}
String moduleName = root.getName();
String chunkPrefix = "ModuleChunk(";
if (moduleName.startsWith(chunkPrefix)) {
//todo[nik] this is temporary workaround to fix tests on TeamCity which compiles the whole modules cycle to a single output directory
moduleName = StringUtil.trimStart(moduleName, chunkPrefix);
moduleName = moduleName.substring(0, moduleName.indexOf(','));
}
return getCommunityModules().contains(moduleName) ? FileSystemLocation.COMMUNITY : FileSystemLocation.ULTIMATE;
}
private synchronized static Set<String> getCommunityModules() {
if (ourCommunityModules != null) {
return ourCommunityModules;
}
ourCommunityModules = new THashSet<>();
File modulesXml = findFileUnderCommunityHome(Project.DIRECTORY_STORE_FOLDER + "/modules.xml");
if (!modulesXml.exists()) {
throw new IllegalStateException("Cannot obtain test data path: " + modulesXml.getAbsolutePath() + " not found");
}
try {
Element element = JDomSerializationUtil.findComponent(JDOMUtil.load(modulesXml), ModuleManagerImpl.COMPONENT_NAME);
assert element != null;
for (ModulePath file : ModuleManagerImpl.getPathsToModuleFiles(element)) {
ourCommunityModules.add(file.getModuleName());
}
return ourCommunityModules;
}
catch (JDOMException | IOException e) {
throw new RuntimeException("Cannot read modules from " + modulesXml.getAbsolutePath(), e);
}
}
/**
* Allows to determine project type by its file system location.
*
* @return project type implied by its file system location
*/
private static FileSystemLocation parseProjectLocation() {
return new File(PathManager.getHomePath(), "community/.idea").isDirectory() ? FileSystemLocation.ULTIMATE : FileSystemLocation.COMMUNITY;
}
/**
* Tries to check test data lookup strategy by target test data directories availability.
* <p/>
* Such an approach has a drawback that it doesn't work correctly at number of scenarios, e.g. when
* {@code 'community'} test is executed under {@code 'ultimate'} project.
*
* @return test data lookup strategy based on target test data directories availability
*/
private static TestDataLookupStrategy guessTestDataLookupStrategyOnDirectoryAvailability() {
String homePath = PathManager.getHomePath();
for (Map.Entry<TestDataLookupStrategy, List<String>> entry : TEST_DATA_RELATIVE_PATHS.entrySet()) {
for (String relativePath : entry.getValue()) {
if (new File(homePath, relativePath).isDirectory()) {
return entry.getKey();
}
}
}
return TestDataLookupStrategy.ULTIMATE;
}
}
|
|
/*
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.dao.support;
import java.util.Collection;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.dao.IncorrectResultSizeDataAccessException;
import org.springframework.dao.TypeMismatchDataAccessException;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.NumberUtils;
/**
* Miscellaneous utility methods for DAO implementations.
* Useful with any data access technology.
*
* @author Juergen Hoeller
* @since 1.0.2
*/
public abstract class DataAccessUtils {
/**
* Return a single result object from the given Collection.
* <p>Returns {@code null} if 0 result objects found;
* throws an exception if more than 1 element found.
* @param results the result Collection (can be {@code null})
* @return the single result object, or {@code null} if none
* @throws IncorrectResultSizeDataAccessException if more than one
* element has been found in the given Collection
*/
@Nullable
public static <T> T singleResult(@Nullable Collection<T> results) throws IncorrectResultSizeDataAccessException {
if (CollectionUtils.isEmpty(results)) {
return null;
}
if (results.size() > 1) {
throw new IncorrectResultSizeDataAccessException(1, results.size());
}
return results.iterator().next();
}
/**
* Return a single result object from the given Collection.
* <p>Throws an exception if 0 or more than 1 element found.
* @param results the result Collection (can be {@code null}
* but is not expected to contain {@code null} elements)
* @return the single result object
* @throws IncorrectResultSizeDataAccessException if more than one
* element has been found in the given Collection
* @throws EmptyResultDataAccessException if no element at all
* has been found in the given Collection
*/
public static <T> T requiredSingleResult(@Nullable Collection<T> results) throws IncorrectResultSizeDataAccessException {
if (CollectionUtils.isEmpty(results)) {
throw new EmptyResultDataAccessException(1);
}
if (results.size() > 1) {
throw new IncorrectResultSizeDataAccessException(1, results.size());
}
return results.iterator().next();
}
/**
* Return a single result object from the given Collection.
* <p>Throws an exception if 0 or more than 1 element found.
* @param results the result Collection (can be {@code null}
* and is also expected to contain {@code null} elements)
* @return the single result object
* @throws IncorrectResultSizeDataAccessException if more than one
* element has been found in the given Collection
* @throws EmptyResultDataAccessException if no element at all
* has been found in the given Collection
* @since 5.0.2
*/
@Nullable
public static <T> T nullableSingleResult(@Nullable Collection<T> results) throws IncorrectResultSizeDataAccessException {
// This is identical to the requiredSingleResult implementation but differs in the
// semantics of the incoming Collection (which we currently can't formally express)
if (CollectionUtils.isEmpty(results)) {
throw new EmptyResultDataAccessException(1);
}
if (results.size() > 1) {
throw new IncorrectResultSizeDataAccessException(1, results.size());
}
return results.iterator().next();
}
/**
* Return a unique result object from the given Collection.
* <p>Returns {@code null} if 0 result objects found;
* throws an exception if more than 1 instance found.
* @param results the result Collection (can be {@code null})
* @return the unique result object, or {@code null} if none
* @throws IncorrectResultSizeDataAccessException if more than one
* result object has been found in the given Collection
* @see org.springframework.util.CollectionUtils#hasUniqueObject
*/
@Nullable
public static <T> T uniqueResult(@Nullable Collection<T> results) throws IncorrectResultSizeDataAccessException {
if (CollectionUtils.isEmpty(results)) {
return null;
}
if (!CollectionUtils.hasUniqueObject(results)) {
throw new IncorrectResultSizeDataAccessException(1, results.size());
}
return results.iterator().next();
}
/**
* Return a unique result object from the given Collection.
* <p>Throws an exception if 0 or more than 1 instance found.
* @param results the result Collection (can be {@code null}
* but is not expected to contain {@code null} elements)
* @return the unique result object
* @throws IncorrectResultSizeDataAccessException if more than one
* result object has been found in the given Collection
* @throws EmptyResultDataAccessException if no result object at all
* has been found in the given Collection
* @see org.springframework.util.CollectionUtils#hasUniqueObject
*/
public static <T> T requiredUniqueResult(@Nullable Collection<T> results) throws IncorrectResultSizeDataAccessException {
if (CollectionUtils.isEmpty(results)) {
throw new EmptyResultDataAccessException(1);
}
if (!CollectionUtils.hasUniqueObject(results)) {
throw new IncorrectResultSizeDataAccessException(1, results.size());
}
return results.iterator().next();
}
/**
* Return a unique result object from the given Collection.
* Throws an exception if 0 or more than 1 result objects found,
* of if the unique result object is not convertible to the
* specified required type.
* @param results the result Collection (can be {@code null}
* but is not expected to contain {@code null} elements)
* @return the unique result object
* @throws IncorrectResultSizeDataAccessException if more than one
* result object has been found in the given Collection
* @throws EmptyResultDataAccessException if no result object
* at all has been found in the given Collection
* @throws TypeMismatchDataAccessException if the unique object does
* not match the specified required type
*/
@SuppressWarnings("unchecked")
public static <T> T objectResult(@Nullable Collection<?> results, @Nullable Class<T> requiredType)
throws IncorrectResultSizeDataAccessException, TypeMismatchDataAccessException {
Object result = requiredUniqueResult(results);
if (requiredType != null && !requiredType.isInstance(result)) {
if (String.class == requiredType) {
result = result.toString();
}
else if (Number.class.isAssignableFrom(requiredType) && result instanceof Number) {
try {
result = NumberUtils.convertNumberToTargetClass(((Number) result), (Class<? extends Number>) requiredType);
}
catch (IllegalArgumentException ex) {
throw new TypeMismatchDataAccessException(ex.getMessage());
}
}
else {
throw new TypeMismatchDataAccessException(
"Result object is of type [" + result.getClass().getName() +
"] and could not be converted to required type [" + requiredType.getName() + "]");
}
}
return (T) result;
}
/**
* Return a unique int result from the given Collection.
* Throws an exception if 0 or more than 1 result objects found,
* of if the unique result object is not convertible to an int.
* @param results the result Collection (can be {@code null}
* but is not expected to contain {@code null} elements)
* @return the unique int result
* @throws IncorrectResultSizeDataAccessException if more than one
* result object has been found in the given Collection
* @throws EmptyResultDataAccessException if no result object
* at all has been found in the given Collection
* @throws TypeMismatchDataAccessException if the unique object
* in the collection is not convertible to an int
*/
public static int intResult(@Nullable Collection<?> results)
throws IncorrectResultSizeDataAccessException, TypeMismatchDataAccessException {
return objectResult(results, Number.class).intValue();
}
/**
* Return a unique long result from the given Collection.
* Throws an exception if 0 or more than 1 result objects found,
* of if the unique result object is not convertible to a long.
* @param results the result Collection (can be {@code null}
* but is not expected to contain {@code null} elements)
* @return the unique long result
* @throws IncorrectResultSizeDataAccessException if more than one
* result object has been found in the given Collection
* @throws EmptyResultDataAccessException if no result object
* at all has been found in the given Collection
* @throws TypeMismatchDataAccessException if the unique object
* in the collection is not convertible to a long
*/
public static long longResult(@Nullable Collection<?> results)
throws IncorrectResultSizeDataAccessException, TypeMismatchDataAccessException {
return objectResult(results, Number.class).longValue();
}
/**
* Return a translated exception if this is appropriate,
* otherwise return the given exception as-is.
* @param rawException an exception that we may wish to translate
* @param pet the PersistenceExceptionTranslator to use to perform the translation
* @return a translated persistence exception if translation is possible,
* or the raw exception if it is not
*/
public static RuntimeException translateIfNecessary(
RuntimeException rawException, PersistenceExceptionTranslator pet) {
Assert.notNull(pet, "PersistenceExceptionTranslator must not be null");
DataAccessException dae = pet.translateExceptionIfPossible(rawException);
return (dae != null ? dae : rawException);
}
}
|
|
/*
* DBeaver - Universal Database Manager
* Copyright (C) 2013-2015 Denis Forveille ([email protected])
* Copyright (C) 2010-2022 DBeaver Corp and others
*
* 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.jkiss.dbeaver.ext.db2.model.security;
import org.jkiss.code.NotNull;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.ext.db2.DB2Constants;
import org.jkiss.dbeaver.ext.db2.model.DB2DataSource;
import org.jkiss.dbeaver.ext.db2.model.DB2GlobalObject;
import org.jkiss.dbeaver.ext.db2.model.dict.DB2YesNo;
import org.jkiss.dbeaver.model.access.DBAPrivilege;
import org.jkiss.dbeaver.model.impl.jdbc.JDBCUtils;
import org.jkiss.dbeaver.model.meta.Property;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.model.struct.DBSObject;
import org.jkiss.utils.CommonUtils;
import java.sql.ResultSet;
/**
* DB2 Database Authorisation
*
* @author Denis Forveille
*/
public class DB2DatabaseAuth extends DB2GlobalObject implements DBAPrivilege {
private DBSObject grantor;
private DB2GrantorGranteeType grantorType;
private Boolean bindAdd;
private Boolean connect;
private Boolean createTab;
private Boolean dbAdm;
private Boolean externalRoutine;
private Boolean implicitSchema;
private Boolean load;
private Boolean noFence;
private Boolean quiesceConnect;
private Boolean libraryAdmin;
private Boolean securityAdmin;
private Boolean sqlAdmin;
private Boolean workLoadAdmin;
private Boolean explain;
private Boolean dataAccess;
private Boolean accessControl;
private Boolean createSecure;
// -----------------------
// Constructors
// -----------------------
public DB2DatabaseAuth(DBRProgressMonitor monitor, DB2DataSource dataSource, ResultSet resultSet) throws DBException
{
super(dataSource, true);
String grantorName = JDBCUtils.safeGetStringTrimmed(resultSet, "GRANTOR");
this.grantorType = CommonUtils.valueOf(DB2GrantorGranteeType.class,
JDBCUtils.safeGetStringTrimmed(resultSet, "GRANTORTYPE"));
switch (grantorType) {
case U:
this.grantor = dataSource.getUser(monitor, grantorName);
break;
case G:
this.grantor = dataSource.getGroup(monitor, grantorName);
break;
default:
break;
}
this.bindAdd = JDBCUtils.safeGetBoolean(resultSet, "BINDADDAUTH", DB2YesNo.Y.name());
this.connect = JDBCUtils.safeGetBoolean(resultSet, "CONNECTAUTH", DB2YesNo.Y.name());
this.createTab = JDBCUtils.safeGetBoolean(resultSet, "CREATETABAUTH", DB2YesNo.Y.name());
this.dbAdm = JDBCUtils.safeGetBoolean(resultSet, "DBADMAUTH", DB2YesNo.Y.name());
this.externalRoutine = JDBCUtils.safeGetBoolean(resultSet, "EXTERNALROUTINEAUTH", DB2YesNo.Y.name());
this.implicitSchema = JDBCUtils.safeGetBoolean(resultSet, "IMPLSCHEMAAUTH", DB2YesNo.Y.name());
this.load = JDBCUtils.safeGetBoolean(resultSet, "LOADAUTH", DB2YesNo.Y.name());
this.noFence = JDBCUtils.safeGetBoolean(resultSet, "NOFENCEAUTH", DB2YesNo.Y.name());
this.quiesceConnect = JDBCUtils.safeGetBoolean(resultSet, "QUIESCECONNECTAUTH", DB2YesNo.Y.name());
this.libraryAdmin = JDBCUtils.safeGetBoolean(resultSet, "LIBRARYADMAUTH", DB2YesNo.Y.name());
this.securityAdmin = JDBCUtils.safeGetBoolean(resultSet, "SECURITYADMAUTH", DB2YesNo.Y.name());
this.sqlAdmin = JDBCUtils.safeGetBoolean(resultSet, "SQLADMAUTH", DB2YesNo.Y.name());
this.workLoadAdmin = JDBCUtils.safeGetBoolean(resultSet, "WLMADMAUTH", DB2YesNo.Y.name());
this.explain = JDBCUtils.safeGetBoolean(resultSet, "EXPLAINAUTH", DB2YesNo.Y.name());
this.dataAccess = JDBCUtils.safeGetBoolean(resultSet, "DATAACCESSAUTH", DB2YesNo.Y.name());
this.accessControl = JDBCUtils.safeGetBoolean(resultSet, "ACCESSCTRLAUTH", DB2YesNo.Y.name());
if (dataSource.isAtLeastV10_1()) {
this.createSecure = JDBCUtils.safeGetBoolean(resultSet, "CREATESECUREAUTH", DB2YesNo.Y.name());
}
}
// -----------------
// Properties
// -----------------
@NotNull
@Override
@Property(hidden = true)
public String getName()
{
return "DBAUTH"; // Fake name
}
@Property(viewable = true, order = 3)
public DBSObject getGrantor()
{
return grantor;
}
@Property(viewable = true, order = 4)
public DB2GrantorGranteeType getGrantorType()
{
return grantorType;
}
@Property(viewable = true, order = 20, category = DB2Constants.CAT_AUTH)
public Boolean getDbAdm()
{
return dbAdm;
}
@Property(viewable = true, order = 21, category = DB2Constants.CAT_AUTH)
public Boolean getBindAdd()
{
return bindAdd;
}
@Property(viewable = true, order = 22, category = DB2Constants.CAT_AUTH)
public Boolean getConnect()
{
return connect;
}
@Property(viewable = true, order = 23, category = DB2Constants.CAT_AUTH)
public Boolean getCreateTab()
{
return createTab;
}
@Property(viewable = true, order = 24, category = DB2Constants.CAT_AUTH)
public Boolean getExternalRoutine()
{
return externalRoutine;
}
@Property(viewable = true, order = 25, category = DB2Constants.CAT_AUTH)
public Boolean getImplicitSchema()
{
return implicitSchema;
}
@Property(viewable = true, order = 26, category = DB2Constants.CAT_AUTH)
public Boolean getLoad()
{
return load;
}
@Property(viewable = true, order = 27, category = DB2Constants.CAT_AUTH)
public Boolean getDataAccess()
{
return dataAccess;
}
@Property(viewable = true, order = 28, category = DB2Constants.CAT_AUTH)
public Boolean getAccessControl()
{
return accessControl;
}
@Property(viewable = false, order = 29, category = DB2Constants.CAT_AUTH)
public Boolean getNoFence()
{
return noFence;
}
@Property(viewable = false, order = 30, category = DB2Constants.CAT_AUTH)
public Boolean getQuiesceConnect()
{
return quiesceConnect;
}
@Property(viewable = false, order = 31, category = DB2Constants.CAT_AUTH)
public Boolean getLibraryAdmin()
{
return libraryAdmin;
}
@Property(viewable = false, order = 32, category = DB2Constants.CAT_AUTH)
public Boolean getSecurityAdmin()
{
return securityAdmin;
}
@Property(viewable = false, order = 33, category = DB2Constants.CAT_AUTH)
public Boolean getSqlAdmin()
{
return sqlAdmin;
}
@Property(viewable = false, order = 34, category = DB2Constants.CAT_AUTH)
public Boolean getWorkLoadAdmin()
{
return workLoadAdmin;
}
@Property(viewable = false, order = 35, category = DB2Constants.CAT_AUTH)
public Boolean getExplain()
{
return explain;
}
@Property(viewable = false, order = 36, category = DB2Constants.CAT_AUTH)
public Boolean getCreateSecure()
{
return createSecure;
}
}
|
|
/*
* 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.ambari.server.security.authentication.jwt;
import static org.easymock.EasyMock.anyObject;
import static org.easymock.EasyMock.capture;
import static org.easymock.EasyMock.eq;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.expectLastCall;
import static org.easymock.EasyMock.newCapture;
import static org.easymock.EasyMock.verify;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.FilterChain;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.ambari.server.configuration.AmbariServerConfigurationKey;
import org.apache.ambari.server.configuration.Configuration;
import org.apache.ambari.server.orm.entities.UserAuthenticationEntity;
import org.apache.ambari.server.orm.entities.UserEntity;
import org.apache.ambari.server.security.AmbariEntryPoint;
import org.apache.ambari.server.security.authentication.AmbariAuthenticationEventHandler;
import org.apache.ambari.server.security.authentication.AmbariAuthenticationException;
import org.apache.ambari.server.security.authentication.AmbariAuthenticationFilter;
import org.apache.ambari.server.security.authorization.User;
import org.apache.ambari.server.security.authorization.UserAuthenticationType;
import org.apache.ambari.server.security.authorization.Users;
import org.apache.commons.lang.StringUtils;
import org.easymock.Capture;
import org.easymock.CaptureType;
import org.easymock.EasyMockSupport;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.AuthenticationEntryPoint;
import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.JWSHeader;
import com.nimbusds.jose.crypto.RSASSASigner;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.SignedJWT;
public class AmbariJwtAuthenticationFilterTest extends EasyMockSupport {
private static RSAPublicKey publicKey;
private static RSAPrivateKey privateKey;
private static RSAPrivateKey invalidPrivateKey;
@BeforeClass
public static void generateKeyPair() throws NoSuchAlgorithmException {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(512);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
publicKey = (RSAPublicKey) keyPair.getPublic();
privateKey = (RSAPrivateKey) keyPair.getPrivate();
keyPair = keyPairGenerator.generateKeyPair();
invalidPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
}
@Before
public void setup() {
SecurityContextHolder.clearContext();
}
private JwtAuthenticationProperties createTestProperties() {
return createTestProperties(Collections.singletonList("test-audience"));
}
private JwtAuthenticationProperties createTestProperties(List<String> audiences) {
final Map<String, String> configurationMap = new HashMap<>();
configurationMap.put(AmbariServerConfigurationKey.SSO_JWT_COOKIE_NAME.key(), "non-default");
configurationMap.put(AmbariServerConfigurationKey.SSO_JWT_AUDIENCES.key(), audiences == null || audiences.isEmpty() ? "" : StringUtils.join(audiences, ","));
configurationMap.put(AmbariServerConfigurationKey.SSO_AUTHENTICATION_ENABLED.key(), "true");
JwtAuthenticationProperties properties = new JwtAuthenticationProperties(configurationMap);
properties.setPublicKey(publicKey);
return properties;
}
private SignedJWT getSignedToken() throws JOSEException {
return getSignedToken("test-audience");
}
private SignedJWT getSignedToken(String audience) throws JOSEException {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.DATE, 1); //add one day
return getSignedToken(calendar.getTime(), audience);
}
private SignedJWT getSignedToken(Date expirationTime, String audience) throws JOSEException {
RSASSASigner signer = new RSASSASigner(privateKey);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
.subject("test-user")
.issuer("unit-test")
.issueTime(calendar.getTime())
.expirationTime(expirationTime)
.audience(audience)
.build();
SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.RS256), claimsSet);
signedJWT.sign(signer);
return signedJWT;
}
private SignedJWT getInvalidToken() throws JOSEException {
RSASSASigner signer = new RSASSASigner(invalidPrivateKey);
Calendar issueTime = Calendar.getInstance();
issueTime.setTimeInMillis(System.currentTimeMillis());
issueTime.add(Calendar.DATE, -2);
Calendar expirationTime = Calendar.getInstance();
issueTime.setTimeInMillis(System.currentTimeMillis());
expirationTime.add(Calendar.DATE, -1);
JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
.subject("test-user")
.issuer("unit-test")
.issueTime(issueTime.getTime())
.expirationTime(issueTime.getTime())
.audience("test-audience-invalid")
.build();
SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.RS256), claimsSet);
signedJWT.sign(signer);
return signedJWT;
}
@Test
public void testGetJWTFromCookie() throws Exception {
HttpServletRequest request = createNiceMock(HttpServletRequest.class);
Cookie cookie = createNiceMock(Cookie.class);
expect(cookie.getName()).andReturn("non-default");
expect(cookie.getValue()).andReturn("stubtokenstring");
expect(request.getCookies()).andReturn(new Cookie[]{cookie});
JwtAuthenticationPropertiesProvider jwtAuthenticationPropertiesProvider = createMock(JwtAuthenticationPropertiesProvider.class);
expect(jwtAuthenticationPropertiesProvider.get()).andReturn(createTestProperties()).anyTimes();
AmbariAuthenticationEventHandler eventHandler = createNiceMock(AmbariAuthenticationEventHandler.class);
replayAll();
AmbariJwtAuthenticationFilter filter = new AmbariJwtAuthenticationFilter(null, jwtAuthenticationPropertiesProvider, null, eventHandler);
String jwtFromCookie = filter.getJWTFromCookie(request);
verifyAll();
assertEquals("stubtokenstring", jwtFromCookie);
}
@Test
public void testValidateSignature() throws Exception {
JwtAuthenticationPropertiesProvider jwtAuthenticationPropertiesProvider = createMock(JwtAuthenticationPropertiesProvider.class);
expect(jwtAuthenticationPropertiesProvider.get()).andReturn(createTestProperties()).anyTimes();
AmbariAuthenticationEventHandler eventHandler = createNiceMock(AmbariAuthenticationEventHandler.class);
replayAll();
AmbariJwtAuthenticationFilter filter = new AmbariJwtAuthenticationFilter(null, jwtAuthenticationPropertiesProvider, null, eventHandler);
assertTrue(filter.validateSignature(getSignedToken()));
assertFalse(filter.validateSignature(getInvalidToken()));
verifyAll();
}
@Test
public void testValidateAudiences() throws Exception {
JwtAuthenticationPropertiesProvider jwtAuthenticationPropertiesProvider = createMock(JwtAuthenticationPropertiesProvider.class);
expect(jwtAuthenticationPropertiesProvider.get()).andReturn(createTestProperties()).anyTimes();
AmbariAuthenticationEventHandler eventHandler = createNiceMock(AmbariAuthenticationEventHandler.class);
replayAll();
AmbariJwtAuthenticationFilter filter = new AmbariJwtAuthenticationFilter(null, jwtAuthenticationPropertiesProvider, null, eventHandler);
assertTrue(filter.validateAudiences(getSignedToken()));
assertFalse(filter.validateAudiences(getInvalidToken()));
verifyAll();
}
@Test
public void testValidateNullAudiences() throws Exception {
JwtAuthenticationPropertiesProvider jwtAuthenticationPropertiesProvider = createMock(JwtAuthenticationPropertiesProvider.class);
expect(jwtAuthenticationPropertiesProvider.get()).andReturn(createTestProperties(null)).anyTimes();
AmbariAuthenticationEventHandler eventHandler = createNiceMock(AmbariAuthenticationEventHandler.class);
replayAll();
AmbariJwtAuthenticationFilter filter = new AmbariJwtAuthenticationFilter(null, jwtAuthenticationPropertiesProvider, null, eventHandler);
assertTrue(filter.validateAudiences(getSignedToken()));
assertTrue(filter.validateAudiences(getInvalidToken()));
verifyAll();
}
@Test
public void testValidateTokenWithoutAudiences() throws Exception {
JwtAuthenticationPropertiesProvider jwtAuthenticationPropertiesProvider = createMock(JwtAuthenticationPropertiesProvider.class);
expect(jwtAuthenticationPropertiesProvider.get()).andReturn(createTestProperties()).anyTimes();
AmbariAuthenticationEventHandler eventHandler = createNiceMock(AmbariAuthenticationEventHandler.class);
replayAll();
AmbariJwtAuthenticationFilter filter = new AmbariJwtAuthenticationFilter(null, jwtAuthenticationPropertiesProvider, null, eventHandler);
assertFalse(filter.validateAudiences(getSignedToken(null)));
verifyAll();
}
@Test
public void testValidateExpiration() throws Exception {
JwtAuthenticationPropertiesProvider jwtAuthenticationPropertiesProvider = createMock(JwtAuthenticationPropertiesProvider.class);
expect(jwtAuthenticationPropertiesProvider.get()).andReturn(createTestProperties()).anyTimes();
AmbariAuthenticationEventHandler eventHandler = createNiceMock(AmbariAuthenticationEventHandler.class);
replayAll();
AmbariJwtAuthenticationFilter filter = new AmbariJwtAuthenticationFilter(null, jwtAuthenticationPropertiesProvider, null, eventHandler);
assertTrue(filter.validateExpiration(getSignedToken()));
assertFalse(filter.validateExpiration(getInvalidToken()));
verifyAll();
}
@Test
public void testValidateNoExpiration() throws Exception {
JwtAuthenticationPropertiesProvider jwtAuthenticationPropertiesProvider = createMock(JwtAuthenticationPropertiesProvider.class);
expect(jwtAuthenticationPropertiesProvider.get()).andReturn(createTestProperties()).anyTimes();
AmbariAuthenticationEventHandler eventHandler = createNiceMock(AmbariAuthenticationEventHandler.class);
replayAll();
AmbariJwtAuthenticationFilter filter = new AmbariJwtAuthenticationFilter(null, jwtAuthenticationPropertiesProvider, null, eventHandler);
assertTrue(filter.validateExpiration(getSignedToken(null, "test-audience")));
assertFalse(filter.validateExpiration(getInvalidToken()));
verifyAll();
}
@Test
public void testShouldApplyTrue() throws JOSEException {
JwtAuthenticationPropertiesProvider jwtAuthenticationPropertiesProvider = createMock(JwtAuthenticationPropertiesProvider.class);
expect(jwtAuthenticationPropertiesProvider.get()).andReturn(createTestProperties()).anyTimes();
SignedJWT token = getInvalidToken();
Cookie cookie = createMock(Cookie.class);
expect(cookie.getName()).andReturn("non-default").atLeastOnce();
expect(cookie.getValue()).andReturn(token.serialize()).atLeastOnce();
HttpServletRequest request = createMock(HttpServletRequest.class);
expect(request.getCookies()).andReturn(new Cookie[]{cookie});
AmbariAuthenticationEventHandler eventHandler = createNiceMock(AmbariAuthenticationEventHandler.class);
replayAll();
AmbariJwtAuthenticationFilter filter = new AmbariJwtAuthenticationFilter(null, jwtAuthenticationPropertiesProvider, null, eventHandler);
assertTrue(filter.shouldApply(request));
verifyAll();
}
@Test
public void testShouldApplyTrueBadToken() throws JOSEException {
JwtAuthenticationPropertiesProvider jwtAuthenticationPropertiesProvider = createMock(JwtAuthenticationPropertiesProvider.class);
expect(jwtAuthenticationPropertiesProvider.get()).andReturn(createTestProperties()).anyTimes();
Cookie cookie = createMock(Cookie.class);
expect(cookie.getName()).andReturn("non-default").atLeastOnce();
expect(cookie.getValue()).andReturn("bad token").atLeastOnce();
HttpServletRequest request = createMock(HttpServletRequest.class);
expect(request.getCookies()).andReturn(new Cookie[]{cookie});
AmbariAuthenticationEventHandler eventHandler = createNiceMock(AmbariAuthenticationEventHandler.class);
replayAll();
AmbariJwtAuthenticationFilter filter = new AmbariJwtAuthenticationFilter(null, jwtAuthenticationPropertiesProvider, null, eventHandler);
assertTrue(filter.shouldApply(request));
verifyAll();
}
@Test
public void testShouldApplyFalseMissingCookie() throws JOSEException {
JwtAuthenticationPropertiesProvider jwtAuthenticationPropertiesProvider = createMock(JwtAuthenticationPropertiesProvider.class);
expect(jwtAuthenticationPropertiesProvider.get()).andReturn(createTestProperties()).anyTimes();
Cookie cookie = createMock(Cookie.class);
expect(cookie.getName()).andReturn("some-other-cookie").atLeastOnce();
HttpServletRequest request = createMock(HttpServletRequest.class);
expect(request.getCookies()).andReturn(new Cookie[]{cookie});
AmbariAuthenticationEventHandler eventHandler = createNiceMock(AmbariAuthenticationEventHandler.class);
replayAll();
AmbariJwtAuthenticationFilter filter = new AmbariJwtAuthenticationFilter(null, jwtAuthenticationPropertiesProvider, null, eventHandler);
assertFalse(filter.shouldApply(request));
verifyAll();
}
@Test
public void testShouldApplyFalseNotEnabled() throws JOSEException {
JwtAuthenticationPropertiesProvider jwtAuthenticationPropertiesProvider = createMock(JwtAuthenticationPropertiesProvider.class);
expect(jwtAuthenticationPropertiesProvider.get()).andReturn(null).anyTimes();
HttpServletRequest request = createMock(HttpServletRequest.class);
AmbariAuthenticationEventHandler eventHandler = createNiceMock(AmbariAuthenticationEventHandler.class);
replayAll();
AmbariJwtAuthenticationFilter filter = new AmbariJwtAuthenticationFilter(null, jwtAuthenticationPropertiesProvider, null, eventHandler);
assertFalse(filter.shouldApply(request));
verify(request);
}
@Test(expected = IllegalArgumentException.class)
public void ensureNonNullEventHandler() {
new AmbariJwtAuthenticationFilter(createNiceMock(AmbariEntryPoint.class), createNiceMock(JwtAuthenticationPropertiesProvider.class), createNiceMock(AmbariJwtAuthenticationProvider.class), null);
}
@Test
public void testDoFilterSuccessful() throws Exception {
Capture<? extends AmbariAuthenticationFilter> captureFilter = newCapture(CaptureType.ALL);
SignedJWT token = getSignedToken();
JwtAuthenticationPropertiesProvider jwtAuthenticationPropertiesProvider = createMock(JwtAuthenticationPropertiesProvider.class);
expect(jwtAuthenticationPropertiesProvider.get()).andReturn(createTestProperties()).anyTimes();
Configuration configuration = createNiceMock(Configuration.class);
expect(configuration.getMaxAuthenticationFailures()).andReturn(10).anyTimes();
HttpServletRequest request = createMock(HttpServletRequest.class);
HttpServletResponse response = createMock(HttpServletResponse.class);
FilterChain filterChain = createMock(FilterChain.class);
Cookie cookie = createMock(Cookie.class);
expect(cookie.getName()).andReturn("non-default").once();
expect(cookie.getValue()).andReturn(token.serialize()).once();
expect(request.getCookies()).andReturn(new Cookie[]{cookie}).once();
UserAuthenticationEntity userAuthenticationEntity = createMock(UserAuthenticationEntity.class);
expect(userAuthenticationEntity.getAuthenticationType()).andReturn(UserAuthenticationType.JWT).anyTimes();
expect(userAuthenticationEntity.getAuthenticationKey()).andReturn("").anyTimes();
UserEntity userEntity = createMock(UserEntity.class);
expect(userEntity.getAuthenticationEntities()).andReturn(Collections.singletonList(userAuthenticationEntity)).atLeastOnce();
User user = createMock(User.class);
Users users = createMock(Users.class);
expect(users.getUserEntity("test-user")).andReturn(userEntity).once();
expect(users.getUser(userEntity)).andReturn(user).once();
expect(users.getUserAuthorities(userEntity)).andReturn(Collections.emptyList()).once();
users.validateLogin(userEntity, "test-user");
expectLastCall().once();
AmbariAuthenticationEventHandler eventHandler = createNiceMock(AmbariAuthenticationEventHandler.class);
eventHandler.beforeAttemptAuthentication(capture(captureFilter), eq(request), eq(response));
expectLastCall().once();
eventHandler.onSuccessfulAuthentication(capture(captureFilter), eq(request), eq(response), anyObject(Authentication.class));
expectLastCall().once();
filterChain.doFilter(request, response);
expectLastCall().once();
AuthenticationEntryPoint entryPoint = createNiceMock(AmbariEntryPoint.class);
replayAll();
AmbariJwtAuthenticationProvider provider = new AmbariJwtAuthenticationProvider(users, configuration);
AmbariJwtAuthenticationFilter filter = new AmbariJwtAuthenticationFilter(entryPoint, jwtAuthenticationPropertiesProvider, provider, eventHandler);
filter.doFilter(request, response, filterChain);
verifyAll();
List<? extends AmbariAuthenticationFilter> capturedFilters = captureFilter.getValues();
for (AmbariAuthenticationFilter capturedFiltered : capturedFilters) {
assertSame(filter, capturedFiltered);
}
}
@Test
public void testDoFilterUnsuccessful() throws Exception {
Capture<? extends AmbariAuthenticationFilter> captureFilter = newCapture(CaptureType.ALL);
SignedJWT token = getSignedToken();
Configuration configuration = createMock(Configuration.class);
JwtAuthenticationPropertiesProvider jwtAuthenticationPropertiesProvider = createMock(JwtAuthenticationPropertiesProvider.class);
expect(jwtAuthenticationPropertiesProvider.get()).andReturn(createTestProperties()).anyTimes();
HttpServletRequest request = createMock(HttpServletRequest.class);
HttpServletResponse response = createMock(HttpServletResponse.class);
FilterChain filterChain = createMock(FilterChain.class);
Cookie cookie = createMock(Cookie.class);
expect(cookie.getName()).andReturn("non-default").once();
expect(cookie.getValue()).andReturn(token.serialize()).once();
expect(request.getCookies()).andReturn(new Cookie[]{cookie}).once();
Users users = createMock(Users.class);
expect(users.getUserEntity("test-user")).andReturn(null).once();
AmbariAuthenticationEventHandler eventHandler = createNiceMock(AmbariAuthenticationEventHandler.class);
eventHandler.beforeAttemptAuthentication(capture(captureFilter), eq(request), eq(response));
expectLastCall().once();
eventHandler.onUnsuccessfulAuthentication(capture(captureFilter), eq(request), eq(response), anyObject(AmbariAuthenticationException.class));
expectLastCall().once();
AuthenticationEntryPoint entryPoint = createNiceMock(AmbariEntryPoint.class);
entryPoint.commence(eq(request), eq(response), anyObject(AmbariAuthenticationException.class));
expectLastCall().once();
replayAll();
AmbariJwtAuthenticationProvider provider = new AmbariJwtAuthenticationProvider(users, configuration);
AmbariJwtAuthenticationFilter filter = new AmbariJwtAuthenticationFilter(entryPoint, jwtAuthenticationPropertiesProvider, provider, eventHandler);
filter.doFilter(request, response, filterChain);
verifyAll();
List<? extends AmbariAuthenticationFilter> capturedFilters = captureFilter.getValues();
for (AmbariAuthenticationFilter capturedFiltered : capturedFilters) {
assertSame(filter, capturedFiltered);
}
}
}
|
|
/*
* Copyright (C) 2016 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.exoplayer2.upstream;
import android.support.annotation.IntDef;
import android.text.TextUtils;
import com.google.android.exoplayer2.util.Predicate;
import com.google.android.exoplayer2.util.Util;
import java.io.IOException;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* An HTTP {@link DataSource}.
*/
public interface HttpDataSource extends DataSource {
/**
* A factory for {@link HttpDataSource} instances.
*/
interface Factory extends DataSource.Factory {
@Override
HttpDataSource createDataSource();
/**
* Gets the default request properties used by all {@link HttpDataSource}s created by the
* factory. Changes to the properties will be reflected in any future requests made by
* {@link HttpDataSource}s created by the factory.
*
* @return The default request properties of the factory.
*/
RequestProperties getDefaultRequestProperties();
/**
* Sets a default request header for {@link HttpDataSource} instances created by the factory.
*
* @deprecated Use {@link #getDefaultRequestProperties} instead.
* @param name The name of the header field.
* @param value The value of the field.
*/
@Deprecated
void setDefaultRequestProperty(String name, String value);
/**
* Clears a default request header for {@link HttpDataSource} instances created by the factory.
*
* @deprecated Use {@link #getDefaultRequestProperties} instead.
* @param name The name of the header field.
*/
@Deprecated
void clearDefaultRequestProperty(String name);
/**
* Clears all default request headers for all {@link HttpDataSource} instances created by the
* factory.
*
* @deprecated Use {@link #getDefaultRequestProperties} instead.
*/
@Deprecated
void clearAllDefaultRequestProperties();
}
/**
* Stores HTTP request properties (aka HTTP headers) and provides methods to modify the headers
* in a thread safe way to avoid the potential of creating snapshots of an inconsistent or
* unintended state.
*/
final class RequestProperties {
private final Map<String, String> requestProperties;
private Map<String, String> requestPropertiesSnapshot;
public RequestProperties() {
requestProperties = new HashMap<>();
}
/**
* Sets the specified property {@code value} for the specified {@code name}. If a property for
* this name previously existed, the old value is replaced by the specified value.
*
* @param name The name of the request property.
* @param value The value of the request property.
*/
public synchronized void set(String name, String value) {
requestPropertiesSnapshot = null;
requestProperties.put(name, value);
}
/**
* Sets the keys and values contained in the map. If a property previously existed, the old
* value is replaced by the specified value. If a property previously existed and is not in the
* map, the property is left unchanged.
*
* @param properties The request properties.
*/
public synchronized void set(Map<String, String> properties) {
requestPropertiesSnapshot = null;
requestProperties.putAll(properties);
}
/**
* Removes all properties previously existing and sets the keys and values of the map.
*
* @param properties The request properties.
*/
public synchronized void clearAndSet(Map<String, String> properties) {
requestPropertiesSnapshot = null;
requestProperties.clear();
requestProperties.putAll(properties);
}
/**
* Removes a request property by name.
*
* @param name The name of the request property to remove.
*/
public synchronized void remove(String name) {
requestPropertiesSnapshot = null;
requestProperties.remove(name);
}
/**
* Clears all request properties.
*/
public synchronized void clear() {
requestPropertiesSnapshot = null;
requestProperties.clear();
}
/**
* Gets a snapshot of the request properties.
*
* @return A snapshot of the request properties.
*/
public synchronized Map<String, String> getSnapshot() {
if (requestPropertiesSnapshot == null) {
requestPropertiesSnapshot = Collections.unmodifiableMap(new HashMap<>(requestProperties));
}
return requestPropertiesSnapshot;
}
}
/**
* Base implementation of {@link Factory} that sets default request properties.
*/
abstract class BaseFactory implements Factory {
private final RequestProperties defaultRequestProperties;
public BaseFactory() {
defaultRequestProperties = new RequestProperties();
}
@Override
public final HttpDataSource createDataSource() {
return createDataSourceInternal(defaultRequestProperties);
}
@Override
public final RequestProperties getDefaultRequestProperties() {
return defaultRequestProperties;
}
@Deprecated
@Override
public final void setDefaultRequestProperty(String name, String value) {
defaultRequestProperties.set(name, value);
}
@Deprecated
@Override
public final void clearDefaultRequestProperty(String name) {
defaultRequestProperties.remove(name);
}
@Deprecated
@Override
public final void clearAllDefaultRequestProperties() {
defaultRequestProperties.clear();
}
/**
* Called by {@link #createDataSource()} to create a {@link HttpDataSource} instance.
*
* @param defaultRequestProperties The default {@code RequestProperties} to be used by the
* {@link HttpDataSource} instance.
* @return A {@link HttpDataSource} instance.
*/
protected abstract HttpDataSource createDataSourceInternal(RequestProperties
defaultRequestProperties);
}
/**
* A {@link Predicate} that rejects content types often used for pay-walls.
*/
Predicate<String> REJECT_PAYWALL_TYPES = new Predicate<String>() {
@Override
public boolean evaluate(String contentType) {
contentType = Util.toLowerInvariant(contentType);
return !TextUtils.isEmpty(contentType)
&& (!contentType.contains("text") || contentType.contains("text/vtt"))
&& !contentType.contains("html") && !contentType.contains("xml");
}
};
/**
* Thrown when an error is encountered when trying to read from a {@link HttpDataSource}.
*/
class HttpDataSourceException extends IOException {
@Retention(RetentionPolicy.SOURCE)
@IntDef({TYPE_OPEN, TYPE_READ, TYPE_CLOSE})
public @interface Type {}
public static final int TYPE_OPEN = 1;
public static final int TYPE_READ = 2;
public static final int TYPE_CLOSE = 3;
@Type public final int type;
/**
* The {@link DataSpec} associated with the current connection.
*/
public final DataSpec dataSpec;
public HttpDataSourceException(DataSpec dataSpec, @Type int type) {
super();
this.dataSpec = dataSpec;
this.type = type;
}
public HttpDataSourceException(String message, DataSpec dataSpec, @Type int type) {
super(message);
this.dataSpec = dataSpec;
this.type = type;
}
public HttpDataSourceException(IOException cause, DataSpec dataSpec, @Type int type) {
super(cause);
this.dataSpec = dataSpec;
this.type = type;
}
public HttpDataSourceException(String message, IOException cause, DataSpec dataSpec,
@Type int type) {
super(message, cause);
this.dataSpec = dataSpec;
this.type = type;
}
}
/**
* Thrown when the content type is invalid.
*/
final class InvalidContentTypeException extends HttpDataSourceException {
public final String contentType;
public InvalidContentTypeException(String contentType, DataSpec dataSpec) {
super("Invalid content type: " + contentType, dataSpec, TYPE_OPEN);
this.contentType = contentType;
}
}
/**
* Thrown when an attempt to open a connection results in a response code not in the 2xx range.
*/
final class InvalidResponseCodeException extends HttpDataSourceException {
/**
* The response code that was outside of the 2xx range.
*/
public final int responseCode;
/**
* An unmodifiable map of the response header fields and values.
*/
public final Map<String, List<String>> headerFields;
public InvalidResponseCodeException(int responseCode, Map<String, List<String>> headerFields,
DataSpec dataSpec) {
super("Response code: " + responseCode, dataSpec, TYPE_OPEN);
this.responseCode = responseCode;
this.headerFields = headerFields;
}
}
@Override
long open(DataSpec dataSpec) throws HttpDataSourceException;
@Override
void close() throws HttpDataSourceException;
@Override
int read(byte[] buffer, int offset, int readLength) throws HttpDataSourceException;
/**
* Sets the value of a request header. The value will be used for subsequent connections
* established by the source.
*
* @param name The name of the header field.
* @param value The value of the field.
*/
void setRequestProperty(String name, String value);
/**
* Clears the value of a request header. The change will apply to subsequent connections
* established by the source.
*
* @param name The name of the header field.
*/
void clearRequestProperty(String name);
/**
* Clears all request headers that were set by {@link #setRequestProperty(String, String)}.
*/
void clearAllRequestProperties();
@Override
Map<String, List<String>> getResponseHeaders();
}
|
|
/*
* 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.distributed.cache.client;
import java.io.DataInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.IOUtils;
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.annotation.lifecycle.OnEnabled;
import org.apache.nifi.annotation.lifecycle.OnStopped;
import org.apache.nifi.components.PropertyDescriptor;
import org.apache.nifi.controller.AbstractControllerService;
import org.apache.nifi.controller.ConfigurationContext;
import org.apache.nifi.distributed.cache.protocol.ProtocolHandshake;
import org.apache.nifi.distributed.cache.protocol.exception.HandshakeException;
import org.apache.nifi.processor.util.StandardValidators;
import org.apache.nifi.remote.StandardVersionNegotiator;
import org.apache.nifi.remote.VersionNegotiator;
import org.apache.nifi.ssl.SSLContextService;
import org.apache.nifi.ssl.SSLContextService.ClientAuth;
import org.apache.nifi.stream.io.ByteArrayOutputStream;
import org.apache.nifi.stream.io.DataOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Tags({"distributed", "cache", "state", "set", "cluster"})
@SeeAlso(classNames = {"org.apache.nifi.distributed.cache.server.DistributedSetCacheServer", "org.apache.nifi.ssl.StandardSSLContextService"})
@CapabilityDescription("Provides the ability to communicate with a DistributedSetCacheServer. This can be used in order to share a Set "
+ "between nodes in a NiFi cluster")
public class DistributedSetCacheClientService extends AbstractControllerService implements DistributedSetCacheClient {
private static final Logger logger = LoggerFactory.getLogger(DistributedMapCacheClientService.class);
public static final PropertyDescriptor HOSTNAME = new PropertyDescriptor.Builder()
.name("Server Hostname")
.description("The name of the server that is running the DistributedSetCacheServer service")
.required(true)
.addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
.build();
public static final PropertyDescriptor PORT = new PropertyDescriptor.Builder()
.name("Server Port")
.description("The port on the remote server that is to be used when communicating with the DistributedSetCacheServer service")
.required(true)
.addValidator(StandardValidators.PORT_VALIDATOR)
.defaultValue("4557")
.build();
public static final PropertyDescriptor SSL_CONTEXT_SERVICE = new PropertyDescriptor.Builder()
.name("SSL Context Service")
.description("If specified, indicates the SSL Context Service that is used to communicate with the "
+ "remote server. If not specified, communications will not be encrypted")
.required(false)
.identifiesControllerService(SSLContextService.class)
.build();
public static final PropertyDescriptor COMMUNICATIONS_TIMEOUT = new PropertyDescriptor.Builder()
.name("Communications Timeout")
.description("Specifices how long to wait when communicating with the remote server before determining "
+ "that there is a communications failure if data cannot be sent or received")
.required(true)
.addValidator(StandardValidators.TIME_PERIOD_VALIDATOR)
.defaultValue("30 secs")
.build();
private final BlockingQueue<CommsSession> queue = new LinkedBlockingQueue<>();
private volatile ConfigurationContext configContext;
private volatile boolean closed = false;
@Override
protected List<PropertyDescriptor> getSupportedPropertyDescriptors() {
final List<PropertyDescriptor> descriptors = new ArrayList<>();
descriptors.add(HOSTNAME);
descriptors.add(PORT);
descriptors.add(SSL_CONTEXT_SERVICE);
descriptors.add(COMMUNICATIONS_TIMEOUT);
return descriptors;
}
@OnEnabled
public void onConfigured(final ConfigurationContext context) {
this.configContext = context;
}
@OnStopped
public void onStopped() throws IOException {
close();
}
public CommsSession createCommsSession(final ConfigurationContext context) throws IOException {
final String hostname = context.getProperty(HOSTNAME).getValue();
final int port = context.getProperty(PORT).asInteger();
final int timeoutMillis = context.getProperty(COMMUNICATIONS_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue();
final SSLContextService sslContextService = context.getProperty(SSL_CONTEXT_SERVICE).asControllerService(SSLContextService.class);
final CommsSession commsSession;
if (sslContextService == null) {
commsSession = new StandardCommsSession(hostname, port, timeoutMillis);
} else {
commsSession = new SSLCommsSession(sslContextService.createSSLContext(ClientAuth.REQUIRED), hostname, port, timeoutMillis);
}
commsSession.setTimeout(timeoutMillis, TimeUnit.MILLISECONDS);
return commsSession;
}
private CommsSession leaseCommsSession() throws IOException {
CommsSession session = queue.poll();
if (session != null && !session.isClosed()) {
return session;
}
session = createCommsSession(configContext);
final VersionNegotiator versionNegotiator = new StandardVersionNegotiator(1);
try {
ProtocolHandshake.initiateHandshake(session.getInputStream(), session.getOutputStream(), versionNegotiator);
session.setProtocolVersion(versionNegotiator.getVersion());
} catch (final HandshakeException e) {
IOUtils.closeQuietly(session);
throw new IOException(e);
}
return session;
}
@Override
public <T> boolean addIfAbsent(final T value, final Serializer<T> serializer) throws IOException {
return invokeRemoteBoolean("addIfAbsent", value, serializer);
}
@Override
public <T> boolean contains(final T value, final Serializer<T> serializer) throws IOException {
return invokeRemoteBoolean("contains", value, serializer);
}
@Override
public <T> boolean remove(final T value, final Serializer<T> serializer) throws IOException {
return invokeRemoteBoolean("remove", value, serializer);
}
@Override
public void close() throws IOException {
this.closed = true;
CommsSession commsSession;
while ((commsSession = queue.poll()) != null) {
try (final DataOutputStream dos = new DataOutputStream(commsSession.getOutputStream())) {
dos.writeUTF("close");
dos.flush();
} catch (final IOException e) {
}
IOUtils.closeQuietly(commsSession);
}
if (logger.isDebugEnabled() && getIdentifier() != null) {
logger.debug("Closed {}", new Object[]{getIdentifier()});
}
}
@Override
protected void finalize() throws Throwable {
if (!closed) {
close();
}
logger.debug("Finalize called");
}
private <T> boolean invokeRemoteBoolean(final String methodName, final T value, final Serializer<T> serializer) throws IOException {
if (closed) {
throw new IllegalStateException("Client is closed");
}
final CommsSession session = leaseCommsSession();
boolean tryToRequeue = true;
try {
final DataOutputStream dos = new DataOutputStream(session.getOutputStream());
dos.writeUTF(methodName);
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
serializer.serialize(value, baos);
dos.writeInt(baos.size());
baos.writeTo(dos);
dos.flush();
final DataInputStream dis = new DataInputStream(session.getInputStream());
return dis.readBoolean();
} catch (final IOException ioe) {
tryToRequeue = false;
throw ioe;
} finally {
if (tryToRequeue == true && this.closed == false) {
queue.offer(session);
} else {
IOUtils.closeQuietly(session);
}
}
}
}
|
|
/*
* 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.android.systemui.qs;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Animatable;
import android.graphics.Bitmap;
import android.graphics.drawable.AnimatedVectorDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RemoteViews;
import com.android.systemui.qs.QSTile.State;
import com.android.systemui.statusbar.policy.BluetoothController;
import com.android.systemui.statusbar.policy.CastController;
import com.android.systemui.statusbar.policy.FlashlightController;
import com.android.systemui.statusbar.policy.HotspotController;
import com.android.systemui.statusbar.policy.KeyguardMonitor;
import com.android.systemui.statusbar.policy.Listenable;
import com.android.systemui.statusbar.policy.LocationController;
import com.android.systemui.statusbar.policy.NetworkController;
import com.android.systemui.statusbar.policy.RotationLockController;
import com.android.systemui.statusbar.policy.ZenModeController;
import cyanogenmod.app.StatusBarPanelCustomTile;
import java.util.Collection;
import java.util.Objects;
/**
* Base quick-settings tile, extend this to create a new tile.
*
* State management done on a looper provided by the host. Tiles should update state in
* handleUpdateState. Callbacks affecting state should use refreshState to trigger another
* state update pass on tile looper.
*/
public abstract class QSTile<TState extends State> implements Listenable {
protected final String TAG = "QSTile." + getClass().getSimpleName();
protected static final boolean DEBUG = Log.isLoggable("QSTile", Log.DEBUG);
protected final Host mHost;
protected final Context mContext;
protected final H mHandler;
protected final Handler mUiHandler = new Handler(Looper.getMainLooper());
private Callback mCallback;
protected TState mState = newTileState();
private TState mTmpState = newTileState();
private boolean mAnnounceNextStateChange;
abstract protected TState newTileState();
abstract protected void handleClick();
abstract protected void handleUpdateState(TState state, Object arg);
/**
* Declare the category of this tile.
*
* Categories are defined in {@link com.android.internal.logging.MetricsLogger}
* or if there is no relevant existing category you may define one in
* {@link com.android.systemui.qs.QSTile}.
*/
abstract public int getMetricsCategory();
protected QSTile(Host host) {
mHost = host;
mContext = host.getContext();
mHandler = new H(host.getLooper());
}
public boolean hasDualTargetsDetails() {
return false;
}
public Host getHost() {
return mHost;
}
public QSTileView createTileView(Context context) {
return new QSTileView(context);
}
public DetailAdapter getDetailAdapter() {
return null; // optional
}
public interface DetailAdapter {
int getTitle();
Boolean getToggleState();
View createDetailView(Context context, View convertView, ViewGroup parent);
Intent getSettingsIntent();
StatusBarPanelCustomTile getCustomTile();
void setToggleState(boolean state);
int getMetricsCategory();
}
// safe to call from any thread
public void setCallback(Callback callback) {
mHandler.obtainMessage(H.SET_CALLBACK, callback).sendToTarget();
}
public void click() {
mHandler.sendEmptyMessage(H.CLICK);
}
public void secondaryClick() {
mHandler.sendEmptyMessage(H.SECONDARY_CLICK);
}
public void longClick() {
mHandler.sendEmptyMessage(H.LONG_CLICK);
}
public void showDetail(boolean show) {
mHandler.obtainMessage(H.SHOW_DETAIL, show ? 1 : 0, 0).sendToTarget();
}
protected final void refreshState() {
refreshState(null);
}
protected final void refreshState(Object arg) {
mHandler.obtainMessage(H.REFRESH_STATE, arg).sendToTarget();
}
public final void clearState() {
mHandler.sendEmptyMessage(H.CLEAR_STATE);
}
public void userSwitch(int newUserId) {
mHandler.obtainMessage(H.USER_SWITCH, newUserId, 0).sendToTarget();
}
public void fireToggleStateChanged(boolean state) {
mHandler.obtainMessage(H.TOGGLE_STATE_CHANGED, state ? 1 : 0, 0).sendToTarget();
}
public void fireScanStateChanged(boolean state) {
mHandler.obtainMessage(H.SCAN_STATE_CHANGED, state ? 1 : 0, 0).sendToTarget();
}
public void destroy() {
mHandler.sendEmptyMessage(H.DESTROY);
}
public TState getState() {
return mState;
}
public void setDetailListening(boolean listening) {
// optional
}
// call only on tile worker looper
private void handleSetCallback(Callback callback) {
mCallback = callback;
handleRefreshState(null);
}
protected void handleSecondaryClick() {
// optional
}
protected void handleLongClick() {
// optional
}
protected void handleClearState() {
mTmpState = newTileState();
mState = newTileState();
}
protected void handleRefreshState(Object arg) {
handleUpdateState(mTmpState, arg);
final boolean changed = mTmpState.copyTo(mState);
if (changed) {
handleStateChanged();
}
}
private void handleStateChanged() {
boolean delayAnnouncement = shouldAnnouncementBeDelayed();
if (mCallback != null) {
mCallback.onStateChanged(mState);
if (mAnnounceNextStateChange && !delayAnnouncement) {
String announcement = composeChangeAnnouncement();
if (announcement != null) {
mCallback.onAnnouncementRequested(announcement);
}
}
}
mAnnounceNextStateChange = mAnnounceNextStateChange && delayAnnouncement;
}
protected boolean shouldAnnouncementBeDelayed() {
return false;
}
protected String composeChangeAnnouncement() {
return null;
}
private void handleShowDetail(boolean show) {
if (mCallback != null) {
mCallback.onShowDetail(show);
}
}
private void handleToggleStateChanged(boolean state) {
if (mCallback != null) {
mCallback.onToggleStateChanged(state);
}
}
private void handleScanStateChanged(boolean state) {
if (mCallback != null) {
mCallback.onScanStateChanged(state);
}
}
protected void handleUserSwitch(int newUserId) {
handleRefreshState(null);
}
protected void handleDestroy() {
setListening(false);
mCallback = null;
}
protected final class H extends Handler {
private static final int SET_CALLBACK = 1;
private static final int CLICK = 2;
private static final int SECONDARY_CLICK = 3;
private static final int LONG_CLICK = 4;
private static final int REFRESH_STATE = 5;
private static final int SHOW_DETAIL = 6;
private static final int USER_SWITCH = 7;
private static final int TOGGLE_STATE_CHANGED = 8;
private static final int SCAN_STATE_CHANGED = 9;
private static final int DESTROY = 10;
private static final int CLEAR_STATE = 11;
private H(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
String name = null;
try {
if (msg.what == SET_CALLBACK) {
name = "handleSetCallback";
handleSetCallback((QSTile.Callback)msg.obj);
} else if (msg.what == CLICK) {
name = "handleClick";
mAnnounceNextStateChange = true;
handleClick();
} else if (msg.what == SECONDARY_CLICK) {
name = "handleSecondaryClick";
handleSecondaryClick();
} else if (msg.what == LONG_CLICK) {
name = "handleLongClick";
handleLongClick();
} else if (msg.what == REFRESH_STATE) {
name = "handleRefreshState";
handleRefreshState(msg.obj);
} else if (msg.what == SHOW_DETAIL) {
name = "handleShowDetail";
handleShowDetail(msg.arg1 != 0);
} else if (msg.what == USER_SWITCH) {
name = "handleUserSwitch";
handleUserSwitch(msg.arg1);
} else if (msg.what == TOGGLE_STATE_CHANGED) {
name = "handleToggleStateChanged";
handleToggleStateChanged(msg.arg1 != 0);
} else if (msg.what == SCAN_STATE_CHANGED) {
name = "handleScanStateChanged";
handleScanStateChanged(msg.arg1 != 0);
} else if (msg.what == DESTROY) {
name = "handleDestroy";
handleDestroy();
} else if (msg.what == CLEAR_STATE) {
name = "handleClearState";
handleClearState();
} else {
throw new IllegalArgumentException("Unknown msg: " + msg.what);
}
} catch (Throwable t) {
final String error = "Error in " + name;
Log.w(TAG, error, t);
mHost.warn(error, t);
}
}
}
public interface Callback {
void onStateChanged(State state);
void onShowDetail(boolean show);
void onToggleStateChanged(boolean state);
void onScanStateChanged(boolean state);
void onAnnouncementRequested(CharSequence announcement);
}
public interface Host {
void removeCustomTile(StatusBarPanelCustomTile customTile);
void startActivityDismissingKeyguard(Intent intent);
void startActivityDismissingKeyguard(PendingIntent intent);
void warn(String message, Throwable t);
void collapsePanels();
RemoteViews.OnClickHandler getOnClickHandler();
Looper getLooper();
Context getContext();
Collection<QSTile<?>> getTiles();
void setCallback(Callback callback);
BluetoothController getBluetoothController();
LocationController getLocationController();
RotationLockController getRotationLockController();
NetworkController getNetworkController();
ZenModeController getZenModeController();
HotspotController getHotspotController();
CastController getCastController();
FlashlightController getFlashlightController();
KeyguardMonitor getKeyguardMonitor();
boolean isEditing();
void setEditing(boolean editing);
void resetTiles();
void goToSettingsPage();
public interface Callback {
void onTilesChanged();
void setEditing(boolean editing);
boolean isEditing();
void goToSettingsPage();
void resetTiles();
}
}
public static abstract class Icon {
abstract public Drawable getDrawable(Context context);
@Override
public int hashCode() {
return Icon.class.hashCode();
}
}
protected class ExternalIcon extends AnimationIcon {
private Context mPackageContext;
private String mPkg;
private int mResId;
public ExternalIcon(String pkg, int resId) {
super(resId);
mPkg = pkg;
mResId = resId;
}
@Override
public Drawable getDrawable(Context context) {
// Get the drawable from the package context
Drawable d = null;
try {
d = super.getDrawable(getPackageContext());
} catch (Throwable t) {
Log.w(TAG, "Error creating package context" + mPkg + " id=" + mResId, t);
}
return d;
}
private Context getPackageContext() {
if (mPackageContext == null) {
try {
mPackageContext = mContext.createPackageContext(mPkg, 0);
} catch (Throwable t) {
Log.w(TAG, "Error creating package context" + mPkg, t);
return null;
}
}
return mPackageContext;
}
}
public static class ResourceIcon extends Icon {
private static final SparseArray<Icon> ICONS = new SparseArray<Icon>();
protected final int mResId;
private ResourceIcon(int resId) {
mResId = resId;
}
public static Icon get(int resId) {
Icon icon = ICONS.get(resId);
if (icon == null) {
icon = new ResourceIcon(resId);
ICONS.put(resId, icon);
}
return icon;
}
@Override
public Drawable getDrawable(Context context) {
Drawable d = context.getDrawable(mResId);
if (d instanceof Animatable) {
((Animatable) d).start();
}
return d;
}
@Override
public boolean equals(Object o) {
return o instanceof ResourceIcon && ((ResourceIcon) o).mResId == mResId;
}
@Override
public String toString() {
return String.format("ResourceIcon[resId=0x%08x]", mResId);
}
}
protected class ExternalBitmapIcon extends Icon {
private Bitmap mBitmap;
public ExternalBitmapIcon(Bitmap bitmap) {
mBitmap = bitmap;
}
@Override
public Drawable getDrawable(Context context) {
// This is gross
BitmapDrawable bitmapDrawable = new BitmapDrawable(context.getResources(), mBitmap);
return bitmapDrawable;
}
}
protected class AnimationIcon extends ResourceIcon {
private boolean mAllowAnimation;
public AnimationIcon(int resId) {
super(resId);
}
public void setAllowAnimation(boolean allowAnimation) {
mAllowAnimation = allowAnimation;
}
@Override
public Drawable getDrawable(Context context) {
// workaround: get a clean state for every new AVD
final Drawable d = super.getDrawable(context).getConstantState().newDrawable();
if (d instanceof AnimatedVectorDrawable) {
((AnimatedVectorDrawable)d).start();
if (mAllowAnimation) {
mAllowAnimation = false;
} else {
((AnimatedVectorDrawable)d).stop(); // skip directly to end state
}
}
return d;
}
}
protected enum UserBoolean {
USER_TRUE(true, true),
USER_FALSE(true, false),
BACKGROUND_TRUE(false, true),
BACKGROUND_FALSE(false, false);
public final boolean value;
public final boolean userInitiated;
private UserBoolean(boolean userInitiated, boolean value) {
this.value = value;
this.userInitiated = userInitiated;
}
}
public static class State {
public boolean visible;
public boolean enabled = true;
public Icon icon;
public String label;
public String contentDescription;
public String dualLabelContentDescription;
public boolean autoMirrorDrawable = true;
public boolean copyTo(State other) {
if (other == null) throw new IllegalArgumentException();
if (!other.getClass().equals(getClass())) throw new IllegalArgumentException();
final boolean changed = other.visible != visible
|| !Objects.equals(other.enabled, enabled)
|| !Objects.equals(other.icon, icon)
|| !Objects.equals(other.label, label)
|| !Objects.equals(other.contentDescription, contentDescription)
|| !Objects.equals(other.autoMirrorDrawable, autoMirrorDrawable)
|| !Objects.equals(other.dualLabelContentDescription,
dualLabelContentDescription);
other.visible = visible;
other.enabled = enabled;
other.icon = icon;
other.label = label;
other.contentDescription = contentDescription;
other.dualLabelContentDescription = dualLabelContentDescription;
other.autoMirrorDrawable = autoMirrorDrawable;
return changed;
}
@Override
public String toString() {
return toStringBuilder().toString();
}
protected StringBuilder toStringBuilder() {
final StringBuilder sb = new StringBuilder(getClass().getSimpleName()).append('[');
sb.append("visible=").append(visible);
sb.append(",enabled=").append(enabled);
sb.append(",icon=").append(icon);
sb.append(",label=").append(label);
sb.append(",contentDescription=").append(contentDescription);
sb.append(",dualLabelContentDescription=").append(dualLabelContentDescription);
sb.append(",autoMirrorDrawable=").append(autoMirrorDrawable);
return sb.append(']');
}
}
public static class BooleanState extends State {
public boolean value;
@Override
public boolean copyTo(State other) {
final BooleanState o = (BooleanState) other;
final boolean changed = super.copyTo(other) || o.value != value;
o.value = value;
return changed;
}
@Override
protected StringBuilder toStringBuilder() {
final StringBuilder rt = super.toStringBuilder();
rt.insert(rt.length() - 1, ",value=" + value);
return rt;
}
}
public static final class SignalState extends State {
public boolean enabled;
public boolean connected;
public boolean activityIn;
public boolean activityOut;
public int overlayIconId;
public boolean filter;
public boolean isOverlayIconWide;
@Override
public boolean copyTo(State other) {
final SignalState o = (SignalState) other;
final boolean changed = o.enabled != enabled
|| o.connected != connected || o.activityIn != activityIn
|| o.activityOut != activityOut
|| o.overlayIconId != overlayIconId
|| o.isOverlayIconWide != isOverlayIconWide;
o.enabled = enabled;
o.connected = connected;
o.activityIn = activityIn;
o.activityOut = activityOut;
o.overlayIconId = overlayIconId;
o.filter = filter;
o.isOverlayIconWide = isOverlayIconWide;
return super.copyTo(other) || changed;
}
@Override
protected StringBuilder toStringBuilder() {
final StringBuilder rt = super.toStringBuilder();
rt.insert(rt.length() - 1, ",enabled=" + enabled);
rt.insert(rt.length() - 1, ",connected=" + connected);
rt.insert(rt.length() - 1, ",activityIn=" + activityIn);
rt.insert(rt.length() - 1, ",activityOut=" + activityOut);
rt.insert(rt.length() - 1, ",overlayIconId=" + overlayIconId);
rt.insert(rt.length() - 1, ",filter=" + filter);
rt.insert(rt.length() - 1, ",wideOverlayIcon=" + isOverlayIconWide);
return rt;
}
}
}
|
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.cassandra.cql3;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import com.google.common.base.Objects;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import org.junit.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.datastax.driver.core.*;
import com.datastax.driver.core.ResultSet;
import org.apache.cassandra.SchemaLoader;
import org.apache.cassandra.concurrent.ScheduledExecutors;
import org.apache.cassandra.config.CFMetaData;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.config.Schema;
import org.apache.cassandra.cql3.functions.FunctionName;
import org.apache.cassandra.cql3.functions.ThreadAwareSecurityManager;
import org.apache.cassandra.cql3.statements.ParsedStatement;
import org.apache.cassandra.db.*;
import org.apache.cassandra.db.commitlog.CommitLog;
import org.apache.cassandra.db.marshal.*;
import org.apache.cassandra.db.marshal.TupleType;
import org.apache.cassandra.dht.Murmur3Partitioner;
import org.apache.cassandra.exceptions.ConfigurationException;
import org.apache.cassandra.exceptions.SyntaxException;
import org.apache.cassandra.io.util.FileUtils;
import org.apache.cassandra.serializers.TypeSerializer;
import org.apache.cassandra.service.ClientState;
import org.apache.cassandra.service.QueryState;
import org.apache.cassandra.service.StorageService;
import org.apache.cassandra.transport.Event;
import org.apache.cassandra.transport.Server;
import org.apache.cassandra.transport.messages.ResultMessage;
import org.apache.cassandra.utils.ByteBufferUtil;
import static junit.framework.Assert.assertNotNull;
/**
* Base class for CQL tests.
*/
public abstract class CQLTester
{
protected static final Logger logger = LoggerFactory.getLogger(CQLTester.class);
public static final String KEYSPACE = "cql_test_keyspace";
public static final String KEYSPACE_PER_TEST = "cql_test_keyspace_alt";
protected static final boolean USE_PREPARED_VALUES = Boolean.valueOf(System.getProperty("cassandra.test.use_prepared", "true"));
protected static final boolean REUSE_PREPARED = Boolean.valueOf(System.getProperty("cassandra.test.reuse_prepared", "true"));
protected static final long ROW_CACHE_SIZE_IN_MB = Integer.valueOf(System.getProperty("cassandra.test.row_cache_size_in_mb", "0"));
private static final AtomicInteger seqNumber = new AtomicInteger();
private static org.apache.cassandra.transport.Server server;
protected static final int nativePort;
protected static final InetAddress nativeAddr;
private static final Map<Integer, Cluster> clusters = new HashMap<>();
private static final Map<Integer, Session> sessions = new HashMap<>();
private static boolean isServerPrepared = false;
public static final List<Integer> PROTOCOL_VERSIONS;
static
{
// The latest versions might not be supported yet by the java driver
ImmutableList.Builder<Integer> builder = ImmutableList.builder();
for (int version = Server.MIN_SUPPORTED_VERSION; version <= Server.CURRENT_VERSION; version++)
{
try
{
ProtocolVersion.fromInt(version);
builder.add(version);
}
catch (IllegalArgumentException e)
{
break;
}
}
PROTOCOL_VERSIONS = builder.build();
// Once per-JVM is enough
prepareServer();
nativeAddr = InetAddress.getLoopbackAddress();
try
{
try (ServerSocket serverSocket = new ServerSocket(0))
{
nativePort = serverSocket.getLocalPort();
}
Thread.sleep(250);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
public static ResultMessage lastSchemaChangeResult;
private List<String> tables = new ArrayList<>();
private List<String> types = new ArrayList<>();
private List<String> functions = new ArrayList<>();
private List<String> aggregates = new ArrayList<>();
// We don't use USE_PREPARED_VALUES in the code below so some test can foce value preparation (if the result
// is not expected to be the same without preparation)
private boolean usePrepared = USE_PREPARED_VALUES;
private static boolean reusePrepared = REUSE_PREPARED;
public static void prepareServer()
{
if (isServerPrepared)
return;
// Cleanup first
try
{
cleanupAndLeaveDirs();
}
catch (IOException e)
{
logger.error("Failed to cleanup and recreate directories.");
throw new RuntimeException(e);
}
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler()
{
public void uncaughtException(Thread t, Throwable e)
{
logger.error("Fatal exception in thread " + t, e);
}
});
ThreadAwareSecurityManager.install();
Keyspace.setInitialized();
isServerPrepared = true;
}
public static void cleanupAndLeaveDirs() throws IOException
{
// We need to stop and unmap all CLS instances prior to cleanup() or we'll get failures on Windows.
CommitLog.instance.stopUnsafe(true);
mkdirs();
cleanup();
mkdirs();
CommitLog.instance.restartUnsafe();
}
public static void cleanup()
{
// clean up commitlog
String[] directoryNames = { DatabaseDescriptor.getCommitLogLocation(), };
for (String dirName : directoryNames)
{
File dir = new File(dirName);
if (!dir.exists())
throw new RuntimeException("No such directory: " + dir.getAbsolutePath());
FileUtils.deleteRecursive(dir);
}
cleanupSavedCaches();
// clean up data directory which are stored as data directory/keyspace/data files
for (String dirName : DatabaseDescriptor.getAllDataFileLocations())
{
File dir = new File(dirName);
if (!dir.exists())
throw new RuntimeException("No such directory: " + dir.getAbsolutePath());
FileUtils.deleteRecursive(dir);
}
}
public static void mkdirs()
{
DatabaseDescriptor.createAllDirectories();
}
public static void cleanupSavedCaches()
{
File cachesDir = new File(DatabaseDescriptor.getSavedCachesLocation());
if (!cachesDir.exists() || !cachesDir.isDirectory())
return;
FileUtils.delete(cachesDir.listFiles());
}
@BeforeClass
public static void setUpClass()
{
if (ROW_CACHE_SIZE_IN_MB > 0)
DatabaseDescriptor.setRowCacheSizeInMB(ROW_CACHE_SIZE_IN_MB);
StorageService.instance.setPartitionerUnsafe(Murmur3Partitioner.instance);
}
@AfterClass
public static void tearDownClass()
{
for (Session sess : sessions.values())
sess.close();
for (Cluster cl : clusters.values())
cl.close();
if (server != null)
server.stop();
// We use queryInternal for CQLTester so prepared statement will populate our internal cache (if reusePrepared is used; otherwise prepared
// statements are not cached but re-prepared every time). So we clear the cache between test files to avoid accumulating too much.
if (reusePrepared)
QueryProcessor.clearInternalStatementsCache();
}
@Before
public void beforeTest() throws Throwable
{
schemaChange(String.format("CREATE KEYSPACE IF NOT EXISTS %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1'}", KEYSPACE));
schemaChange(String.format("CREATE KEYSPACE IF NOT EXISTS %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1'}", KEYSPACE_PER_TEST));
}
@After
public void afterTest() throws Throwable
{
dropPerTestKeyspace();
// Restore standard behavior in case it was changed
usePrepared = USE_PREPARED_VALUES;
reusePrepared = REUSE_PREPARED;
final List<String> tablesToDrop = copy(tables);
final List<String> typesToDrop = copy(types);
final List<String> functionsToDrop = copy(functions);
final List<String> aggregatesToDrop = copy(aggregates);
tables = null;
types = null;
functions = null;
aggregates = null;
// We want to clean up after the test, but dropping a table is rather long so just do that asynchronously
ScheduledExecutors.optionalTasks.execute(new Runnable()
{
public void run()
{
try
{
for (int i = tablesToDrop.size() - 1; i >= 0; i--)
schemaChange(String.format("DROP TABLE IF EXISTS %s.%s", KEYSPACE, tablesToDrop.get(i)));
for (int i = aggregatesToDrop.size() - 1; i >= 0; i--)
schemaChange(String.format("DROP AGGREGATE IF EXISTS %s", aggregatesToDrop.get(i)));
for (int i = functionsToDrop.size() - 1; i >= 0; i--)
schemaChange(String.format("DROP FUNCTION IF EXISTS %s", functionsToDrop.get(i)));
for (int i = typesToDrop.size() - 1; i >= 0; i--)
schemaChange(String.format("DROP TYPE IF EXISTS %s.%s", KEYSPACE, typesToDrop.get(i)));
// Dropping doesn't delete the sstables. It's not a huge deal but it's cleaner to cleanup after us
// Thas said, we shouldn't delete blindly before the TransactionLogs.SSTableTidier for the table we drop
// have run or they will be unhappy. Since those taks are scheduled on StorageService.tasks and that's
// mono-threaded, just push a task on the queue to find when it's empty. No perfect but good enough.
final CountDownLatch latch = new CountDownLatch(1);
ScheduledExecutors.nonPeriodicTasks.execute(new Runnable()
{
public void run()
{
latch.countDown();
}
});
latch.await(2, TimeUnit.SECONDS);
removeAllSSTables(KEYSPACE, tablesToDrop);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
});
}
// lazy initialization for all tests that require Java Driver
protected static void requireNetwork() throws ConfigurationException
{
if (server != null)
return;
SystemKeyspace.finishStartup();
StorageService.instance.initServer();
SchemaLoader.startGossiper();
server = new Server.Builder().withHost(nativeAddr).withPort(nativePort).build();
server.start();
for (int version : PROTOCOL_VERSIONS)
{
if (clusters.containsKey(version))
continue;
Cluster cluster = Cluster.builder()
.addContactPoints(nativeAddr)
.withClusterName("Test Cluster")
.withPort(nativePort)
.withProtocolVersion(ProtocolVersion.fromInt(version))
.build();
clusters.put(version, cluster);
sessions.put(version, cluster.connect());
logger.info("Started Java Driver instance for protocol version {}", version);
}
}
protected void dropPerTestKeyspace() throws Throwable
{
execute(String.format("DROP KEYSPACE IF EXISTS %s", KEYSPACE_PER_TEST));
}
/**
* Returns a copy of the specified list.
* @return a copy of the specified list.
*/
private static List<String> copy(List<String> list)
{
return list.isEmpty() ? Collections.<String>emptyList() : new ArrayList<>(list);
}
public ColumnFamilyStore getCurrentColumnFamilyStore()
{
String currentTable = currentTable();
return currentTable == null
? null
: Keyspace.open(KEYSPACE).getColumnFamilyStore(currentTable);
}
public void flush(boolean forceFlush)
{
if (forceFlush)
flush();
}
public void flush()
{
ColumnFamilyStore store = getCurrentColumnFamilyStore();
if (store != null)
store.forceBlockingFlush();
}
public void disableCompaction()
{
ColumnFamilyStore store = getCurrentColumnFamilyStore();
store.disableAutoCompaction();
}
public void compact()
{
try
{
String currentTable = currentTable();
if (currentTable != null)
Keyspace.open(KEYSPACE).getColumnFamilyStore(currentTable).forceMajorCompaction();
}
catch (InterruptedException | ExecutionException e)
{
throw new RuntimeException(e);
}
}
public void cleanupCache()
{
String currentTable = currentTable();
if (currentTable != null)
Keyspace.open(KEYSPACE).getColumnFamilyStore(currentTable).cleanupCache();
}
public static FunctionName parseFunctionName(String qualifiedName)
{
int i = qualifiedName.indexOf('.');
return i == -1
? FunctionName.nativeFunction(qualifiedName)
: new FunctionName(qualifiedName.substring(0, i).trim(), qualifiedName.substring(i+1).trim());
}
public static String shortFunctionName(String f)
{
return parseFunctionName(f).name;
}
private static void removeAllSSTables(String ks, List<String> tables)
{
// clean up data directory which are stored as data directory/keyspace/data files
for (File d : Directories.getKSChildDirectories(ks))
{
if (d.exists() && containsAny(d.getName(), tables))
FileUtils.deleteRecursive(d);
}
}
private static boolean containsAny(String filename, List<String> tables)
{
for (int i = 0, m = tables.size(); i < m; i++)
// don't accidentally delete in-use directories with the
// same prefix as a table to delete, i.e. table_1 & table_11
if (filename.contains(tables.get(i) + "-"))
return true;
return false;
}
protected String keyspace()
{
return KEYSPACE;
}
protected String currentTable()
{
if (tables.isEmpty())
return null;
return tables.get(tables.size() - 1);
}
protected ByteBuffer unset()
{
return ByteBufferUtil.UNSET_BYTE_BUFFER;
}
protected void forcePreparedValues()
{
this.usePrepared = true;
}
protected void stopForcingPreparedValues()
{
this.usePrepared = USE_PREPARED_VALUES;
}
protected void disablePreparedReuseForTest()
{
this.reusePrepared = false;
}
protected String createType(String query)
{
String typeName = "type_" + seqNumber.getAndIncrement();
String fullQuery = String.format(query, KEYSPACE + "." + typeName);
types.add(typeName);
logger.info(fullQuery);
schemaChange(fullQuery);
return typeName;
}
protected String createFunction(String keyspace, String argTypes, String query) throws Throwable
{
String functionName = keyspace + ".function_" + seqNumber.getAndIncrement();
createFunctionOverload(functionName, argTypes, query);
return functionName;
}
protected void createFunctionOverload(String functionName, String argTypes, String query) throws Throwable
{
String fullQuery = String.format(query, functionName);
functions.add(functionName + '(' + argTypes + ')');
logger.info(fullQuery);
schemaChange(fullQuery);
}
protected String createAggregate(String keyspace, String argTypes, String query) throws Throwable
{
String aggregateName = keyspace + "." + "aggregate_" + seqNumber.getAndIncrement();
createAggregateOverload(aggregateName, argTypes, query);
return aggregateName;
}
protected void createAggregateOverload(String aggregateName, String argTypes, String query) throws Throwable
{
String fullQuery = String.format(query, aggregateName);
aggregates.add(aggregateName + '(' + argTypes + ')');
logger.info(fullQuery);
schemaChange(fullQuery);
}
protected String createTable(String query)
{
String currentTable = createTableName();
String fullQuery = formatQuery(query);
logger.info(fullQuery);
schemaChange(fullQuery);
return currentTable;
}
protected String createTableName()
{
String currentTable = "table_" + seqNumber.getAndIncrement();
tables.add(currentTable);
return currentTable;
}
protected void createTableMayThrow(String query) throws Throwable
{
String currentTable = "table_" + seqNumber.getAndIncrement();
tables.add(currentTable);
String fullQuery = formatQuery(query);
logger.info(fullQuery);
QueryProcessor.executeOnceInternal(fullQuery);
}
protected void alterTable(String query)
{
String fullQuery = formatQuery(query);
logger.info(fullQuery);
schemaChange(fullQuery);
}
protected void alterTableMayThrow(String query) throws Throwable
{
String fullQuery = formatQuery(query);
logger.info(fullQuery);
QueryProcessor.executeOnceInternal(fullQuery);
}
protected void dropTable(String query)
{
String fullQuery = String.format(query, KEYSPACE + "." + currentTable());
logger.info(fullQuery);
schemaChange(fullQuery);
}
protected void createIndex(String query)
{
String fullQuery = formatQuery(query);
logger.info(fullQuery);
schemaChange(fullQuery);
}
/**
* Index creation is asynchronous, this method searches in the system table IndexInfo
* for the specified index and returns true if it finds it, which indicates the
* index was built. If we haven't found it after 5 seconds we give-up.
*/
protected boolean waitForIndex(String keyspace, String table, String index) throws Throwable
{
long start = System.currentTimeMillis();
boolean indexCreated = false;
while (!indexCreated)
{
Object[][] results = getRows(execute("select index_name from system.\"IndexInfo\" where table_name = ?", keyspace));
for(int i = 0; i < results.length; i++)
{
if (index.equals(results[i][0]))
{
indexCreated = true;
break;
}
}
if (System.currentTimeMillis() - start > 5000)
break;
Thread.sleep(10);
}
return indexCreated;
}
protected void createIndexMayThrow(String query) throws Throwable
{
String fullQuery = formatQuery(query);
logger.info(fullQuery);
QueryProcessor.executeOnceInternal(fullQuery);
}
protected void dropIndex(String query) throws Throwable
{
String fullQuery = String.format(query, KEYSPACE);
logger.info(fullQuery);
schemaChange(fullQuery);
}
protected void assertLastSchemaChange(Event.SchemaChange.Change change, Event.SchemaChange.Target target,
String keyspace, String name,
String... argTypes)
{
Assert.assertTrue(lastSchemaChangeResult instanceof ResultMessage.SchemaChange);
ResultMessage.SchemaChange schemaChange = (ResultMessage.SchemaChange) lastSchemaChangeResult;
Assert.assertSame(change, schemaChange.change.change);
Assert.assertSame(target, schemaChange.change.target);
Assert.assertEquals(keyspace, schemaChange.change.keyspace);
Assert.assertEquals(name, schemaChange.change.name);
Assert.assertEquals(argTypes != null ? Arrays.asList(argTypes) : null, schemaChange.change.argTypes);
}
protected static void schemaChange(String query)
{
try
{
ClientState state = ClientState.forInternalCalls();
state.setKeyspace(SystemKeyspace.NAME);
QueryState queryState = new QueryState(state);
ParsedStatement.Prepared prepared = QueryProcessor.parseStatement(query, queryState);
prepared.statement.validate(state);
QueryOptions options = QueryOptions.forInternalCalls(Collections.<ByteBuffer>emptyList());
lastSchemaChangeResult = prepared.statement.executeInternal(queryState, options);
}
catch (Exception e)
{
throw new RuntimeException("Error setting schema for test (query was: " + query + ")", e);
}
}
protected CFMetaData currentTableMetadata()
{
return Schema.instance.getCFMetaData(KEYSPACE, currentTable());
}
protected com.datastax.driver.core.ResultSet executeNet(int protocolVersion, String query, Object... values) throws Throwable
{
return sessionNet(protocolVersion).execute(formatQuery(query), values);
}
protected Session sessionNet()
{
return sessionNet(PROTOCOL_VERSIONS.get(PROTOCOL_VERSIONS.size() - 1));
}
protected Session sessionNet(int protocolVersion)
{
requireNetwork();
return sessions.get(protocolVersion);
}
private String formatQuery(String query)
{
String currentTable = currentTable();
return currentTable == null ? query : String.format(query, KEYSPACE + "." + currentTable);
}
protected UntypedResultSet execute(String query, Object... values) throws Throwable
{
query = formatQuery(query);
UntypedResultSet rs;
if (usePrepared)
{
if (logger.isDebugEnabled())
logger.debug("Executing: {} with values {}", query, formatAllValues(values));
if (reusePrepared)
{
rs = QueryProcessor.executeInternal(query, transformValues(values));
// If a test uses a "USE ...", then presumably its statements use relative table. In that case, a USE
// change the meaning of the current keyspace, so we don't want a following statement to reuse a previously
// prepared statement at this wouldn't use the right keyspace. To avoid that, we drop the previously
// prepared statement.
if (query.startsWith("USE"))
QueryProcessor.clearInternalStatementsCache();
}
else
{
rs = QueryProcessor.executeOnceInternal(query, transformValues(values));
}
}
else
{
query = replaceValues(query, values);
if (logger.isDebugEnabled())
logger.debug("Executing: {}", query);
rs = QueryProcessor.executeOnceInternal(query);
}
if (rs != null)
{
if (logger.isDebugEnabled())
logger.debug("Got {} rows", rs.size());
}
return rs;
}
protected void assertRowsNet(int protocolVersion, ResultSet result, Object[]... rows)
{
// necessary as we need cluster objects to supply CodecRegistry.
// It's reasonably certain that the network setup has already been done
// by the time we arrive at this point, but adding this check doesn't hurt
requireNetwork();
if (result == null)
{
if (rows.length > 0)
Assert.fail(String.format("No rows returned by query but %d expected", rows.length));
return;
}
ColumnDefinitions meta = result.getColumnDefinitions();
Iterator<Row> iter = result.iterator();
int i = 0;
while (iter.hasNext() && i < rows.length)
{
Object[] expected = rows[i];
Row actual = iter.next();
Assert.assertEquals(String.format("Invalid number of (expected) values provided for row %d (using protocol version %d)",
i, protocolVersion),
meta.size(), expected.length);
for (int j = 0; j < meta.size(); j++)
{
DataType type = meta.getType(j);
com.datastax.driver.core.TypeCodec<Object> codec = clusters.get(protocolVersion).getConfiguration()
.getCodecRegistry()
.codecFor(type);
ByteBuffer expectedByteValue = codec.serialize(expected[j], ProtocolVersion.fromInt(protocolVersion));
int expectedBytes = expectedByteValue == null ? -1 : expectedByteValue.remaining();
ByteBuffer actualValue = actual.getBytesUnsafe(meta.getName(j));
int actualBytes = actualValue == null ? -1 : actualValue.remaining();
if (!Objects.equal(expectedByteValue, actualValue))
Assert.fail(String.format("Invalid value for row %d column %d (%s of type %s), " +
"expected <%s> (%d bytes) but got <%s> (%d bytes) " +
"(using protocol version %d)",
i, j, meta.getName(j), type,
codec.format(expected[j]),
expectedBytes,
codec.format(codec.deserialize(actualValue, ProtocolVersion.fromInt(protocolVersion))),
actualBytes,
protocolVersion));
}
i++;
}
if (iter.hasNext())
{
while (iter.hasNext())
{
iter.next();
i++;
}
Assert.fail(String.format("Got less rows than expected. Expected %d but got %d (using protocol version %d).",
rows.length, i, protocolVersion));
}
Assert.assertTrue(String.format("Got %s rows than expected. Expected %d but got %d (using protocol version %d)",
rows.length>i ? "less" : "more", rows.length, i, protocolVersion), i == rows.length);
}
public static void assertRows(UntypedResultSet result, Object[]... rows)
{
if (result == null)
{
if (rows.length > 0)
Assert.fail(String.format("No rows returned by query but %d expected", rows.length));
return;
}
List<ColumnSpecification> meta = result.metadata();
Iterator<UntypedResultSet.Row> iter = result.iterator();
int i = 0;
while (iter.hasNext() && i < rows.length)
{
Object[] expected = rows[i];
UntypedResultSet.Row actual = iter.next();
Assert.assertEquals(String.format("Invalid number of (expected) values provided for row %d", i), expected == null ? 1 : expected.length, meta.size());
for (int j = 0; j < meta.size(); j++)
{
ColumnSpecification column = meta.get(j);
ByteBuffer expectedByteValue = makeByteBuffer(expected == null ? null : expected[j], column.type);
ByteBuffer actualValue = actual.getBytes(column.name.toString());
if (!Objects.equal(expectedByteValue, actualValue))
{
Object actualValueDecoded = actualValue == null ? null : column.type.getSerializer().deserialize(actualValue);
if (!Objects.equal(expected[j], actualValueDecoded))
Assert.fail(String.format("Invalid value for row %d column %d (%s of type %s), expected <%s> but got <%s>",
i,
j,
column.name,
column.type.asCQL3Type(),
formatValue(expectedByteValue, column.type),
formatValue(actualValue, column.type)));
}
}
i++;
}
if (iter.hasNext())
{
while (iter.hasNext())
{
UntypedResultSet.Row actual = iter.next();
i++;
StringBuilder str = new StringBuilder();
for (int j = 0; j < meta.size(); j++)
{
ColumnSpecification column = meta.get(j);
ByteBuffer actualValue = actual.getBytes(column.name.toString());
str.append(String.format("%s=%s ", column.name, formatValue(actualValue, column.type)));
}
logger.info("Extra row num {}: {}", i, str.toString());
}
Assert.fail(String.format("Got more rows than expected. Expected %d but got %d.", rows.length, i));
}
Assert.assertTrue(String.format("Got %s rows than expected. Expected %d but got %d", rows.length>i ? "less" : "more", rows.length, i), i == rows.length);
}
/**
* Like assertRows(), but ignores the ordering of rows.
*/
public static void assertRowsIgnoringOrder(UntypedResultSet result, Object[]... rows)
{
if (result == null)
{
if (rows.length > 0)
Assert.fail(String.format("No rows returned by query but %d expected", rows.length));
return;
}
List<ColumnSpecification> meta = result.metadata();
Set<List<ByteBuffer>> expectedRows = new HashSet<>(rows.length);
for (Object[] expected : rows)
{
Assert.assertEquals("Invalid number of (expected) values provided for row", expected.length, meta.size());
List<ByteBuffer> expectedRow = new ArrayList<>(meta.size());
for (int j = 0; j < meta.size(); j++)
expectedRow.add(makeByteBuffer(expected[j], meta.get(j).type));
expectedRows.add(expectedRow);
}
Set<List<ByteBuffer>> actualRows = new HashSet<>(result.size());
for (UntypedResultSet.Row actual : result)
{
List<ByteBuffer> actualRow = new ArrayList<>(meta.size());
for (int j = 0; j < meta.size(); j++)
actualRow.add(actual.getBytes(meta.get(j).name.toString()));
actualRows.add(actualRow);
}
com.google.common.collect.Sets.SetView<List<ByteBuffer>> extra = com.google.common.collect.Sets.difference(actualRows, expectedRows);
com.google.common.collect.Sets.SetView<List<ByteBuffer>> missing = com.google.common.collect.Sets.difference(expectedRows, actualRows);
if (!extra.isEmpty() || !missing.isEmpty())
{
List<String> extraRows = makeRowStrings(extra, meta);
List<String> missingRows = makeRowStrings(missing, meta);
StringBuilder sb = new StringBuilder();
if (!extra.isEmpty())
{
sb.append("Got ").append(extra.size()).append(" extra row(s) ");
if (!missing.isEmpty())
sb.append("and ").append(missing.size()).append(" missing row(s) ");
sb.append("in result. Extra rows:\n ");
sb.append(extraRows.stream().collect(Collectors.joining("\n ")));
if (!missing.isEmpty())
sb.append("\nMissing Rows:\n ").append(missingRows.stream().collect(Collectors.joining("\n ")));
Assert.fail(sb.toString());
}
if (!missing.isEmpty())
Assert.fail("Missing " + missing.size() + " row(s) in result: \n " + missingRows.stream().collect(Collectors.joining("\n ")));
}
assert expectedRows.size() == actualRows.size();
}
private static List<String> makeRowStrings(Iterable<List<ByteBuffer>> rows, List<ColumnSpecification> meta)
{
List<String> strings = new ArrayList<>();
for (List<ByteBuffer> row : rows)
{
StringBuilder sb = new StringBuilder("row(");
for (int j = 0; j < row.size(); j++)
{
ColumnSpecification column = meta.get(j);
sb.append(column.name.toString()).append("=").append(formatValue(row.get(j), column.type));
if (j < (row.size() - 1))
sb.append(", ");
}
strings.add(sb.append(")").toString());
}
return strings;
}
protected void assertRowCount(UntypedResultSet result, int numExpectedRows)
{
if (result == null)
{
if (numExpectedRows > 0)
Assert.fail(String.format("No rows returned by query but %d expected", numExpectedRows));
return;
}
List<ColumnSpecification> meta = result.metadata();
Iterator<UntypedResultSet.Row> iter = result.iterator();
int i = 0;
while (iter.hasNext() && i < numExpectedRows)
{
UntypedResultSet.Row actual = iter.next();
assertNotNull(actual);
i++;
}
if (iter.hasNext())
{
while (iter.hasNext())
{
iter.next();
i++;
}
Assert.fail(String.format("Got less rows than expected. Expected %d but got %d.", numExpectedRows, i));
}
Assert.assertTrue(String.format("Got %s rows than expected. Expected %d but got %d", numExpectedRows>i ? "less" : "more", numExpectedRows, i), i == numExpectedRows);
}
protected Object[][] getRows(UntypedResultSet result)
{
if (result == null)
return new Object[0][];
List<Object[]> ret = new ArrayList<>();
List<ColumnSpecification> meta = result.metadata();
Iterator<UntypedResultSet.Row> iter = result.iterator();
while (iter.hasNext())
{
UntypedResultSet.Row rowVal = iter.next();
Object[] row = new Object[meta.size()];
for (int j = 0; j < meta.size(); j++)
{
ColumnSpecification column = meta.get(j);
ByteBuffer val = rowVal.getBytes(column.name.toString());
row[j] = val == null ? null : column.type.getSerializer().deserialize(val);
}
ret.add(row);
}
Object[][] a = new Object[ret.size()][];
return ret.toArray(a);
}
protected void assertColumnNames(UntypedResultSet result, String... expectedColumnNames)
{
if (result == null)
{
Assert.fail("No rows returned by query.");
return;
}
List<ColumnSpecification> metadata = result.metadata();
Assert.assertEquals("Got less columns than expected.", expectedColumnNames.length, metadata.size());
for (int i = 0, m = metadata.size(); i < m; i++)
{
ColumnSpecification columnSpec = metadata.get(i);
Assert.assertEquals(expectedColumnNames[i], columnSpec.name.toString());
}
}
protected void assertAllRows(Object[]... rows) throws Throwable
{
assertRows(execute("SELECT * FROM %s"), rows);
}
public static Object[] row(Object... expected)
{
return expected;
}
protected void assertEmpty(UntypedResultSet result) throws Throwable
{
if (result != null && !result.isEmpty())
throw new AssertionError(String.format("Expected empty result but got %d rows", result.size()));
}
protected void assertInvalid(String query, Object... values) throws Throwable
{
assertInvalidMessage(null, query, values);
}
protected void assertInvalidMessage(String errorMessage, String query, Object... values) throws Throwable
{
assertInvalidThrowMessage(errorMessage, null, query, values);
}
protected void assertInvalidThrow(Class<? extends Throwable> exception, String query, Object... values) throws Throwable
{
assertInvalidThrowMessage(null, exception, query, values);
}
protected void assertInvalidThrowMessage(String errorMessage, Class<? extends Throwable> exception, String query, Object... values) throws Throwable
{
assertInvalidThrowMessage(Integer.MIN_VALUE, errorMessage, exception, query, values);
}
// if a protocol version > Integer.MIN_VALUE is supplied, executes
// the query via the java driver, mimicking a real client.
protected void assertInvalidThrowMessage(int protocolVersion,
String errorMessage,
Class<? extends Throwable> exception,
String query,
Object... values) throws Throwable
{
try
{
if (protocolVersion == Integer.MIN_VALUE)
execute(query, values);
else
executeNet(protocolVersion, query, values);
String q = USE_PREPARED_VALUES
? query + " (values: " + formatAllValues(values) + ")"
: replaceValues(query, values);
Assert.fail("Query should be invalid but no error was thrown. Query is: " + q);
}
catch (Exception e)
{
if (exception != null && !exception.isAssignableFrom(e.getClass()))
{
Assert.fail("Query should be invalid but wrong error was thrown. " +
"Expected: " + exception.getName() + ", got: " + e.getClass().getName() + ". " +
"Query is: " + queryInfo(query, values));
}
if (errorMessage != null)
{
assertMessageContains(errorMessage, e);
}
}
}
private static String queryInfo(String query, Object[] values)
{
return USE_PREPARED_VALUES
? query + " (values: " + formatAllValues(values) + ")"
: replaceValues(query, values);
}
protected void assertValidSyntax(String query) throws Throwable
{
try
{
QueryProcessor.parseStatement(query);
}
catch(SyntaxException e)
{
Assert.fail(String.format("Expected query syntax to be valid but was invalid. Query is: %s; Error is %s",
query, e.getMessage()));
}
}
protected void assertInvalidSyntax(String query, Object... values) throws Throwable
{
assertInvalidSyntaxMessage(null, query, values);
}
protected void assertInvalidSyntaxMessage(String errorMessage, String query, Object... values) throws Throwable
{
try
{
execute(query, values);
Assert.fail("Query should have invalid syntax but no error was thrown. Query is: " + queryInfo(query, values));
}
catch (SyntaxException e)
{
if (errorMessage != null)
{
assertMessageContains(errorMessage, e);
}
}
}
/**
* Asserts that the message of the specified exception contains the specified text.
*
* @param text the text that the exception message must contains
* @param e the exception to check
*/
private static void assertMessageContains(String text, Exception e)
{
Assert.assertTrue("Expected error message to contain '" + text + "', but got '" + e.getMessage() + "'",
e.getMessage().contains(text));
}
private static String replaceValues(String query, Object[] values)
{
StringBuilder sb = new StringBuilder();
int last = 0;
int i = 0;
int idx;
while ((idx = query.indexOf('?', last)) > 0)
{
if (i >= values.length)
throw new IllegalArgumentException(String.format("Not enough values provided. The query has at least %d variables but only %d values provided", i, values.length));
sb.append(query.substring(last, idx));
Object value = values[i++];
// When we have a .. IN ? .., we use a list for the value because that's what's expected when the value is serialized.
// When we format as string however, we need to special case to use parenthesis. Hackish but convenient.
if (idx >= 3 && value instanceof List && query.substring(idx - 3, idx).equalsIgnoreCase("IN "))
{
List l = (List)value;
sb.append("(");
for (int j = 0; j < l.size(); j++)
{
if (j > 0)
sb.append(", ");
sb.append(formatForCQL(l.get(j)));
}
sb.append(")");
}
else
{
sb.append(formatForCQL(value));
}
last = idx + 1;
}
sb.append(query.substring(last));
return sb.toString();
}
// We're rellly only returning ByteBuffers but this make the type system happy
private static Object[] transformValues(Object[] values)
{
// We could partly rely on QueryProcessor.executeOnceInternal doing type conversion for us, but
// it would complain with ClassCastException if we pass say a string where an int is excepted (since
// it bases conversion on what the value should be, not what it is). For testing, we sometimes
// want to pass value of the wrong type and assert that this properly raise an InvalidRequestException
// and executeOnceInternal goes into way. So instead, we pre-convert everything to bytes here based
// on the value.
// Besides, we need to handle things like TupleValue that executeOnceInternal don't know about.
Object[] buffers = new ByteBuffer[values.length];
for (int i = 0; i < values.length; i++)
{
Object value = values[i];
if (value == null)
{
buffers[i] = null;
continue;
}
else if (value == ByteBufferUtil.UNSET_BYTE_BUFFER)
{
buffers[i] = ByteBufferUtil.UNSET_BYTE_BUFFER;
continue;
}
try
{
buffers[i] = typeFor(value).decompose(serializeTuples(value));
}
catch (Exception ex)
{
logger.info("Error serializing query parameter {}:", value, ex);
throw ex;
}
}
return buffers;
}
private static Object serializeTuples(Object value)
{
if (value instanceof TupleValue)
{
return ((TupleValue)value).toByteBuffer();
}
// We need to reach inside collections for TupleValue and transform them to ByteBuffer
// since otherwise the decompose method of the collection AbstractType won't know what
// to do with them
if (value instanceof List)
{
List l = (List)value;
List n = new ArrayList(l.size());
for (Object o : l)
n.add(serializeTuples(o));
return n;
}
if (value instanceof Set)
{
Set s = (Set)value;
Set n = new LinkedHashSet(s.size());
for (Object o : s)
n.add(serializeTuples(o));
return n;
}
if (value instanceof Map)
{
Map m = (Map)value;
Map n = new LinkedHashMap(m.size());
for (Object entry : m.entrySet())
n.put(serializeTuples(((Map.Entry)entry).getKey()), serializeTuples(((Map.Entry)entry).getValue()));
return n;
}
return value;
}
private static String formatAllValues(Object[] values)
{
StringBuilder sb = new StringBuilder();
sb.append("[");
for (int i = 0; i < values.length; i++)
{
if (i > 0)
sb.append(", ");
sb.append(formatForCQL(values[i]));
}
sb.append("]");
return sb.toString();
}
private static String formatForCQL(Object value)
{
if (value == null)
return "null";
if (value instanceof TupleValue)
return ((TupleValue)value).toCQLString();
// We need to reach inside collections for TupleValue. Besides, for some reason the format
// of collection that CollectionType.getString gives us is not at all 'CQL compatible'
if (value instanceof Collection || value instanceof Map)
{
StringBuilder sb = new StringBuilder();
if (value instanceof List)
{
List l = (List)value;
sb.append("[");
for (int i = 0; i < l.size(); i++)
{
if (i > 0)
sb.append(", ");
sb.append(formatForCQL(l.get(i)));
}
sb.append("]");
}
else if (value instanceof Set)
{
Set s = (Set)value;
sb.append("{");
Iterator iter = s.iterator();
while (iter.hasNext())
{
sb.append(formatForCQL(iter.next()));
if (iter.hasNext())
sb.append(", ");
}
sb.append("}");
}
else
{
Map m = (Map)value;
sb.append("{");
Iterator iter = m.entrySet().iterator();
while (iter.hasNext())
{
Map.Entry entry = (Map.Entry)iter.next();
sb.append(formatForCQL(entry.getKey())).append(": ").append(formatForCQL(entry.getValue()));
if (iter.hasNext())
sb.append(", ");
}
sb.append("}");
}
return sb.toString();
}
AbstractType type = typeFor(value);
String s = type.getString(type.decompose(value));
if (type instanceof InetAddressType || type instanceof TimestampType)
return String.format("'%s'", s);
else if (type instanceof UTF8Type)
return String.format("'%s'", s.replaceAll("'", "''"));
else if (type instanceof BytesType)
return "0x" + s;
return s;
}
private static ByteBuffer makeByteBuffer(Object value, AbstractType type)
{
if (value == null)
return null;
if (value instanceof TupleValue)
return ((TupleValue)value).toByteBuffer();
if (value instanceof ByteBuffer)
return (ByteBuffer)value;
return type.decompose(value);
}
private static String formatValue(ByteBuffer bb, AbstractType<?> type)
{
if (bb == null)
return "null";
if (type instanceof CollectionType)
{
// CollectionType override getString() to use hexToBytes. We can't change that
// without breaking SSTable2json, but the serializer for collection have the
// right getString so using it directly instead.
TypeSerializer ser = type.getSerializer();
return ser.toString(ser.deserialize(bb));
}
return type.getString(bb);
}
protected Object tuple(Object...values)
{
return new TupleValue(values);
}
protected Object userType(Object... values)
{
return new TupleValue(values).toByteBuffer();
}
protected Object list(Object...values)
{
return Arrays.asList(values);
}
protected Object set(Object...values)
{
return ImmutableSet.copyOf(values);
}
protected Object map(Object...values)
{
if (values.length % 2 != 0)
throw new IllegalArgumentException();
int size = values.length / 2;
Map m = new LinkedHashMap(size);
for (int i = 0; i < size; i++)
m.put(values[2 * i], values[(2 * i) + 1]);
return m;
}
protected com.datastax.driver.core.TupleType tupleTypeOf(int protocolVersion, DataType...types)
{
requireNetwork();
return clusters.get(protocolVersion).getMetadata().newTupleType(types);
}
// Attempt to find an AbstracType from a value (for serialization/printing sake).
// Will work as long as we use types we know of, which is good enough for testing
private static AbstractType typeFor(Object value)
{
if (value instanceof ByteBuffer || value instanceof TupleValue || value == null)
return BytesType.instance;
if (value instanceof Byte)
return ByteType.instance;
if (value instanceof Short)
return ShortType.instance;
if (value instanceof Integer)
return Int32Type.instance;
if (value instanceof Long)
return LongType.instance;
if (value instanceof Float)
return FloatType.instance;
if (value instanceof Double)
return DoubleType.instance;
if (value instanceof BigInteger)
return IntegerType.instance;
if (value instanceof BigDecimal)
return DecimalType.instance;
if (value instanceof String)
return UTF8Type.instance;
if (value instanceof Boolean)
return BooleanType.instance;
if (value instanceof InetAddress)
return InetAddressType.instance;
if (value instanceof Date)
return TimestampType.instance;
if (value instanceof UUID)
return UUIDType.instance;
if (value instanceof List)
{
List l = (List)value;
AbstractType elt = l.isEmpty() ? BytesType.instance : typeFor(l.get(0));
return ListType.getInstance(elt, true);
}
if (value instanceof Set)
{
Set s = (Set)value;
AbstractType elt = s.isEmpty() ? BytesType.instance : typeFor(s.iterator().next());
return SetType.getInstance(elt, true);
}
if (value instanceof Map)
{
Map m = (Map)value;
AbstractType keys, values;
if (m.isEmpty())
{
keys = BytesType.instance;
values = BytesType.instance;
}
else
{
Map.Entry entry = (Map.Entry)m.entrySet().iterator().next();
keys = typeFor(entry.getKey());
values = typeFor(entry.getValue());
}
return MapType.getInstance(keys, values, true);
}
throw new IllegalArgumentException("Unsupported value type (value is " + value + ")");
}
private static class TupleValue
{
private final Object[] values;
TupleValue(Object[] values)
{
this.values = values;
}
public ByteBuffer toByteBuffer()
{
ByteBuffer[] bbs = new ByteBuffer[values.length];
for (int i = 0; i < values.length; i++)
bbs[i] = makeByteBuffer(values[i], typeFor(values[i]));
return TupleType.buildValue(bbs);
}
public String toCQLString()
{
StringBuilder sb = new StringBuilder();
sb.append("(");
for (int i = 0; i < values.length; i++)
{
if (i > 0)
sb.append(", ");
sb.append(formatForCQL(values[i]));
}
sb.append(")");
return sb.toString();
}
public String toString()
{
return "TupleValue" + toCQLString();
}
}
}
|
|
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.orc.writer;
import com.facebook.presto.common.block.Block;
import com.facebook.presto.common.type.Type;
import com.facebook.presto.orc.ColumnWriterOptions;
import com.facebook.presto.orc.DwrfDataEncryptor;
import com.facebook.presto.orc.checkpoint.BooleanStreamCheckpoint;
import com.facebook.presto.orc.checkpoint.ByteStreamCheckpoint;
import com.facebook.presto.orc.metadata.ColumnEncoding;
import com.facebook.presto.orc.metadata.CompressedMetadataWriter;
import com.facebook.presto.orc.metadata.MetadataWriter;
import com.facebook.presto.orc.metadata.RowGroupIndex;
import com.facebook.presto.orc.metadata.Stream;
import com.facebook.presto.orc.metadata.Stream.StreamKind;
import com.facebook.presto.orc.metadata.statistics.ColumnStatistics;
import com.facebook.presto.orc.stream.ByteOutputStream;
import com.facebook.presto.orc.stream.PresentOutputStream;
import com.facebook.presto.orc.stream.StreamDataOutput;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import io.airlift.slice.Slice;
import org.openjdk.jol.info.ClassLayout;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static com.facebook.presto.orc.metadata.ColumnEncoding.ColumnEncodingKind.DIRECT;
import static com.facebook.presto.orc.metadata.CompressionKind.NONE;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Objects.requireNonNull;
public class ByteColumnWriter
implements ColumnWriter
{
private static final int INSTANCE_SIZE = ClassLayout.parseClass(ByteColumnWriter.class).instanceSize();
private static final ColumnEncoding COLUMN_ENCODING = new ColumnEncoding(DIRECT, 0);
private final int column;
private final Type type;
private final boolean compressed;
private final ByteOutputStream dataStream;
private final PresentOutputStream presentStream;
private CompressedMetadataWriter metadataWriter;
private final List<ColumnStatistics> rowGroupColumnStatistics = new ArrayList<>();
private long columnStatisticsRetainedSizeInBytes;
private int nonNullValueCount;
private boolean closed;
public ByteColumnWriter(int column, Type type, ColumnWriterOptions columnWriterOptions, Optional<DwrfDataEncryptor> dwrfEncryptor, MetadataWriter metadataWriter)
{
checkArgument(column >= 0, "column is negative");
requireNonNull(columnWriterOptions, "columnWriterOptions is null");
requireNonNull(dwrfEncryptor, "dwrfEncryptor is null");
requireNonNull(metadataWriter, "metadataWriter is null");
this.column = column;
this.type = requireNonNull(type, "type is null");
this.compressed = columnWriterOptions.getCompressionKind() != NONE;
this.dataStream = new ByteOutputStream(columnWriterOptions, dwrfEncryptor);
this.presentStream = new PresentOutputStream(columnWriterOptions, dwrfEncryptor);
this.metadataWriter = new CompressedMetadataWriter(metadataWriter, columnWriterOptions, dwrfEncryptor);
}
@Override
public Map<Integer, ColumnEncoding> getColumnEncodings()
{
return ImmutableMap.of(column, COLUMN_ENCODING);
}
@Override
public void beginRowGroup()
{
presentStream.recordCheckpoint();
dataStream.recordCheckpoint();
}
@Override
public void writeBlock(Block block)
{
checkState(!closed);
checkArgument(block.getPositionCount() > 0, "Block is empty");
// record nulls
for (int position = 0; position < block.getPositionCount(); position++) {
presentStream.writeBoolean(!block.isNull(position));
}
// record values
for (int position = 0; position < block.getPositionCount(); position++) {
if (!block.isNull(position)) {
dataStream.writeByte((byte) type.getLong(block, position));
nonNullValueCount++;
}
}
}
@Override
public Map<Integer, ColumnStatistics> finishRowGroup()
{
checkState(!closed);
ColumnStatistics statistics = new ColumnStatistics((long) nonNullValueCount, 0, null, null, null, null, null, null, null, null);
rowGroupColumnStatistics.add(statistics);
columnStatisticsRetainedSizeInBytes += statistics.getRetainedSizeInBytes();
nonNullValueCount = 0;
return ImmutableMap.of(column, statistics);
}
@Override
public void close()
{
closed = true;
dataStream.close();
presentStream.close();
}
@Override
public Map<Integer, ColumnStatistics> getColumnStripeStatistics()
{
checkState(closed);
return ImmutableMap.of(column, ColumnStatistics.mergeColumnStatistics(rowGroupColumnStatistics));
}
@Override
public List<StreamDataOutput> getIndexStreams()
throws IOException
{
checkState(closed);
ImmutableList.Builder<RowGroupIndex> rowGroupIndexes = ImmutableList.builder();
List<ByteStreamCheckpoint> dataCheckpoints = dataStream.getCheckpoints();
Optional<List<BooleanStreamCheckpoint>> presentCheckpoints = presentStream.getCheckpoints();
for (int i = 0; i < rowGroupColumnStatistics.size(); i++) {
int groupId = i;
ColumnStatistics columnStatistics = rowGroupColumnStatistics.get(groupId);
ByteStreamCheckpoint dataCheckpoint = dataCheckpoints.get(groupId);
Optional<BooleanStreamCheckpoint> presentCheckpoint = presentCheckpoints.map(checkpoints -> checkpoints.get(groupId));
List<Integer> positions = createByteColumnPositionList(compressed, dataCheckpoint, presentCheckpoint);
rowGroupIndexes.add(new RowGroupIndex(positions, columnStatistics));
}
Slice slice = metadataWriter.writeRowIndexes(rowGroupIndexes.build());
Stream stream = new Stream(column, StreamKind.ROW_INDEX, slice.length(), false);
return ImmutableList.of(new StreamDataOutput(slice, stream));
}
private static List<Integer> createByteColumnPositionList(
boolean compressed,
ByteStreamCheckpoint dataCheckpoint,
Optional<BooleanStreamCheckpoint> presentCheckpoint)
{
ImmutableList.Builder<Integer> positionList = ImmutableList.builder();
presentCheckpoint.ifPresent(booleanStreamCheckpoint -> positionList.addAll(booleanStreamCheckpoint.toPositionList(compressed)));
positionList.addAll(dataCheckpoint.toPositionList(compressed));
return positionList.build();
}
@Override
public List<StreamDataOutput> getDataStreams()
{
checkState(closed);
ImmutableList.Builder<StreamDataOutput> outputDataStreams = ImmutableList.builder();
presentStream.getStreamDataOutput(column).ifPresent(outputDataStreams::add);
outputDataStreams.add(dataStream.getStreamDataOutput(column));
return outputDataStreams.build();
}
@Override
public long getBufferedBytes()
{
return dataStream.getBufferedBytes() + presentStream.getBufferedBytes();
}
@Override
public long getRetainedBytes()
{
return INSTANCE_SIZE + dataStream.getRetainedBytes() + presentStream.getRetainedBytes() + columnStatisticsRetainedSizeInBytes;
}
@Override
public void reset()
{
closed = false;
dataStream.reset();
presentStream.reset();
rowGroupColumnStatistics.clear();
columnStatisticsRetainedSizeInBytes = 0;
nonNullValueCount = 0;
}
}
|
|
package mx.eduardopool.notes.services;
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import java.util.ArrayList;
import io.realm.Realm;
import io.realm.RealmList;
import mx.eduardopool.notes.models.UserModel;
import mx.eduardopool.notes.models.realm.Note;
import mx.eduardopool.notes.models.realm.User;
import mx.eduardopool.notes.models.viewmodels.NoteViewModel;
/**
* An {@link IntentService} subclass for handling asynchronous task requests in
* a service on a separate handler thread.
* <p/>
* helper methods.
*/
public class NoteIntentService extends IntentService {
public static final String EXTRA_NOTE_WRAPPER = "mx.eduardopool.notes.services.extra.NOTE_WRAPPER";
public static final String ACTION_NOTE_ADDED = "mx.eduardopool.notes.services.action.NOTE_ADDED";
public static final String ACTION_NOTE_UPDATED = "mx.eduardopool.notes.services.action.NOTE_UPDATED";
public static final String ACTION_NOTES_DELETED = "mx.eduardopool.notes.services.action.NOTES_DELETED";
public static final String EXTRA_NOTES_DELETED_COUNT = "mx.eduardopool.notes.services.extra.NOTES_DELETED_COUNT";
private static final String ACTION_ADD_NOTE = "mx.eduardopool.notes.services.action.ADD_NOTE";
private static final String ACTION_UPDATE_NOTE = "mx.eduardopool.notes.services.action.UPDATE_NOTE";
private static final String ACTION_DELETE_NOTES = "mx.eduardopool.notes.services.action.DELETE_NOTES";
private static final String EXTRA_NOTE_IDS = "mx.eduardopool.notes.services.extra.NOTE_IDS";
private LocalBroadcastManager localBroadcastManager;
public NoteIntentService() {
super("NoteIntentService");
}
/**
* Starts this service to perform action ADD_NOTE with the given parameters. If
* the service is already performing a task this action will be queued.
*
* @param context Context where this method is invoked.
* @param noteViewModel Note to be added.
*/
public static void startActionAddNote(Context context, NoteViewModel noteViewModel) {
Intent intent = new Intent(context, NoteIntentService.class);
intent.setAction(ACTION_ADD_NOTE);
intent.putExtra(EXTRA_NOTE_WRAPPER, noteViewModel);
context.startService(intent);
}
/**
* Starts this service to perform action UPDATE_NOTE with the given parameters. If
* the service is already performing a task this action will be queued.
*
* @param context Context where this method is invoked.
* @param noteViewModel Note to be updated.
*/
public static void startActionUpdateNote(Context context, NoteViewModel noteViewModel) {
Intent intent = new Intent(context, NoteIntentService.class);
intent.setAction(ACTION_UPDATE_NOTE);
intent.putExtra(EXTRA_NOTE_WRAPPER, noteViewModel);
context.startService(intent);
}
/**
* Starts this service to perform action DELETE_NOTE with the given parameters. If
* the service is already performing a task this action will be queued.
*
* @param context Context where this method is invoked.
* @param noteIds Note ids to be deleted.
*/
public static void startActionDeleteNotes(Context context, ArrayList<String> noteIds) {
Intent intent = new Intent(context, NoteIntentService.class);
intent.setAction(ACTION_DELETE_NOTES);
intent.putExtra(EXTRA_NOTE_IDS, noteIds);
context.startService(intent);
}
@Override
public void onCreate() {
super.onCreate();
localBroadcastManager = LocalBroadcastManager.getInstance(this);
}
@Override
protected void onHandleIntent(Intent intent) {
if (intent != null) {
final String action = intent.getAction();
if (action != null) {
Realm realm = Realm.getDefaultInstance();
NoteViewModel noteViewModel = intent.getParcelableExtra(EXTRA_NOTE_WRAPPER);
switch (action) {
case ACTION_ADD_NOTE:
handleActionAddNote(realm, noteViewModel);
break;
case ACTION_UPDATE_NOTE:
handleActionUpdateNote(realm, noteViewModel);
break;
case ACTION_DELETE_NOTES:
ArrayList<String> noteIds = intent.getStringArrayListExtra(EXTRA_NOTE_IDS);
handleActionDeleteNotes(realm, noteIds);
break;
}
realm.close();
}
}
}
/**
* Handle action ADD_NOTE in the provided background thread with the provided
* parameters.
*
* @param realm Realm instance to do realm transactions.
* @param noteViewModel Note to be added.
*/
private void handleActionAddNote(Realm realm, NoteViewModel noteViewModel) {
Note note = noteViewModel.toRealm(true);
realm.beginTransaction();
Note noteAdded = realm.copyToRealmOrUpdate(note);
realm.where(User.class)
.equalTo(User.ID, UserModel.getCurrentUserId(this))
.findFirst()
.getNotes()
.add(noteAdded);
realm.commitTransaction();
notifyNoteAdded(new NoteViewModel(noteAdded));
}
/**
* Notifies note added.
*
* @param noteViewModel Note added.
*/
private void notifyNoteAdded(NoteViewModel noteViewModel) {
Intent intent = new Intent(ACTION_NOTE_ADDED);
intent.putExtra(EXTRA_NOTE_WRAPPER, noteViewModel);
localBroadcastManager.sendBroadcast(intent);
}
/**
* Handle action UPDATE_NOTE in the provided background thread with the provided
* parameters.
*
* @param realm Realm instance to do realm transactions.
* @param noteViewModel Note to be updated.
*/
private void handleActionUpdateNote(Realm realm, NoteViewModel noteViewModel) {
Note note = noteViewModel.toRealm(false);
realm.beginTransaction();
Note noteUpdated = realm.copyToRealmOrUpdate(note);
realm.commitTransaction();
notifyNoteUpdated(new NoteViewModel(noteUpdated));
}
/**
* Notifies note updated.
*
* @param noteViewModel Note updated.
*/
private void notifyNoteUpdated(NoteViewModel noteViewModel) {
Intent intent = new Intent(ACTION_NOTE_UPDATED);
intent.putExtra(EXTRA_NOTE_WRAPPER, noteViewModel);
localBroadcastManager.sendBroadcast(intent);
}
/**
* Handle action DELETE_NOTE in the provided background thread with the provided
* parameters.
*
* @param realm Realm instance to do realm transactions.
* @param noteIds Note ids to be deleted.
*/
private void handleActionDeleteNotes(Realm realm, ArrayList<String> noteIds) {
realm.beginTransaction();
RealmList<Note> notes = realm.where(User.class)
.equalTo(User.ID, UserModel.getCurrentUserId(this))
.findFirst()
.getNotes();
int notesDeletedCount = 0;
for (String noteId : noteIds) {
Note note = notes.where()
.equalTo(Note.ID, noteId)
.findFirst();
if (note != null) {
note.removeFromRealm();
notesDeletedCount += 1;
}
}
realm.commitTransaction();
notifyNotesDeleted(notesDeletedCount);
}
/**
* Notifies notes deleted.
*
* @param notesDeletedCount Number of notes that were deleted.
*/
private void notifyNotesDeleted(int notesDeletedCount) {
Intent intent = new Intent(ACTION_NOTES_DELETED);
intent.putExtra(EXTRA_NOTES_DELETED_COUNT, notesDeletedCount);
localBroadcastManager.sendBroadcast(intent);
}
}
|
|
// Generated from org/apache/sysml/parser/pydml/Pydml.g4 by ANTLR 4.5.3
package org.apache.sysml.parser.pydml;
/*
* 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 org.antlr.v4.runtime.Lexer;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.Token;
import org.antlr.v4.runtime.TokenStream;
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.atn.*;
import org.antlr.v4.runtime.dfa.DFA;
import org.antlr.v4.runtime.misc.*;
@SuppressWarnings({"all", "warnings", "unchecked", "unused", "cast"})
public class PydmlLexer extends Lexer {
static { RuntimeMetaData.checkVersion("4.5.3", RuntimeMetaData.VERSION); }
protected static final DFA[] _decisionToDFA;
protected static final PredictionContextCache _sharedContextCache =
new PredictionContextCache();
public static final int
T__0=1, T__1=2, T__2=3, T__3=4, T__4=5, T__5=6, T__6=7, T__7=8, T__8=9,
T__9=10, T__10=11, T__11=12, T__12=13, T__13=14, T__14=15, T__15=16, T__16=17,
T__17=18, T__18=19, T__19=20, T__20=21, T__21=22, T__22=23, T__23=24,
T__24=25, T__25=26, T__26=27, T__27=28, T__28=29, T__29=30, T__30=31,
T__31=32, T__32=33, T__33=34, T__34=35, T__35=36, T__36=37, T__37=38,
T__38=39, ID=40, INT=41, DOUBLE=42, DIGIT=43, ALPHABET=44, COMMANDLINE_NAMED_ID=45,
COMMANDLINE_POSITION_ID=46, STRING=47, OPEN_BRACK=48, CLOSE_BRACK=49,
OPEN_PAREN=50, CLOSE_PAREN=51, NEWLINE=52, SKIP_WS=53;
public static String[] modeNames = {
"DEFAULT_MODE"
};
public static final String[] ruleNames = {
"T__0", "T__1", "T__2", "T__3", "T__4", "T__5", "T__6", "T__7", "T__8",
"T__9", "T__10", "T__11", "T__12", "T__13", "T__14", "T__15", "T__16",
"T__17", "T__18", "T__19", "T__20", "T__21", "T__22", "T__23", "T__24",
"T__25", "T__26", "T__27", "T__28", "T__29", "T__30", "T__31", "T__32",
"T__33", "T__34", "T__35", "T__36", "T__37", "T__38", "ID", "INT", "DOUBLE",
"DIGIT", "ALPHABET", "EXP", "COMMANDLINE_NAMED_ID", "COMMANDLINE_POSITION_ID",
"STRING", "ESC", "OPEN_BRACK", "CLOSE_BRACK", "OPEN_PAREN", "CLOSE_PAREN",
"SPACES", "COMMENT", "LINE_JOINING", "NEWLINE", "SKIP_WS"
};
private static final String[] _LITERAL_NAMES = {
null, "'source'", "'as'", "'setwd'", "'='", "'ifdef'", "','", "'if'",
"':'", "'else'", "'for'", "'in'", "'parfor'", "'while'", "'elif'", "'def'",
"'->'", "'defExternal'", "'implemented'", "'**'", "'-'", "'+'", "'//'",
"'%'", "'*'", "'/'", "'>'", "'>='", "'<'", "'<='", "'=='", "'!='", "'!'",
"'&'", "'and'", "'|'", "'or'", "';'", "'True'", "'False'", null, null,
null, null, null, null, null, null, "'['", "']'", "'('", "')'"
};
private static final String[] _SYMBOLIC_NAMES = {
null, null, null, null, null, null, null, null, null, null, null, null,
null, null, null, null, null, null, null, null, null, null, null, null,
null, null, null, null, null, null, null, null, null, null, null, null,
null, null, null, null, "ID", "INT", "DOUBLE", "DIGIT", "ALPHABET", "COMMANDLINE_NAMED_ID",
"COMMANDLINE_POSITION_ID", "STRING", "OPEN_BRACK", "CLOSE_BRACK", "OPEN_PAREN",
"CLOSE_PAREN", "NEWLINE", "SKIP_WS"
};
public static final Vocabulary VOCABULARY = new VocabularyImpl(_LITERAL_NAMES, _SYMBOLIC_NAMES);
/**
* @deprecated Use {@link #VOCABULARY} instead.
*/
@Deprecated
public static final String[] tokenNames;
static {
tokenNames = new String[_SYMBOLIC_NAMES.length];
for (int i = 0; i < tokenNames.length; i++) {
tokenNames[i] = VOCABULARY.getLiteralName(i);
if (tokenNames[i] == null) {
tokenNames[i] = VOCABULARY.getSymbolicName(i);
}
if (tokenNames[i] == null) {
tokenNames[i] = "<INVALID>";
}
}
}
@Override
@Deprecated
public String[] getTokenNames() {
return tokenNames;
}
@Override
public Vocabulary getVocabulary() {
return VOCABULARY;
}
private boolean debugIndentRules = false;
// Indentation level stack
private java.util.Stack<Integer> indents = new java.util.Stack<Integer>();
// Extra tokens queue (see the NEWLINE rule).
private java.util.Queue<Token> tokens = new java.util.LinkedList<Token>();
// Number of opened braces, brackets and parenthesis.
private int opened = 0;
// This is only used to set the line number for dedent
private Token lastToken = null;
@Override
public void emit(Token t) {
if(debugIndentRules)
System.out.println("Emitted token:" + t);
super.setToken(t);
tokens.offer(t);
}
@Override
public Token nextToken() {
if (_input.LA(1) == EOF && !this.indents.isEmpty()) {
if(debugIndentRules)
System.out.println("EOF reached and expecting some DEDENTS, so emitting them");
tokens.poll();
this.emit(commonToken(PydmlParser.NEWLINE, "\n"));
// Now emit as much DEDENT tokens as needed.
while (!indents.isEmpty()) {
if(debugIndentRules)
System.out.println("Emitting (inserted) DEDENTS");
this.emit(createDedent());
indents.pop();
}
// Put the EOF back on the token stream.
this.emit(commonToken(PydmlParser.EOF, "<EOF>"));
}
Token next = super.nextToken();
if (next.getChannel() == Token.DEFAULT_CHANNEL) {
// Keep track of the last token on the default channel.
this.lastToken = next;
}
Token retVal = tokens.isEmpty() ? next : tokens.poll();
if(debugIndentRules)
System.out.println("Returning nextToken: [" + retVal + "]<<" + tokens.isEmpty());
return retVal;
}
private Token createDedent() {
CommonToken dedent = commonToken(PydmlParser.DEDENT, "");
dedent.setLine(this.lastToken.getLine());
return dedent;
}
private CommonToken commonToken(int type, String text) {
// Nike: Main change: This logic was screwed up and was emitting additional 3 characters, so commenting it for now.
// int start = this.getCharIndex();
// int stop = start + text.length();
// return new CommonToken(this._tokenFactorySourcePair, type, DEFAULT_TOKEN_CHANNEL, start, stop);
return new CommonToken(type, text); // Main change
}
// Calculates the indentation level from the spaces:
// "Tabs are replaced (from left to right) by one to eight spaces
// such that the total number of characters up to and including
// the replacement is a multiple of eight [...]"
// https://docs.python.org/3.1/reference/lexical_analysis.html#indentation
static int getIndentationCount(String spaces) {
int count = 0;
for (char ch : spaces.toCharArray()) {
switch (ch) {
case '\t':
count += 8 - (count % 8);
break;
default:
// A normal space char.
count++;
}
}
return count;
}
public PydmlLexer(CharStream input) {
super(input);
_interp = new LexerATNSimulator(this,_ATN,_decisionToDFA,_sharedContextCache);
}
@Override
public String getGrammarFileName() { return "Pydml.g4"; }
@Override
public String[] getRuleNames() { return ruleNames; }
@Override
public String getSerializedATN() { return _serializedATN; }
@Override
public String[] getModeNames() { return modeNames; }
@Override
public ATN getATN() { return _ATN; }
@Override
public void action(RuleContext _localctx, int ruleIndex, int actionIndex) {
switch (ruleIndex) {
case 49:
OPEN_BRACK_action((RuleContext)_localctx, actionIndex);
break;
case 50:
CLOSE_BRACK_action((RuleContext)_localctx, actionIndex);
break;
case 51:
OPEN_PAREN_action((RuleContext)_localctx, actionIndex);
break;
case 52:
CLOSE_PAREN_action((RuleContext)_localctx, actionIndex);
break;
case 56:
NEWLINE_action((RuleContext)_localctx, actionIndex);
break;
}
}
private void OPEN_BRACK_action(RuleContext _localctx, int actionIndex) {
switch (actionIndex) {
case 0:
opened++;
break;
}
}
private void CLOSE_BRACK_action(RuleContext _localctx, int actionIndex) {
switch (actionIndex) {
case 1:
opened--;
break;
}
}
private void OPEN_PAREN_action(RuleContext _localctx, int actionIndex) {
switch (actionIndex) {
case 2:
opened++;
break;
}
}
private void CLOSE_PAREN_action(RuleContext _localctx, int actionIndex) {
switch (actionIndex) {
case 3:
opened--;
break;
}
}
private void NEWLINE_action(RuleContext _localctx, int actionIndex) {
switch (actionIndex) {
case 4:
String newLine = getText().replaceAll("[^\r\n]+", "");
String spaces = getText().replaceAll("[\r\n]+", "");
int next = _input.LA(1);
if (opened > 0 || next == '\r' || next == '\n' || next == '#') {
// If we're inside a list or on a blank line, ignore all indents,
// dedents and line breaks.
skip();
if(debugIndentRules) {
if(next == '\r' || next == '\n') {
System.out.println("4.1 Skipping (blank lines)");
}
else if(next == '#') {
System.out.println("4.2 Skipping (comment)");
}
else {
System.out.println("4.2 Skipping something else");
}
}
}
else {
emit(commonToken(NEWLINE, newLine));
int indent = getIndentationCount(spaces);
int previous = indents.isEmpty() ? 0 : indents.peek();
if (indent == previous) {
if(debugIndentRules)
System.out.println("3. Skipping identation as of same size:" + next);
// skip indents of the same size as the present indent-size
skip();
}
else if (indent > previous) {
if(debugIndentRules)
System.out.println("1. Indent:" + next);
indents.push(indent);
emit(commonToken(PydmlParser.INDENT, spaces));
}
else {
// Possibly emit more than 1 DEDENT token.
while(!indents.isEmpty() && indents.peek() > indent) {
if(debugIndentRules)
System.out.println("2. Dedent:" + next);
this.emit(createDedent());
indents.pop();
}
}
}
break;
}
}
public static final String _serializedATN =
"\3\u0430\ud6d1\u8206\uad2d\u4417\uaef1\u8d80\uaadd\2\67\u01cb\b\1\4\2"+
"\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7\4\b\t\b\4\t\t\t\4\n\t\n\4"+
"\13\t\13\4\f\t\f\4\r\t\r\4\16\t\16\4\17\t\17\4\20\t\20\4\21\t\21\4\22"+
"\t\22\4\23\t\23\4\24\t\24\4\25\t\25\4\26\t\26\4\27\t\27\4\30\t\30\4\31"+
"\t\31\4\32\t\32\4\33\t\33\4\34\t\34\4\35\t\35\4\36\t\36\4\37\t\37\4 \t"+
" \4!\t!\4\"\t\"\4#\t#\4$\t$\4%\t%\4&\t&\4\'\t\'\4(\t(\4)\t)\4*\t*\4+\t"+
"+\4,\t,\4-\t-\4.\t.\4/\t/\4\60\t\60\4\61\t\61\4\62\t\62\4\63\t\63\4\64"+
"\t\64\4\65\t\65\4\66\t\66\4\67\t\67\48\t8\49\t9\4:\t:\4;\t;\3\2\3\2\3"+
"\2\3\2\3\2\3\2\3\2\3\3\3\3\3\3\3\4\3\4\3\4\3\4\3\4\3\4\3\5\3\5\3\6\3\6"+
"\3\6\3\6\3\6\3\6\3\7\3\7\3\b\3\b\3\b\3\t\3\t\3\n\3\n\3\n\3\n\3\n\3\13"+
"\3\13\3\13\3\13\3\f\3\f\3\f\3\r\3\r\3\r\3\r\3\r\3\r\3\r\3\16\3\16\3\16"+
"\3\16\3\16\3\16\3\17\3\17\3\17\3\17\3\17\3\20\3\20\3\20\3\20\3\21\3\21"+
"\3\21\3\22\3\22\3\22\3\22\3\22\3\22\3\22\3\22\3\22\3\22\3\22\3\22\3\23"+
"\3\23\3\23\3\23\3\23\3\23\3\23\3\23\3\23\3\23\3\23\3\23\3\24\3\24\3\24"+
"\3\25\3\25\3\26\3\26\3\27\3\27\3\27\3\30\3\30\3\31\3\31\3\32\3\32\3\33"+
"\3\33\3\34\3\34\3\34\3\35\3\35\3\36\3\36\3\36\3\37\3\37\3\37\3 \3 \3 "+
"\3!\3!\3\"\3\"\3#\3#\3#\3#\3$\3$\3%\3%\3%\3&\3&\3\'\3\'\3\'\3\'\3\'\3"+
"(\3(\3(\3(\3(\3(\3)\3)\3)\3)\7)\u0112\n)\f)\16)\u0115\13)\3)\3)\5)\u0119"+
"\n)\3)\3)\3)\3)\7)\u011f\n)\f)\16)\u0122\13)\3)\3)\3)\3)\3)\3)\3)\3)\3"+
")\3)\3)\3)\5)\u0130\n)\3*\6*\u0133\n*\r*\16*\u0134\3*\5*\u0138\n*\3+\6"+
"+\u013b\n+\r+\16+\u013c\3+\3+\7+\u0141\n+\f+\16+\u0144\13+\3+\5+\u0147"+
"\n+\3+\5+\u014a\n+\3+\6+\u014d\n+\r+\16+\u014e\3+\5+\u0152\n+\3+\5+\u0155"+
"\n+\3+\3+\6+\u0159\n+\r+\16+\u015a\3+\5+\u015e\n+\3+\5+\u0161\n+\5+\u0163"+
"\n+\3,\3,\3-\3-\3.\3.\5.\u016b\n.\3.\3.\3/\3/\3/\3/\3/\7/\u0174\n/\f/"+
"\16/\u0177\13/\3\60\3\60\6\60\u017b\n\60\r\60\16\60\u017c\3\61\3\61\3"+
"\61\7\61\u0182\n\61\f\61\16\61\u0185\13\61\3\61\3\61\3\61\3\61\7\61\u018b"+
"\n\61\f\61\16\61\u018e\13\61\3\61\5\61\u0191\n\61\3\62\3\62\3\62\3\63"+
"\3\63\3\63\3\64\3\64\3\64\3\65\3\65\3\65\3\66\3\66\3\66\3\67\6\67\u01a3"+
"\n\67\r\67\16\67\u01a4\38\38\78\u01a9\n8\f8\168\u01ac\138\39\39\59\u01b0"+
"\n9\39\59\u01b3\n9\39\39\59\u01b7\n9\3:\5:\u01ba\n:\3:\3:\5:\u01be\n:"+
"\3:\5:\u01c1\n:\3:\3:\3;\3;\3;\5;\u01c8\n;\3;\3;\4\u0183\u018c\2<\3\3"+
"\5\4\7\5\t\6\13\7\r\b\17\t\21\n\23\13\25\f\27\r\31\16\33\17\35\20\37\21"+
"!\22#\23%\24\'\25)\26+\27-\30/\31\61\32\63\33\65\34\67\359\36;\37= ?!"+
"A\"C#E$G%I&K\'M(O)Q*S+U,W-Y.[\2]/_\60a\61c\2e\62g\63i\64k\65m\2o\2q\2"+
"s\66u\67\3\2\13\4\2NNnn\4\2C\\c|\4\2GGgg\4\2--//\4\2$$^^\4\2))^^\n\2$"+
"$))^^ddhhppttvv\4\2\13\13\"\"\4\2\f\f\17\17\u01ef\2\3\3\2\2\2\2\5\3\2"+
"\2\2\2\7\3\2\2\2\2\t\3\2\2\2\2\13\3\2\2\2\2\r\3\2\2\2\2\17\3\2\2\2\2\21"+
"\3\2\2\2\2\23\3\2\2\2\2\25\3\2\2\2\2\27\3\2\2\2\2\31\3\2\2\2\2\33\3\2"+
"\2\2\2\35\3\2\2\2\2\37\3\2\2\2\2!\3\2\2\2\2#\3\2\2\2\2%\3\2\2\2\2\'\3"+
"\2\2\2\2)\3\2\2\2\2+\3\2\2\2\2-\3\2\2\2\2/\3\2\2\2\2\61\3\2\2\2\2\63\3"+
"\2\2\2\2\65\3\2\2\2\2\67\3\2\2\2\29\3\2\2\2\2;\3\2\2\2\2=\3\2\2\2\2?\3"+
"\2\2\2\2A\3\2\2\2\2C\3\2\2\2\2E\3\2\2\2\2G\3\2\2\2\2I\3\2\2\2\2K\3\2\2"+
"\2\2M\3\2\2\2\2O\3\2\2\2\2Q\3\2\2\2\2S\3\2\2\2\2U\3\2\2\2\2W\3\2\2\2\2"+
"Y\3\2\2\2\2]\3\2\2\2\2_\3\2\2\2\2a\3\2\2\2\2e\3\2\2\2\2g\3\2\2\2\2i\3"+
"\2\2\2\2k\3\2\2\2\2s\3\2\2\2\2u\3\2\2\2\3w\3\2\2\2\5~\3\2\2\2\7\u0081"+
"\3\2\2\2\t\u0087\3\2\2\2\13\u0089\3\2\2\2\r\u008f\3\2\2\2\17\u0091\3\2"+
"\2\2\21\u0094\3\2\2\2\23\u0096\3\2\2\2\25\u009b\3\2\2\2\27\u009f\3\2\2"+
"\2\31\u00a2\3\2\2\2\33\u00a9\3\2\2\2\35\u00af\3\2\2\2\37\u00b4\3\2\2\2"+
"!\u00b8\3\2\2\2#\u00bb\3\2\2\2%\u00c7\3\2\2\2\'\u00d3\3\2\2\2)\u00d6\3"+
"\2\2\2+\u00d8\3\2\2\2-\u00da\3\2\2\2/\u00dd\3\2\2\2\61\u00df\3\2\2\2\63"+
"\u00e1\3\2\2\2\65\u00e3\3\2\2\2\67\u00e5\3\2\2\29\u00e8\3\2\2\2;\u00ea"+
"\3\2\2\2=\u00ed\3\2\2\2?\u00f0\3\2\2\2A\u00f3\3\2\2\2C\u00f5\3\2\2\2E"+
"\u00f7\3\2\2\2G\u00fb\3\2\2\2I\u00fd\3\2\2\2K\u0100\3\2\2\2M\u0102\3\2"+
"\2\2O\u0107\3\2\2\2Q\u012f\3\2\2\2S\u0132\3\2\2\2U\u0162\3\2\2\2W\u0164"+
"\3\2\2\2Y\u0166\3\2\2\2[\u0168\3\2\2\2]\u016e\3\2\2\2_\u0178\3\2\2\2a"+
"\u0190\3\2\2\2c\u0192\3\2\2\2e\u0195\3\2\2\2g\u0198\3\2\2\2i\u019b\3\2"+
"\2\2k\u019e\3\2\2\2m\u01a2\3\2\2\2o\u01a6\3\2\2\2q\u01ad\3\2\2\2s\u01bd"+
"\3\2\2\2u\u01c7\3\2\2\2wx\7u\2\2xy\7q\2\2yz\7w\2\2z{\7t\2\2{|\7e\2\2|"+
"}\7g\2\2}\4\3\2\2\2~\177\7c\2\2\177\u0080\7u\2\2\u0080\6\3\2\2\2\u0081"+
"\u0082\7u\2\2\u0082\u0083\7g\2\2\u0083\u0084\7v\2\2\u0084\u0085\7y\2\2"+
"\u0085\u0086\7f\2\2\u0086\b\3\2\2\2\u0087\u0088\7?\2\2\u0088\n\3\2\2\2"+
"\u0089\u008a\7k\2\2\u008a\u008b\7h\2\2\u008b\u008c\7f\2\2\u008c\u008d"+
"\7g\2\2\u008d\u008e\7h\2\2\u008e\f\3\2\2\2\u008f\u0090\7.\2\2\u0090\16"+
"\3\2\2\2\u0091\u0092\7k\2\2\u0092\u0093\7h\2\2\u0093\20\3\2\2\2\u0094"+
"\u0095\7<\2\2\u0095\22\3\2\2\2\u0096\u0097\7g\2\2\u0097\u0098\7n\2\2\u0098"+
"\u0099\7u\2\2\u0099\u009a\7g\2\2\u009a\24\3\2\2\2\u009b\u009c\7h\2\2\u009c"+
"\u009d\7q\2\2\u009d\u009e\7t\2\2\u009e\26\3\2\2\2\u009f\u00a0\7k\2\2\u00a0"+
"\u00a1\7p\2\2\u00a1\30\3\2\2\2\u00a2\u00a3\7r\2\2\u00a3\u00a4\7c\2\2\u00a4"+
"\u00a5\7t\2\2\u00a5\u00a6\7h\2\2\u00a6\u00a7\7q\2\2\u00a7\u00a8\7t\2\2"+
"\u00a8\32\3\2\2\2\u00a9\u00aa\7y\2\2\u00aa\u00ab\7j\2\2\u00ab\u00ac\7"+
"k\2\2\u00ac\u00ad\7n\2\2\u00ad\u00ae\7g\2\2\u00ae\34\3\2\2\2\u00af\u00b0"+
"\7g\2\2\u00b0\u00b1\7n\2\2\u00b1\u00b2\7k\2\2\u00b2\u00b3\7h\2\2\u00b3"+
"\36\3\2\2\2\u00b4\u00b5\7f\2\2\u00b5\u00b6\7g\2\2\u00b6\u00b7\7h\2\2\u00b7"+
" \3\2\2\2\u00b8\u00b9\7/\2\2\u00b9\u00ba\7@\2\2\u00ba\"\3\2\2\2\u00bb"+
"\u00bc\7f\2\2\u00bc\u00bd\7g\2\2\u00bd\u00be\7h\2\2\u00be\u00bf\7G\2\2"+
"\u00bf\u00c0\7z\2\2\u00c0\u00c1\7v\2\2\u00c1\u00c2\7g\2\2\u00c2\u00c3"+
"\7t\2\2\u00c3\u00c4\7p\2\2\u00c4\u00c5\7c\2\2\u00c5\u00c6\7n\2\2\u00c6"+
"$\3\2\2\2\u00c7\u00c8\7k\2\2\u00c8\u00c9\7o\2\2\u00c9\u00ca\7r\2\2\u00ca"+
"\u00cb\7n\2\2\u00cb\u00cc\7g\2\2\u00cc\u00cd\7o\2\2\u00cd\u00ce\7g\2\2"+
"\u00ce\u00cf\7p\2\2\u00cf\u00d0\7v\2\2\u00d0\u00d1\7g\2\2\u00d1\u00d2"+
"\7f\2\2\u00d2&\3\2\2\2\u00d3\u00d4\7,\2\2\u00d4\u00d5\7,\2\2\u00d5(\3"+
"\2\2\2\u00d6\u00d7\7/\2\2\u00d7*\3\2\2\2\u00d8\u00d9\7-\2\2\u00d9,\3\2"+
"\2\2\u00da\u00db\7\61\2\2\u00db\u00dc\7\61\2\2\u00dc.\3\2\2\2\u00dd\u00de"+
"\7\'\2\2\u00de\60\3\2\2\2\u00df\u00e0\7,\2\2\u00e0\62\3\2\2\2\u00e1\u00e2"+
"\7\61\2\2\u00e2\64\3\2\2\2\u00e3\u00e4\7@\2\2\u00e4\66\3\2\2\2\u00e5\u00e6"+
"\7@\2\2\u00e6\u00e7\7?\2\2\u00e78\3\2\2\2\u00e8\u00e9\7>\2\2\u00e9:\3"+
"\2\2\2\u00ea\u00eb\7>\2\2\u00eb\u00ec\7?\2\2\u00ec<\3\2\2\2\u00ed\u00ee"+
"\7?\2\2\u00ee\u00ef\7?\2\2\u00ef>\3\2\2\2\u00f0\u00f1\7#\2\2\u00f1\u00f2"+
"\7?\2\2\u00f2@\3\2\2\2\u00f3\u00f4\7#\2\2\u00f4B\3\2\2\2\u00f5\u00f6\7"+
"(\2\2\u00f6D\3\2\2\2\u00f7\u00f8\7c\2\2\u00f8\u00f9\7p\2\2\u00f9\u00fa"+
"\7f\2\2\u00faF\3\2\2\2\u00fb\u00fc\7~\2\2\u00fcH\3\2\2\2\u00fd\u00fe\7"+
"q\2\2\u00fe\u00ff\7t\2\2\u00ffJ\3\2\2\2\u0100\u0101\7=\2\2\u0101L\3\2"+
"\2\2\u0102\u0103\7V\2\2\u0103\u0104\7t\2\2\u0104\u0105\7w\2\2\u0105\u0106"+
"\7g\2\2\u0106N\3\2\2\2\u0107\u0108\7H\2\2\u0108\u0109\7c\2\2\u0109\u010a"+
"\7n\2\2\u010a\u010b\7u\2\2\u010b\u010c\7g\2\2\u010cP\3\2\2\2\u010d\u0113"+
"\5Y-\2\u010e\u0112\5Y-\2\u010f\u0112\5W,\2\u0110\u0112\7a\2\2\u0111\u010e"+
"\3\2\2\2\u0111\u010f\3\2\2\2\u0111\u0110\3\2\2\2\u0112\u0115\3\2\2\2\u0113"+
"\u0111\3\2\2\2\u0113\u0114\3\2\2\2\u0114\u0116\3\2\2\2\u0115\u0113\3\2"+
"\2\2\u0116\u0117\7\60\2\2\u0117\u0119\3\2\2\2\u0118\u010d\3\2\2\2\u0118"+
"\u0119\3\2\2\2\u0119\u011a\3\2\2\2\u011a\u0120\5Y-\2\u011b\u011f\5Y-\2"+
"\u011c\u011f\5W,\2\u011d\u011f\7a\2\2\u011e\u011b\3\2\2\2\u011e\u011c"+
"\3\2\2\2\u011e\u011d\3\2\2\2\u011f\u0122\3\2\2\2\u0120\u011e\3\2\2\2\u0120"+
"\u0121\3\2\2\2\u0121\u0130\3\2\2\2\u0122\u0120\3\2\2\2\u0123\u0124\7k"+
"\2\2\u0124\u0125\7p\2\2\u0125\u0126\7f\2\2\u0126\u0127\7g\2\2\u0127\u0128"+
"\7z\2\2\u0128\u0129\7\60\2\2\u0129\u012a\7t\2\2\u012a\u012b\7g\2\2\u012b"+
"\u012c\7v\2\2\u012c\u012d\7w\2\2\u012d\u012e\7t\2\2\u012e\u0130\7p\2\2"+
"\u012f\u0118\3\2\2\2\u012f\u0123\3\2\2\2\u0130R\3\2\2\2\u0131\u0133\5"+
"W,\2\u0132\u0131\3\2\2\2\u0133\u0134\3\2\2\2\u0134\u0132\3\2\2\2\u0134"+
"\u0135\3\2\2\2\u0135\u0137\3\2\2\2\u0136\u0138\t\2\2\2\u0137\u0136\3\2"+
"\2\2\u0137\u0138\3\2\2\2\u0138T\3\2\2\2\u0139\u013b\5W,\2\u013a\u0139"+
"\3\2\2\2\u013b\u013c\3\2\2\2\u013c\u013a\3\2\2\2\u013c\u013d\3\2\2\2\u013d"+
"\u013e\3\2\2\2\u013e\u0142\7\60\2\2\u013f\u0141\5W,\2\u0140\u013f\3\2"+
"\2\2\u0141\u0144\3\2\2\2\u0142\u0140\3\2\2\2\u0142\u0143\3\2\2\2\u0143"+
"\u0146\3\2\2\2\u0144\u0142\3\2\2\2\u0145\u0147\5[.\2\u0146\u0145\3\2\2"+
"\2\u0146\u0147\3\2\2\2\u0147\u0149\3\2\2\2\u0148\u014a\t\2\2\2\u0149\u0148"+
"\3\2\2\2\u0149\u014a\3\2\2\2\u014a\u0163\3\2\2\2\u014b\u014d\5W,\2\u014c"+
"\u014b\3\2\2\2\u014d\u014e\3\2\2\2\u014e\u014c\3\2\2\2\u014e\u014f\3\2"+
"\2\2\u014f\u0151\3\2\2\2\u0150\u0152\5[.\2\u0151\u0150\3\2\2\2\u0151\u0152"+
"\3\2\2\2\u0152\u0154\3\2\2\2\u0153\u0155\t\2\2\2\u0154\u0153\3\2\2\2\u0154"+
"\u0155\3\2\2\2\u0155\u0163\3\2\2\2\u0156\u0158\7\60\2\2\u0157\u0159\5"+
"W,\2\u0158\u0157\3\2\2\2\u0159\u015a\3\2\2\2\u015a\u0158\3\2\2\2\u015a"+
"\u015b\3\2\2\2\u015b\u015d\3\2\2\2\u015c\u015e\5[.\2\u015d\u015c\3\2\2"+
"\2\u015d\u015e\3\2\2\2\u015e\u0160\3\2\2\2\u015f\u0161\t\2\2\2\u0160\u015f"+
"\3\2\2\2\u0160\u0161\3\2\2\2\u0161\u0163\3\2\2\2\u0162\u013a\3\2\2\2\u0162"+
"\u014c\3\2\2\2\u0162\u0156\3\2\2\2\u0163V\3\2\2\2\u0164\u0165\4\62;\2"+
"\u0165X\3\2\2\2\u0166\u0167\t\3\2\2\u0167Z\3\2\2\2\u0168\u016a\t\4\2\2"+
"\u0169\u016b\t\5\2\2\u016a\u0169\3\2\2\2\u016a\u016b\3\2\2\2\u016b\u016c"+
"\3\2\2\2\u016c\u016d\5S*\2\u016d\\\3\2\2\2\u016e\u016f\7&\2\2\u016f\u0175"+
"\5Y-\2\u0170\u0174\5Y-\2\u0171\u0174\5W,\2\u0172\u0174\7a\2\2\u0173\u0170"+
"\3\2\2\2\u0173\u0171\3\2\2\2\u0173\u0172\3\2\2\2\u0174\u0177\3\2\2\2\u0175"+
"\u0173\3\2\2\2\u0175\u0176\3\2\2\2\u0176^\3\2\2\2\u0177\u0175\3\2\2\2"+
"\u0178\u017a\7&\2\2\u0179\u017b\5W,\2\u017a\u0179\3\2\2\2\u017b\u017c"+
"\3\2\2\2\u017c\u017a\3\2\2\2\u017c\u017d\3\2\2\2\u017d`\3\2\2\2\u017e"+
"\u0183\7$\2\2\u017f\u0182\5c\62\2\u0180\u0182\n\6\2\2\u0181\u017f\3\2"+
"\2\2\u0181\u0180\3\2\2\2\u0182\u0185\3\2\2\2\u0183\u0184\3\2\2\2\u0183"+
"\u0181\3\2\2\2\u0184\u0186\3\2\2\2\u0185\u0183\3\2\2\2\u0186\u0191\7$"+
"\2\2\u0187\u018c\7)\2\2\u0188\u018b\5c\62\2\u0189\u018b\n\7\2\2\u018a"+
"\u0188\3\2\2\2\u018a\u0189\3\2\2\2\u018b\u018e\3\2\2\2\u018c\u018d\3\2"+
"\2\2\u018c\u018a\3\2\2\2\u018d\u018f\3\2\2\2\u018e\u018c\3\2\2\2\u018f"+
"\u0191\7)\2\2\u0190\u017e\3\2\2\2\u0190\u0187\3\2\2\2\u0191b\3\2\2\2\u0192"+
"\u0193\7^\2\2\u0193\u0194\t\b\2\2\u0194d\3\2\2\2\u0195\u0196\7]\2\2\u0196"+
"\u0197\b\63\2\2\u0197f\3\2\2\2\u0198\u0199\7_\2\2\u0199\u019a\b\64\3\2"+
"\u019ah\3\2\2\2\u019b\u019c\7*\2\2\u019c\u019d\b\65\4\2\u019dj\3\2\2\2"+
"\u019e\u019f\7+\2\2\u019f\u01a0\b\66\5\2\u01a0l\3\2\2\2\u01a1\u01a3\t"+
"\t\2\2\u01a2\u01a1\3\2\2\2\u01a3\u01a4\3\2\2\2\u01a4\u01a2\3\2\2\2\u01a4"+
"\u01a5\3\2\2\2\u01a5n\3\2\2\2\u01a6\u01aa\7%\2\2\u01a7\u01a9\n\n\2\2\u01a8"+
"\u01a7\3\2\2\2\u01a9\u01ac\3\2\2\2\u01aa\u01a8\3\2\2\2\u01aa\u01ab\3\2"+
"\2\2\u01abp\3\2\2\2\u01ac\u01aa\3\2\2\2\u01ad\u01af\7^\2\2\u01ae\u01b0"+
"\5m\67\2\u01af\u01ae\3\2\2\2\u01af\u01b0\3\2\2\2\u01b0\u01b6\3\2\2\2\u01b1"+
"\u01b3\7\17\2\2\u01b2\u01b1\3\2\2\2\u01b2\u01b3\3\2\2\2\u01b3\u01b4\3"+
"\2\2\2\u01b4\u01b7\7\f\2\2\u01b5\u01b7\7\17\2\2\u01b6\u01b2\3\2\2\2\u01b6"+
"\u01b5\3\2\2\2\u01b7r\3\2\2\2\u01b8\u01ba\7\17\2\2\u01b9\u01b8\3\2\2\2"+
"\u01b9\u01ba\3\2\2\2\u01ba\u01bb\3\2\2\2\u01bb\u01be\7\f\2\2\u01bc\u01be"+
"\7\17\2\2\u01bd\u01b9\3\2\2\2\u01bd\u01bc\3\2\2\2\u01be\u01c0\3\2\2\2"+
"\u01bf\u01c1\5m\67\2\u01c0\u01bf\3\2\2\2\u01c0\u01c1\3\2\2\2\u01c1\u01c2"+
"\3\2\2\2\u01c2\u01c3\b:\6\2\u01c3t\3\2\2\2\u01c4\u01c8\5m\67\2\u01c5\u01c8"+
"\5o8\2\u01c6\u01c8\5q9\2\u01c7\u01c4\3\2\2\2\u01c7\u01c5\3\2\2\2\u01c7"+
"\u01c6\3\2\2\2\u01c8\u01c9\3\2\2\2\u01c9\u01ca\b;\7\2\u01cav\3\2\2\2("+
"\2\u0111\u0113\u0118\u011e\u0120\u012f\u0134\u0137\u013c\u0142\u0146\u0149"+
"\u014e\u0151\u0154\u015a\u015d\u0160\u0162\u016a\u0173\u0175\u017c\u0181"+
"\u0183\u018a\u018c\u0190\u01a4\u01aa\u01af\u01b2\u01b6\u01b9\u01bd\u01c0"+
"\u01c7\b\3\63\2\3\64\3\3\65\4\3\66\5\3:\6\b\2\2";
public static final ATN _ATN =
new ATNDeserializer().deserialize(_serializedATN.toCharArray());
static {
_decisionToDFA = new DFA[_ATN.getNumberOfDecisions()];
for (int i = 0; i < _ATN.getNumberOfDecisions(); i++) {
_decisionToDFA[i] = new DFA(_ATN.getDecisionState(i), i);
}
}
}
|
|
package org.keycloak.testsuite.arquillian.containers;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.commons.io.FileUtils;
import org.jboss.arquillian.container.spi.client.container.DeployableContainer;
import org.jboss.arquillian.container.spi.client.container.DeploymentException;
import org.jboss.arquillian.container.spi.client.container.LifecycleException;
import org.jboss.arquillian.container.spi.client.protocol.ProtocolDescription;
import org.jboss.arquillian.container.spi.client.protocol.metadata.ProtocolMetaData;
import org.jboss.arquillian.core.api.Instance;
import org.jboss.arquillian.core.api.annotation.Inject;
import org.jboss.logging.Logger;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.descriptor.api.Descriptor;
import org.keycloak.testsuite.arquillian.SuiteContext;
/**
* @author mhajas
*/
public class KeycloakQuarkusServerDeployableContainer implements DeployableContainer<KeycloakQuarkusConfiguration> {
protected static final Logger log = Logger.getLogger(KeycloakQuarkusServerDeployableContainer.class);
private KeycloakQuarkusConfiguration configuration;
private Process container;
private static AtomicBoolean restart = new AtomicBoolean();
@Inject
private Instance<SuiteContext> suiteContext;
private boolean forceReaugmentation;
private List<String> additionalArgs = Collections.emptyList();
@Override
public Class<KeycloakQuarkusConfiguration> getConfigurationClass() {
return KeycloakQuarkusConfiguration.class;
}
@Override
public void setup(KeycloakQuarkusConfiguration configuration) {
this.configuration = configuration;
}
@Override
public void start() throws LifecycleException {
try {
container = startContainer();
waitForReadiness();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void stop() throws LifecycleException {
container.destroy();
try {
container.waitFor(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
container.destroyForcibly();
}
}
@Override
public ProtocolDescription getDefaultProtocol() {
return null;
}
@Override
public ProtocolMetaData deploy(Archive<?> archive) throws DeploymentException {
return null;
}
@Override
public void undeploy(Archive<?> archive) throws DeploymentException {
}
@Override
public void deploy(Descriptor descriptor) throws DeploymentException {
}
@Override
public void undeploy(Descriptor descriptor) throws DeploymentException {
}
private Process startContainer() throws IOException {
ProcessBuilder pb = new ProcessBuilder(getProcessCommands());
File wrkDir = configuration.getProvidersPath().resolve("bin").toFile();
ProcessBuilder builder = pb.directory(wrkDir).inheritIO().redirectErrorStream(true);
String javaOpts = configuration.getJavaOpts();
if (javaOpts != null) {
builder.environment().put("JAVA_OPTS", javaOpts);
}
builder.environment().put("KEYCLOAK_ADMIN", "admin");
builder.environment().put("KEYCLOAK_ADMIN_PASSWORD", "admin");
if (restart.compareAndSet(false, true)) {
FileUtils.deleteDirectory(configuration.getProvidersPath().resolve("data").toFile());
}
if (isReaugmentBeforeStart()) {
List<String> commands = new ArrayList<>(Arrays.asList("./kc.sh", "config", "-Dquarkus.http.root-path=/auth"));
addAdditionalCommands(commands);
ProcessBuilder reaugment = new ProcessBuilder(commands);
reaugment.directory(wrkDir).inheritIO();
try {
log.infof("Re-building the server with the new configuration");
reaugment.start().waitFor(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
throw new RuntimeException("Timeout while waiting for re-augmentation", e);
}
}
return builder.start();
}
private boolean isReaugmentBeforeStart() {
return configuration.isReaugmentBeforeStart() || forceReaugmentation;
}
private String[] getProcessCommands() {
List<String> commands = new ArrayList<>();
commands.add("./kc.sh");
if (configuration.getDebugPort() > 0) {
commands.add("--debug");
commands.add(Integer.toString(configuration.getDebugPort()));
} else if (Boolean.valueOf(System.getProperty("auth.server.debug", "false"))) {
commands.add("--debug");
commands.add(System.getProperty("auth.server.debug.port", "5005"));
}
commands.add("--http-port=" + configuration.getBindHttpPort());
commands.add("--https-port=" + configuration.getBindHttpsPort());
if (configuration.getRoute() != null) {
commands.add("-Djboss.node.name=" + configuration.getRoute());
}
commands.add("--cluster=" + System.getProperty("auth.server.quarkus.cluster.config", "local"));
addAdditionalCommands(commands);
return commands.toArray(new String[commands.size()]);
}
private void addAdditionalCommands(List<String> commands) {
commands.addAll(additionalArgs);
}
private void waitForReadiness() throws MalformedURLException, LifecycleException {
SuiteContext suiteContext = this.suiteContext.get();
//TODO: not sure if the best endpoint but it makes sure that everything is properly initialized. Once we have
// support for MP Health this should change
URL contextRoot = new URL(getBaseUrl(suiteContext) + "/auth/realms/master/");
HttpURLConnection connection;
long startTime = System.currentTimeMillis();
while (true) {
if (System.currentTimeMillis() - startTime > getStartTimeout()) {
stop();
throw new IllegalStateException("Timeout [" + getStartTimeout() + "] while waiting for Quarkus server");
}
try {
// wait before checking for opening a new connection
Thread.sleep(1000);
if ("https".equals(contextRoot.getProtocol())) {
HttpsURLConnection httpsConnection = (HttpsURLConnection) (connection = (HttpURLConnection) contextRoot.openConnection());
httpsConnection.setSSLSocketFactory(createInsecureSslSocketFactory());
httpsConnection.setHostnameVerifier(createInsecureHostnameVerifier());
} else {
connection = (HttpURLConnection) contextRoot.openConnection();
}
connection.setReadTimeout((int) getStartTimeout());
connection.setConnectTimeout((int) getStartTimeout());
connection.connect();
if (connection.getResponseCode() == 200) {
break;
}
connection.disconnect();
} catch (Exception ignore) {
}
}
log.infof("Keycloak is ready at %s", contextRoot);
}
private URL getBaseUrl(SuiteContext suiteContext) throws MalformedURLException {
URL baseUrl = suiteContext.getAuthServerInfo().getContextRoot();
// might be running behind a load balancer
if ("https".equals(baseUrl.getProtocol())) {
baseUrl = new URL(baseUrl.toString().replace(String.valueOf(baseUrl.getPort()), String.valueOf(configuration.getBindHttpsPort())));
} else {
baseUrl = new URL(baseUrl.toString().replace(String.valueOf(baseUrl.getPort()), String.valueOf(configuration.getBindHttpPort())));
}
return baseUrl;
}
private HostnameVerifier createInsecureHostnameVerifier() {
return new HostnameVerifier() {
@Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
};
}
private SSLSocketFactory createInsecureSslSocketFactory() throws IOException {
TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() {
public void checkClientTrusted(final X509Certificate[] chain, final String authType) {
}
public void checkServerTrusted(final X509Certificate[] chain, final String authType) {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}};
SSLContext sslContext;
SSLSocketFactory socketFactory;
try {
sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
socketFactory = sslContext.getSocketFactory();
} catch (NoSuchAlgorithmException | KeyManagementException e) {
throw new IOException("Can't create unsecure trust manager");
}
return socketFactory;
}
private long getStartTimeout() {
return TimeUnit.SECONDS.toMillis(configuration.getStartupTimeoutInSeconds());
}
public void forceReAugmentation(String... args) {
forceReaugmentation = true;
additionalArgs = Arrays.asList(args);
}
public void resetConfiguration() {
additionalArgs = Collections.emptyList();
forceReAugmentation();
}
}
|
|
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.xpack.ml.dataframe.extractor;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.elasticsearch.ResourceNotFoundException;
import org.elasticsearch.action.fieldcaps.FieldCapabilities;
import org.elasticsearch.action.fieldcaps.FieldCapabilitiesResponse;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.collect.Tuple;
import org.elasticsearch.common.regex.Regex;
import org.elasticsearch.index.IndexSettings;
import org.elasticsearch.index.mapper.BooleanFieldMapper;
import org.elasticsearch.index.mapper.ObjectMapper;
import org.elasticsearch.search.fetch.subphase.FetchSourceContext;
import org.elasticsearch.xpack.core.ml.dataframe.DataFrameAnalyticsConfig;
import org.elasticsearch.xpack.core.ml.dataframe.analyses.DataFrameAnalysis;
import org.elasticsearch.xpack.core.ml.dataframe.analyses.FieldCardinalityConstraint;
import org.elasticsearch.xpack.core.ml.dataframe.analyses.RequiredField;
import org.elasticsearch.xpack.core.ml.dataframe.analyses.Types;
import org.elasticsearch.xpack.core.ml.dataframe.explain.FieldSelection;
import org.elasticsearch.xpack.core.ml.job.messages.Messages;
import org.elasticsearch.xpack.core.ml.utils.ExceptionsHelper;
import org.elasticsearch.xpack.core.ml.utils.NameResolver;
import org.elasticsearch.xpack.ml.dataframe.DestinationIndex;
import org.elasticsearch.xpack.ml.extractor.ExtractedField;
import org.elasticsearch.xpack.ml.extractor.ExtractedFields;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class ExtractedFieldsDetector {
private static final Logger LOGGER = LogManager.getLogger(ExtractedFieldsDetector.class);
/**
* Fields to ignore. These are mostly internal meta fields.
*/
private static final List<String> IGNORE_FIELDS = Arrays.asList("_id", "_field_names", "_index", "_parent", "_routing", "_seq_no",
"_source", "_type", "_uid", "_version", "_feature", "_ignored", "_nested_path", DestinationIndex.ID_COPY);
private final String[] index;
private final DataFrameAnalyticsConfig config;
private final int docValueFieldsLimit;
private final FieldCapabilitiesResponse fieldCapabilitiesResponse;
private final Map<String, Long> cardinalitiesForFieldsWithConstraints;
ExtractedFieldsDetector(String[] index, DataFrameAnalyticsConfig config, int docValueFieldsLimit,
FieldCapabilitiesResponse fieldCapabilitiesResponse, Map<String, Long> cardinalitiesForFieldsWithConstraints) {
this.index = Objects.requireNonNull(index);
this.config = Objects.requireNonNull(config);
this.docValueFieldsLimit = docValueFieldsLimit;
this.fieldCapabilitiesResponse = Objects.requireNonNull(fieldCapabilitiesResponse);
this.cardinalitiesForFieldsWithConstraints = Objects.requireNonNull(cardinalitiesForFieldsWithConstraints);
}
public Tuple<ExtractedFields, List<FieldSelection>> detect() {
TreeSet<FieldSelection> fieldSelection = new TreeSet<>(Comparator.comparing(FieldSelection::getName));
Set<String> fields = getIncludedFields(fieldSelection);
checkFieldsHaveCompatibleTypes(fields);
checkRequiredFields(fields);
checkFieldsWithCardinalityLimit();
ExtractedFields extractedFields = detectExtractedFields(fields, fieldSelection);
addIncludedFields(extractedFields, fieldSelection);
return Tuple.tuple(extractedFields, Collections.unmodifiableList(new ArrayList<>(fieldSelection)));
}
private Set<String> getIncludedFields(Set<FieldSelection> fieldSelection) {
Set<String> fields = new TreeSet<>(fieldCapabilitiesResponse.get().keySet());
fields.removeAll(IGNORE_FIELDS);
removeFieldsUnderResultsField(fields);
removeObjects(fields);
applySourceFiltering(fields);
FetchSourceContext analyzedFields = config.getAnalyzedFields();
// If the user has not explicitly included fields we'll include all compatible fields
if (analyzedFields == null || analyzedFields.includes().length == 0) {
removeFieldsWithIncompatibleTypes(fields, fieldSelection);
}
includeAndExcludeFields(fields, fieldSelection);
if (fields.isEmpty()) {
throw ExceptionsHelper.badRequestException("No compatible fields could be detected in index {}. Supported types are {}.",
Arrays.toString(index),
getSupportedTypes());
}
return fields;
}
private void removeFieldsUnderResultsField(Set<String> fields) {
String resultsField = config.getDest().getResultsField();
Iterator<String> fieldsIterator = fields.iterator();
while (fieldsIterator.hasNext()) {
String field = fieldsIterator.next();
if (field.startsWith(resultsField + ".")) {
fieldsIterator.remove();
}
}
fields.removeIf(field -> field.startsWith(resultsField + "."));
}
private void removeObjects(Set<String> fields) {
Iterator<String> fieldsIterator = fields.iterator();
while (fieldsIterator.hasNext()) {
String field = fieldsIterator.next();
Set<String> types = getMappingTypes(field);
if (isObject(types)) {
fieldsIterator.remove();
}
}
}
private void applySourceFiltering(Set<String> fields) {
Iterator<String> fieldsIterator = fields.iterator();
while (fieldsIterator.hasNext()) {
String field = fieldsIterator.next();
if (config.getSource().isFieldExcluded(field)) {
fieldsIterator.remove();
}
}
}
private void addExcludedField(String field, String reason, Set<FieldSelection> fieldSelection) {
fieldSelection.add(FieldSelection.excluded(field, getMappingTypes(field), reason));
}
private Set<String> getMappingTypes(String field) {
Map<String, FieldCapabilities> fieldCaps = fieldCapabilitiesResponse.getField(field);
return fieldCaps == null ? Collections.emptySet() : fieldCaps.keySet();
}
private void removeFieldsWithIncompatibleTypes(Set<String> fields, Set<FieldSelection> fieldSelection) {
Iterator<String> fieldsIterator = fields.iterator();
while (fieldsIterator.hasNext()) {
String field = fieldsIterator.next();
if (hasCompatibleType(field) == false) {
addExcludedField(field, "unsupported type; supported types are " + getSupportedTypes(), fieldSelection);
fieldsIterator.remove();
}
}
}
private boolean hasCompatibleType(String field) {
Map<String, FieldCapabilities> fieldCaps = fieldCapabilitiesResponse.getField(field);
if (fieldCaps == null) {
LOGGER.debug("[{}] incompatible field [{}] because it is missing from mappings", config.getId(), field);
return false;
}
Set<String> fieldTypes = fieldCaps.keySet();
if (Types.numerical().containsAll(fieldTypes)) {
LOGGER.debug("[{}] field [{}] is compatible as it is numerical", config.getId(), field);
return true;
} else if (config.getAnalysis().supportsCategoricalFields() && Types.categorical().containsAll(fieldTypes)) {
LOGGER.debug("[{}] field [{}] is compatible as it is categorical", config.getId(), field);
return true;
} else if (isBoolean(fieldTypes)) {
LOGGER.debug("[{}] field [{}] is compatible as it is boolean", config.getId(), field);
return true;
} else {
LOGGER.debug("[{}] incompatible field [{}]; types {}; supported {}", config.getId(), field, fieldTypes, getSupportedTypes());
return false;
}
}
private Set<String> getSupportedTypes() {
Set<String> supportedTypes = new TreeSet<>(Types.numerical());
if (config.getAnalysis().supportsCategoricalFields()) {
supportedTypes.addAll(Types.categorical());
}
supportedTypes.add(BooleanFieldMapper.CONTENT_TYPE);
return supportedTypes;
}
private void includeAndExcludeFields(Set<String> fields, Set<FieldSelection> fieldSelection) {
FetchSourceContext analyzedFields = config.getAnalyzedFields();
if (analyzedFields == null) {
return;
}
checkIncludesExcludesAreNotObjects(analyzedFields);
String includes = analyzedFields.includes().length == 0 ? "*" : Strings.arrayToCommaDelimitedString(analyzedFields.includes());
String excludes = Strings.arrayToCommaDelimitedString(analyzedFields.excludes());
if (Regex.isMatchAllPattern(includes) && excludes.isEmpty()) {
return;
}
try {
// If the inclusion set does not match anything, that means the user's desired fields cannot be found in
// the collection of supported field types. We should let the user know.
Set<String> includedSet = NameResolver.newUnaliased(fields,
(ex) -> new ResourceNotFoundException(
Messages.getMessage(Messages.DATA_FRAME_ANALYTICS_BAD_FIELD_FILTER, ex)))
.expand(includes, false);
// If the exclusion set does not match anything, that means the fields are already not present
// no need to raise if nothing matched
Set<String> excludedSet = NameResolver.newUnaliased(fieldCapabilitiesResponse.get().keySet(),
(ex) -> new ResourceNotFoundException(
Messages.getMessage(Messages.DATA_FRAME_ANALYTICS_BAD_FIELD_FILTER, ex)))
.expand(excludes, true);
applyIncludesExcludes(fields, includedSet, excludedSet, fieldSelection);
} catch (ResourceNotFoundException ex) {
// Re-wrap our exception so that we throw the same exception type when there are no fields.
throw ExceptionsHelper.badRequestException(ex.getMessage());
}
}
private void checkIncludesExcludesAreNotObjects(FetchSourceContext analyzedFields) {
List<String> objectFields = Stream.concat(Arrays.stream(analyzedFields.includes()), Arrays.stream(analyzedFields.excludes()))
.filter(field -> isObject(getMappingTypes(field)))
.collect(Collectors.toList());
if (objectFields.isEmpty() == false) {
throw ExceptionsHelper.badRequestException("{} must not include or exclude object fields: {}",
DataFrameAnalyticsConfig.ANALYZED_FIELDS.getPreferredName(), objectFields);
}
}
private void applyIncludesExcludes(Set<String> fields, Set<String> includes, Set<String> excludes,
Set<FieldSelection> fieldSelection) {
Iterator<String> fieldsIterator = fields.iterator();
while (fieldsIterator.hasNext()) {
String field = fieldsIterator.next();
if (includes.contains(field)) {
if (IGNORE_FIELDS.contains(field)) {
throw ExceptionsHelper.badRequestException("field [{}] cannot be analyzed", field);
}
if (excludes.contains(field)) {
fieldsIterator.remove();
addExcludedField(field, "field in excludes list", fieldSelection);
}
} else {
fieldsIterator.remove();
addExcludedField(field, "field not in includes list", fieldSelection);
}
}
}
private void checkFieldsHaveCompatibleTypes(Set<String> fields) {
for (String field : fields) {
Map<String, FieldCapabilities> fieldCaps = fieldCapabilitiesResponse.getField(field);
if (fieldCaps == null) {
throw ExceptionsHelper.badRequestException("no mappings could be found for field [{}]", field);
}
if (hasCompatibleType(field) == false) {
throw ExceptionsHelper.badRequestException("field [{}] has unsupported type {}. Supported types are {}.", field,
fieldCaps.keySet(), getSupportedTypes());
}
}
}
private void checkRequiredFields(Set<String> fields) {
List<RequiredField> requiredFields = config.getAnalysis().getRequiredFields();
for (RequiredField requiredField : requiredFields) {
Map<String, FieldCapabilities> fieldCaps = fieldCapabilitiesResponse.getField(requiredField.getName());
if (fields.contains(requiredField.getName()) == false || fieldCaps == null || fieldCaps.isEmpty()) {
List<String> requiredFieldNames = requiredFields.stream().map(RequiredField::getName).collect(Collectors.toList());
throw ExceptionsHelper.badRequestException("required field [{}] is missing; analysis requires fields {}",
requiredField.getName(), requiredFieldNames);
}
Set<String> fieldTypes = fieldCaps.keySet();
if (requiredField.getTypes().containsAll(fieldTypes) == false) {
throw ExceptionsHelper.badRequestException("invalid types {} for required field [{}]; expected types are {}",
fieldTypes, requiredField.getName(), requiredField.getTypes());
}
}
}
private void checkFieldsWithCardinalityLimit() {
for (FieldCardinalityConstraint constraint : config.getAnalysis().getFieldCardinalityConstraints()) {
constraint.check(cardinalitiesForFieldsWithConstraints.get(constraint.getField()));
}
}
private ExtractedFields detectExtractedFields(Set<String> fields, Set<FieldSelection> fieldSelection) {
ExtractedFields extractedFields = ExtractedFields.build(fields, Collections.emptySet(), fieldCapabilitiesResponse,
cardinalitiesForFieldsWithConstraints);
boolean preferSource = extractedFields.getDocValueFields().size() > docValueFieldsLimit;
extractedFields = deduplicateMultiFields(extractedFields, preferSource, fieldSelection);
if (preferSource) {
extractedFields = fetchFromSourceIfSupported(extractedFields);
if (extractedFields.getDocValueFields().size() > docValueFieldsLimit) {
throw ExceptionsHelper.badRequestException("[{}] fields must be retrieved from doc_values but the limit is [{}]; " +
"please adjust the index level setting [{}]", extractedFields.getDocValueFields().size(), docValueFieldsLimit,
IndexSettings.MAX_DOCVALUE_FIELDS_SEARCH_SETTING.getKey());
}
}
extractedFields = fetchBooleanFieldsAsIntegers(extractedFields);
return extractedFields;
}
private ExtractedFields deduplicateMultiFields(ExtractedFields extractedFields, boolean preferSource,
Set<FieldSelection> fieldSelection) {
Set<String> requiredFields = config.getAnalysis().getRequiredFields().stream().map(RequiredField::getName)
.collect(Collectors.toSet());
Map<String, ExtractedField> nameOrParentToField = new LinkedHashMap<>();
for (ExtractedField currentField : extractedFields.getAllFields()) {
String nameOrParent = currentField.isMultiField() ? currentField.getParentField() : currentField.getName();
ExtractedField existingField = nameOrParentToField.putIfAbsent(nameOrParent, currentField);
if (existingField != null) {
ExtractedField parent = currentField.isMultiField() ? existingField : currentField;
ExtractedField multiField = currentField.isMultiField() ? currentField : existingField;
nameOrParentToField.put(nameOrParent,
chooseMultiFieldOrParent(preferSource, requiredFields, parent, multiField, fieldSelection));
}
}
return new ExtractedFields(new ArrayList<>(nameOrParentToField.values()), cardinalitiesForFieldsWithConstraints);
}
private ExtractedField chooseMultiFieldOrParent(boolean preferSource, Set<String> requiredFields, ExtractedField parent,
ExtractedField multiField, Set<FieldSelection> fieldSelection) {
// Check requirements first
if (requiredFields.contains(parent.getName())) {
addExcludedField(multiField.getName(), "[" + parent.getName() + "] is required instead", fieldSelection);
return parent;
}
if (requiredFields.contains(multiField.getName())) {
addExcludedField(parent.getName(), "[" + multiField.getName() + "] is required instead", fieldSelection);
return multiField;
}
// If both are multi-fields it means there are several. In this case parent is the previous multi-field
// we selected. We'll just keep that.
if (parent.isMultiField() && multiField.isMultiField()) {
addExcludedField(multiField.getName(), "[" + parent.getName() + "] came first", fieldSelection);
return parent;
}
// If we prefer source only the parent may support it. If it does we pick it immediately.
if (preferSource && parent.supportsFromSource()) {
addExcludedField(multiField.getName(), "[" + parent.getName() + "] is preferred because it supports fetching from source",
fieldSelection);
return parent;
}
// If any of the two is a doc_value field let's prefer it as it'd support aggregations.
// We check the parent first as it'd be a shorter field name.
if (parent.getMethod() == ExtractedField.Method.DOC_VALUE) {
addExcludedField(multiField.getName(), "[" + parent.getName() + "] is preferred because it is aggregatable", fieldSelection);
return parent;
}
if (multiField.getMethod() == ExtractedField.Method.DOC_VALUE) {
addExcludedField(parent.getName(), "[" + multiField.getName() + "] is preferred because it is aggregatable", fieldSelection);
return multiField;
}
// None is aggregatable. Let's pick the parent for its shorter name.
addExcludedField(multiField.getName(), "[" + parent.getName() + "] is preferred because none of the multi-fields are aggregatable",
fieldSelection);
return parent;
}
private ExtractedFields fetchFromSourceIfSupported(ExtractedFields extractedFields) {
List<ExtractedField> adjusted = new ArrayList<>(extractedFields.getAllFields().size());
for (ExtractedField field : extractedFields.getAllFields()) {
adjusted.add(field.supportsFromSource() ? field.newFromSource() : field);
}
return new ExtractedFields(adjusted, cardinalitiesForFieldsWithConstraints);
}
private ExtractedFields fetchBooleanFieldsAsIntegers(ExtractedFields extractedFields) {
List<ExtractedField> adjusted = new ArrayList<>(extractedFields.getAllFields().size());
for (ExtractedField field : extractedFields.getAllFields()) {
if (isBoolean(field.getTypes())) {
// We convert boolean fields to integers with values 0, 1 as this is the preferred
// way to consume such features in the analytics process regardless of:
// - analysis type
// - whether or not the field is categorical
// - whether or not the field is a dependent variable
adjusted.add(ExtractedFields.applyBooleanMapping(field));
} else {
adjusted.add(field);
}
}
return new ExtractedFields(adjusted, cardinalitiesForFieldsWithConstraints);
}
private void addIncludedFields(ExtractedFields extractedFields, Set<FieldSelection> fieldSelection) {
Set<String> requiredFields = config.getAnalysis().getRequiredFields().stream().map(RequiredField::getName)
.collect(Collectors.toSet());
Set<String> categoricalFields = getCategoricalFields(extractedFields, config.getAnalysis());
for (ExtractedField includedField : extractedFields.getAllFields()) {
FieldSelection.FeatureType featureType = categoricalFields.contains(includedField.getName()) ?
FieldSelection.FeatureType.CATEGORICAL : FieldSelection.FeatureType.NUMERICAL;
fieldSelection.add(FieldSelection.included(includedField.getName(), includedField.getTypes(),
requiredFields.contains(includedField.getName()), featureType));
}
}
static Set<String> getCategoricalFields(ExtractedFields extractedFields, DataFrameAnalysis analysis) {
return extractedFields.getAllFields().stream()
.filter(extractedField -> analysis.getAllowedCategoricalTypes(extractedField.getName())
.containsAll(extractedField.getTypes()))
.map(ExtractedField::getName)
.collect(Collectors.toUnmodifiableSet());
}
private static boolean isBoolean(Set<String> types) {
return types.size() == 1 && types.contains(BooleanFieldMapper.CONTENT_TYPE);
}
private boolean isObject(Set<String> types) {
return types.size() == 1 && types.contains(ObjectMapper.CONTENT_TYPE);
}
}
|
|
/* Created by A. Tan
* on 2 January
* as the main menu for the literary terms practice bank
*/
package literarytermsquestionbank;
import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.Toolkit;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
/**
*
* @author Aaron
*/
public class MainMenu extends javax.swing.JFrame {
/** Creates new form MainMenu */
public MainMenu() {
initComponents();
this.setLocationRelativeTo(null); // Put window in middle of screen
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
underConstructionNote1 = new javax.swing.JLabel();
mainPanel = new javax.swing.JPanel();
shortStoriesLabel = new javax.swing.JLabel();
RomeoAndJulietLabel = new javax.swing.JLabel();
ChristmasCarolLabel = new javax.swing.JLabel();
listLabel = new javax.swing.JLabel();
helpLabel = new javax.swing.JLabel();
creditsLabel = new javax.swing.JLabel();
titleLabel = new javax.swing.JLabel();
backgroundImage = new javax.swing.JLabel();
underConstructionNote1.setText("Under construction!");
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Literary Terms Practice Bank");
setBackground(new java.awt.Color(255, 255, 255));
setBounds(new java.awt.Rectangle(0, 0, 1118, 800));
setName("mainMenuFrame"); // NOI18N
setResizable(false);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowOpened(java.awt.event.WindowEvent evt) {
formWindowOpened(evt);
}
});
mainPanel.setBackground(new java.awt.Color(255, 255, 255));
mainPanel.setMinimumSize(new java.awt.Dimension(691, 822));
mainPanel.setPreferredSize(new java.awt.Dimension(1180, 800));
mainPanel.setLayout(null);
shortStoriesLabel.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
shortStoriesLabelMouseClicked(evt);
}
public void mouseEntered(java.awt.event.MouseEvent evt) {
shortStoriesLabelMouseEntered(evt);
}
});
mainPanel.add(shortStoriesLabel);
shortStoriesLabel.setBounds(60, 30, 110, 430);
RomeoAndJulietLabel.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
RomeoAndJulietLabelMouseClicked(evt);
}
public void mouseEntered(java.awt.event.MouseEvent evt) {
RomeoAndJulietLabelMouseEntered(evt);
}
});
mainPanel.add(RomeoAndJulietLabel);
RomeoAndJulietLabel.setBounds(170, 110, 100, 350);
ChristmasCarolLabel.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
ChristmasCarolLabelMouseClicked(evt);
}
public void mouseEntered(java.awt.event.MouseEvent evt) {
ChristmasCarolLabelMouseEntered(evt);
}
});
mainPanel.add(ChristmasCarolLabel);
ChristmasCarolLabel.setBounds(380, 40, 90, 420);
listLabel.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
listLabel.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
listLabelMouseClicked(evt);
}
public void mouseEntered(java.awt.event.MouseEvent evt) {
listLabelMouseEntered(evt);
}
});
mainPanel.add(listLabel);
listLabel.setBounds(610, 40, 40, 420);
helpLabel.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
helpLabelMouseClicked(evt);
}
public void mouseEntered(java.awt.event.MouseEvent evt) {
helpLabelMouseEntered(evt);
}
});
mainPanel.add(helpLabel);
helpLabel.setBounds(660, 110, 90, 350);
creditsLabel.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N
creditsLabel.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
creditsLabel.setText("<html><em>Made by Aaron Tan</em></html>");
creditsLabel.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);
creditsLabel.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
creditsLabel.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
creditsLabelMouseClicked(evt);
}
});
mainPanel.add(creditsLabel);
creditsLabel.setBounds(600, 490, 140, 20);
titleLabel.setFont(new java.awt.Font("Segoe UI", 0, 24)); // NOI18N
titleLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
titleLabel.setText("<html><em>Literary Terms Practice Bank</em></html>");
titleLabel.setToolTipText("");
mainPanel.add(titleLabel);
titleLabel.setBounds(60, 460, 940, 80);
backgroundImage.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Resources/Images/BookShelf_w_Titles_v3.png"))); // NOI18N
mainPanel.add(backgroundImage);
backgroundImage.setBounds(30, 20, 800, 610);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(mainPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 825, javax.swing.GroupLayout.PREFERRED_SIZE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(mainPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 664, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
// These methods make the mouse cursor turn into a hand when the mouse is over the books
private void ChristmasCarolLabelMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ChristmasCarolLabelMouseEntered
// For example, this method sets the cursor to a hand when the mouse is hovering over A Christmas Carol
ChristmasCarolLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));
}//GEN-LAST:event_ChristmasCarolLabelMouseEntered
private void shortStoriesLabelMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_shortStoriesLabelMouseEntered
shortStoriesLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));
}//GEN-LAST:event_shortStoriesLabelMouseEntered
private void RomeoAndJulietLabelMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_RomeoAndJulietLabelMouseEntered
RomeoAndJulietLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));
}//GEN-LAST:event_RomeoAndJulietLabelMouseEntered
private void listLabelMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_listLabelMouseEntered
listLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));
}//GEN-LAST:event_listLabelMouseEntered
private void helpLabelMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_helpLabelMouseEntered
helpLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));
}//GEN-LAST:event_helpLabelMouseEntered
// These methods hide the main menu and open the correct frame for the selection
private void shortStoriesLabelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_shortStoriesLabelMouseClicked
this.setVisible(false); // Hides the main menu
new ShortStories().setVisible(true); // Shows the short stories frame
}//GEN-LAST:event_shortStoriesLabelMouseClicked
private void RomeoAndJulietLabelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_RomeoAndJulietLabelMouseClicked
this.setVisible(false);
new RomeoAndJuliet().setVisible(true);
}//GEN-LAST:event_RomeoAndJulietLabelMouseClicked
private void ChristmasCarolLabelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ChristmasCarolLabelMouseClicked
this.setVisible(false);
new AChristmasCarol().setVisible(true);
}//GEN-LAST:event_ChristmasCarolLabelMouseClicked
// Opens the list of Literayr Devices
private void listLabelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_listLabelMouseClicked
try {
// This app gets the file located at the filepath
String inputPDF = "Resources/Files/LiteraryTermsList.pdf";
InputStream literaryDevicesAsStream = getClass().getClassLoader().getResourceAsStream(inputPDF);
Path tempOutput = Files.createTempFile("TempList", ".pdf");
tempOutput.toFile().deleteOnExit();
Files.copy(literaryDevicesAsStream, tempOutput, StandardCopyOption.REPLACE_EXISTING);
File literaryTermsList = new File(tempOutput.toFile().getPath());
// And then opens the PDF file with whatever the user has installed as their PDF reader
Desktop.getDesktop().open(literaryTermsList);
} catch (IOException e) { // User does not have a program to open PDFs
JOptionPane.showMessageDialog(null, "Seem like you don't have a program to open PDF files.", "Uh-oh!", JOptionPane.ERROR_MESSAGE);
}
}//GEN-LAST:event_listLabelMouseClicked
private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
this.setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("/Resources/Images/book-icon.png")));
}//GEN-LAST:event_formWindowOpened
// Opens help manual
private void helpLabelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_helpLabelMouseClicked
try {
// This app gets the file located at the filepath
String inputPDF = "Resources/Files/LiteraryDevicesHelp.pdf";
InputStream literaryDevicesAsStream = getClass().getClassLoader().getResourceAsStream(inputPDF);
Path tempOutput = Files.createTempFile("TempList", ".pdf");
tempOutput.toFile().deleteOnExit();
Files.copy(literaryDevicesAsStream, tempOutput, StandardCopyOption.REPLACE_EXISTING);
File literaryTermsList = new File(tempOutput.toFile().getPath());
// And then opens the PDF file with whatever the user has installed as their PDF reader
Desktop.getDesktop().open(literaryTermsList);
} catch (IOException e) { // User does not have a program to open PDFs
JOptionPane.showMessageDialog(null, "Seem like you don't have a program to open PDF files.", "Uh-oh!", JOptionPane.ERROR_MESSAGE);
}
}//GEN-LAST:event_helpLabelMouseClicked
// Open web browser to GitHub page when user clicks the label
private void creditsLabelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_creditsLabelMouseClicked
if (Desktop.isDesktopSupported()) {
try {
Desktop.getDesktop().browse(new URI(("http://github.com/cheeseisdisgusting/")));
} catch (IOException ex) {
Logger.getLogger(MainMenu.class.getName()).log(Level.SEVERE, null, ex);
} catch (URISyntaxException ex) {
Logger.getLogger(MainMenu.class.getName()).log(Level.SEVERE, null, ex);
}
}
}//GEN-LAST:event_creditsLabelMouseClicked
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(MainMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MainMenu().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel ChristmasCarolLabel;
private javax.swing.JLabel RomeoAndJulietLabel;
private javax.swing.JLabel backgroundImage;
private javax.swing.JLabel creditsLabel;
private javax.swing.JLabel helpLabel;
private javax.swing.JLabel listLabel;
private javax.swing.JPanel mainPanel;
private javax.swing.JLabel shortStoriesLabel;
private javax.swing.JLabel titleLabel;
private javax.swing.JLabel underConstructionNote1;
// End of variables declaration//GEN-END:variables
}
|
|
/*
Derby - Class org.apache.derby.impl.store.raw.data.RFResource
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.derby.impl.store.raw.data;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import org.apache.derby.shared.common.error.StandardException;
import org.apache.derby.shared.common.reference.SQLState;
import org.apache.derby.iapi.services.context.ContextManager;
import org.apache.derby.iapi.services.context.ContextService;
import org.apache.derby.iapi.services.daemon.Serviceable;
import org.apache.derby.iapi.store.access.AccessFactoryGlobals;
import org.apache.derby.iapi.store.access.FileResource;
import org.apache.derby.iapi.store.raw.xact.RawTransaction;
import org.apache.derby.io.StorageFile;
class RFResource implements FileResource {
private final BaseDataFileFactory factory;
RFResource(BaseDataFileFactory dataFactory) {
this.factory = dataFactory;
}
/**
@see FileResource#add
@exception StandardException Oops
*/
public long add(String name, InputStream source)
throws StandardException
{
OutputStream os = null;
if (factory.isReadOnly())
{
throw StandardException.newException(SQLState.FILE_READ_ONLY);
}
long generationId = factory.getNextId();
try
{
StorageFile file = getAsFile(name, generationId);
if (file.exists())
{
throw StandardException.newException(
SQLState.FILE_EXISTS, file);
}
ContextManager cm =
FileContainer.getContextService().getCurrentContextManager();
RawTransaction tran =
factory.getRawStoreFactory().getXactFactory().findUserTransaction(
factory.getRawStoreFactory(),
cm,
AccessFactoryGlobals.USER_TRANS_NAME);
// Block the backup, If backup is already in progress wait
// for the backup to finish. Jar files are unlogged but the
// changes to the references to the jar file in the catalogs
// is logged. A consistent backup can not be made when jar file
// is being added.
tran.blockBackup(true);
StorageFile directory = file.getParentDir();
StorageFile parentDir = directory.getParentDir();
boolean pdExisted = parentDir.exists();
if (!directory.exists())
{
if (!directory.mkdirs())
{
throw StandardException.newException(
SQLState.FILE_CANNOT_CREATE_SEGMENT, directory);
}
directory.limitAccessToOwner();
if (!pdExisted) {
parentDir.limitAccessToOwner();
}
}
os = file.getOutputStream();
byte[] data = new byte[4096];
int len;
factory.writeInProgress();
try
{
while ((len = source.read(data)) != -1) {
os.write(data, 0, len);
}
factory.writableStorageFactory.sync( os, false);
}
finally
{
factory.writeFinished();
}
}
catch (IOException ioe)
{
throw StandardException.newException(
SQLState.FILE_UNEXPECTED_EXCEPTION, ioe);
}
finally
{
try {
if (os != null) {
os.close();
}
} catch (IOException ioe2) {/*RESOLVE: Why ignore this?*/}
try {
if (source != null)source.close();
} catch (IOException ioe2) {/* RESOLVE: Why ignore this?*/}
}
return generationId;
}
/**
* @see FileResource#removeJarDir
*/
public void removeJarDir(String f) throws StandardException {
if (factory.isReadOnly())
throw StandardException.newException(SQLState.FILE_READ_ONLY);
ContextManager cm =
FileContainer.getContextService().getCurrentContextManager();
RawTransaction tran =
factory.getRawStoreFactory().getXactFactory().findUserTransaction(
factory.getRawStoreFactory(),
cm,
AccessFactoryGlobals.USER_TRANS_NAME);
StorageFile ff = factory.storageFactory.newStorageFile(f);
Serviceable s = new RemoveFile(ff);
// Since this code is only used during upgrade to post-10.8 databases
// we do no bother to build code for a special RemoveDirOperation and
// do tran.logAndDo (cf. logic in #remove). If the post-commit removal
// doesn't get completed, that is no big issue, the dirs can be removed
// by hand if need be. A prudent DBA will rerun the upgrade from a
// backup if something crashes anyway..
tran.addPostCommitWork(s);
}
/**
@see FileResource#remove
@exception StandardException Oops
*/
public void remove(String name, long currentGenerationId)
throws StandardException
{
if (factory.isReadOnly())
throw StandardException.newException(SQLState.FILE_READ_ONLY);
ContextManager cm = FileContainer.getContextService().getCurrentContextManager();
RawTransaction tran =
factory.getRawStoreFactory().getXactFactory().findUserTransaction(
factory.getRawStoreFactory(),
cm,
AccessFactoryGlobals.USER_TRANS_NAME);
// Block the backup, If backup is already in progress wait
// for the backup to finish. Jar files are unlogged but the
// changes to the references to the jar file in the catalogs
// is logged. A consistent backup can not be made when jar file
// is being removed.
tran.blockBackup(true);
tran.logAndDo(new RemoveFileOperation(name, currentGenerationId, true));
Serviceable s = new RemoveFile(getAsFile(name, currentGenerationId));
tran.addPostCommitWork(s);
}
/**
@see FileResource#replace
@exception StandardException Oops
*/
public long replace(String name, long currentGenerationId, InputStream source)
throws StandardException
{
if (factory.isReadOnly())
throw StandardException.newException(SQLState.FILE_READ_ONLY);
remove(name, currentGenerationId);
long generationId = add(name, source);
return generationId;
}
/**
@see FileResource#getAsFile
*/
public StorageFile getAsFile(String name, long generationId)
{
String versionedFileName = factory.getVersionedName(name, generationId);
return factory.storageFactory.newStorageFile( versionedFileName);
}
public char getSeparatorChar()
{
return factory.storageFactory.getSeparator();
}
} // end of class RFResource
final class RemoveFile implements Serviceable, PrivilegedExceptionAction<Object>
{
private final StorageFile fileToGo;
RemoveFile(StorageFile fileToGo)
{
this.fileToGo = fileToGo;
}
public int performWork(ContextManager context)
throws StandardException
{
try {
AccessController.doPrivileged(this);
} catch (PrivilegedActionException e) {
throw (StandardException) (e.getException());
}
return Serviceable.DONE;
}
public boolean serviceASAP()
{
return false;
}
/**
* File deletion is a quick operation and typically releases substantial
* amount of space very quickly, this work should be done on the
* user thread.
* @return true, this work needs to done on user thread.
*/
public boolean serviceImmediately()
{
return true;
}
public Object run() throws StandardException {
// SECURITY PERMISSION - MP1, OP5
if (fileToGo.exists()) {
if (fileToGo.isDirectory()) {
if (!fileToGo.deleteAll()) {
throw StandardException.newException(
SQLState.FILE_CANNOT_REMOVE_JAR_FILE, fileToGo);
}
} else {
if (!fileToGo.delete()) {
throw StandardException.newException(
SQLState.FILE_CANNOT_REMOVE_JAR_FILE, fileToGo);
}
}
}
return null;
}
}
|
|
/*
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.target;
import java.util.NoSuchElementException;
import org.apache.commons.pool.impl.GenericObjectPool;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.aop.framework.Advised;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.support.StaticApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.tests.sample.beans.Person;
import org.springframework.tests.sample.beans.SerializablePerson;
import org.springframework.tests.sample.beans.SideEffectBean;
import org.springframework.util.SerializationTestUtils;
import static org.junit.Assert.*;
/**
* Tests for pooling invoker interceptor.
* TODO: need to make these tests stronger: it's hard to
* make too many assumptions about a pool.
*
* @author Rod Johnson
* @author Rob Harrop
* @author Chris Beams
*/
@SuppressWarnings("deprecation")
public class CommonsPoolTargetSourceTests {
/**
* Initial count value set in bean factory XML
*/
private static final int INITIAL_COUNT = 10;
private DefaultListableBeanFactory beanFactory;
@Before
public void setUp() throws Exception {
this.beanFactory = new DefaultListableBeanFactory();
new XmlBeanDefinitionReader(this.beanFactory).loadBeanDefinitions(
new ClassPathResource(getClass().getSimpleName() + "-context.xml", getClass()));
}
/**
* We must simulate container shutdown, which should clear threads.
*/
@After
public void tearDown() {
// Will call pool.close()
this.beanFactory.destroySingletons();
}
private void testFunctionality(String name) {
SideEffectBean pooled = (SideEffectBean) beanFactory.getBean(name);
assertEquals(INITIAL_COUNT, pooled.getCount());
pooled.doWork();
assertEquals(INITIAL_COUNT + 1, pooled.getCount());
pooled = (SideEffectBean) beanFactory.getBean(name);
// Just check that it works--we can't make assumptions
// about the count
pooled.doWork();
//assertEquals(INITIAL_COUNT + 1, apartment.getCount() );
}
@Test
public void testFunctionality() {
testFunctionality("pooled");
}
@Test
public void testFunctionalityWithNoInterceptors() {
testFunctionality("pooledNoInterceptors");
}
@Test
public void testConfigMixin() {
SideEffectBean pooled = (SideEffectBean) beanFactory.getBean("pooledWithMixin");
assertEquals(INITIAL_COUNT, pooled.getCount());
PoolingConfig conf = (PoolingConfig) beanFactory.getBean("pooledWithMixin");
// TODO one invocation from setup
//assertEquals(1, conf.getInvocations());
pooled.doWork();
// assertEquals("No objects active", 0, conf.getActive());
assertEquals("Correct target source", 25, conf.getMaxSize());
// assertTrue("Some free", conf.getFree() > 0);
//assertEquals(2, conf.getInvocations());
assertEquals(25, conf.getMaxSize());
}
@Test
public void testTargetSourceSerializableWithoutConfigMixin() throws Exception {
CommonsPoolTargetSource cpts = (CommonsPoolTargetSource) beanFactory.getBean("personPoolTargetSource");
SingletonTargetSource serialized = (SingletonTargetSource) SerializationTestUtils.serializeAndDeserialize(cpts);
assertTrue(serialized.getTarget() instanceof Person);
}
@Test
public void testProxySerializableWithoutConfigMixin() throws Exception {
Person pooled = (Person) beanFactory.getBean("pooledPerson");
//System.out.println(((Advised) pooled).toProxyConfigString());
assertTrue(((Advised) pooled).getTargetSource() instanceof CommonsPoolTargetSource);
//((Advised) pooled).setTargetSource(new SingletonTargetSource(new SerializablePerson()));
Person serialized = (Person) SerializationTestUtils.serializeAndDeserialize(pooled);
assertTrue(((Advised) serialized).getTargetSource() instanceof SingletonTargetSource);
serialized.setAge(25);
assertEquals(25, serialized.getAge());
}
@Test
public void testHitMaxSize() throws Exception {
int maxSize = 10;
CommonsPoolTargetSource targetSource = new CommonsPoolTargetSource();
targetSource.setMaxSize(maxSize);
targetSource.setMaxWait(1);
prepareTargetSource(targetSource);
Object[] pooledInstances = new Object[maxSize];
for (int x = 0; x < maxSize; x++) {
Object instance = targetSource.getTarget();
assertNotNull(instance);
pooledInstances[x] = instance;
}
// should be at maximum now
try {
targetSource.getTarget();
fail("Should throw NoSuchElementException");
}
catch (NoSuchElementException ex) {
// desired
}
// lets now release an object and try to accquire a new one
targetSource.releaseTarget(pooledInstances[9]);
pooledInstances[9] = targetSource.getTarget();
// release all objects
for (int i = 0; i < pooledInstances.length; i++) {
targetSource.releaseTarget(pooledInstances[i]);
}
}
@Test
public void testHitMaxSizeLoadedFromContext() throws Exception {
Advised person = (Advised) beanFactory.getBean("maxSizePooledPerson");
CommonsPoolTargetSource targetSource = (CommonsPoolTargetSource) person.getTargetSource();
int maxSize = targetSource.getMaxSize();
Object[] pooledInstances = new Object[maxSize];
for (int x = 0; x < maxSize; x++) {
Object instance = targetSource.getTarget();
assertNotNull(instance);
pooledInstances[x] = instance;
}
// should be at maximum now
try {
targetSource.getTarget();
fail("Should throw NoSuchElementException");
}
catch (NoSuchElementException ex) {
// desired
}
// lets now release an object and try to accquire a new one
targetSource.releaseTarget(pooledInstances[9]);
pooledInstances[9] = targetSource.getTarget();
// release all objects
for (int i = 0; i < pooledInstances.length; i++) {
targetSource.releaseTarget(pooledInstances[i]);
}
}
@Test
public void testSetWhenExhaustedAction() {
CommonsPoolTargetSource targetSource = new CommonsPoolTargetSource();
targetSource.setWhenExhaustedActionName("WHEN_EXHAUSTED_BLOCK");
assertEquals(GenericObjectPool.WHEN_EXHAUSTED_BLOCK, targetSource.getWhenExhaustedAction());
}
private void prepareTargetSource(CommonsPoolTargetSource targetSource) {
String beanName = "target";
StaticApplicationContext applicationContext = new StaticApplicationContext();
applicationContext.registerPrototype(beanName, SerializablePerson.class);
targetSource.setTargetBeanName(beanName);
targetSource.setBeanFactory(applicationContext);
}
}
|
|
/*
* Copyright (C) 2014 ParanoidAndroid 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.reindeercrafts.notificationpeek.peek;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.preference.PreferenceManager;
import android.util.Log;
import com.reindeercrafts.notificationpeek.settings.PreferenceKeys;
public class SensorActivityHandler {
public final static String ACTION_UPDATE_SENSOR_USE = "NotificationPeek.update_sensor_use";
private final static String TAG = "NotificationPeek.SensorActivityHandler";
private final static int INCREMENTS_TO_DISABLE = 5;
private final static float NOISE_THRESHOLD = 0.5f;
// Minimum proximity detected distance from object. Some devices use 0/1 to indicate
// "near"/"far", others use actual values.
private static final float MIN_PROX_DISTANCE = 3.0f;
private SensorManager mSensorManager;
private SensorEventListener mProximityEventListener;
private SensorEventListener mGyroscopeEventListener;
private Sensor mProximityLightSensor;
private Sensor mGyroscopeSensor;
private ScreenReceiver mScreenReceiver;
private SensorChangedCallback mCallback;
private Context mContext;
private float mLastX = 0, mLastY = 0, mLastZ = 0;
private int mSensorIncrement = 0;
private boolean mWaitingForMovement;
private boolean mHasInitialValues;
private boolean mScreenReceiverRegistered;
private boolean mProximityRegistered;
private boolean mGyroscopeRegistered;
private boolean mInPocket;
private boolean mOnTable;
// User preferences of using sensors or not.
private boolean mUseGyroSensor;
private boolean mUseProxLightSensor;
public SensorActivityHandler(Context context, SensorChangedCallback callback) {
mContext = context;
mCallback = callback;
mScreenReceiver = new ScreenReceiver();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
mUseProxLightSensor = preferences.getBoolean(PreferenceKeys.PREF_PROX_LIGHT_SENSOR, true);
mUseGyroSensor = preferences.getBoolean(PreferenceKeys.PREF_GYRO_SENSOR, true);
initSensors(context);
}
private void initSensors(Context context) {
mSensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
initProximityLightSensor();
initGyroscopeSensor();
}
private void initGyroscopeSensor() {
// get gyroscope sensor for on-table detection
if (mUseGyroSensor) {
mGyroscopeSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
}
if (mGyroscopeSensor != null) {
mGyroscopeEventListener = new SensorEventListener() {
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
@Override
public void onSensorChanged(SensorEvent event) {
float x = event.values[0];
float y = event.values[1];
float z = event.values[1];
boolean storeValues = false;
if (mHasInitialValues) {
float dX = Math.abs(mLastX - x);
float dY = Math.abs(mLastY - y);
float dZ = Math.abs(mLastZ - z);
if (dX >= NOISE_THRESHOLD ||
dY >= NOISE_THRESHOLD || dZ >= NOISE_THRESHOLD) {
if (mWaitingForMovement) {
if (NotificationPeek.DEBUG) {
Log.d(TAG, "On table: false");
}
mOnTable = false;
// If proximity/light sensor is not used, set mInPocket to the same
// as mOnTable to synchronize status.
if (!mUseProxLightSensor) {
mInPocket = mOnTable;
}
mCallback.onTableModeChanged(mOnTable);
registerEventListeners();
mWaitingForMovement = false;
mSensorIncrement = 0;
}
storeValues = true;
} else {
if (mSensorIncrement < INCREMENTS_TO_DISABLE) {
mSensorIncrement++;
if (mSensorIncrement == INCREMENTS_TO_DISABLE) {
unregisterProximityLightEvent();
if (NotificationPeek.DEBUG) {
Log.d(TAG, "On table: true");
}
mOnTable = true;
if (!mUseProxLightSensor) {
mInPocket = mOnTable;
}
mCallback.onTableModeChanged(mOnTable);
mWaitingForMovement = true;
}
}
}
}
if (!mHasInitialValues || storeValues) {
mHasInitialValues = true;
mLastX = x;
mLastY = y;
mLastZ = z;
}
}
};
} else {
// no accelerometer? time to buy a nexus
}
}
private void initProximityLightSensor() {
// get proximity sensor for in-pocket detection, if no proximity sensor detected, try
// light sensor.
if (mUseProxLightSensor) {
mProximityLightSensor =
mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY) != null ?
mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY) :
mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
}
if (mProximityLightSensor != null) {
mProximityEventListener = new SensorEventListener() {
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
@Override
public void onSensorChanged(SensorEvent event) {
boolean inPocket = event.values[0] == 0 || event.values[0] <= MIN_PROX_DISTANCE;
if (inPocket) {
if (mUseGyroSensor) {
mOnTable =
false; // we can't have phone on table and pocket at the same time
}
unregisterGyroscopeEvent();
} else {
// Only register gyroscope sensor listener if user chooses to use it.
if (!mGyroscopeRegistered && mUseGyroSensor) {
registerEventListeners();
}
}
if (NotificationPeek.DEBUG) {
Log.d(TAG, "In pocket: " + inPocket + ", old: " + mInPocket);
}
boolean oldInPocket = mInPocket;
mInPocket = inPocket;
if (!mUseGyroSensor) {
mOnTable = mInPocket;
}
if (oldInPocket != inPocket) {
mCallback.onPocketModeChanged(mInPocket);
}
}
};
} else {
// ugh, that's bad, run now that you can.
}
}
public void updateUseSensors() {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mContext);
boolean useGyro = preferences.getBoolean(PreferenceKeys.PREF_GYRO_SENSOR, true);
boolean useProxLight = preferences.getBoolean(PreferenceKeys.PREF_PROX_LIGHT_SENSOR, true);
if (useGyro == mUseGyroSensor && useProxLight == mUseProxLightSensor) {
// Same as current, return.
return;
}
mUseGyroSensor = useGyro;
mUseProxLightSensor = useProxLight;
if (!mUseGyroSensor) {
unregisterGyroscopeEvent();
mGyroscopeSensor = null;
mOnTable = false;
} else {
initGyroscopeSensor();
}
if (!mUseProxLightSensor) {
unregisterProximityLightEvent();
mProximityLightSensor = null;
mInPocket = false;
} else {
initProximityLightSensor();
}
}
public boolean isInPocket() {
return mInPocket;
}
public boolean isOnTable() {
return mOnTable;
}
public void registerScreenReceiver() {
if (!mScreenReceiverRegistered) {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
intentFilter.addAction(Intent.ACTION_SCREEN_ON);
// Add intent filter for listening to sensor use changes.
intentFilter.addAction(ACTION_UPDATE_SENSOR_USE);
mContext.registerReceiver(mScreenReceiver, intentFilter);
mScreenReceiverRegistered = true;
}
}
public void unregisterScreenReceiver() {
if (mScreenReceiverRegistered) {
mContext.unregisterReceiver(mScreenReceiver);
mScreenReceiverRegistered = false;
}
}
public void registerEventListeners() {
if (mProximityLightSensor != null && !mProximityRegistered && mUseProxLightSensor) {
if (NotificationPeek.DEBUG) {
Log.d(TAG, "Registering proximity polling");
}
mSensorManager.registerListener(mProximityEventListener, mProximityLightSensor,
SensorManager.SENSOR_DELAY_NORMAL);
mProximityRegistered = true;
}
if (mGyroscopeSensor != null && !mGyroscopeRegistered && mUseGyroSensor) {
if (NotificationPeek.DEBUG) {
Log.d(TAG, "Registering gyroscope polling");
}
mSensorManager.registerListener(mGyroscopeEventListener, mGyroscopeSensor,
SensorManager.SENSOR_DELAY_NORMAL);
mGyroscopeRegistered = true;
}
}
public void unregisterEventListeners() {
unregisterProximityLightEvent();
unregisterGyroscopeEvent();
}
private void unregisterProximityLightEvent() {
if (mProximityLightSensor != null && mProximityRegistered) {
if (NotificationPeek.DEBUG) {
Log.d(TAG, "Unregistering proximity polling");
}
mSensorManager.unregisterListener(mProximityEventListener);
mProximityRegistered = false;
}
}
private void unregisterGyroscopeEvent() {
if (mGyroscopeSensor != null && mGyroscopeRegistered) {
if (NotificationPeek.DEBUG) {
Log.d(TAG, "Unregistering gyroscope polling");
}
mSensorManager.unregisterListener(mGyroscopeEventListener);
mLastX = mLastY = mLastZ = 0;
mSensorIncrement = 0;
mGyroscopeRegistered = false;
mHasInitialValues = false;
}
}
public interface SensorChangedCallback {
public abstract void onPocketModeChanged(boolean inPocket);
public abstract void onTableModeChanged(boolean onTable);
public abstract void onScreenStateChanged(boolean screenOn);
}
public class ScreenReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
mCallback.onScreenStateChanged(false);
registerEventListeners();
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
mCallback.onScreenStateChanged(true);
unregisterEventListeners();
} else if (intent.getAction().equals(ACTION_UPDATE_SENSOR_USE)) {
// Update sensor use preferences.
Log.d(TAG, "Update sensor uses");
updateUseSensors();
}
}
}
}
|
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/datastore/v1/query.proto
package com.google.datastore.v1;
/**
* <pre>
* A filter on a specific property.
* </pre>
*
* Protobuf type {@code google.datastore.v1.PropertyFilter}
*/
public final class PropertyFilter extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.datastore.v1.PropertyFilter)
PropertyFilterOrBuilder {
private static final long serialVersionUID = 0L;
// Use PropertyFilter.newBuilder() to construct.
private PropertyFilter(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private PropertyFilter() {
op_ = 0;
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private PropertyFilter(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!parseUnknownFieldProto3(
input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
case 10: {
com.google.datastore.v1.PropertyReference.Builder subBuilder = null;
if (property_ != null) {
subBuilder = property_.toBuilder();
}
property_ = input.readMessage(com.google.datastore.v1.PropertyReference.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(property_);
property_ = subBuilder.buildPartial();
}
break;
}
case 16: {
int rawValue = input.readEnum();
op_ = rawValue;
break;
}
case 26: {
com.google.datastore.v1.Value.Builder subBuilder = null;
if (value_ != null) {
subBuilder = value_.toBuilder();
}
value_ = input.readMessage(com.google.datastore.v1.Value.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(value_);
value_ = subBuilder.buildPartial();
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.datastore.v1.QueryProto.internal_static_google_datastore_v1_PropertyFilter_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.datastore.v1.QueryProto.internal_static_google_datastore_v1_PropertyFilter_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.datastore.v1.PropertyFilter.class, com.google.datastore.v1.PropertyFilter.Builder.class);
}
/**
* <pre>
* A property filter operator.
* </pre>
*
* Protobuf enum {@code google.datastore.v1.PropertyFilter.Operator}
*/
public enum Operator
implements com.google.protobuf.ProtocolMessageEnum {
/**
* <pre>
* Unspecified. This value must not be used.
* </pre>
*
* <code>OPERATOR_UNSPECIFIED = 0;</code>
*/
OPERATOR_UNSPECIFIED(0),
/**
* <pre>
* Less than.
* </pre>
*
* <code>LESS_THAN = 1;</code>
*/
LESS_THAN(1),
/**
* <pre>
* Less than or equal.
* </pre>
*
* <code>LESS_THAN_OR_EQUAL = 2;</code>
*/
LESS_THAN_OR_EQUAL(2),
/**
* <pre>
* Greater than.
* </pre>
*
* <code>GREATER_THAN = 3;</code>
*/
GREATER_THAN(3),
/**
* <pre>
* Greater than or equal.
* </pre>
*
* <code>GREATER_THAN_OR_EQUAL = 4;</code>
*/
GREATER_THAN_OR_EQUAL(4),
/**
* <pre>
* Equal.
* </pre>
*
* <code>EQUAL = 5;</code>
*/
EQUAL(5),
/**
* <pre>
* Has ancestor.
* </pre>
*
* <code>HAS_ANCESTOR = 11;</code>
*/
HAS_ANCESTOR(11),
UNRECOGNIZED(-1),
;
/**
* <pre>
* Unspecified. This value must not be used.
* </pre>
*
* <code>OPERATOR_UNSPECIFIED = 0;</code>
*/
public static final int OPERATOR_UNSPECIFIED_VALUE = 0;
/**
* <pre>
* Less than.
* </pre>
*
* <code>LESS_THAN = 1;</code>
*/
public static final int LESS_THAN_VALUE = 1;
/**
* <pre>
* Less than or equal.
* </pre>
*
* <code>LESS_THAN_OR_EQUAL = 2;</code>
*/
public static final int LESS_THAN_OR_EQUAL_VALUE = 2;
/**
* <pre>
* Greater than.
* </pre>
*
* <code>GREATER_THAN = 3;</code>
*/
public static final int GREATER_THAN_VALUE = 3;
/**
* <pre>
* Greater than or equal.
* </pre>
*
* <code>GREATER_THAN_OR_EQUAL = 4;</code>
*/
public static final int GREATER_THAN_OR_EQUAL_VALUE = 4;
/**
* <pre>
* Equal.
* </pre>
*
* <code>EQUAL = 5;</code>
*/
public static final int EQUAL_VALUE = 5;
/**
* <pre>
* Has ancestor.
* </pre>
*
* <code>HAS_ANCESTOR = 11;</code>
*/
public static final int HAS_ANCESTOR_VALUE = 11;
public final int getNumber() {
if (this == UNRECOGNIZED) {
throw new java.lang.IllegalArgumentException(
"Can't get the number of an unknown enum value.");
}
return value;
}
/**
* @deprecated Use {@link #forNumber(int)} instead.
*/
@java.lang.Deprecated
public static Operator valueOf(int value) {
return forNumber(value);
}
public static Operator forNumber(int value) {
switch (value) {
case 0: return OPERATOR_UNSPECIFIED;
case 1: return LESS_THAN;
case 2: return LESS_THAN_OR_EQUAL;
case 3: return GREATER_THAN;
case 4: return GREATER_THAN_OR_EQUAL;
case 5: return EQUAL;
case 11: return HAS_ANCESTOR;
default: return null;
}
}
public static com.google.protobuf.Internal.EnumLiteMap<Operator>
internalGetValueMap() {
return internalValueMap;
}
private static final com.google.protobuf.Internal.EnumLiteMap<
Operator> internalValueMap =
new com.google.protobuf.Internal.EnumLiteMap<Operator>() {
public Operator findValueByNumber(int number) {
return Operator.forNumber(number);
}
};
public final com.google.protobuf.Descriptors.EnumValueDescriptor
getValueDescriptor() {
return getDescriptor().getValues().get(ordinal());
}
public final com.google.protobuf.Descriptors.EnumDescriptor
getDescriptorForType() {
return getDescriptor();
}
public static final com.google.protobuf.Descriptors.EnumDescriptor
getDescriptor() {
return com.google.datastore.v1.PropertyFilter.getDescriptor().getEnumTypes().get(0);
}
private static final Operator[] VALUES = values();
public static Operator valueOf(
com.google.protobuf.Descriptors.EnumValueDescriptor desc) {
if (desc.getType() != getDescriptor()) {
throw new java.lang.IllegalArgumentException(
"EnumValueDescriptor is not for this type.");
}
if (desc.getIndex() == -1) {
return UNRECOGNIZED;
}
return VALUES[desc.getIndex()];
}
private final int value;
private Operator(int value) {
this.value = value;
}
// @@protoc_insertion_point(enum_scope:google.datastore.v1.PropertyFilter.Operator)
}
public static final int PROPERTY_FIELD_NUMBER = 1;
private com.google.datastore.v1.PropertyReference property_;
/**
* <pre>
* The property to filter by.
* </pre>
*
* <code>.google.datastore.v1.PropertyReference property = 1;</code>
*/
public boolean hasProperty() {
return property_ != null;
}
/**
* <pre>
* The property to filter by.
* </pre>
*
* <code>.google.datastore.v1.PropertyReference property = 1;</code>
*/
public com.google.datastore.v1.PropertyReference getProperty() {
return property_ == null ? com.google.datastore.v1.PropertyReference.getDefaultInstance() : property_;
}
/**
* <pre>
* The property to filter by.
* </pre>
*
* <code>.google.datastore.v1.PropertyReference property = 1;</code>
*/
public com.google.datastore.v1.PropertyReferenceOrBuilder getPropertyOrBuilder() {
return getProperty();
}
public static final int OP_FIELD_NUMBER = 2;
private int op_;
/**
* <pre>
* The operator to filter by.
* </pre>
*
* <code>.google.datastore.v1.PropertyFilter.Operator op = 2;</code>
*/
public int getOpValue() {
return op_;
}
/**
* <pre>
* The operator to filter by.
* </pre>
*
* <code>.google.datastore.v1.PropertyFilter.Operator op = 2;</code>
*/
public com.google.datastore.v1.PropertyFilter.Operator getOp() {
com.google.datastore.v1.PropertyFilter.Operator result = com.google.datastore.v1.PropertyFilter.Operator.valueOf(op_);
return result == null ? com.google.datastore.v1.PropertyFilter.Operator.UNRECOGNIZED : result;
}
public static final int VALUE_FIELD_NUMBER = 3;
private com.google.datastore.v1.Value value_;
/**
* <pre>
* The value to compare the property to.
* </pre>
*
* <code>.google.datastore.v1.Value value = 3;</code>
*/
public boolean hasValue() {
return value_ != null;
}
/**
* <pre>
* The value to compare the property to.
* </pre>
*
* <code>.google.datastore.v1.Value value = 3;</code>
*/
public com.google.datastore.v1.Value getValue() {
return value_ == null ? com.google.datastore.v1.Value.getDefaultInstance() : value_;
}
/**
* <pre>
* The value to compare the property to.
* </pre>
*
* <code>.google.datastore.v1.Value value = 3;</code>
*/
public com.google.datastore.v1.ValueOrBuilder getValueOrBuilder() {
return getValue();
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (property_ != null) {
output.writeMessage(1, getProperty());
}
if (op_ != com.google.datastore.v1.PropertyFilter.Operator.OPERATOR_UNSPECIFIED.getNumber()) {
output.writeEnum(2, op_);
}
if (value_ != null) {
output.writeMessage(3, getValue());
}
unknownFields.writeTo(output);
}
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (property_ != null) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(1, getProperty());
}
if (op_ != com.google.datastore.v1.PropertyFilter.Operator.OPERATOR_UNSPECIFIED.getNumber()) {
size += com.google.protobuf.CodedOutputStream
.computeEnumSize(2, op_);
}
if (value_ != null) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(3, getValue());
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.datastore.v1.PropertyFilter)) {
return super.equals(obj);
}
com.google.datastore.v1.PropertyFilter other = (com.google.datastore.v1.PropertyFilter) obj;
boolean result = true;
result = result && (hasProperty() == other.hasProperty());
if (hasProperty()) {
result = result && getProperty()
.equals(other.getProperty());
}
result = result && op_ == other.op_;
result = result && (hasValue() == other.hasValue());
if (hasValue()) {
result = result && getValue()
.equals(other.getValue());
}
result = result && unknownFields.equals(other.unknownFields);
return result;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (hasProperty()) {
hash = (37 * hash) + PROPERTY_FIELD_NUMBER;
hash = (53 * hash) + getProperty().hashCode();
}
hash = (37 * hash) + OP_FIELD_NUMBER;
hash = (53 * hash) + op_;
if (hasValue()) {
hash = (37 * hash) + VALUE_FIELD_NUMBER;
hash = (53 * hash) + getValue().hashCode();
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.datastore.v1.PropertyFilter parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.datastore.v1.PropertyFilter parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.datastore.v1.PropertyFilter parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.datastore.v1.PropertyFilter parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.datastore.v1.PropertyFilter parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.datastore.v1.PropertyFilter parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.datastore.v1.PropertyFilter parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.datastore.v1.PropertyFilter parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.datastore.v1.PropertyFilter parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.datastore.v1.PropertyFilter parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.datastore.v1.PropertyFilter parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.datastore.v1.PropertyFilter parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.datastore.v1.PropertyFilter prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* <pre>
* A filter on a specific property.
* </pre>
*
* Protobuf type {@code google.datastore.v1.PropertyFilter}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.datastore.v1.PropertyFilter)
com.google.datastore.v1.PropertyFilterOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.datastore.v1.QueryProto.internal_static_google_datastore_v1_PropertyFilter_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.datastore.v1.QueryProto.internal_static_google_datastore_v1_PropertyFilter_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.datastore.v1.PropertyFilter.class, com.google.datastore.v1.PropertyFilter.Builder.class);
}
// Construct using com.google.datastore.v1.PropertyFilter.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
}
}
public Builder clear() {
super.clear();
if (propertyBuilder_ == null) {
property_ = null;
} else {
property_ = null;
propertyBuilder_ = null;
}
op_ = 0;
if (valueBuilder_ == null) {
value_ = null;
} else {
value_ = null;
valueBuilder_ = null;
}
return this;
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.datastore.v1.QueryProto.internal_static_google_datastore_v1_PropertyFilter_descriptor;
}
public com.google.datastore.v1.PropertyFilter getDefaultInstanceForType() {
return com.google.datastore.v1.PropertyFilter.getDefaultInstance();
}
public com.google.datastore.v1.PropertyFilter build() {
com.google.datastore.v1.PropertyFilter result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public com.google.datastore.v1.PropertyFilter buildPartial() {
com.google.datastore.v1.PropertyFilter result = new com.google.datastore.v1.PropertyFilter(this);
if (propertyBuilder_ == null) {
result.property_ = property_;
} else {
result.property_ = propertyBuilder_.build();
}
result.op_ = op_;
if (valueBuilder_ == null) {
result.value_ = value_;
} else {
result.value_ = valueBuilder_.build();
}
onBuilt();
return result;
}
public Builder clone() {
return (Builder) super.clone();
}
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return (Builder) super.setField(field, value);
}
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return (Builder) super.clearField(field);
}
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return (Builder) super.clearOneof(oneof);
}
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return (Builder) super.setRepeatedField(field, index, value);
}
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return (Builder) super.addRepeatedField(field, value);
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.datastore.v1.PropertyFilter) {
return mergeFrom((com.google.datastore.v1.PropertyFilter)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.datastore.v1.PropertyFilter other) {
if (other == com.google.datastore.v1.PropertyFilter.getDefaultInstance()) return this;
if (other.hasProperty()) {
mergeProperty(other.getProperty());
}
if (other.op_ != 0) {
setOpValue(other.getOpValue());
}
if (other.hasValue()) {
mergeValue(other.getValue());
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
public final boolean isInitialized() {
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.datastore.v1.PropertyFilter parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.google.datastore.v1.PropertyFilter) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private com.google.datastore.v1.PropertyReference property_ = null;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.datastore.v1.PropertyReference, com.google.datastore.v1.PropertyReference.Builder, com.google.datastore.v1.PropertyReferenceOrBuilder> propertyBuilder_;
/**
* <pre>
* The property to filter by.
* </pre>
*
* <code>.google.datastore.v1.PropertyReference property = 1;</code>
*/
public boolean hasProperty() {
return propertyBuilder_ != null || property_ != null;
}
/**
* <pre>
* The property to filter by.
* </pre>
*
* <code>.google.datastore.v1.PropertyReference property = 1;</code>
*/
public com.google.datastore.v1.PropertyReference getProperty() {
if (propertyBuilder_ == null) {
return property_ == null ? com.google.datastore.v1.PropertyReference.getDefaultInstance() : property_;
} else {
return propertyBuilder_.getMessage();
}
}
/**
* <pre>
* The property to filter by.
* </pre>
*
* <code>.google.datastore.v1.PropertyReference property = 1;</code>
*/
public Builder setProperty(com.google.datastore.v1.PropertyReference value) {
if (propertyBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
property_ = value;
onChanged();
} else {
propertyBuilder_.setMessage(value);
}
return this;
}
/**
* <pre>
* The property to filter by.
* </pre>
*
* <code>.google.datastore.v1.PropertyReference property = 1;</code>
*/
public Builder setProperty(
com.google.datastore.v1.PropertyReference.Builder builderForValue) {
if (propertyBuilder_ == null) {
property_ = builderForValue.build();
onChanged();
} else {
propertyBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
* <pre>
* The property to filter by.
* </pre>
*
* <code>.google.datastore.v1.PropertyReference property = 1;</code>
*/
public Builder mergeProperty(com.google.datastore.v1.PropertyReference value) {
if (propertyBuilder_ == null) {
if (property_ != null) {
property_ =
com.google.datastore.v1.PropertyReference.newBuilder(property_).mergeFrom(value).buildPartial();
} else {
property_ = value;
}
onChanged();
} else {
propertyBuilder_.mergeFrom(value);
}
return this;
}
/**
* <pre>
* The property to filter by.
* </pre>
*
* <code>.google.datastore.v1.PropertyReference property = 1;</code>
*/
public Builder clearProperty() {
if (propertyBuilder_ == null) {
property_ = null;
onChanged();
} else {
property_ = null;
propertyBuilder_ = null;
}
return this;
}
/**
* <pre>
* The property to filter by.
* </pre>
*
* <code>.google.datastore.v1.PropertyReference property = 1;</code>
*/
public com.google.datastore.v1.PropertyReference.Builder getPropertyBuilder() {
onChanged();
return getPropertyFieldBuilder().getBuilder();
}
/**
* <pre>
* The property to filter by.
* </pre>
*
* <code>.google.datastore.v1.PropertyReference property = 1;</code>
*/
public com.google.datastore.v1.PropertyReferenceOrBuilder getPropertyOrBuilder() {
if (propertyBuilder_ != null) {
return propertyBuilder_.getMessageOrBuilder();
} else {
return property_ == null ?
com.google.datastore.v1.PropertyReference.getDefaultInstance() : property_;
}
}
/**
* <pre>
* The property to filter by.
* </pre>
*
* <code>.google.datastore.v1.PropertyReference property = 1;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.datastore.v1.PropertyReference, com.google.datastore.v1.PropertyReference.Builder, com.google.datastore.v1.PropertyReferenceOrBuilder>
getPropertyFieldBuilder() {
if (propertyBuilder_ == null) {
propertyBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
com.google.datastore.v1.PropertyReference, com.google.datastore.v1.PropertyReference.Builder, com.google.datastore.v1.PropertyReferenceOrBuilder>(
getProperty(),
getParentForChildren(),
isClean());
property_ = null;
}
return propertyBuilder_;
}
private int op_ = 0;
/**
* <pre>
* The operator to filter by.
* </pre>
*
* <code>.google.datastore.v1.PropertyFilter.Operator op = 2;</code>
*/
public int getOpValue() {
return op_;
}
/**
* <pre>
* The operator to filter by.
* </pre>
*
* <code>.google.datastore.v1.PropertyFilter.Operator op = 2;</code>
*/
public Builder setOpValue(int value) {
op_ = value;
onChanged();
return this;
}
/**
* <pre>
* The operator to filter by.
* </pre>
*
* <code>.google.datastore.v1.PropertyFilter.Operator op = 2;</code>
*/
public com.google.datastore.v1.PropertyFilter.Operator getOp() {
com.google.datastore.v1.PropertyFilter.Operator result = com.google.datastore.v1.PropertyFilter.Operator.valueOf(op_);
return result == null ? com.google.datastore.v1.PropertyFilter.Operator.UNRECOGNIZED : result;
}
/**
* <pre>
* The operator to filter by.
* </pre>
*
* <code>.google.datastore.v1.PropertyFilter.Operator op = 2;</code>
*/
public Builder setOp(com.google.datastore.v1.PropertyFilter.Operator value) {
if (value == null) {
throw new NullPointerException();
}
op_ = value.getNumber();
onChanged();
return this;
}
/**
* <pre>
* The operator to filter by.
* </pre>
*
* <code>.google.datastore.v1.PropertyFilter.Operator op = 2;</code>
*/
public Builder clearOp() {
op_ = 0;
onChanged();
return this;
}
private com.google.datastore.v1.Value value_ = null;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.datastore.v1.Value, com.google.datastore.v1.Value.Builder, com.google.datastore.v1.ValueOrBuilder> valueBuilder_;
/**
* <pre>
* The value to compare the property to.
* </pre>
*
* <code>.google.datastore.v1.Value value = 3;</code>
*/
public boolean hasValue() {
return valueBuilder_ != null || value_ != null;
}
/**
* <pre>
* The value to compare the property to.
* </pre>
*
* <code>.google.datastore.v1.Value value = 3;</code>
*/
public com.google.datastore.v1.Value getValue() {
if (valueBuilder_ == null) {
return value_ == null ? com.google.datastore.v1.Value.getDefaultInstance() : value_;
} else {
return valueBuilder_.getMessage();
}
}
/**
* <pre>
* The value to compare the property to.
* </pre>
*
* <code>.google.datastore.v1.Value value = 3;</code>
*/
public Builder setValue(com.google.datastore.v1.Value value) {
if (valueBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
value_ = value;
onChanged();
} else {
valueBuilder_.setMessage(value);
}
return this;
}
/**
* <pre>
* The value to compare the property to.
* </pre>
*
* <code>.google.datastore.v1.Value value = 3;</code>
*/
public Builder setValue(
com.google.datastore.v1.Value.Builder builderForValue) {
if (valueBuilder_ == null) {
value_ = builderForValue.build();
onChanged();
} else {
valueBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
* <pre>
* The value to compare the property to.
* </pre>
*
* <code>.google.datastore.v1.Value value = 3;</code>
*/
public Builder mergeValue(com.google.datastore.v1.Value value) {
if (valueBuilder_ == null) {
if (value_ != null) {
value_ =
com.google.datastore.v1.Value.newBuilder(value_).mergeFrom(value).buildPartial();
} else {
value_ = value;
}
onChanged();
} else {
valueBuilder_.mergeFrom(value);
}
return this;
}
/**
* <pre>
* The value to compare the property to.
* </pre>
*
* <code>.google.datastore.v1.Value value = 3;</code>
*/
public Builder clearValue() {
if (valueBuilder_ == null) {
value_ = null;
onChanged();
} else {
value_ = null;
valueBuilder_ = null;
}
return this;
}
/**
* <pre>
* The value to compare the property to.
* </pre>
*
* <code>.google.datastore.v1.Value value = 3;</code>
*/
public com.google.datastore.v1.Value.Builder getValueBuilder() {
onChanged();
return getValueFieldBuilder().getBuilder();
}
/**
* <pre>
* The value to compare the property to.
* </pre>
*
* <code>.google.datastore.v1.Value value = 3;</code>
*/
public com.google.datastore.v1.ValueOrBuilder getValueOrBuilder() {
if (valueBuilder_ != null) {
return valueBuilder_.getMessageOrBuilder();
} else {
return value_ == null ?
com.google.datastore.v1.Value.getDefaultInstance() : value_;
}
}
/**
* <pre>
* The value to compare the property to.
* </pre>
*
* <code>.google.datastore.v1.Value value = 3;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.datastore.v1.Value, com.google.datastore.v1.Value.Builder, com.google.datastore.v1.ValueOrBuilder>
getValueFieldBuilder() {
if (valueBuilder_ == null) {
valueBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
com.google.datastore.v1.Value, com.google.datastore.v1.Value.Builder, com.google.datastore.v1.ValueOrBuilder>(
getValue(),
getParentForChildren(),
isClean());
value_ = null;
}
return valueBuilder_;
}
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFieldsProto3(unknownFields);
}
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.datastore.v1.PropertyFilter)
}
// @@protoc_insertion_point(class_scope:google.datastore.v1.PropertyFilter)
private static final com.google.datastore.v1.PropertyFilter DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.datastore.v1.PropertyFilter();
}
public static com.google.datastore.v1.PropertyFilter getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<PropertyFilter>
PARSER = new com.google.protobuf.AbstractParser<PropertyFilter>() {
public PropertyFilter parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new PropertyFilter(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<PropertyFilter> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<PropertyFilter> getParserForType() {
return PARSER;
}
public com.google.datastore.v1.PropertyFilter getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
|
/*
* Copyright (c) 2008-2020, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.jet.impl.execution;
import com.hazelcast.cluster.Address;
import com.hazelcast.internal.metrics.MetricDescriptor;
import com.hazelcast.internal.metrics.MetricsCollectionContext;
import com.hazelcast.internal.metrics.Probe;
import com.hazelcast.internal.metrics.ProbeUnit;
import com.hazelcast.internal.nio.BufferObjectDataInput;
import com.hazelcast.internal.nio.Connection;
import com.hazelcast.internal.serialization.InternalSerializationService;
import com.hazelcast.internal.util.concurrent.MPSCQueue;
import com.hazelcast.internal.util.counters.Counter;
import com.hazelcast.internal.util.counters.SwCounter;
import com.hazelcast.jet.RestartableException;
import com.hazelcast.jet.config.InstanceConfig;
import com.hazelcast.jet.core.metrics.MetricNames;
import com.hazelcast.jet.core.metrics.MetricTags;
import com.hazelcast.jet.impl.util.ObjectWithPartitionId;
import com.hazelcast.jet.impl.util.ProgressState;
import com.hazelcast.jet.impl.util.ProgressTracker;
import com.hazelcast.logging.ILogger;
import com.hazelcast.logging.LoggingService;
import javax.annotation.Nonnull;
import java.io.IOException;
import java.util.ArrayDeque;
import java.util.Objects;
import java.util.Queue;
import static com.hazelcast.jet.impl.execution.DoneItem.DONE_ITEM;
import static com.hazelcast.jet.impl.util.ExceptionUtil.rethrow;
import static com.hazelcast.jet.impl.util.LoggingUtil.logFinest;
import static com.hazelcast.jet.impl.util.PrefixedLogger.prefixedLogger;
import static java.lang.Math.ceil;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
/**
* Receives from a remote member the data associated with a single edge.
*/
public class ReceiverTasklet implements Tasklet {
/**
* The {@code ackedSeq} field holds the sequence number acknowledged to the
* sender as having been received and processed. The sequence increments in
* terms of the estimated heap occupancy of each received item, in bytes.
* However, to save on network traffic, the number reported to the sender
* is coarser-grained: it counts in units of {@code 1 <<
* COMPRESSED_SEQ_UNIT_LOG2}. For example, with a value of 20 the unit
* would be one megabyte. The coarse-grained seq is called "compressed
* seq".
*/
static final int COMPRESSED_SEQ_UNIT_LOG2 = 16;
/**
* The Receive Window, in analogy to TCP's RWIN, is the number of compressed
* seq units the sender can be ahead of the acknowledged seq. The
* correspondence between a compressed seq unit and bytes is defined by the
* constant {@link #COMPRESSED_SEQ_UNIT_LOG2}.
* <p>
* This constant specifies the initial size of the receive window. The
* window is constantly adapted according to the actual data flow through
* the receiver tasklet.
*/
static final int INITIAL_RECEIVE_WINDOW_COMPRESSED = 800;
/**
* The Receive Window converges towards the amount of data processed per
* flow-control period multiplied by this number.
*/
private final int rwinMultiplier;
private final double flowControlPeriodNs;
private final ILogger logger;
/* Used for metrics */
private final String sourceAddressString;
private final String ordinalString;
private final String destinationVertexName;
private final Connection memberConnection;
private final Queue<BufferObjectDataInput> incoming = new MPSCQueue<>(null);
private final ProgressTracker tracker = new ProgressTracker();
private final ArrayDeque<ObjWithPtionIdAndSize> inbox = new ArrayDeque<>();
private final OutboundCollector collector;
private final InternalSerializationService serializationService;
private boolean receptionDone;
@Probe(name = MetricNames.DISTRIBUTED_ITEMS_IN)
private final Counter itemsInCounter = SwCounter.newSwCounter();
@Probe(name = MetricNames.DISTRIBUTED_BYTES_IN, unit = ProbeUnit.BYTES)
private final Counter bytesInCounter = SwCounter.newSwCounter();
// FLOW-CONTROL STATE
// All arrays are indexed by sender ID.
// read by a task scheduler thread, written by a tasklet execution thread
private volatile long ackedSeq;
private volatile int numWaitingInInbox;
private volatile boolean connectionChanged;
// read and written by updateAndGetSendSeqLimitCompressed(), which is invoked sequentially by a task scheduler
private int receiveWindowCompressed;
private int prevAckedSeqCompressed;
private long prevTimestamp;
// END FLOW-CONTROL STATE
public ReceiverTasklet(
OutboundCollector collector, InternalSerializationService serializationService,
int rwinMultiplier, int flowControlPeriodMs, LoggingService loggingService,
Address sourceAddress, int ordinal, String destinationVertexName,
Connection memberConnection, String jobPrefix
) {
this.collector = collector;
this.serializationService = serializationService;
this.rwinMultiplier = rwinMultiplier;
this.flowControlPeriodNs = (double) MILLISECONDS.toNanos(flowControlPeriodMs);
this.sourceAddressString = sourceAddress.toString();
this.ordinalString = "" + ordinal;
this.destinationVertexName = destinationVertexName;
this.memberConnection = memberConnection;
String prefix = String.format("%s/receiverFor:%s#%d", jobPrefix, destinationVertexName, ordinal);
this.logger = prefixedLogger(loggingService.getLogger(getClass()), prefix);
this.receiveWindowCompressed = INITIAL_RECEIVE_WINDOW_COMPRESSED;
}
@Override
@Nonnull
public ProgressState call() {
if (receptionDone) {
return collector.offerBroadcast(DONE_ITEM);
}
if (connectionChanged) {
throw new RestartableException("The member was reconnected: " + sourceAddressString);
}
tracker.reset();
tracker.notDone();
tryFillInbox();
int ackItemLocal = 0;
for (ObjWithPtionIdAndSize o; (o = inbox.peek()) != null; ) {
final Object item = o.getItem();
if (item == DONE_ITEM) {
receptionDone = true;
inbox.remove();
assert inbox.peek() == null : "Found something in the queue beyond the DONE_ITEM: " + inbox.remove();
break;
}
ProgressState outcome = item instanceof BroadcastItem
? collector.offerBroadcast((BroadcastItem) item)
: collector.offer(item, o.getPartitionId());
if (!outcome.isDone()) {
tracker.madeProgress(outcome.isMadeProgress());
break;
}
tracker.madeProgress();
inbox.remove();
ackItemLocal += o.estimatedMemoryFootprint;
}
ackItem(ackItemLocal);
numWaitingInInbox = inbox.size();
return tracker.toProgressState();
}
void receiveStreamPacket(byte[] payload, int offset) {
BufferObjectDataInput input = serializationService.createObjectDataInput(payload, offset);
incoming.add(input);
}
/**
* Calls {@link #updateAndGetSendSeqLimitCompressed(long, Connection)} with {@code
* System.nanoTime()} and the current acked seq for the given sender ID.
*/
public int updateAndGetSendSeqLimitCompressed(Connection expectedConnection) {
return updateAndGetSendSeqLimitCompressed(System.nanoTime(), expectedConnection);
}
/**
* Calculates the upper limit for the compressed value of {@link
* SenderTasklet#sentSeq}, which constrains how much more data the remote
* sender tasklet can send to this tasklet. Steps to calculate the limit:
* <ol><li>
* Calculate the following:
* <ol type="a"><li>
* {@code timeDelta} = difference between the timestamps of this and previous
* method call
* </li><li>
* {@code seqDelta} = amount of data processed by the receiver between the calls,
* measured in compressed seq units (see {@link #COMPRESSED_SEQ_UNIT_LOG2})
* </li><li>
* {@code seqsPerAckPeriod = (seqDelta / timeDelta) * }
* {@link InstanceConfig#setFlowControlPeriodMs(int)
* flowControlPeriodMs}, projected amount of data processed by the receiver
* in one standard flow control period (called "ack period" for short)
* </li></ol>
* </li><li>
* Define the <emph>target receive window</emph> as {@code 3 * seqsPerAckPeriod}.
* </li><li>
* Adjust the current receive window halfway toward the target receive window.
* </li><li>
* Return the {@code sentSeq} limit as the current acked seq plus the current
* receive window.
* </li></ol>
*
* @param timestampNow value of the timestamp at the time the method is called. The timestamp
* must be obtained from {@code System.nanoTime()}.
* @param expectedConnection The connection to which the result will be sent. We use it
* to check that it's the same connection the tasklet was crated with.
*/
// Invoked sequentially by a task scheduler
int updateAndGetSendSeqLimitCompressed(long timestampNow, Connection expectedConnection) {
if (!Objects.equals(expectedConnection, memberConnection)) {
connectionChanged = true;
}
final boolean hadPrevStats = prevTimestamp != 0 || prevAckedSeqCompressed != 0;
final long ackTimeDelta = timestampNow - prevTimestamp;
prevTimestamp = timestampNow;
final int ackedSeqCompressed = compressSeq(ackedSeq);
final int ackedSeqCompressedDelta = ackedSeqCompressed - prevAckedSeqCompressed;
prevAckedSeqCompressed = ackedSeqCompressed;
if (hadPrevStats) {
final double ackedSeqsPerAckPeriod = flowControlPeriodNs * ackedSeqCompressedDelta / ackTimeDelta;
final int targetRwin = rwinMultiplier * (int) ceil(ackedSeqsPerAckPeriod);
int rwinDiff = targetRwin - receiveWindowCompressed;
int numWaitingInInbox = this.numWaitingInInbox;
// If nothing is waiting in the inbox, our processing speed isn't the cause
// for less traffic through the processor, it's the sender who's not
// sending enough data. Don't shrink the RWIN in this case.
if (numWaitingInInbox == 0 && rwinDiff < 0) {
rwinDiff = 0;
}
rwinDiff /= 2;
receiveWindowCompressed += rwinDiff;
if (rwinDiff != 0) {
logFinest(logger, "receiveWindowCompressed changed by %d to %d", rwinDiff, receiveWindowCompressed);
}
}
return ackedSeqCompressed + receiveWindowCompressed;
}
// Only one thread writes to ackedSeq
@SuppressWarnings("NonAtomicOperationOnVolatileField")
long ackItem(long itemWeight) {
return ackedSeq += itemWeight;
}
/**
* To be called only from testing code.
*/
void setNumWaitingInInbox(int value) {
this.numWaitingInInbox = value;
}
@Override
public String toString() {
return "ReceiverTasklet";
}
static int compressSeq(long seq) {
return (int) (seq >> COMPRESSED_SEQ_UNIT_LOG2);
}
static long estimatedMemoryFootprint(long itemBlobSize) {
final int inboxSlot = 4; // slot in ArrayDeque<ObjPtionAndSenderId> inbox
final int objPtionAndSenderIdHeader = 16; // object header of ObjPtionAndSenderId instance
final int itemField = 4; // ObjectWithPartitionId.item
final int itemObjHeader = 16; // header of the item object (unknown type)
final int partitionIdField = 4; // ObjectWithPartitionId.item
final int senderIdField = 4; // ObjectWithPartitionId.senderId
final int estimatedMemoryFootprintField = 8; // ObjectWithPartitionId.estimatedMemoryFootprint
final int overhead = inboxSlot + objPtionAndSenderIdHeader + itemField + itemObjHeader + partitionIdField
+ senderIdField + estimatedMemoryFootprintField;
return overhead + itemBlobSize;
}
private void tryFillInbox() {
try {
long totalBytes = 0;
long totalItems = 0;
for (BufferObjectDataInput received; (received = incoming.poll()) != null; ) {
final int itemCount = received.readInt();
for (int i = 0; i < itemCount; i++) {
final int mark = received.position();
final Object item = received.readObject();
final int itemSize = received.position() - mark;
inbox.add(new ObjWithPtionIdAndSize(item, received.readInt(), itemSize));
}
totalItems += itemCount;
totalBytes += received.position();
received.close();
tracker.madeProgress();
}
bytesInCounter.inc(totalBytes);
itemsInCounter.inc(totalItems);
} catch (IOException e) {
throw rethrow(e);
}
}
private static class ObjWithPtionIdAndSize extends ObjectWithPartitionId {
final long estimatedMemoryFootprint;
ObjWithPtionIdAndSize(Object item, int partitionId, int itemBlobSize) {
super(item, partitionId);
this.estimatedMemoryFootprint = estimatedMemoryFootprint(itemBlobSize);
}
}
@Override
public void provideDynamicMetrics(MetricDescriptor descriptor, MetricsCollectionContext context) {
descriptor = descriptor.withTag(MetricTags.VERTEX, destinationVertexName)
.withTag(MetricTags.SOURCE_ADDRESS, sourceAddressString)
.withTag(MetricTags.ORDINAL, ordinalString);
context.collect(descriptor, 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
*
* 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.indexing.overlord;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.base.Supplier;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.test.TestingCluster;
import org.apache.druid.common.guava.DSuppliers;
import org.apache.druid.curator.PotentiallyGzippedCompressionProvider;
import org.apache.druid.curator.cache.PathChildrenCacheFactory;
import org.apache.druid.indexer.TaskLocation;
import org.apache.druid.indexer.TaskStatus;
import org.apache.druid.indexing.common.IndexingServiceCondition;
import org.apache.druid.indexing.common.TestUtils;
import org.apache.druid.indexing.common.task.Task;
import org.apache.druid.indexing.overlord.autoscaling.NoopProvisioningStrategy;
import org.apache.druid.indexing.overlord.autoscaling.ProvisioningStrategy;
import org.apache.druid.indexing.overlord.config.RemoteTaskRunnerConfig;
import org.apache.druid.indexing.overlord.setup.DefaultWorkerBehaviorConfig;
import org.apache.druid.indexing.overlord.setup.WorkerBehaviorConfig;
import org.apache.druid.indexing.worker.TaskAnnouncement;
import org.apache.druid.indexing.worker.Worker;
import org.apache.druid.indexing.worker.config.WorkerConfig;
import org.apache.druid.java.util.common.StringUtils;
import org.apache.druid.java.util.http.client.HttpClient;
import org.apache.druid.server.initialization.IndexerZkConfig;
import org.apache.druid.server.initialization.ZkPathsConfig;
import org.apache.zookeeper.CreateMode;
import java.util.concurrent.atomic.AtomicReference;
/**
*/
public class RemoteTaskRunnerTestUtils
{
static final Joiner JOINER = Joiner.on("/");
static final String BASE_PATH = "/test/druid";
static final String ANNOUNCEMENTS_PATH = StringUtils.format("%s/indexer/announcements", BASE_PATH);
static final String TASKS_PATH = StringUtils.format("%s/indexer/tasks", BASE_PATH);
static final String STATUS_PATH = StringUtils.format("%s/indexer/status", BASE_PATH);
static final TaskLocation DUMMY_LOCATION = TaskLocation.create("dummy", 9000, -1);
private TestingCluster testingCluster;
private CuratorFramework cf;
private ObjectMapper jsonMapper;
RemoteTaskRunnerTestUtils()
{
TestUtils testUtils = new TestUtils();
jsonMapper = testUtils.getTestObjectMapper();
}
CuratorFramework getCuratorFramework()
{
return cf;
}
ObjectMapper getObjectMapper()
{
return jsonMapper;
}
void setUp() throws Exception
{
testingCluster = new TestingCluster(1);
testingCluster.start();
cf = CuratorFrameworkFactory.builder()
.connectString(testingCluster.getConnectString())
.retryPolicy(new ExponentialBackoffRetry(1, 10))
.compressionProvider(new PotentiallyGzippedCompressionProvider(false))
.build();
cf.start();
cf.blockUntilConnected();
cf.create().creatingParentsIfNeeded().forPath(BASE_PATH);
cf.create().creatingParentsIfNeeded().forPath(TASKS_PATH);
}
void tearDown() throws Exception
{
cf.close();
testingCluster.stop();
}
RemoteTaskRunner makeRemoteTaskRunner(RemoteTaskRunnerConfig config)
{
NoopProvisioningStrategy<WorkerTaskRunner> resourceManagement = new NoopProvisioningStrategy<>();
return makeRemoteTaskRunner(config, resourceManagement);
}
public RemoteTaskRunner makeRemoteTaskRunner(
RemoteTaskRunnerConfig config,
ProvisioningStrategy<WorkerTaskRunner> provisioningStrategy
)
{
RemoteTaskRunner remoteTaskRunner = new TestableRemoteTaskRunner(
jsonMapper,
config,
new IndexerZkConfig(
new ZkPathsConfig()
{
@Override
public String getBase()
{
return BASE_PATH;
}
}, null, null, null, null
),
cf,
new PathChildrenCacheFactory.Builder(),
null,
DSuppliers.of(new AtomicReference<>(DefaultWorkerBehaviorConfig.defaultConfig())),
provisioningStrategy
);
remoteTaskRunner.start();
return remoteTaskRunner;
}
Worker makeWorker(final String workerId, final int capacity) throws Exception
{
Worker worker = new Worker(
"http",
workerId,
workerId,
capacity,
"0",
WorkerConfig.DEFAULT_CATEGORY
);
cf.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(
JOINER.join(ANNOUNCEMENTS_PATH, workerId),
jsonMapper.writeValueAsBytes(worker)
);
cf.create().creatingParentsIfNeeded().forPath(JOINER.join(TASKS_PATH, workerId));
return worker;
}
void disableWorker(Worker worker) throws Exception
{
cf.setData().forPath(
JOINER.join(ANNOUNCEMENTS_PATH, worker.getHost()),
jsonMapper.writeValueAsBytes(new Worker(
worker.getScheme(),
worker.getHost(),
worker.getIp(),
worker.getCapacity(),
"",
worker.getCategory()
))
);
}
void mockWorkerRunningTask(final String workerId, final Task task) throws Exception
{
cf.delete().forPath(JOINER.join(TASKS_PATH, workerId, task.getId()));
final String taskStatusPath = JOINER.join(STATUS_PATH, workerId, task.getId());
TaskAnnouncement taskAnnouncement = TaskAnnouncement.create(task, TaskStatus.running(task.getId()), DUMMY_LOCATION);
cf.create()
.creatingParentsIfNeeded()
.forPath(taskStatusPath, jsonMapper.writeValueAsBytes(taskAnnouncement));
Preconditions.checkNotNull(
cf.checkExists().forPath(taskStatusPath),
"Failed to write status on [%s]",
taskStatusPath
);
}
void mockWorkerCompleteSuccessfulTask(final String workerId, final Task task) throws Exception
{
TaskAnnouncement taskAnnouncement = TaskAnnouncement.create(task, TaskStatus.success(task.getId()), DUMMY_LOCATION);
cf.setData().forPath(JOINER.join(STATUS_PATH, workerId, task.getId()), jsonMapper.writeValueAsBytes(taskAnnouncement));
}
void mockWorkerCompleteFailedTask(final String workerId, final Task task) throws Exception
{
TaskAnnouncement taskAnnouncement = TaskAnnouncement.create(task, TaskStatus.failure(task.getId()), DUMMY_LOCATION);
cf.setData().forPath(JOINER.join(STATUS_PATH, workerId, task.getId()), jsonMapper.writeValueAsBytes(taskAnnouncement));
}
boolean workerRunningTask(final String workerId, final String taskId)
{
return pathExists(JOINER.join(STATUS_PATH, workerId, taskId));
}
boolean taskAnnounced(final String workerId, final String taskId)
{
return pathExists(JOINER.join(TASKS_PATH, workerId, taskId));
}
boolean pathExists(final String path)
{
return TestUtils.conditionValid(
new IndexingServiceCondition()
{
@Override
public boolean isValid()
{
try {
return cf.checkExists().forPath(path) != null;
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public String toString()
{
return StringUtils.format("Path[%s] exists", path);
}
}
);
}
public static class TestableRemoteTaskRunner extends RemoteTaskRunner
{
private long currentTimeMillis = System.currentTimeMillis();
public TestableRemoteTaskRunner(
ObjectMapper jsonMapper,
RemoteTaskRunnerConfig config,
IndexerZkConfig indexerZkConfig,
CuratorFramework cf,
PathChildrenCacheFactory.Builder pathChildrenCacheFactory,
HttpClient httpClient,
Supplier<WorkerBehaviorConfig> workerConfigRef,
ProvisioningStrategy<WorkerTaskRunner> provisioningStrategy
)
{
super(
jsonMapper,
config,
indexerZkConfig,
cf,
pathChildrenCacheFactory,
httpClient,
workerConfigRef,
provisioningStrategy
);
}
void setCurrentTimeMillis(long currentTimeMillis)
{
this.currentTimeMillis = currentTimeMillis;
}
@Override
protected long getCurrentTimeMillis()
{
return currentTimeMillis;
}
}
}
|
|
package com.crazyhitty.chdev.ks.firebasechat.ui.fragments;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.crazyhitty.chdev.ks.firebasechat.R;
import com.crazyhitty.chdev.ks.firebasechat.core.chat.ChatContract;
import com.crazyhitty.chdev.ks.firebasechat.core.chat.ChatPresenter;
import com.crazyhitty.chdev.ks.firebasechat.events.PushNotificationEvent;
import com.crazyhitty.chdev.ks.firebasechat.models.Chat;
import com.crazyhitty.chdev.ks.firebasechat.ui.activities.TakePhotoDelegateActivity;
import com.crazyhitty.chdev.ks.firebasechat.ui.adapters.ChatRecyclerAdapter;
import com.crazyhitty.chdev.ks.firebasechat.utils.Constants;
import com.crazyhitty.chdev.ks.firebasechat.utils.UploadImageUtil;
import com.google.firebase.auth.FirebaseAuth;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import java.io.File;
import java.util.ArrayList;
import java.util.logging.MemoryHandler;
/**
* Author: Kartik Sharma
* Created on: 8/28/2016 , 10:36 AM
* Project: FirebaseChat
*/
public class ChatFragment extends Fragment implements ChatContract.View, TextView.OnEditorActionListener {
static final int REQ_TAKE_PHOTO = 0;
private RecyclerView mRecyclerViewChat;
private EditText mETxtMessage;
private ImageView myAvatarIV;
private ImageView otherAvatarIV;
private ImageButton uploadPicBtn;
private ProgressDialog mProgressDialog;
private ChatRecyclerAdapter mChatRecyclerAdapter;
private ChatPresenter mChatPresenter;
private String mChatId;
private Handler mHandler;
private Runnable mLoadingImageTask = new Runnable() {
@Override
public void run() {
if (mOtherImageUrl == null) {
return;
}
Glide.with(getActivity())
.load(mOtherImageUrl)
.placeholder(otherAvatarIV.getDrawable())
.priority(Priority.IMMEDIATE)
.skipMemoryCache(false)
.dontTransform()
.diskCacheStrategy(DiskCacheStrategy.NONE)
.into(otherAvatarIV);
}
};
private String mMyImageUrl;
private String mOtherImageUrl;
private Runnable mLoadMeImageTask = new Runnable() {
@Override
public void run() {
if (mMyImageUrl == null) {
return;
}
Glide.with(getActivity())
.load(mMyImageUrl)
.placeholder(myAvatarIV.getDrawable())
.priority(Priority.IMMEDIATE)
.skipMemoryCache(false)
.dontTransform()
.diskCacheStrategy(DiskCacheStrategy.NONE)
.into(myAvatarIV);
}
};
public static ChatFragment newInstance(String receiver,
String receiverUid,
String firebaseToken) {
Bundle args = new Bundle();
args.putString(Constants.ARG_RECEIVER, receiver);
args.putString(Constants.ARG_RECEIVER_UID, receiverUid);
args.putString(Constants.ARG_FIREBASE_TOKEN, firebaseToken);
ChatFragment fragment = new ChatFragment();
fragment.setArguments(args);
return fragment;
}
@Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
@Override
public void onStop() {
super.onStop();
EventBus.getDefault().unregister(this);
if(mHandler != null){
mHandler.removeCallbacks(mLoadMeImageTask);
mHandler.removeCallbacks(mLoadingImageTask);
}
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View fragmentView = inflater.inflate(R.layout.fragment_chat, container, false);
bindViews(fragmentView);
mHandler = new Handler();
return fragmentView;
}
private void bindViews(View view) {
mRecyclerViewChat = (RecyclerView) view.findViewById(R.id.recycler_view_chat);
mETxtMessage = (EditText) view.findViewById(R.id.edit_text_message);
myAvatarIV = (ImageView) view.findViewById(R.id.myAvatarIV);
otherAvatarIV = (ImageView) view.findViewById(R.id.otherAvatarIV);
uploadPicBtn = (ImageButton) view.findViewById(R.id.uploadPicBtn);
uploadPicBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//FIXME: hardcode chatId
final String receiverUid = getArguments().getString(Constants.ARG_RECEIVER_UID);
final String senderUid = FirebaseAuth.getInstance().getCurrentUser().getUid();
if(ChatRecyclerAdapter.VIEW_TYPE_ME == mChatRecyclerAdapter.getItemViewType(0)){
mChatId = senderUid + "_" + receiverUid;
}else{
mChatId = receiverUid + "_" + senderUid;
}
startActivityForResult( new Intent(getActivity(), TakePhotoDelegateActivity.class), REQ_TAKE_PHOTO);
}
});
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
init();
}
private void init() {
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setTitle(getString(R.string.loading));
mProgressDialog.setMessage(getString(R.string.please_wait));
mProgressDialog.setIndeterminate(true);
mProgressDialog.show();
mETxtMessage.setOnEditorActionListener(this);
mChatPresenter = new ChatPresenter(this);
mChatPresenter.getMessage(FirebaseAuth.getInstance().getCurrentUser().getUid(),
getArguments().getString(Constants.ARG_RECEIVER_UID));
}
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEND) {
sendMessage();
return true;
}
return false;
}
private void sendMessage() {
String message = mETxtMessage.getText().toString();
if(!"".equals(message.trim())){
String receiver = getArguments().getString(Constants.ARG_RECEIVER);
String receiverUid = getArguments().getString(Constants.ARG_RECEIVER_UID);
String sender = FirebaseAuth.getInstance().getCurrentUser().getEmail();
String senderUid = FirebaseAuth.getInstance().getCurrentUser().getUid();
String receiverFirebaseToken = getArguments().getString(Constants.ARG_FIREBASE_TOKEN);
Chat chat = new Chat(sender,
receiver,
senderUid,
receiverUid,
message,
System.currentTimeMillis()
);
mChatPresenter.sendMessage(getActivity().getApplicationContext(),
chat,
receiverFirebaseToken);
}
}
@Override
public void onSendMessageSuccess() {
mETxtMessage.setText("");
Toast.makeText(getActivity(), "Message sent", Toast.LENGTH_SHORT).show();
}
@Override
public void onSendMessageFailure(String message) {
Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
}
@Override
public void onGetMessagesSuccess(Chat chat) {
if (mChatRecyclerAdapter == null) {
mChatRecyclerAdapter = new ChatRecyclerAdapter(new ArrayList<Chat>());
mRecyclerViewChat.setAdapter(mChatRecyclerAdapter);
mProgressDialog.dismiss();
}
mChatRecyclerAdapter.add(chat);
mRecyclerViewChat.smoothScrollToPosition(mChatRecyclerAdapter.getItemCount() - 1);
}
@Override
public void onGetMessagesFailure(String message) {
Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
}
//FIXME: !!!about Avatar!!!
@Override
public void onSendAvatarSuccess() {
}
@Override
public void onSendAvatarFailure(String message) {
}
@Override
public void onGetAvatarSuccess(String userUid, String imageUrl) {
String myUid = FirebaseAuth.getInstance().getCurrentUser().getUid();
if (userUid.equals(myUid)) {
mMyImageUrl = imageUrl;
mHandler.removeCallbacks(mLoadMeImageTask);
mHandler.postDelayed(mLoadMeImageTask, 500);
} else {
mOtherImageUrl = imageUrl;
mHandler.removeCallbacks(mLoadingImageTask);
mHandler.postDelayed(mLoadingImageTask, 500);
}
}
@Override
public void onGetAvatarFailure(String message) {
}
@Subscribe
public void onPushNotificationEvent(PushNotificationEvent pushNotificationEvent) {
if (mChatRecyclerAdapter == null || mChatRecyclerAdapter.getItemCount() == 0) {
mChatPresenter.getMessage(FirebaseAuth.getInstance().getCurrentUser().getUid(),
pushNotificationEvent.getUid());
}
}
@Override
public void onActivityResult(int requestCode,
int resultCode,
final Intent data) {
switch (requestCode) {
case REQ_TAKE_PHOTO:
if(data != null) {
new Thread(new Runnable() {
@Override
public void run() {
String senderUid = FirebaseAuth.getInstance().getCurrentUser().getUid();
final File file = new File(data.getData().getPath());
try {
//UploadImageUtil.uploadPhoto(file, "YoLung", "YoLung");
UploadImageUtil.upload(file, mChatId, senderUid);
} catch (Exception e) {
e.printStackTrace();
}
//
}
}).start();
break;
}
default:
break;
}
}
@Override
public void onDestroy(){
super.onDestroy();
mChatPresenter.removeListener();
}
}
|
|
package graphene.services;
import graphene.dao.DocumentBuilder;
import graphene.dao.G_Parser;
import graphene.dao.HyperGraphBuilder;
import graphene.dao.StopWordService;
import graphene.dao.StyleService;
import graphene.model.graph.CreateOrUpdateEdgeRequest;
import graphene.model.graph.CreateOrUpdateNodeRequest;
import graphene.model.idl.G_CallBack;
import graphene.model.idl.G_CanonicalRelationshipType;
import graphene.model.idl.G_Constraint;
import graphene.model.idl.G_DataAccess;
import graphene.model.idl.G_DocumentError;
import graphene.model.idl.G_Entity;
import graphene.model.idl.G_EntityQuery;
import graphene.model.idl.G_PropertyKeyTypeAccess;
import graphene.model.idl.G_PropertyMatchDescriptor;
import graphene.model.idl.G_PropertyType;
import graphene.model.idl.G_SearchResult;
import graphene.model.idl.G_SearchResults;
import graphene.model.idl.G_SymbolConstants;
import graphene.model.idlhelper.ListRangeHelper;
import graphene.model.idlhelper.PropertyHelper;
import graphene.model.idlhelper.QueryHelper;
import graphene.util.DataFormatConstants;
import graphene.util.StringUtils;
import graphene.util.validator.ValidationUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Set;
import java.util.Stack;
import mil.darpa.vande.generic.V_GenericEdge;
import mil.darpa.vande.generic.V_GenericGraph;
import mil.darpa.vande.generic.V_GenericNode;
import mil.darpa.vande.generic.V_GraphQuery;
import mil.darpa.vande.generic.V_LegendItem;
import org.apache.tapestry5.Link;
import org.apache.tapestry5.alerts.Severity;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.ioc.annotations.Symbol;
import org.apache.tapestry5.services.URLEncoder;
import org.slf4j.Logger;
public abstract class AbstractGraphBuilder implements G_CallBack, HyperGraphBuilder {
@Inject
@Symbol(G_SymbolConstants.INHERIT_NODE_ATTRIBUTES)
protected boolean inheritAttributes;
@Inject
protected StopWordService stopwordService;
@Inject
protected StyleService style;
protected ArrayList<String> skipInheritanceTypes;
@Inject
@Symbol(G_SymbolConstants.ENABLE_GRAPH_QUERY_PATH)
private boolean enableGraphQueryPath;
@Inject
private DocumentBuilder db;
@Inject
protected URLEncoder encoder;
public static final int MIN_NODE_SIZE = 16;
public static final int MAX_NODE_SIZE = 0;
@Inject
protected G_PropertyKeyTypeAccess propertyKeyTypeAccess;
protected Map<String, V_GenericEdge> edgeList = new HashMap<String, V_GenericEdge>();
protected List<G_DocumentError> errors = new ArrayList<G_DocumentError>();
protected Set<String> scannedQueries = new HashSet<String>();
protected Set<String> scannedResults = new HashSet<String>();
protected Stack<G_EntityQuery> queriesToRunNextDegree = new Stack<G_EntityQuery>();
protected Map<String, V_GenericNode> nodeList = new HashMap<String, V_GenericNode>();
protected Set<V_LegendItem> legendItems = new HashSet<V_LegendItem>();
@Inject
private Logger logger;
protected LinkGenerator linkGenerator;
@Inject
@Symbol(G_SymbolConstants.DEFAULT_MAX_SEARCH_RESULTS)
protected Integer defaultMaxResults;
public AbstractGraphBuilder() {
super();
}
@Override
public void addError(final G_DocumentError e) {
if (ValidationUtils.isValid(e)) {
errors.add(e);
}
}
@Override
public void addGraphQueryPath(final V_GenericNode reportNode, final G_EntityQuery q, final V_GenericGraph vg) {
if (enableGraphQueryPath && ValidationUtils.isValid(reportNode, q)) {
createEdge(q.getInitiatorId(), G_CanonicalRelationshipType.CONTAINED_IN.name(), reportNode.getId(),
G_CanonicalRelationshipType.CONTAINED_IN.name(), vg);
}
}
@Override
public void addScannedResult(final String reportId) {
scannedResults.add(reportId);
}
@Override
public V_GenericGraph buildFromSubGraphs(final V_GraphQuery graphQuery) {
V_GenericGraph g = new V_GenericGraph();
g.setNodes(new HashMap<String, V_GenericNode>());
g.setEdges(new HashMap<String, V_GenericEdge>());
scannedQueries = new HashSet<String>();
final PriorityQueue<G_EntityQuery> queriesToRun = new PriorityQueue<G_EntityQuery>(10, new ScoreComparator());
Map<String, V_GenericNode> nodesFromPreviousDegree = new HashMap<String, V_GenericNode>();
Map<String, V_GenericEdge> edgesFromPreviousDegree = new HashMap<String, V_GenericEdge>();
if (graphQuery.getMaxHops() <= 0) {
return new V_GenericGraph();
} else {
logger.debug("Attempting a graph for query " + graphQuery.toString());
}
int intStatus = 0;
String strStatus = "Graph Loaded";
final G_PropertyMatchDescriptor identifierList = G_PropertyMatchDescriptor.newBuilder().setKey("_all")
.setListRange(new ListRangeHelper(G_PropertyType.STRING, graphQuery.getSearchIds()))
.setSingletonRange(null).setBoundedRange(null).setConstraint(G_Constraint.EQUALS).build();
final QueryHelper qh = new QueryHelper(identifierList);
qh.setMaxResult((long) graphQuery.getMaxEdgesPerNode());
// Add initial query
queriesToRun.add(qh);
int currentDegree = 0;
for (currentDegree = 0; (currentDegree < graphQuery.getMaxHops())
&& (g.getNodes().size() < graphQuery.getMaxNodes()); currentDegree++) {
G_EntityQuery eq = null;
logger.debug("$$$$There are " + queriesToRun.size() + " queries to run in the current degree.");
while ((queriesToRun.size() > 0) && ((eq = queriesToRun.poll()) != null)
&& (g.getNodes().size() < graphQuery.getMaxNodes())) {
if (ValidationUtils.isValid(eq.getPropertyMatchDescriptors())) {
nodesFromPreviousDegree = new HashMap<String, V_GenericNode>(g.getNodes());
edgesFromPreviousDegree = new HashMap<String, V_GenericEdge>(g.getEdges());
logger.debug("Processing degree " + currentDegree);
G_SearchResults searchResults;
try {
// Get a bunch of records
searchResults = getDAO().search(eq);
for (final G_SearchResult t : searchResults.getResults()) {
if (ValidationUtils.isValid(t.getResult())) {
final G_Entity entity = (G_Entity) t.getResult();
final String type = (String) PropertyHelper
.getSingletonValue(entity.getProperties().get(G_Parser.REPORT_TYPE));
// Find a parser for the document type
final G_Parser parser = db.getParserForObject(type);
if (parser != null) {
final V_GenericGraph subGraph = parser.parse(t, eq);
if (ValidationUtils.isValid(subGraph)) {
logger.debug("Merging nodes from subgraph");
g.getEdges().putAll(subGraph.getEdges());
g.getNodes().putAll(subGraph.getNodes());
// FIXME: Switch legend items to a map
// with
// a priority index, then do putAll
g.getLegend().addAll(subGraph.getLegend());
} else {
logger.debug("no subgraph returned due to duplicate id (likely) or an error.");
}
} else {
logger.warn("No parser was found for the supplied type, but carrying on.");
}
} else {
logger.warn("Invalid search result, but carrying on.");
}
}
} catch (final Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
logger.debug("3333====After running " + eq.getId() + ", there are " + queriesToRunNextDegree.size()
+ " queries to run in the next degree.");
}
} // end while loop
// very important!!
// unscannedNodeList.clear();
// ////////////////////////////////////////////////
logger.debug("4444==== At the end of degree " + currentDegree + ", there are " + g.getNodes().size()
+ " nodes and " + g.getEdges().size() + " edges");
logger.debug("5555====There are " + queriesToRunNextDegree.size() + " queries to run in the next degree.");
queriesToRun.addAll(queriesToRunNextDegree);
queriesToRunNextDegree.clear();
}
// All hops have been done
// Check to see if we have too many nodes.
if (g.getNodes().size() > graphQuery.getMaxNodes()) {
g.setNodes(nodesFromPreviousDegree);
g.setEdges(edgesFromPreviousDegree);
intStatus = 1; // will trigger the message.
strStatus = "Returning only " + currentDegree + " hops, as maximum nodes you requested would be exceeded";
} else {
intStatus = 1; // will trigger the message.
strStatus = "Returning " + g.getNodes().size() + " nodes and " + g.getEdges().size() + " edges.";
}
// NOW finally add in all those unique edges.
g = performPostProcess(graphQuery, g);
// final V_GenericGraph g = new V_GenericGraph(g.getNodes(), edgeList);
g.setIntStatus(intStatus);
g.setStrStatus(strStatus);
logger.debug("Graph status: " + g.getStrStatus());
// for (final V_LegendItem li : g.getLegend()) {
// g.addLegendItem(li);
// }
return g;
}
/**
* Override this in your graph builder so you can control how queries are made
* based on node types/properties.
*/
@Override
public void buildQueryForNextIteration(final V_GenericNode... nodes) {
if (ValidationUtils.isValid(nodes)) {
for (final V_GenericNode n : nodes) {
for (final G_EntityQuery eq : createQueriesFromNode(n)) {
final String queryToString = eq.toString();
// Have we done this EXACT query before? Note: a query
// id
// may be different than a node id, depending on how the
// query is constructed.
// TODO: Use a bloom filter
// XXX: make sure the .toString is unique since we now
// have
// time and user, etc.
if (!scannedQueries.contains(queryToString)) {
scannedQueries.add(queryToString);
logger.debug("Query eq is new: " + queryToString);
queriesToRunNextDegree.add(eq);
} else {
logger.debug("Skipping query eq! " + queryToString);
}
}
}
} else {
logger.warn("Will not build a query for the node(s) passed in");
}
logger.debug("There are " + queriesToRunNextDegree.size() + " queries to run for the next degree. ref ");
}
/**
* This is used for the initial query when starting a new graph or expand. This
* method is here so you can override it and put in custom query parameters to
* boost certain result types that were not part of the V_GenericGraphQuery.
*
* @param graphQuery
* @return
*/
public G_EntityQuery convertFrom(final V_GraphQuery graphQuery) {
final G_PropertyMatchDescriptor identifierList = G_PropertyMatchDescriptor.newBuilder().setKey("_all")
.setListRange(new ListRangeHelper(G_PropertyType.STRING, graphQuery.getSearchIds()))
.setConstraint(G_Constraint.EQUALS).build();
final QueryHelper qh = new QueryHelper(identifierList);
qh.setMaxResult(new Long(graphQuery.getMaxEdgesPerNode()));
return qh;
}
// TODO: We want to remove query path edges if we have other edges going to
// it.
//CreateOrUpdateEdgeRequest req
public boolean createEdge(final String fromId, final String relationType, final String toId,
final String relationValue, final V_GenericGraph vg) {
if (ValidationUtils.isValid(fromId, toId)) {
final String key = generateEdgeId(fromId, relationType, toId);
// final V_GenericNode a = nodeList.get(fromId);
// final V_GenericNode b = nodeList.get(toId);
// if (ValidationUtils.isValid(key, a, b) &&
// !edgeList.containsKey(key)) {
if (!vg.getEdges().containsKey(key)) {
final V_GenericEdge v = new V_GenericEdge(key, fromId, toId);
v.setIdType(relationType);
v.setLabel(null);
v.setIdVal(relationType);
// v.addData("Value", StringUtils.coalesc(" ", a.getLabel(),
// relationValue, b.getLabel()));
vg.getEdges().put(key, v);
return true;
}
}
return false;
}
/**
* Creates an edge between two nodes, and sets relationship information.
* Override this if you want to style nodes or add attributes as you build the
* edges.
*
* @return
*/
@Override
public V_GenericEdge createEdge(CreateOrUpdateEdgeRequest req) {
V_GenericEdge edge = null;
if (ValidationUtils.isValid(req.getNodeA())) {
final String key = generateEdgeId(req.getNodeB().getId(), req.getRelationType(), req.getNodeA().getId());
if ((key != null) && !edgeList.containsKey(key)) {
edge = new V_GenericEdge(key, req.getNodeA(), req.getNodeB());
edge.setIdType(req.getRelationType());
edge.setLabel(null);
edge.setIdVal(req.getRelationType());
if (req.getNodeCertainty() < 100.0) {
edge.addData("Certainty", DataFormatConstants.formatPercent(req.getNodeCertainty()));
edge.setLineStyle("dotted");
// edge.setColor("#787878");
}
// edge.addData("Local_Priority", "" + localPriority);
// edge.addData("Min_Score_Required", "" +
// minimumScoreRequired);
// edge.addData("Parent_Score", "" + inheritedScore);
edge.addData("Value", StringUtils.coalesc(" ", req.getNodeA().getLabel(), req.getRelationValue(),
req.getNodeB().getLabel()));
edgeList.put(key, edge);
}
// if this flag is set, we'll add the attributes to the
// attached node.
if (inheritAttributes) {
req.getNodeB().inheritPropertiesOfExcept(req.getNodeA(), skipInheritanceTypes);
}
}
return edge;
}
// @Override
// public V_GenericNode createNodeInSubgraph(final double
// minimumScoreRequired, final double inheritedScore,
// final double localPriority, final String originalId, final String idType,
// final String nodeType,
// final V_GenericNode attachTo, final String relationType, final String
// relationValue,
// final double nodeCertainty, final V_GenericGraph subgraph) {
// V_GenericNode a = null;
// Map<String, V_GenericNode> nodeList;
// Map<String, V_GenericEdge> edgeList;
// if (subgraph != null) {
// nodeList = subgraph.getNodes();
// edgeList = subgraph.getEdges();
// } else {
// nodeList = this.nodeList;
// edgeList = this.edgeList;
// }
// if (ValidationUtils.isValid(originalId)) {
// if (!stopwordService.isValid(originalId)) {
// addError(new G_DocumentError("Bad Identifier", "The " + nodeType + " (" +
// originalId
// + ") contains a stopword", Severity.WARN.toString()));
// } else {
// final String id = generateNodeId(originalId);
// a = nodeList.get(id);
// final double calculatedPriority = inheritedScore * localPriority;
// if (a == null) {
// a = new V_GenericNode(id);
// a.setIdType(idType);
// // This is important because we use it to search on the next
// // traversal.
// a.setIdVal(originalId);
// a.setNodeType(nodeType);
// a.setColor(style.getHexColorForNode(a.getNodeType()));
// a.setMinScore(minimumScoreRequired);
// a.setPriority(calculatedPriority);
// // Remove leading zeros from the label
// a.setLabel(StringUtils.removeLeadingZeros(originalId));
// // XXX: need a way of getting the link to the page with TYPE
// a.addData(nodeType, getCombinedSearchLink(nodeType, originalId));
// nodeList.put(id, a);
// legendItems.add(new V_LegendItem(a.getColor(), a.getNodeType()));
// }
// // now we have a valid node. Attach it to the other node
// // provided.
// if (ValidationUtils.isValid(a, attachTo)) {
// final String key = generateEdgeId(attachTo.getId(), relationType,
// a.getId());
// if ((key != null) && (edgeList.get(key) == null)) {
// final V_GenericEdge edge = new V_GenericEdge(key, a, attachTo);
// edge.setIdType(relationType);
// edge.setLabel(null);
// edge.setIdVal(relationType);
// if (nodeCertainty < 100.0) {
// edge.addData("Certainty",
// DataFormatConstants.formatPercent(nodeCertainty));
// edge.setLineStyle("dotted");
// // edge.setColor("#787878");
// }
// edge.addData("Local_Priority", "" + localPriority);
// edge.addData("Min_Score_Required", "" + minimumScoreRequired);
// edge.addData("Parent_Score", "" + inheritedScore);
// edge.addData("Value",
// StringUtils.coalesc(" ", a.getLabel(), relationValue,
// attachTo.getLabel()));
// edgeList.put(key, edge);
// }
//
// // if this flag is set, we'll add the attributes to the
// // attached
// // node.
// if (inheritAttributes) {
// attachTo.inheritPropertiesOfExcept(a, skipInheritanceTypes);
// }
// }
// }
// } else {
// logger.error("Invalid id for " + nodeType + " of node " + attachTo);
// }
// return a;
// }
@Override
public V_GenericNode createOrUpdateNode(CreateOrUpdateNodeRequest req) {
// final double minimumScoreRequired, final String originalId,
// final String idType, final String nodeType, final V_GenericNode attachTo,
// final String relationType,
// final String relationValue, final double nodeCertainty, final V_GenericGraph
// subgraph)
V_GenericNode a = null;
Map<String, V_GenericNode> nodeList;
Map<String, V_GenericEdge> edgeList;
if (req.getSubgraph() != null) {
nodeList = req.getSubgraph().getNodes();
edgeList = req.getSubgraph().getEdges();
} else {
logger.error("BAD Subgraph provided.");
return null;
}
if (ValidationUtils.isValid(req.getOriginalId())) {
if (!stopwordService.isValid(req.getOriginalId())) {
logger.error("ID contained a stopword, not creating this node.");
addError(new G_DocumentError("Bad Identifier",
"The " + req.getNodeType() + " (" + req.getOriginalId() + ") contains a stopword", Severity.WARN.toString()));
} else {
final String id = generateNodeId(req.getOriginalId());
a = nodeList.get(id);
// final double calculatedPriority = inheritedScore *
// localPriority;
if (a == null) {
a = new V_GenericNode(id);
a.setIdType(req.getIdType());
// This is important because we use it to search on the next
// traversal.
a.setIdVal(req.getOriginalId());
a.setNodeType(req.getNodeType());
a.setColor(style.getHexColorForNode(a.getNodeType()));
a.setMinScore(req.getMinimumScoreRequired());
// a.setPriority(calculatedPriority);
// Remove leading zeros from the label
a.setLabel(StringUtils.removeLeadingZeros(req.getOriginalId()));
// XXX: need a way of getting the link to the page with TYPE
a.addData(req.getNodeType(), getCombinedSearchLink(req.getNodeType(), req.getOriginalId()));
nodeList.put(id, a);
req.getSubgraph().addLegendItem(new V_LegendItem(a.getColor(), a.getNodeType()));
}
// now we have a valid node. Attach it to the other node
// provided.
CreateOrUpdateEdgeRequest edgeReq= new CreateOrUpdateEdgeRequest();
edgeReq.setNodeA(a);
edgeReq.setRelationType(req.getRelationType());
edgeReq.setRelationValue(req.getRelationValue());
edgeReq.setNodeB(req.getAttachTo());
edgeReq.setNodeCertainty(req.getNodeCertainty());
edgeReq.setMinimumScoreRequired(req.getMinimumScoreRequired());
edgeReq.setEdgeList(edgeList);
createEdge(edgeReq);
}
} else {
logger.error("Invalid id for nodetype " + req.getNodeType() + " of idtype " + req.getIdType());
}
return a;
}
public abstract List<G_EntityQuery> createQueriesFromNode(V_GenericNode n);
/**
* Doesn't matter what this does, as long as it is unique.
*
* @param v
* @return
*/
protected String generateEdgeId(final String... addendIds) {
String key = null;
// Allow for null values as part of the id.
if ((addendIds != null) && (addendIds.length > 0)) {
key = Arrays.toString(addendIds).toLowerCase();
} else {
logger.error("Unable to contruct an generateEdgeId for " + Arrays.toString(addendIds).toLowerCase());
}
return key;
}
/**
* This is a very important method. Changes to this method will affect which
* nodes get joined together, and what constitutes a unique id.
*
* @param addendIds
* @return
*/
protected String generateNodeId(final String... addendIds) {
String key = null;
boolean foundValue = false;
// Allow for null values as part of the id.
if ((addendIds != null) && (addendIds.length == 1) && ValidationUtils.isValid(addendIds[0])) {
// removes all non alphanumeric, and converts to lowercase
key = addendIds[0].replaceAll("[\\W]|_", "").toLowerCase();
// replace leading zeros as part of the id.
key = StringUtils.removeLeadingZeros(key);
} else if ((addendIds != null) && (addendIds.length > 0)) {
for (final String a : addendIds) {
// make sure something is non null.
if ((a != null) && !a.isEmpty()) {
foundValue = true;
break;
}
}
if (foundValue) {
key = Arrays.toString(addendIds).toLowerCase();
}
} else {
logger.error("Unable to contruct an generateNodeId for " + Arrays.toString(addendIds).toLowerCase());
}
return key;
}
protected String getCombinedSearchLink(final String nodeType, final String identifier) {
if (linkGenerator != null) {
// FIXME: Need to find a way to inject the page into the builder, so
// we can call set()
// logger.debug("Search page is defined when making a link for " +
// identifier);
final Link link = linkGenerator.set(null, null, null, identifier, defaultMaxResults);
return "<a href=\"" + link.toRedirectURI() + "\" target=\"" + identifier + "\" class=\"btn btn-primary\" >"
+ identifier + "</a>";
} else {
// logger.warn("No linkGenerator search page defined when making a link for "
// + identifier);
final String encodedIdentifier = encoder.encode(identifier);
String matchType = "COMPARE_CONTAINS";
if (nodeType.contains("ADDRESS")) {
matchType = "COMPARE_EQUALS";
}
return "<a href=\"graphene\\CombinedEntitySearchPage/?term=" + encodedIdentifier + "&match=" + matchType
+ "\" target=\"" + identifier + "\" class=\"btn btn-primary\" >" + identifier + "</a>";
}
}
/*
* (non-Javadoc)
*
* @see graphene.services.HyperGraphBuilder#getDAO()
*/
@Override
public abstract G_DataAccess getDAO();
/**
* @return the errors
*/
@Override
public final List<G_DocumentError> getErrors() {
return errors;
}
/**
* @return the scannedQueries
*/
public final Set<String> getScannedQueries() {
return scannedQueries;
}
/**
* @return the scannedResults
*/
public final Set<String> getScannedResults() {
return scannedResults;
}
@Override
public void inheritLabelIfNeeded(final V_GenericNode a, final V_GenericNode... nodes) {
for (final V_GenericNode n : nodes) {
if ((n != null) && ValidationUtils.isValid(n.getLabel())) {
a.setLabel(n.getLabel());
return;
}
}
}
/**
* Returns true if this result id has previously been scanned.
*
* @param reportId
* @return
*/
@Override
public boolean isPreviouslyScannedResult(final String reportId) {
return scannedResults.contains(reportId);
}
/*
* (non-Javadoc)
*
* @see graphene.services.HyperGraphBuilder#makeGraphResponse(mil.darpa.vande
* .generic.V_GraphQuery)
*/
@Override
public V_GenericGraph makeGraphResponse(final V_GraphQuery graphQuery) throws Exception {
return null;
// nodeList = new HashMap<String, V_GenericNode>();
// edgeList = new HashMap<String, V_GenericEdge>();
// scannedQueries = new HashSet<String>();
//
// final PriorityQueue<G_EntityQuery> queriesToRun = new
// PriorityQueue<G_EntityQuery>(10, new ScoreComparator());
// Map<String, V_GenericNode> nodesFromPreviousDegree = new
// HashMap<String, V_GenericNode>();
// Map<String, V_GenericEdge> edgesFromPreviousDegree = new
// HashMap<String, V_GenericEdge>();
//
// if (graphQuery.getMaxHops() <= 0) {
// return new V_GenericGraph();
// } else {
// logger.debug("Attempting a graph for query " +
// graphQuery.toString());
// }
// queriesToRun.add(convertFrom(graphQuery));
//
// int intStatus = 0;
// String strStatus = "Graph Loaded";
// int currentDegree = 0;
// for (currentDegree = 0; (currentDegree < graphQuery.getMaxHops())
// && (nodeList.size() < graphQuery.getMaxNodes()); currentDegree++) {
// G_EntityQuery eq = null;
// logger.debug("$$$$There are " + queriesToRun.size() +
// " queries to run in the current degree.");
// while ((queriesToRun.size() > 0) && ((eq = queriesToRun.poll()) !=
// null)
// && (nodeList.size() < graphQuery.getMaxNodes())) {
//
// if (ValidationUtils.isValid(eq.getPropertyMatchDescriptors())) {
// nodesFromPreviousDegree = new HashMap<String,
// V_GenericNode>(nodeList);
// edgesFromPreviousDegree = new HashMap<String,
// V_GenericEdge>(edgeList);
// logger.debug("Processing degree " + currentDegree);
//
// /**
// * This will end up building nodes and edges, and creating
// * new queries for the queue
// */
// logger.debug("1111=====Running query " + eq.toString());
// getDAO().performCallback(0, eq.getMaxResult(), this, eq);
// logger.debug("3333====After running " + eq.toString() +
// ", there are "
// + queriesToRunNextDegree.size() +
// " queries to run in the next degree.");
// }
// }// end while loop
//
// // very important!!
// // unscannedNodeList.clear();
// // ////////////////////////////////////////////////
// logger.debug("4444==== At the end of degree " + currentDegree +
// ", there are " + nodeList.size()
// + " nodes and " + edgeList.size() + " edges");
//
// logger.debug("5555====There are " + queriesToRunNextDegree.size() +
// " queries to run in the next degree.");
// queriesToRun.addAll(queriesToRunNextDegree);
// queriesToRunNextDegree.clear();
// }
//
// // All hops have been done
// // Check to see if we have too many nodes.
// if (nodeList.size() > graphQuery.getMaxNodes()) {
// nodeList = nodesFromPreviousDegree;
// edgeList = edgesFromPreviousDegree;
// intStatus = 1; // will trigger the message.
// strStatus = "Returning only " + currentDegree +
// " hops, as maximum nodes you requested would be exceeded";
// } else {
// intStatus = 1; // will trigger the message.
// strStatus = "Returning " + nodeList.size() + " nodes and " +
// edgeList.size() + " edges.";
// }
//
// // NOW finally add in all those unique edges.
//
// performPostProcess(graphQuery);
// final V_GenericGraph g = new V_GenericGraph(nodeList, edgeList);
// g.setIntStatus(intStatus);
// g.setStrStatus(strStatus);
// logger.debug("Graph status: " + g.getStrStatus());
// for (final V_LegendItem li : legendItems) {
// g.addLegendItem(li);
// }
//
// return g;
}
/*
* (non-Javadoc)
*
* @see graphene.services.HyperGraphBuilder#performPostProcess(mil.darpa.vande
* .generic.V_GraphQuery)
*/
@Deprecated
@Override
public void performPostProcess(final V_GraphQuery graphQuery) {
// default blank
}
@Override
public V_GenericGraph performPostProcess(final V_GraphQuery graphQuery, final V_GenericGraph g) {
// default blank
return g;
}
/**
* @param errors
* the errors to set
*/
public final void setErrors(final List<G_DocumentError> errors) {
this.errors = errors;
}
/**
* @param scannedQueries
* the scannedQueries to set
*/
@Override
public final void setScannedQueries(final Set<String> scannedQueries) {
this.scannedQueries = scannedQueries;
}
/**
* @param scannedResults
* the scannedResults to set
*/
@Override
public final void setScannedResults(final Set<String> scannedResults) {
this.scannedResults = scannedResults;
}
}
|
|
package org.bouncycastle.asn1;
import java.io.IOException;
/**
* ASN.1 TaggedObject - in ASN.1 notation this is any object preceded by
* a [n] where n is some number - these are assumed to follow the construction
* rules (as with sequences).
*/
public abstract class ASN1TaggedObject
extends ASN1Primitive
implements ASN1TaggedObjectParser
{
int tagNo;
boolean empty = false;
boolean explicit = true;
ASN1Encodable obj = null;
static public ASN1TaggedObject getInstance(
ASN1TaggedObject obj,
boolean explicit)
{
if (explicit)
{
return (ASN1TaggedObject)obj.getObject();
}
throw new IllegalArgumentException("implicitly tagged tagged object");
}
static public ASN1TaggedObject getInstance(
Object obj)
{
if (obj == null || obj instanceof ASN1TaggedObject)
{
return (ASN1TaggedObject)obj;
}
else if (obj instanceof byte[])
{
try
{
return ASN1TaggedObject.getInstance(fromByteArray((byte[])obj));
}
catch (IOException e)
{
throw new IllegalArgumentException("failed to construct tagged object from byte[]: " + e.getMessage());
}
}
throw new IllegalArgumentException("unknown object in getInstance: " + obj.getClass().getName());
}
/**
* Create a tagged object with the style given by the value of explicit.
* <p>
* If the object implements ASN1Choice the tag style will always be changed
* to explicit in accordance with the ASN.1 encoding rules.
* </p>
* @param explicit true if the object is explicitly tagged.
* @param tagNo the tag number for this object.
* @param obj the tagged object.
*/
public ASN1TaggedObject(
boolean explicit,
int tagNo,
ASN1Encodable obj)
{
if (obj instanceof ASN1Choice)
{
this.explicit = true;
}
else
{
this.explicit = explicit;
}
this.tagNo = tagNo;
if (this.explicit)
{
this.obj = obj;
}
else
{
ASN1Primitive prim = obj.toASN1Primitive();
if (prim instanceof ASN1Set)
{
ASN1Set s = null;
}
this.obj = obj;
}
}
boolean asn1Equals(
ASN1Primitive o)
{
if (!(o instanceof ASN1TaggedObject))
{
return false;
}
ASN1TaggedObject other = (ASN1TaggedObject)o;
if (tagNo != other.tagNo || empty != other.empty || explicit != other.explicit)
{
return false;
}
if(obj == null)
{
if (other.obj != null)
{
return false;
}
}
else
{
if (!(obj.toASN1Primitive().equals(other.obj.toASN1Primitive())))
{
return false;
}
}
return true;
}
public int hashCode()
{
int code = tagNo;
// TODO: actually this is wrong - the problem is that a re-encoded
// object may end up with a different hashCode due to implicit
// tagging. As implicit tagging is ambiguous if a sequence is involved
// it seems the only correct method for both equals and hashCode is to
// compare the encodings...
if (obj != null)
{
code ^= obj.hashCode();
}
return code;
}
public int getTagNo()
{
return tagNo;
}
/**
* return whether or not the object may be explicitly tagged.
* <p>
* Note: if the object has been read from an input stream, the only
* time you can be sure if isExplicit is returning the true state of
* affairs is if it returns false. An implicitly tagged object may appear
* to be explicitly tagged, so you need to understand the context under
* which the reading was done as well, see getObject below.
*/
public boolean isExplicit()
{
return explicit;
}
public boolean isEmpty()
{
return empty;
}
/**
* return whatever was following the tag.
* <p>
* Note: tagged objects are generally context dependent if you're
* trying to extract a tagged object you should be going via the
* appropriate getInstance method.
*/
public ASN1Primitive getObject()
{
if (obj != null)
{
return obj.toASN1Primitive();
}
return null;
}
/**
* Return the object held in this tagged object as a parser assuming it has
* the type of the passed in tag. If the object doesn't have a parser
* associated with it, the base object is returned.
*/
public ASN1Encodable getObjectParser(
int tag,
boolean isExplicit)
{
switch (tag)
{
case BERTags.SET:
return ASN1Set.getInstance(this, isExplicit).parser();
case BERTags.SEQUENCE:
return ASN1Sequence.getInstance(this, isExplicit).parser();
case BERTags.OCTET_STRING:
return ASN1OctetString.getInstance(this, isExplicit).parser();
}
if (isExplicit)
{
return getObject();
}
throw new RuntimeException("implicit tagging not implemented for tag: " + tag);
}
public ASN1Primitive getLoadedObject()
{
return this.toASN1Primitive();
}
ASN1Primitive toDERObject()
{
return new DERTaggedObject(explicit, tagNo, obj);
}
ASN1Primitive toDLObject()
{
return new DLTaggedObject(explicit, tagNo, obj);
}
abstract void encode(ASN1OutputStream out)
throws IOException;
public String toString()
{
return "[" + tagNo + "]" + obj;
}
}
|
|
package org.batfish.vendor.check_point_management.parsing;
import static com.google.common.base.MoreObjects.firstNonNull;
import static com.google.common.collect.Maps.immutableEntry;
import static org.batfish.common.BfConsts.RELPATH_CHECKPOINT_MANAGEMENT_DIR;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.LinkedListMultimap;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.batfish.common.Warning;
import org.batfish.common.util.BatfishObjectMapper;
import org.batfish.datamodel.answers.ParseVendorConfigurationAnswerElement;
import org.batfish.vendor.check_point_management.AccessLayer;
import org.batfish.vendor.check_point_management.AccessRule;
import org.batfish.vendor.check_point_management.AccessRuleOrSection;
import org.batfish.vendor.check_point_management.AccessSection;
import org.batfish.vendor.check_point_management.CheckpointManagementConfiguration;
import org.batfish.vendor.check_point_management.Domain;
import org.batfish.vendor.check_point_management.GatewaysAndServers;
import org.batfish.vendor.check_point_management.ManagementDomain;
import org.batfish.vendor.check_point_management.ManagementPackage;
import org.batfish.vendor.check_point_management.ManagementServer;
import org.batfish.vendor.check_point_management.NamedManagementObject;
import org.batfish.vendor.check_point_management.NatRule;
import org.batfish.vendor.check_point_management.NatRuleOrSection;
import org.batfish.vendor.check_point_management.NatRulebase;
import org.batfish.vendor.check_point_management.NatSection;
import org.batfish.vendor.check_point_management.ObjectPage;
import org.batfish.vendor.check_point_management.Package;
import org.batfish.vendor.check_point_management.TypedManagementObject;
import org.batfish.vendor.check_point_management.Uid;
public class CheckpointManagementParser {
public static @Nonnull CheckpointManagementConfiguration parseCheckpointManagementData(
Map<String, String> cpManagementData, ParseVendorConfigurationAnswerElement pvcae) {
/* Organize server data into maps */
// server -> domain -> filename -> file contents
Map<String, Map<String, Map<String, String>>> domainFileMap = new HashMap<>();
// server -> domain -> -> package -> filename -> file contents
Map<String, Map<String, Map<String, Map<String, String>>>> packageFileMap = new HashMap<>();
cpManagementData.forEach(
(filePath, fileContent) -> {
String[] parts = filePath.split("/");
if (parts.length == 4) {
// checkpoint_management/SERVER_NAME/DOMAIN_NAME/foo.json
String serverName = parts[1];
String domainName = parts[2];
String fileName = parts[3];
domainFileMap
.computeIfAbsent(serverName, n -> new HashMap<>())
.computeIfAbsent(domainName, n -> new HashMap<>())
.put(fileName, fileContent);
} else if (parts.length == 5) {
// checkpoint_management/SERVER_NAME/DOMAIN_NAME/PACKAGE_NAME/foo.json
String serverName = parts[1];
String domainName = parts[2];
String packageName = parts[3];
String fileName = parts[4];
packageFileMap
.computeIfAbsent(serverName, n -> new HashMap<>())
.computeIfAbsent(domainName, n -> new HashMap<>())
.computeIfAbsent(packageName, n -> new HashMap<>())
.put(fileName, fileContent);
}
});
return new CheckpointManagementConfiguration(
buildServersMap(domainFileMap, packageFileMap, pvcae));
}
/** Read Access Layer data. */
private static @Nonnull List<AccessLayer> readAccessLayers(
Package pakij,
String domainName,
Map<String, String> packageFiles,
ParseVendorConfigurationAnswerElement pvcae,
String serverName) {
return mergeAccessLayers(
firstNonNull(
tryParseCheckpointPackageFile(
packageFiles,
new TypeReference<List<AccessLayer>>() {},
pvcae,
serverName,
domainName,
pakij.getName(),
RELPATH_CHECKPOINT_SHOW_ACCESS_RULEBASE),
ImmutableList.of()),
pvcae);
}
/**
* Returns a single AccessRuleOrSection representing the specified collection.
*
* <p>The specified collection of items should contain one of the following:
*
* <ul>
* <li>1. a single AccessRule (rules can't be split across pages)
* <li>2. a single AccessSection (contained fully on a single page)
* <li>3. multiple AccessSection (all with the same name and uid, with different rules)
* </ul>
*/
private static @Nonnull AccessRuleOrSection mergeRuleOrSection(
Collection<AccessRuleOrSection> items, ParseVendorConfigurationAnswerElement pvcae) {
AccessRuleOrSection first = items.iterator().next();
if (items.stream().anyMatch(AccessRule.class::isInstance)) {
// Shouldn't happen w/ well-formed data, but check to prevent bad casting below
if (items.size() > 1) {
pvcae.addRedFlagWarning(
RELPATH_CHECKPOINT_MANAGEMENT_DIR,
new Warning(
String.format(
"Cannot merge AccessRule pages (for uid %s), ignoring instances after the"
+ " first",
((AccessRule) first).getUid().getValue()),
"Checkpoint"));
}
return first;
}
AccessSection firstSection = (AccessSection) first;
return new AccessSection(
firstSection.getName(),
items.stream()
.flatMap(s -> ((AccessSection) s).getRulebase().stream())
.collect(ImmutableList.toImmutableList()),
firstSection.getUid());
}
/**
* Returns a list of unique Access Rules and Access Sections, generated from the specified
* collection of non-unique items; i.e. multiple partial Access Sections can be specified and will
* be merged into a single Access Section in the resulting list.
*
* <p>The items should be provided in order.
*/
private static @Nonnull List<AccessRuleOrSection> mergeRuleOrSections(
Collection<AccessRuleOrSection> items, ParseVendorConfigurationAnswerElement pvcae) {
LinkedListMultimap<Uid, AccessRuleOrSection> uidToChunks = LinkedListMultimap.create();
items.forEach(i -> uidToChunks.put(((NamedManagementObject) i).getUid(), i));
return uidToChunks.keySet().stream()
.map(uid -> mergeRuleOrSection(uidToChunks.get(uid), pvcae))
.collect(ImmutableList.toImmutableList());
}
/**
* Merges multiple pages of a <i>single</i> Access Layer and returns the resulting Access Layer.
*
* <p>Assumes all supplied pages are for the same AccessLayer.
*/
private static @Nonnull AccessLayer mergeAccessLayer(
Collection<AccessLayer> pages, ParseVendorConfigurationAnswerElement pvcae) {
assert !pages.isEmpty();
AccessLayer first = pages.iterator().next();
Uid uid = first.getUid();
String name = first.getName();
Map<Uid, NamedManagementObject> objs = new HashMap<>();
pages.stream()
.flatMap(p -> p.getObjectsDictionary().entrySet().stream())
.forEach(o -> objs.put(o.getKey(), o.getValue()));
return new AccessLayer(
ImmutableMap.copyOf(objs),
mergeRuleOrSections(
pages.stream()
.flatMap(p -> p.getRulebase().stream())
.collect(ImmutableList.toImmutableList()),
pvcae),
uid,
name);
}
/**
* Merges multiple pages of non-unique Access Layers.
*
* <p>The pages should be provided in order.
*/
@VisibleForTesting
static @Nonnull List<AccessLayer> mergeAccessLayers(
Collection<AccessLayer> pages, ParseVendorConfigurationAnswerElement pvcae) {
LinkedListMultimap<Uid, AccessLayer> uidToPages = LinkedListMultimap.create();
pages.forEach(p -> uidToPages.put(p.getUid(), p));
return uidToPages.keySet().stream()
.map(uid -> mergeAccessLayer(uidToPages.get(uid), pvcae))
.collect(ImmutableList.toImmutableList());
}
/** Read NAT rulebase data. */
@VisibleForTesting
static @Nullable NatRulebase readNatRulebase(
Package pakij,
String domainName,
Map<String, String> packageFiles,
ParseVendorConfigurationAnswerElement pvcae,
String serverName) {
if (!pakij.hasNatPolicy()) {
return null;
}
String packageName = pakij.getName();
List<NatRulebase> natRulebases =
tryParseCheckpointPackageFile(
packageFiles,
new TypeReference<List<NatRulebase>>() {},
pvcae,
serverName,
domainName,
packageName,
RELPATH_CHECKPOINT_SHOW_NAT_RULEBASE);
if (natRulebases == null) {
return null;
} else if (natRulebases.isEmpty()) {
warnCheckpointPackageFile(
serverName,
domainName,
packageName,
RELPATH_CHECKPOINT_SHOW_NAT_RULEBASE,
"JSON file contains no NAT rulebase information.",
pvcae,
null);
return null;
}
long numUids = natRulebases.stream().map(NatRulebase::getUid).distinct().count();
Uid uid = natRulebases.iterator().next().getUid();
if (numUids > 1) {
warnCheckpointPackageFile(
serverName,
domainName,
packageName,
RELPATH_CHECKPOINT_SHOW_NAT_RULEBASE,
String.format(
"JSON file should contain one or more pages for exactly one NAT rulebase, but"
+ " contains %s. Only reading pages for the first, with UID '%s'.",
numUids, uid.getValue()),
pvcae,
null);
}
return mergeNatRulebasePages(
natRulebases.stream()
.filter(rulebase -> rulebase.getUid().equals(uid))
.collect(ImmutableList.toImmutableList()),
pvcae);
}
/**
* Returns a single NatRuleOrSection representing the specified collection.
*
* <p>The specified collection of items should contain one of the following:
*
* <ul>
* <li>1. a single NatRule (rules can't be split across pages)
* <li>2. a single NatSection part (contained fully on a single page)
* <li>3. multiple NatSection parts (all with the same name and uid, with different rules)
* </ul>
*/
@VisibleForTesting
static @Nonnull NatRuleOrSection mergeNatRuleOrSection(
Collection<NatRuleOrSection> items, ParseVendorConfigurationAnswerElement pvcae) {
NatRuleOrSection first = items.iterator().next();
if (items.stream().anyMatch(NatRule.class::isInstance)) {
// Shouldn't happen w/ well-formed data, but check to prevent bad casting below
if (items.size() > 1) {
Uid uid = first.getUid();
pvcae.addRedFlagWarning(
RELPATH_CHECKPOINT_MANAGEMENT_DIR,
new Warning(
String.format(
"Cannot merge NatRule pages (for uid %s), ignoring instances after the"
+ " first",
uid.getValue()),
"Checkpoint"));
}
return first;
}
NatSection firstSection = (NatSection) first;
return new NatSection(
firstSection.getName(),
items.stream()
.flatMap(s -> ((NatSection) s).getRulebase().stream())
.collect(ImmutableList.toImmutableList()),
firstSection.getUid());
}
/**
* Returns a list of unique NAT Rules and NAT Sections, generated from the specified collection of
* non-unique items; i.e. multiple partial NAT Sections can be specified and will be merged into a
* single NAT Section in the resulting list.
*
* <p>The items should be provided in order.
*/
private static @Nonnull List<NatRuleOrSection> mergeNatRuleOrSections(
Collection<NatRuleOrSection> items, ParseVendorConfigurationAnswerElement pvcae) {
LinkedListMultimap<Uid, NatRuleOrSection> uidToParts = LinkedListMultimap.create();
items.forEach(i -> uidToParts.put((i).getUid(), i));
return uidToParts.keySet().stream()
.map(uid -> mergeNatRuleOrSection(uidToParts.get(uid), pvcae))
.collect(ImmutableList.toImmutableList());
}
/**
* Merges multiple pages of a <i>single</i> NAT rulebase and returns the resulting rulebase.
*
* <p>Assumes all supplied pages are for the same rulebase.
*/
static @Nonnull NatRulebase mergeNatRulebasePages(
Collection<NatRulebase> pages, ParseVendorConfigurationAnswerElement pvcae) {
assert !pages.isEmpty();
NatRulebase first = pages.iterator().next();
Uid uid = first.getUid();
Map<Uid, TypedManagementObject> objs = new HashMap<>();
pages.stream()
.flatMap(p -> p.getObjectsDictionary().entrySet().stream())
.forEach(o -> objs.put(o.getKey(), o.getValue()));
return new NatRulebase(
ImmutableMap.copyOf(objs),
mergeNatRuleOrSections(
pages.stream()
.flatMap(p -> p.getRulebase().stream())
.collect(ImmutableList.toImmutableList()),
pvcae),
uid);
}
/**
* Reads all {@link ObjectPage}s from specified {@code filename} and returns a consolidated list
* of {@link TypedManagementObject} from all pages.
*/
private static List<TypedManagementObject> readObjects(
String filename,
Map<String, Map<String, Map<String, String>>> domainFileMap,
String domainName,
String serverName,
ParseVendorConfigurationAnswerElement pvcae) {
List<ObjectPage> objectPages =
tryParseCheckpointDomainFile(
domainFileMap,
new TypeReference<List<ObjectPage>>() {},
pvcae,
serverName,
domainName,
filename);
return objectPages == null
? ImmutableList.of()
: objectPages.stream()
.flatMap(p -> p.getObjects().stream())
.collect(ImmutableList.toImmutableList());
}
@VisibleForTesting
static List<TypedManagementObject> buildObjectsList(
Map<String, Map<String, Map<String, String>>> domainFileMap,
String domainName,
String serverName,
ParseVendorConfigurationAnswerElement pvcae) {
return ImmutableList.of(
RELPATH_CHECKPOINT_SHOW_GROUPS,
RELPATH_CHECKPOINT_SHOW_HOSTS,
RELPATH_CHECKPOINT_SHOW_NETWORKS,
RELPATH_CHECKPOINT_SHOW_SERVICE_GROUPS,
RELPATH_CHECKPOINT_SHOW_SERVICES_ICMP,
RELPATH_CHECKPOINT_SHOW_SERVICES_OTHER,
RELPATH_CHECKPOINT_SHOW_SERVICES_TCP,
RELPATH_CHECKPOINT_SHOW_SERVICES_UDP)
.stream()
.flatMap(f -> readObjects(f, domainFileMap, domainName, serverName, pvcae).stream())
.filter(Objects::nonNull)
.collect(ImmutableList.toImmutableList());
}
/**
* Returns a map of server name to {@link ManagementServer} based on supplied domain and package
* files.
*
* <p>{@code domainFileMap} is a map of server -> domain -> filename -> file contents
*
* <p>{@code packageFileMap} is a map of server -> domain -> -> package -> filename -> file
* contents
*/
private static Map<String, ManagementServer> buildServersMap(
Map<String, Map<String, Map<String, String>>> domainFileMap,
Map<String, Map<String, Map<String, Map<String, String>>>> packageFileMap,
ParseVendorConfigurationAnswerElement pvcae) {
Map<Entry<String, String>, ManagementDomain> domainByServerDomain =
domainFileMap.entrySet().stream()
.flatMap(
domainsByServerEntry -> {
String serverName = domainsByServerEntry.getKey();
return domainsByServerEntry.getValue().keySet().stream()
.map(domainName -> immutableEntry(serverName, domainName));
})
.parallel() // stream of entries of <serverName, domainName>
.map(
serverDomain ->
immutableEntry(
serverDomain,
buildManagementDomain(
serverDomain.getKey(),
serverDomain.getValue(),
domainFileMap,
packageFileMap,
pvcae)))
.filter(domainByServerDomainEntry -> domainByServerDomainEntry.getValue() != null)
.collect(ImmutableMap.toImmutableMap(Entry::getKey, Entry::getValue));
Map<String, ImmutableMap.Builder<String, ManagementDomain>> domainsByServer = new HashMap<>();
domainByServerDomain.forEach(
(domainsByServerDomainEntry, managementDomain) -> {
String serverName = domainsByServerDomainEntry.getKey();
String domainName = domainsByServerDomainEntry.getValue();
domainsByServer
.computeIfAbsent(serverName, n -> ImmutableMap.builder())
.put(domainName, managementDomain);
});
ImmutableMap.Builder<String, ManagementServer> serversMap = ImmutableMap.builder();
domainsByServer.forEach(
(serverName, domainByName) ->
serversMap.put(serverName, new ManagementServer(domainByName.build(), serverName)));
return serversMap.build();
}
private static @Nullable ManagementDomain buildManagementDomain(
String serverName,
String domainName,
Map<String, Map<String, Map<String, String>>> domainFileMap,
Map<String, Map<String, Map<String, Map<String, String>>>> packageFileMap,
ParseVendorConfigurationAnswerElement pvcae) {
GatewaysAndServers gatewaysAndServers =
readGatewaysAndServers(serverName, domainName, domainFileMap, pvcae);
if (gatewaysAndServers == null) {
return null;
}
List<TypedManagementObject> objects =
buildObjectsList(domainFileMap, domainName, serverName, pvcae);
ImmutableMap.Builder<Uid, ManagementPackage> packagesBuilder = ImmutableMap.builder();
for (Entry<String, Map<String, String>> packageEntry :
packageFileMap.get(serverName).get(domainName).entrySet()) {
String packageName = packageEntry.getKey();
Map<String, String> packageFiles = packageEntry.getValue();
List<Package> showPackageListEntries =
tryParseCheckpointPackageFile(
packageFiles,
new TypeReference<List<Package>>() {},
pvcae,
serverName,
domainName,
packageName,
RELPATH_CHECKPOINT_SHOW_PACKAGE);
if (showPackageListEntries == null) {
continue;
} else if (showPackageListEntries.isEmpty()) {
warnCheckpointPackageFile(
serverName,
domainName,
packageName,
RELPATH_CHECKPOINT_SHOW_PACKAGE,
"has no package entry in the JSON",
pvcae,
null);
continue;
} else if (showPackageListEntries.size() > 1) {
warnCheckpointPackageFile(
serverName,
domainName,
packageName,
RELPATH_CHECKPOINT_SHOW_PACKAGE,
"has extra packages in the JSON. Using the first entry.",
pvcae,
null);
}
Package pakij = showPackageListEntries.get(0);
// Note that warnings from hereon will use package name from JSON rather than directory
// name. In the future we may want to encode that name in base64 so we can guarantee
// the same package name can be retrieved from JSON and directory name.
List<AccessLayer> accessLayers =
readAccessLayers(pakij, domainName, packageFiles, pvcae, serverName);
NatRulebase natRulebase = readNatRulebase(pakij, domainName, packageFiles, pvcae, serverName);
ManagementPackage mgmtPackage = new ManagementPackage(accessLayers, natRulebase, pakij);
packagesBuilder.put(mgmtPackage.getPackage().getUid(), mgmtPackage);
}
Map<Uid, ManagementPackage> packages = packagesBuilder.build();
if (packages.isEmpty()) {
String message =
String.format(
"Ignoring Checkpoint management domain %s on server %s: no packages present",
domainName, serverName);
pvcae.addRedFlagWarning(
RELPATH_CHECKPOINT_MANAGEMENT_DIR, new Warning(message, "Checkpoint"));
LOGGER.warn(message);
return null;
}
// Use any package to find domain
Domain domain = packages.values().iterator().next().getPackage().getDomain();
return new ManagementDomain(
domain, gatewaysAndServers.getGatewaysAndServers(), packages, objects);
}
/** Read gateways and servers data. */
@VisibleForTesting
static GatewaysAndServers readGatewaysAndServers(
String serverName,
String domainName,
Map<String, Map<String, Map<String, String>>> domainFileMap,
ParseVendorConfigurationAnswerElement pvcae) {
List<GatewaysAndServers> gatewaysAndServersList =
tryParseCheckpointDomainFile(
domainFileMap,
new TypeReference<List<GatewaysAndServers>>() {},
pvcae,
serverName,
domainName,
RELPATH_CHECKPOINT_SHOW_GATEWAYS_AND_SERVERS);
if (gatewaysAndServersList == null) {
return null;
} else if (gatewaysAndServersList.isEmpty()) {
warnCheckpointDomainFile(
serverName,
domainName,
RELPATH_CHECKPOINT_SHOW_GATEWAYS_AND_SERVERS,
"JSON file contains no gateways-and-servers pages.",
pvcae,
null);
return null;
}
return mergeGatewaysAndServersPages(gatewaysAndServersList);
}
private static @Nullable <T> T tryParseCheckpointDomainFile(
Map<String, Map<String, Map<String, String>>> domainFileMap,
TypeReference<T> typeReference,
ParseVendorConfigurationAnswerElement pvcae,
String serverName,
String domainName,
String filename) {
String jsonText =
domainFileMap
.getOrDefault(serverName, ImmutableMap.of())
.getOrDefault(domainName, ImmutableMap.of())
.get(filename);
if (jsonText == null) {
warnCheckpointDomainFile(serverName, domainName, filename, "file is missing", pvcae, null);
return null;
}
try {
return BatfishObjectMapper.ignoreUnknownMapper().readValue(jsonText, typeReference);
} catch (JsonProcessingException e) {
warnCheckpointDomainFile(serverName, domainName, filename, "failed to parse JSON", pvcae, e);
return null;
}
}
private static void warnCheckpointDomainFile(
String serverName,
String domainName,
String filename,
String reason,
ParseVendorConfigurationAnswerElement pvcae,
@Nullable Throwable throwable) {
String inputObjectKey =
String.format(
"%s/%s/%s/%s", RELPATH_CHECKPOINT_MANAGEMENT_DIR, serverName, domainName, filename);
String warning =
String.format(
"Checkpoint management server '%s' domain '%s' file '%s' at '%s': %s",
serverName, domainName, filename, inputObjectKey, reason);
if (throwable != null) {
LOGGER.warn(warning, throwable);
pvcae.addRedFlagWarning(
RELPATH_CHECKPOINT_MANAGEMENT_DIR,
new Warning(
String.format("%s: %s", warning, Throwables.getStackTraceAsString(throwable)),
"Checkpoint"));
} else {
LOGGER.warn(warning);
pvcae.addRedFlagWarning(
RELPATH_CHECKPOINT_MANAGEMENT_DIR, new Warning(warning, "Checkpoint"));
}
}
private static @Nullable <T> T tryParseCheckpointPackageFile(
Map<String, String> packageFiles,
TypeReference<T> typeReference,
ParseVendorConfigurationAnswerElement pvcae,
String serverName,
String domainName,
String packageName,
String filename) {
String jsonText = packageFiles.get(filename);
if (jsonText == null) {
warnCheckpointPackageFile(
serverName, domainName, packageName, filename, "file is missing", pvcae, null);
return null;
}
try {
return BatfishObjectMapper.ignoreUnknownMapper().readValue(jsonText, typeReference);
} catch (JsonProcessingException e) {
warnCheckpointPackageFile(
serverName, domainName, packageName, filename, "failed to parse JSON", pvcae, e);
return null;
}
}
private static void warnCheckpointPackageFile(
String serverName,
String domainName,
String packageName,
String filename,
String reason,
ParseVendorConfigurationAnswerElement pvcae,
@Nullable Throwable throwable) {
String inputObjectKey =
String.format(
"%s/%s/%s/%s/%s",
RELPATH_CHECKPOINT_MANAGEMENT_DIR, serverName, domainName, packageName, filename);
String warning =
String.format(
"Checkpoint management server '%s' domain '%s' package '%s' file '%s' at '%s': %s",
serverName, domainName, packageName, filename, inputObjectKey, reason);
if (throwable != null) {
LOGGER.warn(warning, throwable);
pvcae.addRedFlagWarning(
RELPATH_CHECKPOINT_MANAGEMENT_DIR,
new Warning(
String.format("%s: %s", warning, Throwables.getStackTraceAsString(throwable)),
"Checkpoint"));
} else {
LOGGER.warn(warning);
pvcae.addRedFlagWarning(
RELPATH_CHECKPOINT_MANAGEMENT_DIR, new Warning(warning, "Checkpoint"));
}
}
/**
* Merge objects from each page of gateways and servers data into a single {@link
* GatewaysAndServers} object.
*/
private static @Nonnull GatewaysAndServers mergeGatewaysAndServersPages(
List<GatewaysAndServers> gatewaysAndServersList) {
if (gatewaysAndServersList.size() == 1) {
return gatewaysAndServersList.get(0);
}
return new GatewaysAndServers(
gatewaysAndServersList.stream()
.map(GatewaysAndServers::getGatewaysAndServers)
.map(Map::entrySet)
.flatMap(Collection::stream)
.collect(ImmutableMap.toImmutableMap(Entry::getKey, Entry::getValue)));
}
private static final Logger LOGGER = LogManager.getLogger(CheckpointManagementParser.class);
private static final String RELPATH_CHECKPOINT_SHOW_ACCESS_RULEBASE = "show-access-rulebase.json";
@VisibleForTesting
static final String RELPATH_CHECKPOINT_SHOW_GATEWAYS_AND_SERVERS =
"show-gateways-and-servers.json";
@VisibleForTesting static final String RELPATH_CHECKPOINT_SHOW_GROUPS = "show-groups.json";
private static final String RELPATH_CHECKPOINT_SHOW_HOSTS = "show-hosts.json";
@VisibleForTesting
static final String RELPATH_CHECKPOINT_SHOW_NAT_RULEBASE = "show-nat-rulebase.json";
private static final String RELPATH_CHECKPOINT_SHOW_NETWORKS = "show-networks.json";
private static final String RELPATH_CHECKPOINT_SHOW_PACKAGE = "show-package.json";
@VisibleForTesting
static final String RELPATH_CHECKPOINT_SHOW_SERVICE_GROUPS = "show-service-groups.json";
@VisibleForTesting
static final String RELPATH_CHECKPOINT_SHOW_SERVICES_ICMP = "show-services-icmp.json";
@VisibleForTesting
static final String RELPATH_CHECKPOINT_SHOW_SERVICES_OTHER = "show-services-other.json";
@VisibleForTesting
static final String RELPATH_CHECKPOINT_SHOW_SERVICES_TCP = "show-services-tcp.json";
@VisibleForTesting
static final String RELPATH_CHECKPOINT_SHOW_SERVICES_UDP = "show-services-udp.json";
}
|
|
/*
* Copyright 2014 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.impl.exhaustivesearch;
import java.util.Arrays;
import java.util.Collections;
import org.junit.Test;
import org.optaplanner.core.api.score.buildin.simple.SimpleScore;
import org.optaplanner.core.api.solver.Solver;
import org.optaplanner.core.api.solver.SolverFactory;
import org.optaplanner.core.config.exhaustivesearch.ExhaustiveSearchPhaseConfig;
import org.optaplanner.core.impl.domain.solution.descriptor.SolutionDescriptor;
import org.optaplanner.core.impl.exhaustivesearch.decider.ExhaustiveSearchDecider;
import org.optaplanner.core.impl.exhaustivesearch.node.ExhaustiveSearchLayer;
import org.optaplanner.core.impl.exhaustivesearch.node.ExhaustiveSearchNode;
import org.optaplanner.core.impl.exhaustivesearch.scope.ExhaustiveSearchPhaseScope;
import org.optaplanner.core.impl.exhaustivesearch.scope.ExhaustiveSearchStepScope;
import org.optaplanner.core.impl.heuristic.move.Move;
import org.optaplanner.core.impl.heuristic.selector.entity.EntitySelector;
import org.optaplanner.core.impl.score.director.ScoreDirector;
import org.optaplanner.core.impl.testdata.domain.TestdataEntity;
import org.optaplanner.core.impl.testdata.domain.TestdataSolution;
import org.optaplanner.core.impl.testdata.domain.TestdataValue;
import org.optaplanner.core.impl.testdata.domain.immovable.TestdataImmovableEntity;
import org.optaplanner.core.impl.testdata.domain.immovable.TestdataImmovableSolution;
import org.optaplanner.core.impl.testdata.domain.reinitialize.TestdataReinitializeEntity;
import org.optaplanner.core.impl.testdata.domain.reinitialize.TestdataReinitializeSolution;
import org.optaplanner.core.impl.testdata.util.PlannerTestUtils;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.*;
import static org.optaplanner.core.impl.testdata.util.PlannerAssert.*;
public class DefaultExhaustiveSearchPhaseTest {
@Test
public void restoreWorkingSolution() {
ExhaustiveSearchPhaseScope<TestdataSolution> phaseScope = mock(ExhaustiveSearchPhaseScope.class);
ExhaustiveSearchStepScope<TestdataSolution> lastCompletedStepScope = mock(ExhaustiveSearchStepScope.class);
when(phaseScope.getLastCompletedStepScope()).thenReturn(lastCompletedStepScope);
ExhaustiveSearchStepScope<TestdataSolution> stepScope = mock(ExhaustiveSearchStepScope.class);
when(stepScope.getPhaseScope()).thenReturn(phaseScope);
TestdataSolution workingSolution = new TestdataSolution();
when(phaseScope.getWorkingSolution()).thenReturn(workingSolution);
SolutionDescriptor<TestdataSolution> solutionDescriptor = TestdataSolution.buildSolutionDescriptor();
when(phaseScope.getSolutionDescriptor()).thenReturn(solutionDescriptor);
ExhaustiveSearchLayer layer0 = new ExhaustiveSearchLayer(0, mock(Object.class));
ExhaustiveSearchLayer layer1 = new ExhaustiveSearchLayer(1, mock(Object.class));
ExhaustiveSearchLayer layer2 = new ExhaustiveSearchLayer(2, mock(Object.class));
ExhaustiveSearchLayer layer3 = new ExhaustiveSearchLayer(3, mock(Object.class));
ExhaustiveSearchLayer layer4 = new ExhaustiveSearchLayer(4, mock(Object.class));
ExhaustiveSearchNode node0 = new ExhaustiveSearchNode(layer0, null);
node0.setMove(mock(Move.class));
node0.setUndoMove(mock(Move.class));
ExhaustiveSearchNode node1 = new ExhaustiveSearchNode(layer1, node0);
node1.setMove(mock(Move.class));
node1.setUndoMove(mock(Move.class));
ExhaustiveSearchNode node2A = new ExhaustiveSearchNode(layer2, node1);
node2A.setMove(mock(Move.class));
node2A.setUndoMove(mock(Move.class));
ExhaustiveSearchNode node3A = new ExhaustiveSearchNode(layer3, node2A); // oldNode
node3A.setMove(mock(Move.class));
node3A.setUndoMove(mock(Move.class));
ExhaustiveSearchNode node2B = new ExhaustiveSearchNode(layer2, node1);
node2B.setMove(mock(Move.class));
node2B.setUndoMove(mock(Move.class));
ExhaustiveSearchNode node3B = new ExhaustiveSearchNode(layer3, node2B);
node3B.setMove(mock(Move.class));
node3B.setUndoMove(mock(Move.class));
ExhaustiveSearchNode node4B = new ExhaustiveSearchNode(layer4, node3B); // newNode
node4B.setMove(mock(Move.class));
node4B.setUndoMove(mock(Move.class));
node4B.setScore(SimpleScore.valueOfUninitialized(-96, 7));
when(lastCompletedStepScope.getExpandingNode()).thenReturn(node3A);
when(stepScope.getExpandingNode()).thenReturn(node4B);
DefaultExhaustiveSearchPhase<TestdataSolution> phase = new DefaultExhaustiveSearchPhase<>(0, "", null, null);
phase.setEntitySelector(mock(EntitySelector.class));
phase.setDecider(mock(ExhaustiveSearchDecider.class));
phase.restoreWorkingSolution(stepScope);
verify(node0.getMove(), times(0)).doMove(any(ScoreDirector.class));
verify(node0.getUndoMove(), times(0)).doMove(any(ScoreDirector.class));
verify(node1.getMove(), times(0)).doMove(any(ScoreDirector.class));
verify(node1.getUndoMove(), times(0)).doMove(any(ScoreDirector.class));
verify(node2A.getMove(), times(0)).doMove(any(ScoreDirector.class));
verify(node2A.getUndoMove(), times(1)).doMove(any(ScoreDirector.class));
verify(node3A.getMove(), times(0)).doMove(any(ScoreDirector.class));
verify(node3A.getUndoMove(), times(1)).doMove(any(ScoreDirector.class));
verify(node2B.getMove(), times(1)).doMove(any(ScoreDirector.class));
verify(node2B.getUndoMove(), times(0)).doMove(any(ScoreDirector.class));
verify(node3B.getMove(), times(1)).doMove(any(ScoreDirector.class));
verify(node3B.getUndoMove(), times(0)).doMove(any(ScoreDirector.class));
verify(node4B.getMove(), times(1)).doMove(any(ScoreDirector.class));
verify(node4B.getUndoMove(), times(0)).doMove(any(ScoreDirector.class));
// TODO FIXME
// verify(workingSolution).setScore(newScore);
}
@Test
public void solveWithInitializedEntities() {
SolverFactory<TestdataSolution> solverFactory = PlannerTestUtils.buildSolverFactory(
TestdataSolution.class, TestdataEntity.class);
solverFactory.getSolverConfig().setPhaseConfigList(Collections.singletonList(
new ExhaustiveSearchPhaseConfig()));
Solver<TestdataSolution> solver = solverFactory.buildSolver();
TestdataSolution solution = new TestdataSolution("s1");
TestdataValue v1 = new TestdataValue("v1");
TestdataValue v2 = new TestdataValue("v2");
TestdataValue v3 = new TestdataValue("v3");
solution.setValueList(Arrays.asList(v1, v2, v3));
solution.setEntityList(Arrays.asList(
new TestdataEntity("e1", null),
new TestdataEntity("e2", v2),
new TestdataEntity("e3", v1)));
solution = solver.solve(solution);
assertNotNull(solution);
TestdataEntity solvedE1 = solution.getEntityList().get(0);
assertCode("e1", solvedE1);
assertNotNull(solvedE1.getValue());
TestdataEntity solvedE2 = solution.getEntityList().get(1);
assertCode("e2", solvedE2);
assertEquals(v2, solvedE2.getValue());
TestdataEntity solvedE3 = solution.getEntityList().get(2);
assertCode("e3", solvedE3);
assertEquals(v1, solvedE3.getValue());
assertEquals(0, solution.getScore().getInitScore());
}
@Test
public void solveWithImmovableEntities() {
SolverFactory<TestdataImmovableSolution> solverFactory = PlannerTestUtils.buildSolverFactory(
TestdataImmovableSolution.class, TestdataImmovableEntity.class);
solverFactory.getSolverConfig().setPhaseConfigList(Collections.singletonList(
new ExhaustiveSearchPhaseConfig()));
Solver<TestdataImmovableSolution> solver = solverFactory.buildSolver();
TestdataImmovableSolution solution = new TestdataImmovableSolution("s1");
TestdataValue v1 = new TestdataValue("v1");
TestdataValue v2 = new TestdataValue("v2");
TestdataValue v3 = new TestdataValue("v3");
solution.setValueList(Arrays.asList(v1, v2, v3));
solution.setEntityList(Arrays.asList(
new TestdataImmovableEntity("e1", null, false, false),
new TestdataImmovableEntity("e2", v2, true, false),
new TestdataImmovableEntity("e3", null, false, true)));
solution = solver.solve(solution);
assertNotNull(solution);
TestdataImmovableEntity solvedE1 = solution.getEntityList().get(0);
assertCode("e1", solvedE1);
assertNotNull(solvedE1.getValue());
TestdataImmovableEntity solvedE2 = solution.getEntityList().get(1);
assertCode("e2", solvedE2);
assertEquals(v2, solvedE2.getValue());
TestdataImmovableEntity solvedE3 = solution.getEntityList().get(2);
assertCode("e3", solvedE3);
assertEquals(null, solvedE3.getValue());
assertEquals(-1, solution.getScore().getInitScore());
}
@Test
public void solveWithEmptyEntityList() {
SolverFactory<TestdataSolution> solverFactory = PlannerTestUtils.buildSolverFactory(
TestdataSolution.class, TestdataEntity.class);
solverFactory.getSolverConfig().setPhaseConfigList(Collections.singletonList(
new ExhaustiveSearchPhaseConfig()));
Solver<TestdataSolution> solver = solverFactory.buildSolver();
TestdataSolution solution = new TestdataSolution("s1");
TestdataValue v1 = new TestdataValue("v1");
TestdataValue v2 = new TestdataValue("v2");
TestdataValue v3 = new TestdataValue("v3");
solution.setValueList(Arrays.asList(v1, v2, v3));
solution.setEntityList(Collections.emptyList());
solution = solver.solve(solution);
assertNotNull(solution);
assertEquals(0, solution.getEntityList().size());
}
@Test
public void solveWithReinitializeVariable() {
SolverFactory<TestdataReinitializeSolution> solverFactory = PlannerTestUtils.buildSolverFactory(
TestdataReinitializeSolution.class, TestdataReinitializeEntity.class);
solverFactory.getSolverConfig().setPhaseConfigList(Collections.singletonList(
new ExhaustiveSearchPhaseConfig()));
Solver<TestdataReinitializeSolution> solver = solverFactory.buildSolver();
TestdataReinitializeSolution solution = new TestdataReinitializeSolution("s1");
TestdataValue v1 = new TestdataValue("v1");
TestdataValue v2 = new TestdataValue("v2");
TestdataValue v3 = new TestdataValue("v3");
solution.setValueList(Arrays.asList(v1, v2, v3));
solution.setEntityList(Arrays.asList(
new TestdataReinitializeEntity("e1", null, false),
new TestdataReinitializeEntity("e2", v2, false),
new TestdataReinitializeEntity("e3", v2, true),
new TestdataReinitializeEntity("e4", null, true)));
solution = solver.solve(solution);
assertNotNull(solution);
TestdataReinitializeEntity solvedE1 = solution.getEntityList().get(0);
assertCode("e1", solvedE1);
assertNotNull(solvedE1.getValue());
TestdataReinitializeEntity solvedE2 = solution.getEntityList().get(1);
assertCode("e2", solvedE2);
assertNotNull(solvedE2.getValue());
TestdataReinitializeEntity solvedE3 = solution.getEntityList().get(2);
assertCode("e3", solvedE3);
assertEquals(v2, solvedE3.getValue());
TestdataReinitializeEntity solvedE4 = solution.getEntityList().get(3);
assertCode("e4", solvedE4);
assertEquals(null, solvedE4.getValue());
assertEquals(-1, solution.getScore().getInitScore());
}
}
|
|
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.trino.testing;
import com.google.common.collect.ImmutableSet;
import io.trino.plugin.tpch.TpchMetadata;
import io.trino.testing.tpch.TpchIndexSpec;
import io.trino.testing.tpch.TpchIndexSpec.Builder;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
public abstract class AbstractTestIndexedQueries
extends AbstractTestQueryFramework
{
// Generate the indexed data sets
public static final TpchIndexSpec INDEX_SPEC = new Builder()
.addIndex("orders", TpchMetadata.TINY_SCALE_FACTOR, ImmutableSet.of("orderkey"))
.addIndex("orders", TpchMetadata.TINY_SCALE_FACTOR, ImmutableSet.of("orderkey", "orderstatus"))
.addIndex("orders", TpchMetadata.TINY_SCALE_FACTOR, ImmutableSet.of("orderkey", "custkey"))
.addIndex("orders", TpchMetadata.TINY_SCALE_FACTOR, ImmutableSet.of("orderstatus", "shippriority"))
.build();
@Test
public void testExampleSystemTable()
{
assertQuery("SELECT name FROM sys.example", "SELECT 'test' AS name");
MaterializedResult result = computeActual("SHOW SCHEMAS");
assertTrue(result.getOnlyColumnAsSet().containsAll(ImmutableSet.of("sf100", "tiny", "sys")));
result = computeActual("SHOW TABLES FROM sys");
assertEquals(result.getOnlyColumnAsSet(), ImmutableSet.of("example"));
}
@Test
public void testExplainAnalyzeIndexJoin()
{
assertQuerySucceeds(getSession(), "EXPLAIN ANALYZE " +
" SELECT *\n" +
"FROM (\n" +
" SELECT *\n" +
" FROM lineitem\n" +
" WHERE partkey % 8 = 0) l\n" +
"JOIN orders o\n" +
" ON l.orderkey = o.orderkey");
}
@Test
public void testBasicIndexJoin()
{
assertQuery("" +
"SELECT *\n" +
"FROM (\n" +
" SELECT *\n" +
" FROM lineitem\n" +
" WHERE partkey % 8 = 0) l\n" +
"JOIN orders o\n" +
" ON l.orderkey = o.orderkey");
}
@Test
public void testBasicIndexJoinReverseCandidates()
{
assertQuery("" +
"SELECT *\n" +
"FROM orders o " +
"JOIN (\n" +
" SELECT *\n" +
" FROM lineitem\n" +
" WHERE partkey % 8 = 0) l\n" +
" ON o.orderkey = l.orderkey");
}
@Test
public void testBasicIndexJoinWithNullKeys()
{
assertQuery("" +
"SELECT *\n" +
"FROM (\n" +
" SELECT CASE WHEN suppkey % 2 = 0 THEN orderkey ELSE NULL END AS orderkey\n" +
" FROM lineitem\n" +
" WHERE partkey % 8 = 0) l\n" +
"JOIN orders o\n" +
" ON l.orderkey = o.orderkey");
}
@Test
public void testMultiKeyIndexJoinAligned()
{
assertQuery("" +
"SELECT *\n" +
"FROM (\n" +
" SELECT orderkey, CASE WHEN suppkey % 2 = 0 THEN 'F' ELSE 'O' END AS orderstatus\n" +
" FROM lineitem\n" +
" WHERE partkey % 8 = 0) l\n" +
"JOIN orders o\n" +
" ON l.orderkey = o.orderkey AND l.orderstatus = o.orderstatus");
}
@Test
public void testMultiKeyIndexJoinUnaligned()
{
// This test a join order that is different from the inner select column ordering
assertQuery("" +
"SELECT *\n" +
"FROM (\n" +
" SELECT orderkey, CASE WHEN suppkey % 2 = 0 THEN 'F' ELSE 'O' END AS orderstatus\n" +
" FROM lineitem\n" +
" WHERE partkey % 8 = 0) l\n" +
"JOIN orders o\n" +
" ON l.orderstatus = o.orderstatus AND l.orderkey = o.orderkey");
}
@Test
public void testJoinWithNonJoinExpression()
{
assertQuery("SELECT COUNT(*) FROM lineitem JOIN orders ON lineitem.orderkey = orders.orderkey AND orders.custkey = 1");
}
@Test
public void testPredicateDerivedKey()
{
assertQuery("" +
"SELECT *\n" +
"FROM (\n" +
" SELECT orderkey\n" +
" FROM lineitem\n" +
" WHERE partkey % 8 = 0) l\n" +
"JOIN orders o\n" +
" ON l.orderkey = o.orderkey\n" +
"WHERE o.orderstatus = 'F'");
}
@Test
public void testCompoundPredicateDerivedKey()
{
assertQuery("" +
"SELECT *\n" +
"FROM (\n" +
" SELECT orderkey\n" +
" FROM lineitem\n" +
" WHERE partkey % 8 = 0) l\n" +
"JOIN orders o\n" +
" ON l.orderkey = o.orderkey\n" +
"WHERE o.orderstatus = 'F'\n" +
" AND o.custkey % 2 = 0");
}
@Test
public void testChainedIndexJoin()
{
assertQuery("" +
"SELECT *\n" +
"FROM (\n" +
" SELECT orderkey, CASE WHEN suppkey % 2 = 0 THEN 'F' ELSE 'O' END AS orderstatus\n" +
" FROM lineitem\n" +
" WHERE partkey % 8 = 0) l\n" +
"JOIN orders o1\n" +
" ON l.orderkey = o1.orderkey AND l.orderstatus = o1.orderstatus\n" +
"JOIN orders o2\n" +
" ON o1.custkey % 1024 = o2.orderkey");
}
@Test
public void testBasicLeftIndexJoin()
{
assertQuery("" +
"SELECT *\n" +
"FROM (\n" +
" SELECT *\n" +
" FROM lineitem\n" +
" WHERE partkey % 8 = 0) l\n" +
"LEFT JOIN orders o\n" +
" ON l.orderkey = o.orderkey");
}
@Test
public void testNonIndexLeftJoin()
{
assertQuery("" +
"SELECT *\n" +
"FROM orders o " +
"LEFT JOIN (\n" +
" SELECT *\n" +
" FROM lineitem\n" +
" WHERE partkey % 8 = 0) l\n" +
" ON o.orderkey = l.orderkey");
}
@Test
public void testBasicRightIndexJoin()
{
assertQuery("" +
"SELECT COUNT(*)\n" +
"FROM orders o " +
"RIGHT JOIN (\n" +
" SELECT *\n" +
" FROM lineitem\n" +
" WHERE partkey % 8 = 0) l\n" +
" ON o.orderkey = l.orderkey");
}
@Test
public void testNonIndexRightJoin()
{
assertQuery("" +
"SELECT COUNT(*)\n" +
"FROM (\n" +
" SELECT *\n" +
" FROM lineitem\n" +
" WHERE partkey % 8 = 0) l\n" +
"RIGHT JOIN orders o\n" +
" ON l.orderkey = o.orderkey");
}
@Test
public void testIndexJoinThroughAggregation()
{
assertQuery("" +
"SELECT *\n" +
"FROM (\n" +
" SELECT *\n" +
" FROM lineitem\n" +
" WHERE partkey % 8 = 0) l\n" +
"JOIN (\n" +
" SELECT orderkey, COUNT(*)\n" +
" FROM orders\n" +
" WHERE custkey % 8 = 0\n" +
" GROUP BY orderkey\n" +
" ORDER BY orderkey) o\n" +
" ON l.orderkey = o.orderkey");
}
@Test
public void testIndexJoinThroughMultiKeyAggregation()
{
assertQuery("" +
"SELECT *\n" +
"FROM (\n" +
" SELECT *\n" +
" FROM lineitem\n" +
" WHERE partkey % 8 = 0) l\n" +
"JOIN (\n" +
" SELECT shippriority, orderkey, COUNT(*)\n" +
" FROM orders\n" +
" WHERE custkey % 8 = 0\n" +
" GROUP BY shippriority, orderkey\n" +
" ORDER BY orderkey) o\n" +
" ON l.orderkey = o.orderkey");
}
@Test
public void testNonIndexableKeys()
{
assertQuery("" +
"SELECT *\n" +
"FROM (\n" +
" SELECT *\n" +
" FROM lineitem\n" +
" WHERE partkey % 8 = 0) l\n" +
"JOIN (\n" +
" SELECT orderkey % 2 as orderkey\n" +
" FROM orders) o\n" +
" ON l.orderkey = o.orderkey");
}
@Test
public void testComposableIndexJoins()
{
assertQuery("" +
"SELECT *\n" +
"FROM (\n" +
" SELECT *\n" +
" FROM lineitem\n" +
" WHERE partkey % 8 = 0) x\n" +
"JOIN (\n" +
" SELECT o1.orderkey as orderkey, o2.custkey as custkey\n" +
" FROM orders o1\n" +
" JOIN orders o2\n" +
" ON o1.orderkey = o2.orderkey) y\n" +
" ON x.orderkey = y.orderkey\n");
}
@Test
public void testNonComposableIndexJoins()
{
assertQuery("" +
"SELECT *\n" +
"FROM (\n" +
" SELECT *\n" +
" FROM lineitem\n" +
" WHERE partkey % 8 = 0) x\n" +
"JOIN (\n" +
" SELECT l.orderkey as orderkey, o.custkey as custkey\n" +
" FROM lineitem l\n" +
" JOIN orders o\n" +
" ON l.orderkey = o.orderkey) y\n" +
" ON x.orderkey = y.orderkey\n");
}
@Test
public void testOverlappingIndexJoinLookupSymbol()
{
assertQuery("" +
"SELECT *\n" +
"FROM (\n" +
" SELECT *\n" +
" FROM lineitem\n" +
" WHERE partkey % 8 = 0) l\n" +
"JOIN orders o\n" +
" ON l.orderkey % 1024 = o.orderkey AND l.partkey % 1024 = o.orderkey");
}
@Test
public void testOverlappingSourceOuterIndexJoinLookupSymbol()
{
assertQuery("" +
"SELECT *\n" +
"FROM (\n" +
" SELECT *\n" +
" FROM lineitem\n" +
" WHERE partkey % 8 = 0) l\n" +
"LEFT JOIN orders o\n" +
" ON l.orderkey % 1024 = o.orderkey AND l.partkey % 1024 = o.orderkey");
}
@Test
public void testOverlappingIndexJoinProbeSymbol()
{
assertQuery("" +
"SELECT *\n" +
"FROM (\n" +
" SELECT *\n" +
" FROM lineitem\n" +
" WHERE partkey % 8 = 0) l\n" +
"JOIN orders o\n" +
" ON l.orderkey = o.orderkey AND l.orderkey = o.custkey");
}
@Test
public void testOverlappingSourceOuterIndexJoinProbeSymbol()
{
assertQuery("" +
"SELECT *\n" +
"FROM (\n" +
" SELECT *\n" +
" FROM lineitem\n" +
" WHERE partkey % 8 = 0) l\n" +
"LEFT JOIN orders o\n" +
" ON l.orderkey = o.orderkey AND l.orderkey = o.custkey");
}
@Test
public void testRepeatedIndexJoinClause()
{
assertQuery("" +
"SELECT *\n" +
"FROM (\n" +
" SELECT *\n" +
" FROM lineitem\n" +
" WHERE partkey % 8 = 0) l\n" +
"JOIN orders o\n" +
" ON l.orderkey = o.orderkey AND l.orderkey = o.orderkey");
}
/**
* Assure nulls in probe readahead does not leak into connectors.
*/
@Test
public void testProbeNullInReadahead()
{
assertQuery(
"select count(*) from (values (1), (cast(null as bigint))) x(orderkey) join orders using (orderkey)",
"select count(*) from orders where orderkey = 1");
}
@Test
public void testHighCardinalityIndexJoinResult()
{
assertQuery("" +
"SELECT *\n" +
"FROM (\n" +
" SELECT *\n" +
" FROM orders\n" +
" WHERE orderkey % 10000 = 0) o1\n" +
"JOIN (\n" +
" SELECT *\n" +
" FROM orders\n" +
" WHERE orderkey % 4 = 0) o2\n" +
" ON o1.orderstatus = o2.orderstatus AND o1.shippriority = o2.shippriority");
}
@Test
public void testReducedIndexProbeKey()
{
assertQuery("" +
"SELECT *\n" +
"FROM (\n" +
" SELECT orderkey % 64 AS a, suppkey % 2 AS b\n" +
" FROM lineitem\n" +
" WHERE partkey % 8 = 0) l\n" +
"JOIN (\n" +
" SELECT orderkey AS a, SUM(LENGTH(comment)) % 2 AS b\n" +
" FROM orders\n" +
" GROUP BY orderkey) o\n" +
" ON l.a = o.a AND l.b = o.b");
}
@Test
public void testReducedIndexProbeKeyNegativeCaching()
{
// Not every column 'b' can be matched through the join
assertQuery("" +
"SELECT *\n" +
"FROM (\n" +
" SELECT orderkey % 64 AS a, (suppkey % 2) + 1 AS b\n" +
" FROM lineitem\n" +
" WHERE partkey % 8 = 0) l\n" +
"JOIN (\n" +
" SELECT orderkey AS a, SUM(LENGTH(comment)) % 2 AS b\n" +
" FROM orders\n" +
" GROUP BY orderkey) o\n" +
" ON l.a = o.a AND l.b = o.b");
}
@Test
public void testHighCardinalityReducedIndexProbeKey()
{
assertQuery("" +
"SELECT *\n" +
"FROM (\n" +
" SELECT *, custkey % 4 AS x, custkey % 2 AS y\n" +
" FROM orders\n" +
" WHERE orderkey % 10000 = 0) o1\n" +
"JOIN (\n" +
" SELECT *, custkey % 5 AS x, custkey % 3 AS y\n" +
" FROM orders\n" +
" WHERE orderkey % 4 = 0) o2\n" +
" ON o1.orderstatus = o2.orderstatus AND o1.shippriority = o2.shippriority AND o1.x = o2.x AND o1.y = o2.y");
}
@Test
public void testReducedIndexProbeKeyComplexQueryShapes()
{
// Reduce the probe key through projections, aggregations, and joins
assertQuery("" +
"SELECT *\n" +
"FROM (\n" +
" SELECT orderkey % 64 AS a, suppkey % 2 AS b, orderkey AS c, linenumber % 2 AS d\n" +
" FROM lineitem\n" +
" WHERE partkey % 7 = 0) l\n" +
"JOIN (\n" +
" SELECT t1.a AS a, t1.b AS b, t2.orderkey AS c, SUM(LENGTH(t2.comment)) % 2 AS d\n" +
" FROM (\n" +
" SELECT orderkey AS a, custkey % 3 AS b\n" +
" FROM orders\n" +
" ) t1\n" +
" JOIN orders t2 ON t1.a = (t2.orderkey % 1000)\n" +
" WHERE t1.a % 1000 = 0\n" +
" GROUP BY t1.a, t1.b, t2.orderkey) o\n" +
" ON l.a = o.a AND l.b = o.b AND l.c = o.c AND l.d = o.d");
}
@Test
public void testIndexJoinConstantPropagation()
{
assertQuery("" +
"SELECT x, y, COUNT(*)\n" +
"FROM (SELECT orderkey, 0 AS x FROM orders) a \n" +
"JOIN (SELECT orderkey, 1 AS y FROM orders) b \n" +
"ON a.orderkey = b.orderkey\n" +
"GROUP BY 1, 2");
}
@Test
public void testIndexJoinThroughWindow()
{
assertQuery("" +
"SELECT *\n" +
"FROM (\n" +
" SELECT *\n" +
" FROM lineitem\n" +
" WHERE partkey % 16 = 0) l\n" +
"JOIN (\n" +
" SELECT *, COUNT(*) OVER (PARTITION BY orderkey)\n" +
" FROM orders) o\n" +
" ON l.orderkey = o.orderkey",
"" +
"SELECT *\n" +
"FROM (\n" +
" SELECT *\n" +
" FROM lineitem\n" +
" WHERE partkey % 16 = 0) l\n" +
"JOIN (\n" +
" SELECT *, 1\n" +
" FROM orders) o\n" +
" ON l.orderkey = o.orderkey");
}
@Test
public void testIndexJoinThroughWindowDoubleAggregation()
{
assertQuery("" +
"SELECT *\n" +
"FROM (\n" +
" SELECT *\n" +
" FROM lineitem\n" +
" WHERE partkey % 16 = 0) l\n" +
"JOIN (\n" +
" SELECT *, COUNT(*) OVER (PARTITION BY orderkey), SUM(orderkey) OVER (PARTITION BY orderkey)\n" +
" FROM orders) o\n" +
" ON l.orderkey = o.orderkey",
"" +
"SELECT *\n" +
"FROM (\n" +
" SELECT *\n" +
" FROM lineitem\n" +
" WHERE partkey % 16 = 0) l\n" +
"JOIN (\n" +
" SELECT *, 1, orderkey as o\n" +
" FROM orders) o\n" +
" ON l.orderkey = o.orderkey");
}
@Test
public void testIndexJoinThroughWindowPartialPartition()
{
assertQuery("" +
"SELECT *\n" +
"FROM (\n" +
" SELECT *\n" +
" FROM lineitem\n" +
" WHERE partkey % 16 = 0) l\n" +
"JOIN (\n" +
" SELECT *, COUNT(*) OVER (PARTITION BY orderkey, custkey)\n" +
" FROM orders) o\n" +
" ON l.orderkey = o.orderkey",
"" +
"SELECT *\n" +
"FROM (\n" +
" SELECT *\n" +
" FROM lineitem\n" +
" WHERE partkey % 16 = 0) l\n" +
"JOIN (\n" +
" SELECT *, 1\n" +
" FROM orders) o\n" +
" ON l.orderkey = o.orderkey");
}
@Test
public void testNoIndexJoinThroughWindowWithRowNumberFunction()
{
assertQuery("" +
"SELECT *\n" +
"FROM (\n" +
" SELECT *\n" +
" FROM lineitem\n" +
" WHERE partkey % 16 = 0) l\n" +
"JOIN (\n" +
" SELECT *, row_number() OVER (PARTITION BY orderkey)\n" +
" FROM orders) o\n" +
" ON l.orderkey = o.orderkey",
"" +
"SELECT *\n" +
"FROM (\n" +
" SELECT *\n" +
" FROM lineitem\n" +
" WHERE partkey % 16 = 0) l\n" +
"JOIN (\n" +
" SELECT *, 1\n" +
" FROM orders) o\n" +
" ON l.orderkey = o.orderkey");
}
@Test
public void testNoIndexJoinThroughWindowWithOrderBy()
{
assertQuery("" +
"SELECT *\n" +
"FROM (\n" +
" SELECT *\n" +
" FROM lineitem\n" +
" WHERE partkey % 16 = 0) l\n" +
"JOIN (\n" +
" SELECT *, COUNT(*) OVER (PARTITION BY orderkey ORDER BY custkey)\n" +
" FROM orders) o\n" +
" ON l.orderkey = o.orderkey",
"" +
"SELECT *\n" +
"FROM (\n" +
" SELECT *\n" +
" FROM lineitem\n" +
" WHERE partkey % 16 = 0) l\n" +
"JOIN (\n" +
" SELECT *, 1\n" +
" FROM orders) o\n" +
" ON l.orderkey = o.orderkey");
}
@Test
public void testNoIndexJoinThroughWindowWithRowFrame()
{
assertQuery("" +
"SELECT l.orderkey, o.c\n" +
"FROM (\n" +
" SELECT *\n" +
" FROM lineitem\n" +
" WHERE partkey % 16 = 0) l\n" +
"JOIN (\n" +
" SELECT *, COUNT(*) OVER (PARTITION BY orderkey ROWS 1 PRECEDING) as c\n" +
" FROM orders) o\n" +
" ON l.orderkey = o.orderkey",
"" +
"SELECT l.orderkey, o.c\n" +
"FROM (\n" +
" SELECT *\n" +
" FROM lineitem\n" +
" WHERE partkey % 16 = 0) l\n" +
"JOIN (\n" +
" SELECT *, 1 as c\n" +
" FROM orders) o\n" +
" ON l.orderkey = o.orderkey");
}
@Test
public void testOuterNonEquiJoins()
{
assertQuery("SELECT COUNT(*) FROM lineitem LEFT OUTER JOIN orders ON lineitem.orderkey = orders.orderkey AND lineitem.quantity > 5 WHERE orders.orderkey IS NULL");
assertQuery("SELECT COUNT(*) FROM orders RIGHT OUTER JOIN lineitem ON lineitem.orderkey = orders.orderkey AND lineitem.quantity > 5 WHERE orders.orderkey IS NULL");
}
@Test
public void testNonEquiJoin()
{
assertQuery("SELECT COUNT(*) FROM lineitem JOIN orders ON lineitem.orderkey = orders.orderkey AND lineitem.quantity + length(orders.comment) > 7");
}
}
|
|
/**
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package abi41_0_0.host.exp.exponent.modules.api.components.viewpager;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.widget.ViewPager2;
import com.facebook.infer.annotation.Assertions;
import abi41_0_0.com.facebook.react.bridge.ReadableArray;
import abi41_0_0.com.facebook.react.common.MapBuilder;
import abi41_0_0.com.facebook.react.uimanager.PixelUtil;
import abi41_0_0.com.facebook.react.uimanager.ThemedReactContext;
import abi41_0_0.com.facebook.react.uimanager.UIManagerModule;
import abi41_0_0.com.facebook.react.uimanager.ViewGroupManager;
import abi41_0_0.com.facebook.react.uimanager.annotations.ReactProp;
import abi41_0_0.com.facebook.react.uimanager.events.EventDispatcher;
import abi41_0_0.host.exp.exponent.modules.api.components.viewpager.event.PageScrollEvent;
import abi41_0_0.host.exp.exponent.modules.api.components.viewpager.event.PageScrollStateChangedEvent;
import abi41_0_0.host.exp.exponent.modules.api.components.viewpager.event.PageSelectedEvent;
import java.util.Map;
import static androidx.viewpager2.widget.ViewPager2.ORIENTATION_HORIZONTAL;
import static androidx.viewpager2.widget.ViewPager2.SCROLL_STATE_DRAGGING;
import static androidx.viewpager2.widget.ViewPager2.SCROLL_STATE_IDLE;
import static androidx.viewpager2.widget.ViewPager2.SCROLL_STATE_SETTLING;
public class ReactViewPagerManager extends ViewGroupManager<ViewPager2> {
private static final String REACT_CLASS = "RNCViewPager";
private static final int COMMAND_SET_PAGE = 1;
private static final int COMMAND_SET_PAGE_WITHOUT_ANIMATION = 2;
private static final int COMMAND_SET_SCROLL_ENABLED = 3;
private EventDispatcher eventDispatcher;
@NonNull
@Override
public String getName() {
return REACT_CLASS;
}
@NonNull
@Override
protected ViewPager2 createViewInstance(@NonNull ThemedReactContext reactContext) {
final ViewPager2 vp = new ViewPager2(reactContext);
final FragmentAdapter adapter = new FragmentAdapter((FragmentActivity) reactContext.getCurrentActivity());
vp.setAdapter(adapter);
//https://github.com/callstack/react-native-viewpager/issues/183
vp.setSaveEnabled(false);
eventDispatcher = reactContext.getNativeModule(UIManagerModule.class).getEventDispatcher();
vp.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
super.onPageScrolled(position, positionOffset, positionOffsetPixels);
eventDispatcher.dispatchEvent(
new PageScrollEvent(vp.getId(), position, positionOffset));
}
@Override
public void onPageSelected(int position) {
super.onPageSelected(position);
eventDispatcher.dispatchEvent(
new PageSelectedEvent(vp.getId(), position));
}
@Override
public void onPageScrollStateChanged(int state) {
super.onPageScrollStateChanged(state);
String pageScrollState;
switch (state) {
case SCROLL_STATE_IDLE:
pageScrollState = "idle";
break;
case SCROLL_STATE_DRAGGING:
pageScrollState = "dragging";
break;
case SCROLL_STATE_SETTLING:
pageScrollState = "settling";
break;
default:
throw new IllegalStateException("Unsupported pageScrollState");
}
eventDispatcher.dispatchEvent(
new PageScrollStateChangedEvent(vp.getId(), pageScrollState));
}
});
return vp;
}
private void setCurrentItem(final ViewPager2 view, int selectedTab, boolean scrollSmooth) {
view.post(new Runnable() {
@Override
public void run() {
view.measure(
View.MeasureSpec.makeMeasureSpec(view.getWidth(), View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(view.getHeight(), View.MeasureSpec.EXACTLY));
view.layout(view.getLeft(), view.getTop(), view.getRight(), view.getBottom());
}
});
view.setCurrentItem(selectedTab, scrollSmooth);
}
@Override
public void addView(ViewPager2 parent, View child, int index) {
if (child == null) {
return;
}
((FragmentAdapter) parent.getAdapter()).addFragment(child, index);
}
@Override
public int getChildCount(ViewPager2 parent) {
return parent.getAdapter().getItemCount();
}
@Override
public View getChildAt(ViewPager2 parent, int index) {
return ((FragmentAdapter) parent.getAdapter()).getChildViewAt(index);
}
@Override
public void removeView(ViewPager2 parent, View view) {
((FragmentAdapter) parent.getAdapter()).removeFragment(view);
}
public void removeAllViews(ViewPager2 parent) {
parent.setUserInputEnabled(false);
FragmentAdapter adapter = ((FragmentAdapter) parent.getAdapter());
adapter.removeAll();
}
@Override
public void removeViewAt(ViewPager2 parent, int index) {
FragmentAdapter adapter = ((FragmentAdapter) parent.getAdapter());
adapter.removeFragmentAt(index);
}
@Override
public boolean needsCustomLayoutForChildren() {
return true;
}
@ReactProp(name = "scrollEnabled", defaultBoolean = true)
public void setScrollEnabled(ViewPager2 viewPager, boolean value) {
viewPager.setUserInputEnabled(value);
}
@ReactProp(name = "orientation")
public void setOrientation(ViewPager2 viewPager, String value) {
viewPager.setOrientation(value.equals("vertical") ? ViewPager2.ORIENTATION_VERTICAL : ORIENTATION_HORIZONTAL);
}
@ReactProp(name = "offscreenPageLimit", defaultInt = ViewPager2.OFFSCREEN_PAGE_LIMIT_DEFAULT)
public void set(ViewPager2 viewPager, int value) {
viewPager.setOffscreenPageLimit(value);
}
@ReactProp(name = "overScrollMode")
public void setOverScrollMode(ViewPager2 viewPager, String value) {
View child = viewPager.getChildAt(0);
if (value.equals("never")) {
child.setOverScrollMode(ViewPager2.OVER_SCROLL_NEVER);
} else if (value.equals("always")) {
child.setOverScrollMode(ViewPager2.OVER_SCROLL_ALWAYS);
} else {
child.setOverScrollMode(ViewPager2.OVER_SCROLL_IF_CONTENT_SCROLLS);
}
}
@Override
public Map getExportedCustomDirectEventTypeConstants() {
return MapBuilder.of(
PageScrollEvent.EVENT_NAME, MapBuilder.of("registrationName", "onPageScroll"),
PageScrollStateChangedEvent.EVENT_NAME, MapBuilder.of("registrationName", "onPageScrollStateChanged"),
PageSelectedEvent.EVENT_NAME, MapBuilder.of("registrationName", "onPageSelected"));
}
@Override
public Map<String, Integer> getCommandsMap() {
return MapBuilder.of(
"setPage",
COMMAND_SET_PAGE,
"setPageWithoutAnimation",
COMMAND_SET_PAGE_WITHOUT_ANIMATION,
"setScrollEnabled",
COMMAND_SET_SCROLL_ENABLED);
}
@Override
public void receiveCommand(@NonNull final ViewPager2 root, int commandId, @Nullable final ReadableArray args) {
super.receiveCommand(root, commandId, args);
Assertions.assertNotNull(root);
Assertions.assertNotNull(args);
switch (commandId) {
case COMMAND_SET_PAGE: {
setCurrentItem(root, args.getInt(0), true);
eventDispatcher.dispatchEvent(new PageSelectedEvent(root.getId(), args.getInt(0)));
return;
}
case COMMAND_SET_PAGE_WITHOUT_ANIMATION: {
setCurrentItem(root, args.getInt(0), false);
eventDispatcher.dispatchEvent(new PageSelectedEvent(root.getId(), args.getInt(0)));
return;
}
case COMMAND_SET_SCROLL_ENABLED: {
root.setUserInputEnabled(args.getBoolean(0));
return;
}
default:
throw new IllegalArgumentException(String.format(
"Unsupported command %d received by %s.",
commandId,
getClass().getSimpleName()));
}
}
@ReactProp(name = "pageMargin", defaultFloat = 0)
public void setPageMargin(ViewPager2 pager, float margin) {
final int pageMargin = (int) PixelUtil.toPixelFromDIP(margin);
final ViewPager2 vp = pager;
/**
* Don't use MarginPageTransformer to be able to support negative margins
*/
pager.setPageTransformer(new ViewPager2.PageTransformer() {
@Override
public void transformPage(@NonNull View page, float position) {
float offset = pageMargin * position;
if (vp.getOrientation() == ViewPager2.ORIENTATION_HORIZONTAL) {
boolean isRTL = vp.getLayoutDirection() == View.LAYOUT_DIRECTION_RTL;
page.setTranslationX(isRTL ? -offset : offset);
} else {
page.setTranslationY(offset);
}
}
});
}
}
|
|
/*
*
* 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.geode.tools.pulse.internal.controllers;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.geode.tools.pulse.internal.data.Cluster;
import org.apache.geode.tools.pulse.internal.data.PulseConstants;
import org.apache.geode.tools.pulse.internal.data.PulseVersion;
import org.apache.geode.tools.pulse.internal.data.Repository;
import org.apache.geode.tools.pulse.internal.service.PulseService;
import org.apache.geode.tools.pulse.internal.service.PulseServiceFactory;
import org.apache.geode.tools.pulse.internal.service.SystemAlertsService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Class PulseController
*
* This class contains the implementations for all http Ajax requests needs to be served in Pulse.
*
* @since GemFire version 7.5
*/
@Controller
public class PulseController {
private static final Logger logger = LogManager.getLogger();
// CONSTANTS
private final String DEFAULT_EXPORT_FILENAME = "DataBrowserQueryResult.json";
private final String QUERYSTRING_PARAM_ACTION = "action";
private final String QUERYSTRING_PARAM_QUERYID = "queryId";
private final String ACTION_VIEW = "view";
private final String ACTION_DELETE = "delete";
private String STATUS_REPSONSE_SUCCESS = "success";
private String STATUS_REPSONSE_FAIL = "fail";
private String ERROR_REPSONSE_QUERYNOTFOUND = "No queries found";
private String ERROR_REPSONSE_QUERYIDMISSING = "Query id is missing";
private static final String EMPTY_JSON = "{}";
// Shared object to hold pulse version details
public static PulseVersion pulseVersion = new PulseVersion();
// default is gemfire
private static String pulseProductSupport = PulseConstants.PRODUCT_NAME_GEMFIRE;
private final ObjectMapper mapper = new ObjectMapper();
@Autowired
PulseServiceFactory pulseServiceFactory;
@RequestMapping(value = "/pulseUpdate", method = RequestMethod.POST)
public void getPulseUpdate(HttpServletRequest request, HttpServletResponse response)
throws IOException {
String pulseData = request.getParameter("pulseData");
ObjectNode responseMap = mapper.createObjectNode();
JsonNode requestMap = null;
try {
requestMap = mapper.readTree(pulseData);
Iterator<?> keys = requestMap.fieldNames();
// Execute Services
while (keys.hasNext()) {
String serviceName = keys.next().toString();
try {
PulseService pulseService = pulseServiceFactory.getPulseServiceInstance(serviceName);
responseMap.put(serviceName, pulseService.execute(request));
} catch (Exception serviceException) {
logger.warn("serviceException [for service {}] = {}", serviceName,
serviceException.getMessage());
responseMap.put(serviceName, EMPTY_JSON);
}
}
} catch (Exception e) {
logger.debug("Exception Occurred : ", e);
}
// Create Response
response.getOutputStream().write(responseMap.toString().getBytes());
}
@RequestMapping(value = "/authenticateUser", method = RequestMethod.GET)
public void authenticateUser(HttpServletRequest request, HttpServletResponse response)
throws IOException {
// json object to be sent as response
ObjectNode responseJSON = mapper.createObjectNode();
try {
responseJSON.put("isUserLoggedIn", this.isUserLoggedIn(request));
// Send json response
response.getOutputStream().write(responseJSON.toString().getBytes());
} catch (Exception e) {
logger.debug("Exception Occurred : ", e);
}
}
/**
* Method isUserLoggedIn Check whether user is logged in or not.
*
* @param request
* @return boolean
*/
protected boolean isUserLoggedIn(HttpServletRequest request) {
return null != request.getUserPrincipal();
}
@RequestMapping(value = "/pulseVersion", method = RequestMethod.GET)
public void pulseVersion(HttpServletRequest request, HttpServletResponse response)
throws IOException {
// json object to be sent as response
ObjectNode responseJSON = mapper.createObjectNode();
try {
// Reference to repository
Repository repository = Repository.get();
// set pulse web app url
String pulseWebAppUrl = request.getScheme() + "://" + request.getServerName() + ":"
+ request.getServerPort() + request.getContextPath();
repository.setPulseWebAppUrl(pulseWebAppUrl);
// Response
responseJSON.put("pulseVersion", PulseController.pulseVersion.getPulseVersion());
responseJSON.put("buildId", PulseController.pulseVersion.getPulseBuildId());
responseJSON.put("buildDate", PulseController.pulseVersion.getPulseBuildDate());
responseJSON.put("sourceDate", PulseController.pulseVersion.getPulseSourceDate());
responseJSON.put("sourceRevision", PulseController.pulseVersion.getPulseSourceRevision());
responseJSON.put("sourceRepository", PulseController.pulseVersion.getPulseSourceRepository());
} catch (Exception e) {
logger.debug("Exception Occurred : ", e);
}
// Send json response
response.getOutputStream().write(responseJSON.toString().getBytes());
}
@RequestMapping(value = "/clearAlerts", method = RequestMethod.GET)
public void clearAlerts(HttpServletRequest request, HttpServletResponse response)
throws IOException {
int alertType;
ObjectNode responseJSON = mapper.createObjectNode();
try {
alertType = Integer.valueOf(request.getParameter("alertType"));
} catch (NumberFormatException e) {
// Empty json response
response.getOutputStream().write(responseJSON.toString().getBytes());
logger.debug(e);
return;
}
try {
boolean isClearAll = Boolean.valueOf(request.getParameter("clearAll"));
// get cluster object
Cluster cluster = Repository.get().getCluster();
cluster.clearAlerts(alertType, isClearAll);
responseJSON.put("status", "deleted");
responseJSON.put("systemAlerts",
SystemAlertsService.getAlertsJson(cluster, cluster.getNotificationPageNumber()));
responseJSON.put("pageNumber", cluster.getNotificationPageNumber());
boolean isGFConnected = cluster.isConnectedFlag();
if (isGFConnected) {
responseJSON.put("connectedFlag", isGFConnected);
} else {
responseJSON.put("connectedFlag", isGFConnected);
responseJSON.put("connectedErrorMsg", cluster.getConnectionErrorMsg());
}
} catch (Exception e) {
logger.debug("Exception Occurred : ", e);
}
// Send json response
response.getOutputStream().write(responseJSON.toString().getBytes());
}
@RequestMapping(value = "/acknowledgeAlert", method = RequestMethod.GET)
public void acknowledgeAlert(HttpServletRequest request, HttpServletResponse response)
throws IOException {
int alertId;
ObjectNode responseJSON = mapper.createObjectNode();
try {
alertId = Integer.valueOf(request.getParameter("alertId"));
} catch (NumberFormatException e) {
// Empty json response
response.getOutputStream().write(responseJSON.toString().getBytes());
logger.debug(e);
return;
}
try {
// get cluster object
Cluster cluster = Repository.get().getCluster();
// set alert is acknowledged
cluster.acknowledgeAlert(alertId);
responseJSON.put("status", "deleted");
} catch (Exception e) {
logger.debug("Exception Occurred : {}", e);
}
// Send json response
response.getOutputStream().write(responseJSON.toString().getBytes());
}
@RequestMapping(value = "/dataBrowserRegions", method = RequestMethod.GET)
public void dataBrowserRegions(HttpServletRequest request, HttpServletResponse response)
throws IOException {
// get cluster object
Cluster cluster = Repository.get().getCluster();
// json object to be sent as response
ObjectNode responseJSON = mapper.createObjectNode();
ArrayNode regionsData = mapper.createArrayNode();
try {
// getting cluster's Regions
responseJSON.put("clusterName", cluster.getServerName());
regionsData = getRegionsJson(cluster);
responseJSON.put("clusterRegions", regionsData);
responseJSON.put("connectedFlag", cluster.isConnectedFlag());
responseJSON.put("connectedErrorMsg", cluster.getConnectionErrorMsg());
} catch (Exception e) {
logger.debug("Exception Occurred : {}", e);
}
// Send json response
response.getOutputStream().write(responseJSON.toString().getBytes());
}
/**
* This method creates json for list of cluster regions
*
* @param cluster
* @return ArrayNode JSON array
*/
private ArrayNode getRegionsJson(Cluster cluster) {
Collection<Cluster.Region> clusterRegions = cluster.getClusterRegions().values();
ArrayNode regionsListJson = mapper.createArrayNode();
if (!clusterRegions.isEmpty()) {
for (Cluster.Region region : clusterRegions) {
ObjectNode regionJSON = mapper.createObjectNode();
regionJSON.put("name", region.getName());
regionJSON.put("fullPath", region.getFullPath());
regionJSON.put("regionType", region.getRegionType());
if (region.getRegionType().contains("PARTITION")) {
regionJSON.put("isPartition", true);
} else {
regionJSON.put("isPartition", false);
}
regionJSON.put("memberCount", region.getMemberCount());
List<String> regionsMembers = region.getMemberName();
ArrayNode jsonRegionMembers = mapper.createArrayNode();
for (int i = 0; i < regionsMembers.size(); i++) {
Cluster.Member member = cluster.getMembersHMap().get(regionsMembers.get(i));
ObjectNode jsonMember = mapper.createObjectNode();
jsonMember.put("key", regionsMembers.get(i));
jsonMember.put("id", member.getId());
jsonMember.put("name", member.getName());
jsonRegionMembers.add(jsonMember);
}
regionJSON.put("members", jsonRegionMembers);
regionsListJson.add(regionJSON);
}
}
return regionsListJson;
}
@RequestMapping(value = "/dataBrowserQuery", method = RequestMethod.GET)
public void dataBrowserQuery(HttpServletRequest request, HttpServletResponse response)
throws IOException {
// get query string
String query = request.getParameter("query");
String members = request.getParameter("members");
int limit = 0;
try {
limit = Integer.valueOf(request.getParameter("limit"));
} catch (NumberFormatException e) {
limit = 0;
logger.debug(e);
}
ObjectNode queryResult = mapper.createObjectNode();
try {
if (StringUtils.isNotBlank(query)) {
// get cluster object
Cluster cluster = Repository.get().getCluster();
String userName = request.getUserPrincipal().getName();
// Call execute query method
queryResult = cluster.executeQuery(query, members, limit);
// Add query in history if query is executed successfully
if (!queryResult.has("error")) {
// Add html escaped query to history
String escapedQuery = StringEscapeUtils.escapeHtml(query);
cluster.addQueryInHistory(escapedQuery, userName);
}
}
} catch (Exception e) {
logger.debug("Exception Occurred : ", e);
}
response.getOutputStream().write(queryResult.toString().getBytes());
}
@RequestMapping(value = "/dataBrowserQueryHistory", method = RequestMethod.GET)
public void dataBrowserQueryHistory(HttpServletRequest request, HttpServletResponse response)
throws IOException {
ObjectNode responseJSON = mapper.createObjectNode();
ArrayNode queryResult = null;
String action = "";
try {
// get cluster object
Cluster cluster = Repository.get().getCluster();
String userName = request.getUserPrincipal().getName();
// get query string
action = request.getParameter(QUERYSTRING_PARAM_ACTION);
if (StringUtils.isBlank(action)) {
action = ACTION_VIEW;
}
if (action.toLowerCase().equalsIgnoreCase(ACTION_DELETE)) {
String queryId = request.getParameter(QUERYSTRING_PARAM_QUERYID);
if (StringUtils.isNotBlank(queryId)) {
boolean deleteStatus = cluster.deleteQueryById(userName, queryId);
if (deleteStatus) {
responseJSON.put("status", STATUS_REPSONSE_SUCCESS);
} else {
responseJSON.put("status", STATUS_REPSONSE_FAIL);
responseJSON.put("error", ERROR_REPSONSE_QUERYNOTFOUND);
}
} else {
responseJSON.put("status", STATUS_REPSONSE_FAIL);
responseJSON.put("error", ERROR_REPSONSE_QUERYIDMISSING);
}
}
// Get list of past executed queries
queryResult = cluster.getQueryHistoryByUserId(userName);
responseJSON.put("queryHistory", queryResult);
} catch (Exception e) {
logger.debug("Exception Occurred : ", e);
}
response.getOutputStream().write(responseJSON.toString().getBytes());
}
@RequestMapping(value = "/dataBrowserExport", method = RequestMethod.GET)
public void dataBrowserExport(HttpServletRequest request, HttpServletResponse response)
throws IOException {
// get query string
String query = request.getParameter("query");
String members = request.getParameter("members");
int limit = 0;
try {
limit = Integer.valueOf(request.getParameter("limit"));
} catch (NumberFormatException e) {
limit = 0;
logger.debug(e);
}
ObjectNode queryResult = mapper.createObjectNode();
try {
if (StringUtils.isNotBlank(query)) {
// get cluster object
Cluster cluster = Repository.get().getCluster();
String userName = request.getUserPrincipal().getName();
// Call execute query method
queryResult = cluster.executeQuery(query, members, limit);
// Add query in history if query is executed successfully
if (!queryResult.has("error")) {
// Add html escaped query to history
String escapedQuery = StringEscapeUtils.escapeHtml(query);
cluster.addQueryInHistory(escapedQuery, userName);
}
}
} catch (Exception e) {
logger.debug("Exception Occurred : ", e);
}
response.setContentType("application/json");
response.setHeader("Content-Disposition", "attachment; filename=results.json");
response.getOutputStream().write(queryResult.toString().getBytes());
}
@RequestMapping(value = "/getQueryStatisticsGridModel", method = RequestMethod.GET)
public void getQueryStatisticsGridModel(HttpServletRequest request, HttpServletResponse response)
throws IOException {
ObjectNode responseJSON = mapper.createObjectNode();
// get cluster object
Cluster cluster = Repository.get().getCluster();
String userName = request.getUserPrincipal().getName();
try {
String[] arrColNames = Cluster.Statement.getGridColumnNames();
String[] arrColAttribs = Cluster.Statement.getGridColumnAttributes();
int[] arrColWidths = Cluster.Statement.getGridColumnWidths();
ArrayNode colNamesList = mapper.createArrayNode();
for (int i = 0; i < arrColNames.length; ++i) {
colNamesList.add(arrColNames[i]);
}
ArrayNode colModelList = mapper.createArrayNode();
for (int i = 0; i < arrColAttribs.length; ++i) {
ObjectNode columnJSON = mapper.createObjectNode();
columnJSON.put("name", arrColAttribs[i]);
columnJSON.put("index", arrColAttribs[i]);
columnJSON.put("width", arrColWidths[i]);
columnJSON.put("sortable", "true");
columnJSON.put("sorttype", ((i == 0) ? "String" : "integer"));
colModelList.add(columnJSON);
}
responseJSON.put("columnNames", colNamesList);
responseJSON.put("columnModels", colModelList);
responseJSON.put("clusterName", cluster.getServerName());
responseJSON.put("userName", userName);
// Send json response
response.getOutputStream().write(responseJSON.toString().getBytes());
} catch (Exception e) {
logger.debug("Exception Occurred : ", 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.hadoop.yarn.server.resourcemanager.webapp;
import java.io.IOException;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.Response;
import org.apache.hadoop.classification.InterfaceAudience.Private;
import org.apache.hadoop.classification.InterfaceStability.Evolving;
import org.apache.hadoop.security.authorize.AuthorizationException;
import org.apache.hadoop.yarn.api.ApplicationBaseProtocol;
import org.apache.hadoop.yarn.api.ApplicationClientProtocol;
import org.apache.hadoop.yarn.api.protocolrecords.ReservationDeleteRequest;
import org.apache.hadoop.yarn.exceptions.YarnException;
import org.apache.hadoop.yarn.server.api.ResourceManagerAdministrationProtocol;
import org.apache.hadoop.yarn.server.resourcemanager.webapp.dao.ActivitiesInfo;
import org.apache.hadoop.yarn.server.resourcemanager.webapp.dao.AppActivitiesInfo;
import org.apache.hadoop.yarn.server.resourcemanager.webapp.dao.AppAttemptsInfo;
import org.apache.hadoop.yarn.server.resourcemanager.webapp.dao.AppInfo;
import org.apache.hadoop.yarn.server.resourcemanager.webapp.dao.AppPriority;
import org.apache.hadoop.yarn.server.resourcemanager.webapp.dao.AppQueue;
import org.apache.hadoop.yarn.server.resourcemanager.webapp.dao.AppState;
import org.apache.hadoop.yarn.server.resourcemanager.webapp.dao.AppTimeoutInfo;
import org.apache.hadoop.yarn.server.resourcemanager.webapp.dao.AppTimeoutsInfo;
import org.apache.hadoop.yarn.server.resourcemanager.webapp.dao.ApplicationStatisticsInfo;
import org.apache.hadoop.yarn.server.resourcemanager.webapp.dao.ApplicationSubmissionContextInfo;
import org.apache.hadoop.yarn.server.resourcemanager.webapp.dao.AppsInfo;
import org.apache.hadoop.yarn.server.resourcemanager.webapp.dao.ClusterInfo;
import org.apache.hadoop.yarn.server.resourcemanager.webapp.dao.ClusterMetricsInfo;
import org.apache.hadoop.yarn.server.resourcemanager.webapp.dao.ClusterUserInfo;
import org.apache.hadoop.yarn.server.resourcemanager.webapp.dao.DelegationToken;
import org.apache.hadoop.yarn.server.resourcemanager.webapp.dao.LabelsToNodesInfo;
import org.apache.hadoop.yarn.server.resourcemanager.webapp.dao.NodeInfo;
import org.apache.hadoop.yarn.server.resourcemanager.webapp.dao.NodeLabelsInfo;
import org.apache.hadoop.yarn.server.resourcemanager.webapp.dao.NodeToLabelsEntryList;
import org.apache.hadoop.yarn.server.resourcemanager.webapp.dao.NodeToLabelsInfo;
import org.apache.hadoop.yarn.server.resourcemanager.webapp.dao.NodesInfo;
import org.apache.hadoop.yarn.server.resourcemanager.webapp.dao.RMQueueAclInfo;
import org.apache.hadoop.yarn.server.resourcemanager.webapp.dao.ReservationDeleteRequestInfo;
import org.apache.hadoop.yarn.server.resourcemanager.webapp.dao.ReservationSubmissionRequestInfo;
import org.apache.hadoop.yarn.server.resourcemanager.webapp.dao.ReservationUpdateRequestInfo;
import org.apache.hadoop.yarn.server.resourcemanager.webapp.dao.ResourceInfo;
import org.apache.hadoop.yarn.server.resourcemanager.webapp.dao.ResourceOptionInfo;
import org.apache.hadoop.yarn.server.resourcemanager.webapp.dao.BulkActivitiesInfo;
import org.apache.hadoop.yarn.server.resourcemanager.webapp.dao.SchedulerTypeInfo;
/**
* <p>
* The protocol between clients and the <code>ResourceManager</code> to
* submit/abort jobs and to get information on applications, cluster metrics,
* nodes, queues, ACLs and reservations via REST calls.
* </p>
*
* The WebService is reachable by using {@link RMWSConsts#RM_WEB_SERVICE_PATH}
*/
@Private
@Evolving
public interface RMWebServiceProtocol {
/**
* This method retrieves the cluster information, and it is reachable by using
* {@link RMWSConsts#INFO}.
*
* @return the cluster information
*/
ClusterInfo get();
/**
* This method retrieves the cluster information, and it is reachable by using
* {@link RMWSConsts#INFO}.
*
* @return the cluster information
*/
ClusterInfo getClusterInfo();
/**
* This method retrieves the cluster user information, and it is reachable by using
* {@link RMWSConsts#CLUSTER_USER_INFO}.
*
* @return the cluster user information
*/
ClusterUserInfo getClusterUserInfo(HttpServletRequest hsr);
/**
* This method retrieves the cluster metrics information, and it is reachable
* by using {@link RMWSConsts#METRICS}.
*
* @see ApplicationClientProtocol#getClusterMetrics
* @return the cluster metrics information
*/
ClusterMetricsInfo getClusterMetricsInfo();
/**
* This method retrieves the current scheduler status, and it is reachable by
* using {@link RMWSConsts#SCHEDULER}.
*
* @return the current scheduler status
*/
SchedulerTypeInfo getSchedulerInfo();
/**
* This method dumps the scheduler logs for the time got in input, and it is
* reachable by using {@link RMWSConsts#SCHEDULER_LOGS}.
*
* @param time the period of time. It is a FormParam.
* @param hsr the servlet request
* @return the result of the operation
* @throws IOException when it cannot create dump log file
*/
String dumpSchedulerLogs(String time, HttpServletRequest hsr)
throws IOException;
/**
* This method retrieves all the nodes information in the cluster, and it is
* reachable by using {@link RMWSConsts#NODES}.
*
* @see ApplicationClientProtocol#getClusterNodes
* @param states the states we want to filter. It is a QueryParam.
* @return all nodes in the cluster. If the states param is given, returns all
* nodes that are in the comma-separated list of states
*/
NodesInfo getNodes(String states);
/**
* This method retrieves a specific node information, and it is reachable by
* using {@link RMWSConsts#NODES_NODEID}.
*
* @param nodeId the node we want to retrieve the information. It is a
* PathParam.
* @return the information about the node in input
*/
NodeInfo getNode(String nodeId);
/**
* This method changes the resources of a specific node, and it is reachable
* by using {@link RMWSConsts#NODE_RESOURCE}.
*
* @param hsr The servlet request.
* @param nodeId The node we want to retrieve the information for.
* It is a PathParam.
* @param resourceOption The resource change.
* @throws AuthorizationException If the user is not authorized.
*/
ResourceInfo updateNodeResource(HttpServletRequest hsr, String nodeId,
ResourceOptionInfo resourceOption) throws AuthorizationException;
/**
* This method retrieves all the app reports in the cluster, and it is
* reachable by using {@link RMWSConsts#APPS}.
*
* @see ApplicationClientProtocol#getApplications
* @param hsr the servlet request
* @param stateQuery right now the stateQuery is deprecated. It is a
* QueryParam.
* @param statesQuery filter the result by states. It is a QueryParam.
* @param finalStatusQuery filter the result by final states. It is a
* QueryParam.
* @param userQuery filter the result by user. It is a QueryParam.
* @param queueQuery filter the result by queue. It is a QueryParam.
* @param count set a limit of the result. It is a QueryParam.
* @param startedBegin filter the result by started begin time. It is a
* QueryParam.
* @param startedEnd filter the result by started end time. It is a
* QueryParam.
* @param finishBegin filter the result by finish begin time. It is a
* QueryParam.
* @param finishEnd filter the result by finish end time. It is a QueryParam.
* @param applicationTypes filter the result by types. It is a QueryParam.
* @param applicationTags filter the result by tags. It is a QueryParam.
* @param name filter the name of the application. It is a QueryParam.
* @param unselectedFields De-selected params to avoid from report. It is a
* QueryParam.
* @return all apps in the cluster
*/
@SuppressWarnings("checkstyle:parameternumber")
AppsInfo getApps(HttpServletRequest hsr, String stateQuery,
Set<String> statesQuery, String finalStatusQuery, String userQuery,
String queueQuery, String count, String startedBegin, String startedEnd,
String finishBegin, String finishEnd, Set<String> applicationTypes,
Set<String> applicationTags, String name, Set<String> unselectedFields);
/**
* This method retrieve all the activities in a specific node, and it is
* reachable by using {@link RMWSConsts#SCHEDULER_ACTIVITIES}.
*
* @param hsr the servlet request
* @param nodeId the node we want to retrieve the activities. It is a
* QueryParam.
* @param groupBy the groupBy type by which the activities should be
* aggregated. It is a QueryParam.
* @return all the activities in the specific node
*/
ActivitiesInfo getActivities(HttpServletRequest hsr, String nodeId,
String groupBy);
/**
* This method retrieve the last n activities inside scheduler and it is
* reachable by using {@link RMWSConsts#SCHEDULER_BULK_ACTIVITIES}.
*
* @param hsr the servlet request
* @param groupBy the groupBy type by which the activities should be
* aggregated. It is a QueryParam.
* @param activitiesCount number of activities
* @return last n activities
*/
BulkActivitiesInfo getBulkActivities(HttpServletRequest hsr,
String groupBy, int activitiesCount) throws InterruptedException;
/**
* This method retrieves all the activities for a specific app for a specific
* period of time, and it is reachable by using
* {@link RMWSConsts#SCHEDULER_APP_ACTIVITIES}.
*
* @param hsr the servlet request
* @param appId the applicationId we want to retrieve the activities. It is a
* QueryParam.
* @param time for how long we want to retrieve the activities. It is a
* QueryParam.
* @param requestPriorities the request priorities we want to retrieve the
* activities. It is a QueryParam.
* @param allocationRequestIds the allocation request ids we want to retrieve
* the activities. It is a QueryParam.
* @param groupBy the groupBy type by which the activities should be
* aggregated. It is a QueryParam.
* @param limit set a limit of the result. It is a QueryParam.
* @param actions the required actions of app activities. It is a QueryParam.
* @param summarize whether app activities in multiple scheduling processes
* need to be summarized. It is a QueryParam.
* @return all the activities about a specific app for a specific time
*/
AppActivitiesInfo getAppActivities(HttpServletRequest hsr, String appId,
String time, Set<String> requestPriorities,
Set<String> allocationRequestIds, String groupBy, String limit,
Set<String> actions, boolean summarize);
/**
* This method retrieves all the statistics for a specific app, and it is
* reachable by using {@link RMWSConsts#APP_STATISTICS}.
*
* @param hsr the servlet request
* @param stateQueries filter the result by states. It is a QueryParam.
* @param typeQueries filter the result by type names. It is a QueryParam.
* @return the application's statistics for specific states and types
*/
ApplicationStatisticsInfo getAppStatistics(HttpServletRequest hsr,
Set<String> stateQueries, Set<String> typeQueries);
/**
* This method retrieves the report for a specific app, and it is reachable by
* using {@link RMWSConsts#APPS_APPID}.
*
* @see ApplicationClientProtocol#getApplicationReport
* @param hsr the servlet request
* @param appId the Id of the application we want the report. It is a
* PathParam.
* @param unselectedFields De-selected param list to avoid from report. It is
* a QueryParam.
* @return the app report for a specific application
*/
AppInfo getApp(HttpServletRequest hsr, String appId,
Set<String> unselectedFields);
/**
* This method retrieves the state for a specific app, and it is reachable by
* using {@link RMWSConsts#APPS_APPID_STATE}.
*
* @param hsr the servlet request
* @param appId the Id of the application we want the state. It is a
* PathParam.
* @return the state for a specific application
* @throws AuthorizationException if the user is not authorized
*/
AppState getAppState(HttpServletRequest hsr, String appId)
throws AuthorizationException;
/**
* This method updates the state of the app in input, and it is reachable by
* using {@link RMWSConsts#APPS_APPID_STATE}.
*
* @param targetState the target state for the app. It is a content param.
* @param hsr the servlet request
* @param appId the Id of the application we want to update the state. It is a
* PathParam.
* @return Response containing the status code
* @throws AuthorizationException if the user is not authorized to invoke this
* method
* @throws YarnException if app does not exist
* @throws InterruptedException if interrupted
* @throws IOException if doAs action throws an IOException
*/
Response updateAppState(AppState targetState, HttpServletRequest hsr,
String appId) throws AuthorizationException, YarnException,
InterruptedException, IOException;
/**
* This method retrieves all the node labels with the respective nodes in the
* cluster, and it is reachable by using
* {@link RMWSConsts#GET_NODE_TO_LABELS}.
*
* @see ApplicationClientProtocol#getNodeToLabels
* @param hsr the servlet request
* @return all the nodes within a node label
* @throws IOException if an IOException happened
*/
NodeToLabelsInfo getNodeToLabels(HttpServletRequest hsr) throws IOException;
/**
* This method retrieves all the node within multiple node labels in the
* cluster, and it is reachable by using {@link RMWSConsts#LABEL_MAPPINGS}.
*
* @see ApplicationClientProtocol#getLabelsToNodes
* @param labels filter the result by node labels. It is a QueryParam.
* @return all the nodes within multiple node labels
* @throws IOException if an IOException happened
*/
LabelsToNodesInfo getLabelsToNodes(Set<String> labels) throws IOException;
/**
* This method replaces all the node labels for specific nodes, and it is
* reachable by using {@link RMWSConsts#REPLACE_NODE_TO_LABELS}.
*
* @see ResourceManagerAdministrationProtocol#replaceLabelsOnNode
* @param newNodeToLabels the list of new labels. It is a content param.
* @param hsr the servlet request
* @return Response containing the status code
* @throws Exception if an exception happened
*/
Response replaceLabelsOnNodes(NodeToLabelsEntryList newNodeToLabels,
HttpServletRequest hsr) throws Exception;
/**
* This method replaces all the node labels for specific node, and it is
* reachable by using {@link RMWSConsts#NODES_NODEID_REPLACE_LABELS}.
*
* @see ResourceManagerAdministrationProtocol#replaceLabelsOnNode
* @param newNodeLabelsName the list of new labels. It is a QueryParam.
* @param hsr the servlet request
* @param nodeId the node we want to replace the node labels. It is a
* PathParam.
* @return Response containing the status code
* @throws Exception if an exception happened
*/
Response replaceLabelsOnNode(Set<String> newNodeLabelsName,
HttpServletRequest hsr, String nodeId) throws Exception;
/**
* This method retrieves all the node labels in the cluster, and it is
* reachable by using {@link RMWSConsts#GET_NODE_LABELS}.
*
* @see ApplicationClientProtocol#getClusterNodeLabels
* @param hsr the servlet request
* @return all the node labels in the cluster
* @throws IOException if an IOException happened
*/
NodeLabelsInfo getClusterNodeLabels(HttpServletRequest hsr)
throws IOException;
/**
* This method adds specific node labels for specific nodes, and it is
* reachable by using {@link RMWSConsts#ADD_NODE_LABELS}.
*
* @see ResourceManagerAdministrationProtocol#addToClusterNodeLabels
* @param newNodeLabels the node labels to add. It is a content param.
* @param hsr the servlet request
* @return Response containing the status code
* @throws Exception in case of bad request
*/
Response addToClusterNodeLabels(NodeLabelsInfo newNodeLabels,
HttpServletRequest hsr) throws Exception;
/**
* This method removes all the node labels for specific nodes, and it is
* reachable by using {@link RMWSConsts#REMOVE_NODE_LABELS}.
*
* @see ResourceManagerAdministrationProtocol#removeFromClusterNodeLabels
* @param oldNodeLabels the node labels to remove. It is a QueryParam.
* @param hsr the servlet request
* @return Response containing the status code
* @throws Exception in case of bad request
*/
Response removeFromClusterNodeLabels(Set<String> oldNodeLabels,
HttpServletRequest hsr) throws Exception;
/**
* This method retrieves all the node labels for specific node, and it is
* reachable by using {@link RMWSConsts#NODES_NODEID_GETLABELS}.
*
* @param hsr the servlet request
* @param nodeId the node we want to get all the node labels. It is a
* PathParam.
* @return all the labels for a specific node.
* @throws IOException if an IOException happened
*/
NodeLabelsInfo getLabelsOnNode(HttpServletRequest hsr, String nodeId)
throws IOException;
/**
* This method retrieves the priority for a specific app, and it is reachable
* by using {@link RMWSConsts#APPS_APPID_PRIORITY}.
*
* @param hsr the servlet request
* @param appId the app we want to get the priority. It is a PathParam.
* @return the priority for a specific application
* @throws AuthorizationException in case of the user is not authorized
*/
AppPriority getAppPriority(HttpServletRequest hsr, String appId)
throws AuthorizationException;
/**
* This method updates the priority for a specific application, and it is
* reachable by using {@link RMWSConsts#APPS_APPID_PRIORITY}.
*
* @param targetPriority the priority we want to set for the app. It is a
* content param.
* @param hsr the servlet request
* @param appId the application we want to update its priority. It is a
* PathParam.
* @return Response containing the status code
* @throws AuthorizationException if the user is not authenticated
* @throws YarnException if the target is null
* @throws IOException if the update fails.
* @throws InterruptedException if interrupted.
*/
Response updateApplicationPriority(AppPriority targetPriority,
HttpServletRequest hsr, String appId) throws AuthorizationException,
YarnException, InterruptedException, IOException;
/**
* This method retrieves the queue for a specific app, and it is reachable by
* using {@link RMWSConsts#APPS_APPID_QUEUE}.
*
* @param hsr the servlet request
* @param appId the application we want to retrieve its queue. It is a
* PathParam.
* @return the Queue for a specific application.
* @throws AuthorizationException if the user is not authenticated
*/
AppQueue getAppQueue(HttpServletRequest hsr, String appId)
throws AuthorizationException;
/**
* This method updates the queue for a specific application, and it is
* reachable by using {@link RMWSConsts#APPS_APPID_QUEUE}.
*
* @param targetQueue the queue we want to set. It is a content param.
* @param hsr the servlet request
* @param appId the application we want to change its queue. It is a
* PathParam.
* @return Response containing the status code
* @throws AuthorizationException if the user is not authenticated
* @throws YarnException if the app is not found
* @throws IOException if the update fails.
* @throws InterruptedException if interrupted.
*/
Response updateAppQueue(AppQueue targetQueue, HttpServletRequest hsr,
String appId) throws AuthorizationException, YarnException,
InterruptedException, IOException;
/**
* Generates a new ApplicationId which is then sent to the client. This method
* is reachable by using {@link RMWSConsts#APPS_NEW_APPLICATION}.
*
* @see ApplicationClientProtocol#getNewApplication
*
* @param hsr the servlet request
* @return Response containing the app id and the maximum resource
* capabilities
* @throws AuthorizationException if the user is not authorized to invoke this
* method
* @throws IOException if the creation fails
* @throws InterruptedException if interrupted
*/
Response createNewApplication(HttpServletRequest hsr)
throws AuthorizationException, IOException, InterruptedException;
/**
* Function to submit an app to the RM. This method is reachable by using
* {@link RMWSConsts#APPS}.
*
* @see ApplicationClientProtocol#submitApplication
*
* @param newApp structure containing information to construct the
* ApplicationSubmissionContext. It is a content param.
* @param hsr the servlet request
* @return Response containing the status code
* @throws AuthorizationException if the user is not authorized to invoke this
* method
* @throws IOException if the submission failed
* @throws InterruptedException if interrupted
*/
Response submitApplication(ApplicationSubmissionContextInfo newApp,
HttpServletRequest hsr)
throws AuthorizationException, IOException, InterruptedException;
/**
* This method posts a delegation token from the client, and it is reachable
* by using {@link RMWSConsts#DELEGATION_TOKEN}.
*
* @see ApplicationBaseProtocol#getDelegationToken
* @param tokenData the token to delegate. It is a content param.
* @param hsr the servlet request
* @return Response containing the status code
* @throws AuthorizationException if Kerberos auth failed
* @throws IOException if the delegation failed
* @throws InterruptedException if interrupted
* @throws Exception in case of bad request
*/
Response postDelegationToken(DelegationToken tokenData,
HttpServletRequest hsr) throws AuthorizationException, IOException,
InterruptedException, Exception;
/**
* This method updates the expiration for a delegation token from the client,
* and it is reachable by using
* {@link RMWSConsts#DELEGATION_TOKEN_EXPIRATION}.
*
* @see ApplicationBaseProtocol#renewDelegationToken
* @param hsr the servlet request
* @return Response containing the status code
* @throws AuthorizationException if Kerberos auth failed
* @throws IOException if the delegation failed
* @throws Exception in case of bad request
*/
Response postDelegationTokenExpiration(HttpServletRequest hsr)
throws AuthorizationException, IOException, Exception;
/**
* This method cancel the delegation token from the client, and it is
* reachable by using {@link RMWSConsts#DELEGATION_TOKEN}.
*
* @see ApplicationBaseProtocol#cancelDelegationToken
* @param hsr the servlet request
* @return Response containing the status code
* @throws AuthorizationException if Kerberos auth failed
* @throws IOException if the delegation failed
* @throws InterruptedException if interrupted
* @throws Exception in case of bad request
*/
Response cancelDelegationToken(HttpServletRequest hsr)
throws AuthorizationException, IOException, InterruptedException,
Exception;
/**
* Generates a new ReservationId which is then sent to the client. This method
* is reachable by using {@link RMWSConsts#RESERVATION_NEW}.
*
* @see ApplicationClientProtocol#getNewReservation
*
* @param hsr the servlet request
* @return Response containing the app id and the maximum resource
* capabilities
* @throws AuthorizationException if the user is not authorized to invoke this
* method.
* @throws IOException if creation failed
* @throws InterruptedException if interrupted
*/
Response createNewReservation(HttpServletRequest hsr)
throws AuthorizationException, IOException, InterruptedException;
/**
* Function to submit a Reservation to the RM.This method is reachable by
* using {@link RMWSConsts#RESERVATION_SUBMIT}.
*
* @see ApplicationClientProtocol#submitReservation
*
* @param resContext provides information to construct the
* ReservationSubmissionRequest. It is a content param.
* @param hsr the servlet request
* @return Response containing the status code
* @throws AuthorizationException if the user is not authorized to invoke this
* method
* @throws IOException if creation failed
* @throws InterruptedException if interrupted
*/
Response submitReservation(ReservationSubmissionRequestInfo resContext,
HttpServletRequest hsr)
throws AuthorizationException, IOException, InterruptedException;
/**
* Function to update a Reservation to the RM. This method is reachable by
* using {@link RMWSConsts#RESERVATION_UPDATE}.
*
* @see ApplicationClientProtocol#updateReservation
*
* @param resContext provides information to construct the
* ReservationUpdateRequest. It is a content param.
* @param hsr the servlet request
* @return Response containing the status code
* @throws AuthorizationException if the user is not authorized to invoke this
* method
* @throws IOException if the operation failed
* @throws InterruptedException if interrupted
*/
Response updateReservation(ReservationUpdateRequestInfo resContext,
HttpServletRequest hsr)
throws AuthorizationException, IOException, InterruptedException;
/**
* Function to delete a Reservation to the RM. This method is reachable by
* using {@link RMWSConsts#RESERVATION_DELETE}.
*
* @see ApplicationClientProtocol#deleteReservation
*
* @param resContext provides information to construct the
* ReservationDeleteRequest. It is a content param.
* @param hsr the servlet request
* @return Response containing the status code
* @throws AuthorizationException when the user group information cannot be
* retrieved.
* @throws IOException when a {@link ReservationDeleteRequest} cannot be
* created from the {@link ReservationDeleteRequestInfo}. This
* exception is also thrown on
* {@code ClientRMService.deleteReservation} invokation failure.
* @throws InterruptedException if doAs action throws an InterruptedException.
*/
Response deleteReservation(ReservationDeleteRequestInfo resContext,
HttpServletRequest hsr)
throws AuthorizationException, IOException, InterruptedException;
/**
* Function to retrieve a list of all the reservations. This method is
* reachable by using {@link RMWSConsts#RESERVATION_LIST}.
*
* @see ApplicationClientProtocol#listReservations
* @param queue filter the result by queue. It is a QueryParam.
* @param reservationId filter the result by reservationId. It is a
* QueryParam.
* @param startTime filter the result by start time. It is a QueryParam.
* @param endTime filter the result by end time. It is a QueryParam.
* @param includeResourceAllocations true if the resource allocation should be
* in the result, false otherwise. It is a QueryParam.
* @param hsr the servlet request
* @return Response containing the status code
* @throws Exception in case of bad request
*/
Response listReservation(String queue, String reservationId, long startTime,
long endTime, boolean includeResourceAllocations, HttpServletRequest hsr)
throws Exception;
/**
* This method retrieves the timeout information for a specific app with a
* specific type, and it is reachable by using
* {@link RMWSConsts#APPS_TIMEOUTS_TYPE}.
*
* @param hsr the servlet request
* @param appId the application we want to get the timeout. It is a PathParam.
* @param type the type of the timeouts. It is a PathParam.
* @return the timeout for a specific application with a specific type.
* @throws AuthorizationException if the user is not authorized
*/
AppTimeoutInfo getAppTimeout(HttpServletRequest hsr, String appId,
String type) throws AuthorizationException;
/**
* This method retrieves the timeout information for a specific app, and it is
* reachable by using {@link RMWSConsts#APPS_TIMEOUTS}.
*
* @param hsr the servlet request
* @param appId the application we want to get the timeouts. It is a
* PathParam.
* @return the timeouts for a specific application
* @throws AuthorizationException if the user is not authorized
*/
AppTimeoutsInfo getAppTimeouts(HttpServletRequest hsr, String appId)
throws AuthorizationException;
/**
* This method updates the timeout information for a specific app, and it is
* reachable by using {@link RMWSConsts#APPS_TIMEOUT}.
*
* @see ApplicationClientProtocol#updateApplicationTimeouts
* @param appTimeout the appTimeoutInfo. It is a content param.
* @param hsr the servlet request
* @param appId the application we want to update. It is a PathParam.
* @return Response containing the status code
* @throws AuthorizationException if the user is not authorized to invoke this
* method
* @throws YarnException in case of bad request
* @throws IOException if the operation failed
* @throws InterruptedException if interrupted
*/
Response updateApplicationTimeout(AppTimeoutInfo appTimeout,
HttpServletRequest hsr, String appId) throws AuthorizationException,
YarnException, InterruptedException, IOException;
/**
* This method retrieves all the attempts information for a specific app, and
* it is reachable by using {@link RMWSConsts#APPS_APPID_APPATTEMPTS}.
*
* @see ApplicationBaseProtocol#getApplicationAttempts
* @param hsr the servlet request
* @param appId the application we want to get the attempts. It is a
* PathParam.
* @return all the attempts info for a specific application
*/
AppAttemptsInfo getAppAttempts(HttpServletRequest hsr, String appId);
/**
* This method verifies if an user has access to a specified queue.
*
* @return Response containing the status code.
*
* @param queue queue
* @param username user
* @param queueAclType acl type of queue, it could be
* SUBMIT_APPLICATIONS/ADMINISTER_QUEUE
* @param hsr request
*
* @throws AuthorizationException if the user is not authorized to invoke this
* method.
*/
RMQueueAclInfo checkUserAccessToQueue(String queue, String username,
String queueAclType, HttpServletRequest hsr)
throws AuthorizationException;
/**
* This method sends a signal to container.
* @param containerId containerId
* @param command signal command, it could be OUTPUT_THREAD_DUMP/
* GRACEFUL_SHUTDOWN/FORCEFUL_SHUTDOWN
* @param req request
* @return Response containing the status code
* @throws AuthorizationException if the user is not authorized to invoke this
* method.
*/
Response signalToContainer(String containerId, String command,
HttpServletRequest req) throws AuthorizationException;
}
|
|
// 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.cloudstack.storage.image.db;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.naming.ConfigurationException;
import com.cloud.utils.db.DB;
import org.apache.cloudstack.engine.subsystem.api.storage.DataObjectInStore;
import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine;
import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine.Event;
import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine.State;
import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreDao;
import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreVO;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import com.cloud.storage.DataStoreRole;
import com.cloud.utils.db.GenericDaoBase;
import com.cloud.utils.db.SearchBuilder;
import com.cloud.utils.db.SearchCriteria;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.db.SearchCriteria.Op;
import com.cloud.utils.db.UpdateBuilder;
@Component
public class SnapshotDataStoreDaoImpl extends GenericDaoBase<SnapshotDataStoreVO, Long> implements SnapshotDataStoreDao {
private static final Logger s_logger = Logger.getLogger(SnapshotDataStoreDaoImpl.class);
private SearchBuilder<SnapshotDataStoreVO> updateStateSearch;
private SearchBuilder<SnapshotDataStoreVO> storeSearch;
private SearchBuilder<SnapshotDataStoreVO> destroyedSearch;
private SearchBuilder<SnapshotDataStoreVO> cacheSearch;
private SearchBuilder<SnapshotDataStoreVO> snapshotSearch;
private SearchBuilder<SnapshotDataStoreVO> storeSnapshotSearch;
private SearchBuilder<SnapshotDataStoreVO> snapshotIdSearch;
private String parentSearch = "select store_id, store_role, snapshot_id from cloud.snapshot_store_ref where store_id = ? " +
" and store_role = ? and volume_id = ? and state = 'Ready'" +
" order by created DESC " +
" limit 1";
@Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
super.configure(name, params);
// Note that snapshot_store_ref stores snapshots on primary as well as
// those on secondary, so we need to
// use (store_id, store_role) to search
storeSearch = createSearchBuilder();
storeSearch.and("store_id", storeSearch.entity().getDataStoreId(), SearchCriteria.Op.EQ);
storeSearch.and("store_role", storeSearch.entity().getRole(), SearchCriteria.Op.EQ);
storeSearch.and("state", storeSearch.entity().getState(), SearchCriteria.Op.NEQ);
storeSearch.done();
destroyedSearch = createSearchBuilder();
destroyedSearch.and("store_id", destroyedSearch.entity().getDataStoreId(), SearchCriteria.Op.EQ);
destroyedSearch.and("store_role", destroyedSearch.entity().getRole(), SearchCriteria.Op.EQ);
destroyedSearch.and("state", destroyedSearch.entity().getState(), SearchCriteria.Op.EQ);
destroyedSearch.done();
cacheSearch = createSearchBuilder();
cacheSearch.and("store_id", cacheSearch.entity().getDataStoreId(), SearchCriteria.Op.EQ);
cacheSearch.and("store_role", cacheSearch.entity().getRole(), SearchCriteria.Op.EQ);
cacheSearch.and("state", cacheSearch.entity().getState(), SearchCriteria.Op.NEQ);
cacheSearch.and("ref_cnt", cacheSearch.entity().getRefCnt(), SearchCriteria.Op.NEQ);
cacheSearch.done();
updateStateSearch = this.createSearchBuilder();
updateStateSearch.and("id", updateStateSearch.entity().getId(), Op.EQ);
updateStateSearch.and("state", updateStateSearch.entity().getState(), Op.EQ);
updateStateSearch.and("updatedCount", updateStateSearch.entity().getUpdatedCount(), Op.EQ);
updateStateSearch.done();
snapshotSearch = createSearchBuilder();
snapshotSearch.and("snapshot_id", snapshotSearch.entity().getSnapshotId(), SearchCriteria.Op.EQ);
snapshotSearch.and("store_role", snapshotSearch.entity().getRole(), SearchCriteria.Op.EQ);
snapshotSearch.done();
storeSnapshotSearch = createSearchBuilder();
storeSnapshotSearch.and("snapshot_id", storeSnapshotSearch.entity().getSnapshotId(), SearchCriteria.Op.EQ);
storeSnapshotSearch.and("store_id", storeSnapshotSearch.entity().getDataStoreId(), SearchCriteria.Op.EQ);
storeSnapshotSearch.and("store_role", storeSnapshotSearch.entity().getRole(), SearchCriteria.Op.EQ);
storeSnapshotSearch.done();
snapshotIdSearch = createSearchBuilder();
snapshotIdSearch.and("snapshot_id", snapshotIdSearch.entity().getSnapshotId(), SearchCriteria.Op.EQ);
snapshotIdSearch.done();
return true;
}
@Override
public boolean updateState(State currentState, Event event, State nextState, DataObjectInStore vo, Object data) {
SnapshotDataStoreVO dataObj = (SnapshotDataStoreVO) vo;
Long oldUpdated = dataObj.getUpdatedCount();
Date oldUpdatedTime = dataObj.getUpdated();
SearchCriteria<SnapshotDataStoreVO> sc = updateStateSearch.create();
sc.setParameters("id", dataObj.getId());
sc.setParameters("state", currentState);
sc.setParameters("updatedCount", dataObj.getUpdatedCount());
dataObj.incrUpdatedCount();
UpdateBuilder builder = getUpdateBuilder(dataObj);
builder.set(dataObj, "state", nextState);
builder.set(dataObj, "updated", new Date());
int rows = update(dataObj, sc);
if (rows == 0 && s_logger.isDebugEnabled()) {
SnapshotDataStoreVO dbVol = findByIdIncludingRemoved(dataObj.getId());
if (dbVol != null) {
StringBuilder str = new StringBuilder("Unable to update ").append(dataObj.toString());
str.append(": DB Data={id=").append(dbVol.getId()).append("; state=").append(dbVol.getState())
.append("; updatecount=").append(dbVol.getUpdatedCount()).append(";updatedTime=")
.append(dbVol.getUpdated());
str.append(": New Data={id=").append(dataObj.getId()).append("; state=").append(nextState)
.append("; event=").append(event).append("; updatecount=").append(dataObj.getUpdatedCount())
.append("; updatedTime=").append(dataObj.getUpdated());
str.append(": stale Data={id=").append(dataObj.getId()).append("; state=").append(currentState)
.append("; event=").append(event).append("; updatecount=").append(oldUpdated)
.append("; updatedTime=").append(oldUpdatedTime);
} else {
s_logger.debug("Unable to update objectIndatastore: id=" + dataObj.getId()
+ ", as there is no such object exists in the database anymore");
}
}
return rows > 0;
}
@Override
public List<SnapshotDataStoreVO> listByStoreId(long id, DataStoreRole role) {
SearchCriteria<SnapshotDataStoreVO> sc = storeSearch.create();
sc.setParameters("store_id", id);
sc.setParameters("store_role", role);
sc.setParameters("state", ObjectInDataStoreStateMachine.State.Destroyed);
return listBy(sc);
}
@Override
public void deletePrimaryRecordsForStore(long id, DataStoreRole role) {
SearchCriteria<SnapshotDataStoreVO> sc = storeSearch.create();
sc.setParameters("store_id", id);
sc.setParameters("store_role", role);
Transaction txn = Transaction.currentTxn();
txn.start();
remove(sc);
txn.commit();
}
@Override
public SnapshotDataStoreVO findByStoreSnapshot(DataStoreRole role, long storeId, long snapshotId) {
SearchCriteria<SnapshotDataStoreVO> sc = storeSnapshotSearch.create();
sc.setParameters("store_id", storeId);
sc.setParameters("snapshot_id", snapshotId);
sc.setParameters("store_role", role);
return findOneBy(sc);
}
@Override
@DB
public SnapshotDataStoreVO findParent(DataStoreRole role, Long storeId, Long volumeId) {
Transaction txn = Transaction.currentTxn();
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
pstmt = txn.prepareStatement(parentSearch);
pstmt.setLong(1, storeId);
pstmt.setString(2, role.toString());
pstmt.setLong(3, volumeId);
rs = pstmt.executeQuery();
while (rs.next()) {
long sid = rs.getLong(1);
String rl = rs.getString(2);
long snid = rs.getLong(3);
return this.findByStoreSnapshot(role, sid, snid);
}
} catch (SQLException e) {
s_logger.debug("Failed to find parent snapshot: " + e.toString());
}
return null;
}
@Override
public SnapshotDataStoreVO findBySnapshot(long snapshotId, DataStoreRole role) {
SearchCriteria<SnapshotDataStoreVO> sc = snapshotSearch.create();
sc.setParameters("snapshot_id", snapshotId);
sc.setParameters("store_role", role);
return findOneBy(sc);
}
@Override
public List<SnapshotDataStoreVO> findBySnapshotId(long snapshotId) {
SearchCriteria<SnapshotDataStoreVO> sc = snapshotIdSearch.create();
sc.setParameters("snapshot_id", snapshotId);
return listBy(sc);
}
@Override
public List<SnapshotDataStoreVO> listDestroyed(long id) {
SearchCriteria<SnapshotDataStoreVO> sc = destroyedSearch.create();
sc.setParameters("store_id", id);
sc.setParameters("store_role", DataStoreRole.Image);
sc.setParameters("state", ObjectInDataStoreStateMachine.State.Destroyed);
return listBy(sc);
}
@Override
public List<SnapshotDataStoreVO> listActiveOnCache(long id) {
SearchCriteria<SnapshotDataStoreVO> sc = cacheSearch.create();
sc.setParameters("store_id", id);
sc.setParameters("store_role", DataStoreRole.ImageCache);
sc.setParameters("state", ObjectInDataStoreStateMachine.State.Destroyed);
sc.setParameters("ref_cnt", 0);
return listBy(sc);
}
}
|
|
package mightypork.rogue.world.entity.modules;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Set;
import mightypork.rogue.world.entity.Entity;
import mightypork.rogue.world.entity.EntityModule;
import mightypork.utils.ion.IonDataBundle;
import mightypork.utils.math.algo.Coord;
import mightypork.utils.math.algo.Move;
import mightypork.utils.math.constraints.vect.VectConst;
public class EntityModulePosition extends EntityModule {
/** Last pos, will be freed upon finishing move */
private Coord lastPos = new Coord(0, 0);
private boolean walking = false;
private final Queue<Move> path = new LinkedList<>();
private final EntityPos entityPos = new EntityPos();
private double stepTime = 0.5;
// marks for simple renderers
public int lastXDir = 1;
public int lastYDir = 1;
private final Set<EntityMoveListener> moveListeners = new LinkedHashSet<>();
public EntityModulePosition(Entity entity)
{
super(entity);
}
@Override
public void save(IonDataBundle bundle)
{
bundle.putSequence("path", path);
bundle.put("lpos", lastPos);
bundle.putBundled("pos", entityPos);
bundle.put("step_time", stepTime);
}
@Override
public void load(IonDataBundle bundle)
{
bundle.loadSequence("path", path);
lastPos = bundle.get("lpos", lastPos);
bundle.loadBundled("pos", entityPos);
stepTime = bundle.get("step_time", stepTime);
}
@Override
public boolean isModuleSaved()
{
return true;
}
/**
* Set coord without animation
*
* @param coord coord
*/
public void setCoord(Coord coord)
{
freeTile(); // release old tile
entityPos.setTo(coord);
lastPos.setTo(coord);
cancelPath(); // discard remaining steps
occupyTile();
}
/**
* Occupy current tile in level
*/
public void occupyTile()
{
if (entity.getLevel() != null) {
entity.getLevel().occupyTile(getCoord());
}
}
/**
* free current tile in level
*/
public void freeTile()
{
if (entity.getLevel() != null) {
entity.getLevel().freeTile(getCoord());
}
}
/**
* @param delta delta time
*/
@Override
public void update(double delta)
{
if (entity.isDead()) return; // corpses dont walk
if (!entityPos.isFinished()) {
entityPos.update(delta);
}
if (walking && entityPos.isFinished()) {
walking = false;
for (final EntityMoveListener l : moveListeners) {
l.onStepFinished();
}
if (path.isEmpty()) {
for (final EntityMoveListener l : moveListeners) {
l.onPathFinished();
}
}
}
if (!walking && !path.isEmpty()) {
walking = true;
final Move step = path.poll();
final Coord planned = entityPos.getCoord().add(step.toCoord());
if (!entity.getLevel().isWalkable(planned)) {
cancelPath();
for (final EntityMoveListener l : moveListeners) {
l.onPathInterrupted();
}
walking = false;
} else {
// tmp for renderer
if (step.x() != 0) this.lastXDir = step.x();
if (step.y() != 0) this.lastYDir = step.y();
freeTile();
lastPos.setTo(entityPos.getCoord());
entityPos.walk(step, stepTime);
occupyTile();
}
}
}
/**
* @return true if path buffer is empty
*/
public boolean isPathFinished()
{
return entityPos.isFinished() && path.isEmpty();
}
/**
* Add a step to path buffer
*
* @param step
*/
public void addStep(Move step)
{
if (path.isEmpty() && !canGoTo(step)) return;
path.add(step);
}
/**
* Discard steps in buffer
*/
public void cancelPath()
{
path.clear();
}
/**
* Find path to
*
* @param target
* @return path found
*/
public boolean navigateTo(Coord target)
{
if (target.equals(getCoord())) return true;
final List<Move> newPath = entity.getPathFinder().findPathRelative(entityPos.getCoord(), target);
if (newPath == null) return false;
cancelPath();
addSteps(newPath);
return true;
}
/**
* Add a move listener. If already present, do nothing.
*
* @param listener the listener
*/
public void addMoveListener(EntityMoveListener listener)
{
moveListeners.add(listener);
}
/**
* Add steps to path buffer
*
* @param path steps
*/
public void addSteps(List<Move> path)
{
this.path.addAll(path);
}
/**
* @return coord in level
*/
public Coord getCoord()
{
return entityPos.getCoord();
}
/**
* Set step time (seconds)
*
* @param stepTime step time
*/
public void setStepTime(double stepTime)
{
this.stepTime = stepTime;
}
/**
* @return step progress 0..1
*/
public double getProgress()
{
return entityPos.getProgress();
}
/**
* @return visual pos in level; interpolated from last to new coord
*/
public VectConst getVisualPos()
{
return entityPos.getVisualPos();
}
public boolean isMoving()
{
return walking;
}
public boolean hasPath()
{
return isMoving() || !path.isEmpty();
}
public boolean canGoTo(Move side)
{
return entity.getPathFinder().isAccessible(getCoord().add(side));
}
public Coord getLastPos()
{
return lastPos;
}
}
|
|
/*
* Copyright 2001-present Stephen Colebourne
*
* 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.joda.beans.impl.direct;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.NoSuchElementException;
import org.joda.beans.Bean;
import org.joda.beans.MetaBean;
import org.joda.beans.PropertyStyle;
import org.joda.beans.impl.BasicMetaProperty;
/**
* A meta-property implementation designed for use by the code generator.
* <p>
* This meta-property uses reflection to find the {@code Field} to obtain the annotations.
*
* @param <P> the type of the property content
*/
public final class DirectMetaProperty<P> extends BasicMetaProperty<P> {
/** The meta-bean. */
private final MetaBean metaBean;
/** The property type. */
private final Class<P> propertyType;
/** The declaring type. */
private final Class<?> declaringType;
/** The field implementing the property. */
private final Field field;
/** The style. */
private final PropertyStyle style;
/**
* Factory to create a read-write meta-property avoiding duplicate generics.
*
* @param <P> the property type
* @param metaBean the meta-bean, not null
* @param propertyName the property name, not empty
* @param declaringType the type declaring the property, not null
* @param propertyType the property type, not null
* @return the property, not null
*/
public static <P> DirectMetaProperty<P> ofReadWrite(
MetaBean metaBean, String propertyName, Class<?> declaringType, Class<P> propertyType) {
Field field = findField(metaBean, propertyName);
return new DirectMetaProperty<>(metaBean, propertyName, declaringType, propertyType, PropertyStyle.READ_WRITE, field);
}
/**
* Factory to create a read-only meta-property avoiding duplicate generics.
*
* @param <P> the property type
* @param metaBean the meta-bean, not null
* @param propertyName the property name, not empty
* @param declaringType the type declaring the property, not null
* @param propertyType the property type, not null
* @return the property, not null
*/
public static <P> DirectMetaProperty<P> ofReadOnly(
MetaBean metaBean, String propertyName, Class<?> declaringType, Class<P> propertyType) {
Field field = findField(metaBean, propertyName);
return new DirectMetaProperty<>(metaBean, propertyName, declaringType, propertyType, PropertyStyle.READ_ONLY, field);
}
/**
* Factory to create a write-only meta-property avoiding duplicate generics.
*
* @param <P> the property type
* @param metaBean the meta-bean, not null
* @param propertyName the property name, not empty
* @param declaringType the type declaring the property, not null
* @param propertyType the property type, not null
* @return the property, not null
*/
public static <P> DirectMetaProperty<P> ofWriteOnly(
MetaBean metaBean, String propertyName, Class<?> declaringType, Class<P> propertyType) {
Field field = findField(metaBean, propertyName);
return new DirectMetaProperty<>(metaBean, propertyName, declaringType, propertyType, PropertyStyle.WRITE_ONLY, field);
}
/**
* Factory to create a buildable read-only meta-property avoiding duplicate generics.
*
* @param <P> the property type
* @param metaBean the meta-bean, not null
* @param propertyName the property name, not empty
* @param declaringType the type declaring the property, not null
* @param propertyType the property type, not null
* @return the property, not null
*/
public static <P> DirectMetaProperty<P> ofReadOnlyBuildable(
MetaBean metaBean, String propertyName, Class<?> declaringType, Class<P> propertyType) {
Field field = findField(metaBean, propertyName);
return new DirectMetaProperty<>(metaBean, propertyName, declaringType, propertyType, PropertyStyle.READ_ONLY_BUILDABLE, field);
}
/**
* Factory to create a derived read-only meta-property avoiding duplicate generics.
*
* @param <P> the property type
* @param metaBean the meta-bean, not null
* @param propertyName the property name, not empty
* @param declaringType the type declaring the property, not null
* @param propertyType the property type, not null
* @return the property, not null
*/
public static <P> DirectMetaProperty<P> ofDerived(
MetaBean metaBean, String propertyName, Class<?> declaringType, Class<P> propertyType) {
Field field = findField(metaBean, propertyName);
return new DirectMetaProperty<>(metaBean, propertyName, declaringType, propertyType, PropertyStyle.DERIVED, field);
}
/**
* Factory to create an imutable meta-property avoiding duplicate generics.
*
* @param <P> the property type
* @param metaBean the meta-bean, not null
* @param propertyName the property name, not empty
* @param declaringType the type declaring the property, not null
* @param propertyType the property type, not null
* @return the property, not null
*/
public static <P> DirectMetaProperty<P> ofImmutable(
MetaBean metaBean, String propertyName, Class<?> declaringType, Class<P> propertyType) {
Field field = findField(metaBean, propertyName);
return new DirectMetaProperty<>(metaBean, propertyName, declaringType, propertyType, PropertyStyle.IMMUTABLE, field);
}
private static Field findField(MetaBean metaBean, String propertyName) {
Field field = null;
Class<?> cls = metaBean.beanType();
while (cls != DirectBean.class && cls != Object.class && cls != null) {
try {
field = cls.getDeclaredField(propertyName);
break;
} catch (NoSuchFieldException ex) {
try {
field = cls.getDeclaredField("_" + propertyName);
break;
} catch (NoSuchFieldException ex2) {
cls = cls.getSuperclass();
}
}
}
return field;
}
/**
* Constructor.
*
* @param metaBean the meta-bean, not null
* @param propertyName the property name, not empty
* @param declaringType the declaring type, not null
* @param propertyType the property type, not null
* @param style the style, not null
* @param field the reflected field, not null
*/
private DirectMetaProperty(MetaBean metaBean, String propertyName, Class<?> declaringType,
Class<P> propertyType, PropertyStyle style, Field field) {
super(propertyName);
if (metaBean == null) {
throw new NullPointerException("MetaBean must not be null");
}
if (declaringType == null) {
throw new NullPointerException("Declaring type must not be null");
}
if (propertyType == null) {
throw new NullPointerException("Property type must not be null");
}
if (style == null) {
throw new NullPointerException("PropertyStyle must not be null");
}
this.metaBean = metaBean;
this.propertyType = propertyType;
this.declaringType = declaringType;
this.style = style;
this.field = field; // may be null
}
//-----------------------------------------------------------------------
@Override
public MetaBean metaBean() {
return metaBean;
}
@Override
public Class<?> declaringType() {
return declaringType;
}
@Override
public Class<P> propertyType() {
return propertyType;
}
@Override
public Type propertyGenericType() {
if (field == null) {
return propertyType;
}
return field.getGenericType();
}
@Override
public PropertyStyle style() {
return style;
}
@Override
public <A extends Annotation> A annotation(Class<A> annotationClass) {
if (field == null) {
throw new UnsupportedOperationException("Field not found for property: " + name());
}
A annotation = field.getAnnotation(annotationClass);
if (annotation == null) {
throw new NoSuchElementException("Unknown annotation: " + annotationClass.getName());
}
return annotation;
}
@Override
public List<Annotation> annotations() {
if (field == null) {
return Collections.emptyList();
}
return Arrays.asList(field.getDeclaredAnnotations());
}
//-----------------------------------------------------------------------
@SuppressWarnings("unchecked")
@Override
public P get(Bean bean) {
DirectMetaBean meta = (DirectMetaBean) bean.metaBean();
return (P) meta.propertyGet(bean, name(), false);
}
@Override
public void set(Bean bean, Object value) {
DirectMetaBean meta = (DirectMetaBean) bean.metaBean();
meta.propertySet(bean, name(), value, false);
}
}
|
|
/*
* 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.script;
import com.google.common.collect.*;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.script.ScriptService.ScriptType;
import org.elasticsearch.script.expression.ExpressionScriptEngineService;
import org.elasticsearch.script.groovy.GroovyScriptEngineService;
import org.elasticsearch.script.mustache.MustacheScriptEngineService;
import org.elasticsearch.search.lookup.SearchLookup;
import org.elasticsearch.test.ESTestCase;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.*;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.notNullValue;
public class ScriptModesTests extends ESTestCase {
private static final Set<String> ALL_LANGS = ImmutableSet.of(GroovyScriptEngineService.NAME, MustacheScriptEngineService.NAME, ExpressionScriptEngineService.NAME, "custom", "test");
static final String[] ENABLE_VALUES = new String[]{"on", "true", "yes", "1"};
static final String[] DISABLE_VALUES = new String[]{"off", "false", "no", "0"};
ScriptContextRegistry scriptContextRegistry;
private ScriptContext[] scriptContexts;
private Map<String, ScriptEngineService> scriptEngines;
private ScriptModes scriptModes;
private Set<String> checkedSettings;
private boolean assertAllSettingsWereChecked;
private boolean assertScriptModesNonNull;
@Before
public void setupScriptEngines() {
//randomly register custom script contexts
int randomInt = randomIntBetween(0, 3);
//prevent duplicates using map
Map<String, ScriptContext.Plugin> contexts = Maps.newHashMap();
for (int i = 0; i < randomInt; i++) {
String plugin = randomAsciiOfLength(randomIntBetween(1, 10));
String operation = randomAsciiOfLength(randomIntBetween(1, 30));
String context = plugin + "-" + operation;
contexts.put(context, new ScriptContext.Plugin(plugin, operation));
}
scriptContextRegistry = new ScriptContextRegistry(contexts.values());
scriptContexts = scriptContextRegistry.scriptContexts().toArray(new ScriptContext[scriptContextRegistry.scriptContexts().size()]);
scriptEngines = buildScriptEnginesByLangMap(ImmutableSet.of(
new GroovyScriptEngineService(Settings.EMPTY),
new MustacheScriptEngineService(Settings.EMPTY),
new ExpressionScriptEngineService(Settings.EMPTY),
//add the native engine just to make sure it gets filtered out
new NativeScriptEngineService(Settings.EMPTY, Collections.<String, NativeScriptFactory>emptyMap()),
new CustomScriptEngineService()));
checkedSettings = new HashSet<>();
assertAllSettingsWereChecked = true;
assertScriptModesNonNull = true;
}
@After
public void assertNativeScriptsAreAlwaysAllowed() {
if (assertScriptModesNonNull) {
assertThat(scriptModes.getScriptMode(NativeScriptEngineService.NAME, randomFrom(ScriptType.values()), randomFrom(scriptContexts)), equalTo(ScriptMode.ON));
}
}
@After
public void assertAllSettingsWereChecked() {
if (assertScriptModesNonNull) {
assertThat(scriptModes, notNullValue());
//4 is the number of engines (native excluded), custom is counted twice though as it's associated with two different names
int numberOfSettings = 5 * ScriptType.values().length * scriptContextRegistry.scriptContexts().size();
assertThat(scriptModes.scriptModes.size(), equalTo(numberOfSettings));
if (assertAllSettingsWereChecked) {
assertThat(checkedSettings.size(), equalTo(numberOfSettings));
}
}
}
@Test
public void testDefaultSettings() {
this.scriptModes = new ScriptModes(scriptEngines, scriptContextRegistry, Settings.EMPTY);
assertScriptModesAllOps(ScriptMode.ON, ALL_LANGS, ScriptType.FILE);
assertScriptModesAllOps(ScriptMode.SANDBOX, ALL_LANGS, ScriptType.INDEXED, ScriptType.INLINE);
}
@Test(expected = IllegalArgumentException.class)
public void testMissingSetting() {
assertAllSettingsWereChecked = false;
this.scriptModes = new ScriptModes(scriptEngines, scriptContextRegistry, Settings.EMPTY);
scriptModes.getScriptMode("non_existing", randomFrom(ScriptType.values()), randomFrom(scriptContexts));
}
@Test
public void testScriptTypeGenericSettings() {
int randomInt = randomIntBetween(1, ScriptType.values().length - 1);
Set<ScriptType> randomScriptTypesSet = Sets.newHashSet();
ScriptMode[] randomScriptModes = new ScriptMode[randomInt];
for (int i = 0; i < randomInt; i++) {
boolean added = false;
while (added == false) {
added = randomScriptTypesSet.add(randomFrom(ScriptType.values()));
}
randomScriptModes[i] = randomFrom(ScriptMode.values());
}
ScriptType[] randomScriptTypes = randomScriptTypesSet.toArray(new ScriptType[randomScriptTypesSet.size()]);
Settings.Builder builder = Settings.builder();
for (int i = 0; i < randomInt; i++) {
builder.put(ScriptModes.SCRIPT_SETTINGS_PREFIX + randomScriptTypes[i], randomScriptModes[i]);
}
this.scriptModes = new ScriptModes(scriptEngines, scriptContextRegistry, builder.build());
for (int i = 0; i < randomInt; i++) {
assertScriptModesAllOps(randomScriptModes[i], ALL_LANGS, randomScriptTypes[i]);
}
if (randomScriptTypesSet.contains(ScriptType.FILE) == false) {
assertScriptModesAllOps(ScriptMode.ON, ALL_LANGS, ScriptType.FILE);
}
if (randomScriptTypesSet.contains(ScriptType.INDEXED) == false) {
assertScriptModesAllOps(ScriptMode.SANDBOX, ALL_LANGS, ScriptType.INDEXED);
}
if (randomScriptTypesSet.contains(ScriptType.INLINE) == false) {
assertScriptModesAllOps(ScriptMode.SANDBOX, ALL_LANGS, ScriptType.INLINE);
}
}
@Test
public void testScriptContextGenericSettings() {
int randomInt = randomIntBetween(1, scriptContexts.length - 1);
Set<ScriptContext> randomScriptContextsSet = Sets.newHashSet();
ScriptMode[] randomScriptModes = new ScriptMode[randomInt];
for (int i = 0; i < randomInt; i++) {
boolean added = false;
while (added == false) {
added = randomScriptContextsSet.add(randomFrom(scriptContexts));
}
randomScriptModes[i] = randomFrom(ScriptMode.values());
}
ScriptContext[] randomScriptContexts = randomScriptContextsSet.toArray(new ScriptContext[randomScriptContextsSet.size()]);
Settings.Builder builder = Settings.builder();
for (int i = 0; i < randomInt; i++) {
builder.put(ScriptModes.SCRIPT_SETTINGS_PREFIX + randomScriptContexts[i].getKey(), randomScriptModes[i]);
}
this.scriptModes = new ScriptModes(scriptEngines, scriptContextRegistry, builder.build());
for (int i = 0; i < randomInt; i++) {
assertScriptModesAllTypes(randomScriptModes[i], ALL_LANGS, randomScriptContexts[i]);
}
ScriptContext[] complementOf = complementOf(randomScriptContexts);
assertScriptModes(ScriptMode.ON, ALL_LANGS, new ScriptType[]{ScriptType.FILE}, complementOf);
assertScriptModes(ScriptMode.SANDBOX, ALL_LANGS, new ScriptType[]{ScriptType.INDEXED, ScriptType.INLINE}, complementOf);
}
@Test
public void testConflictingScriptTypeAndOpGenericSettings() {
ScriptContext scriptContext = randomFrom(scriptContexts);
Settings.Builder builder = Settings.builder().put(ScriptModes.SCRIPT_SETTINGS_PREFIX + scriptContext.getKey(), randomFrom(DISABLE_VALUES))
.put("script.indexed", randomFrom(ENABLE_VALUES)).put("script.inline", ScriptMode.SANDBOX);
//operations generic settings have precedence over script type generic settings
this.scriptModes = new ScriptModes(scriptEngines, scriptContextRegistry, builder.build());
assertScriptModesAllTypes(ScriptMode.OFF, ALL_LANGS, scriptContext);
ScriptContext[] complementOf = complementOf(scriptContext);
assertScriptModes(ScriptMode.ON, ALL_LANGS, new ScriptType[]{ScriptType.FILE, ScriptType.INDEXED}, complementOf);
assertScriptModes(ScriptMode.SANDBOX, ALL_LANGS, new ScriptType[]{ScriptType.INLINE}, complementOf);
}
@Test
public void testEngineSpecificSettings() {
Settings.Builder builder = Settings.builder()
.put(specificEngineOpSettings(GroovyScriptEngineService.NAME, ScriptType.INLINE, ScriptContext.Standard.MAPPING), randomFrom(DISABLE_VALUES))
.put(specificEngineOpSettings(GroovyScriptEngineService.NAME, ScriptType.INLINE, ScriptContext.Standard.UPDATE), randomFrom(DISABLE_VALUES));
ImmutableSet<String> groovyLangSet = ImmutableSet.of(GroovyScriptEngineService.NAME);
Set<String> allButGroovyLangSet = new HashSet<>(ALL_LANGS);
allButGroovyLangSet.remove(GroovyScriptEngineService.NAME);
this.scriptModes = new ScriptModes(scriptEngines, scriptContextRegistry, builder.build());
assertScriptModes(ScriptMode.OFF, groovyLangSet, new ScriptType[]{ScriptType.INLINE}, ScriptContext.Standard.MAPPING, ScriptContext.Standard.UPDATE);
assertScriptModes(ScriptMode.SANDBOX, groovyLangSet, new ScriptType[]{ScriptType.INLINE}, complementOf(ScriptContext.Standard.MAPPING, ScriptContext.Standard.UPDATE));
assertScriptModesAllOps(ScriptMode.SANDBOX, allButGroovyLangSet, ScriptType.INLINE);
assertScriptModesAllOps(ScriptMode.SANDBOX, ALL_LANGS, ScriptType.INDEXED);
assertScriptModesAllOps(ScriptMode.ON, ALL_LANGS, ScriptType.FILE);
}
@Test
public void testInteractionBetweenGenericAndEngineSpecificSettings() {
Settings.Builder builder = Settings.builder().put("script.inline", randomFrom(DISABLE_VALUES))
.put(specificEngineOpSettings(MustacheScriptEngineService.NAME, ScriptType.INLINE, ScriptContext.Standard.AGGS), randomFrom(ENABLE_VALUES))
.put(specificEngineOpSettings(MustacheScriptEngineService.NAME, ScriptType.INLINE, ScriptContext.Standard.SEARCH), randomFrom(ENABLE_VALUES));
ImmutableSet<String> mustacheLangSet = ImmutableSet.of(MustacheScriptEngineService.NAME);
Set<String> allButMustacheLangSet = new HashSet<>(ALL_LANGS);
allButMustacheLangSet.remove(MustacheScriptEngineService.NAME);
this.scriptModes = new ScriptModes(scriptEngines, scriptContextRegistry, builder.build());
assertScriptModes(ScriptMode.ON, mustacheLangSet, new ScriptType[]{ScriptType.INLINE}, ScriptContext.Standard.AGGS, ScriptContext.Standard.SEARCH);
assertScriptModes(ScriptMode.OFF, mustacheLangSet, new ScriptType[]{ScriptType.INLINE}, complementOf(ScriptContext.Standard.AGGS, ScriptContext.Standard.SEARCH));
assertScriptModesAllOps(ScriptMode.OFF, allButMustacheLangSet, ScriptType.INLINE);
assertScriptModesAllOps(ScriptMode.SANDBOX, ALL_LANGS, ScriptType.INDEXED);
assertScriptModesAllOps(ScriptMode.ON, ALL_LANGS, ScriptType.FILE);
}
private void assertScriptModesAllOps(ScriptMode expectedScriptMode, Set<String> langs, ScriptType... scriptTypes) {
assertScriptModes(expectedScriptMode, langs, scriptTypes, scriptContexts);
}
private void assertScriptModesAllTypes(ScriptMode expectedScriptMode, Set<String> langs, ScriptContext... scriptContexts) {
assertScriptModes(expectedScriptMode, langs, ScriptType.values(), scriptContexts);
}
private void assertScriptModes(ScriptMode expectedScriptMode, Set<String> langs, ScriptType[] scriptTypes, ScriptContext... scriptContexts) {
assert langs.size() > 0;
assert scriptTypes.length > 0;
assert scriptContexts.length > 0;
for (String lang : langs) {
for (ScriptType scriptType : scriptTypes) {
for (ScriptContext scriptContext : scriptContexts) {
assertThat(lang + "." + scriptType + "." + scriptContext.getKey() + " doesn't have the expected value", scriptModes.getScriptMode(lang, scriptType, scriptContext), equalTo(expectedScriptMode));
checkedSettings.add(lang + "." + scriptType + "." + scriptContext);
}
}
}
}
private ScriptContext[] complementOf(ScriptContext... scriptContexts) {
Map<String, ScriptContext> copy = Maps.newHashMap();
for (ScriptContext scriptContext : scriptContextRegistry.scriptContexts()) {
copy.put(scriptContext.getKey(), scriptContext);
}
for (ScriptContext scriptContext : scriptContexts) {
copy.remove(scriptContext.getKey());
}
return copy.values().toArray(new ScriptContext[copy.size()]);
}
private static String specificEngineOpSettings(String lang, ScriptType scriptType, ScriptContext scriptContext) {
return ScriptModes.ENGINE_SETTINGS_PREFIX + "." + lang + "." + scriptType + "." + scriptContext.getKey();
}
static ImmutableMap<String, ScriptEngineService> buildScriptEnginesByLangMap(Set<ScriptEngineService> scriptEngines) {
ImmutableMap.Builder<String, ScriptEngineService> builder = ImmutableMap.builder();
for (ScriptEngineService scriptEngine : scriptEngines) {
for (String type : scriptEngine.types()) {
builder.put(type, scriptEngine);
}
}
return builder.build();
}
private static class CustomScriptEngineService implements ScriptEngineService {
@Override
public String[] types() {
return new String[]{"custom", "test"};
}
@Override
public String[] extensions() {
return new String[0];
}
@Override
public boolean sandboxed() {
return false;
}
@Override
public Object compile(String script) {
return null;
}
@Override
public ExecutableScript executable(CompiledScript compiledScript, @Nullable Map<String, Object> vars) {
return null;
}
@Override
public SearchScript search(CompiledScript compiledScript, SearchLookup lookup, @Nullable Map<String, Object> vars) {
return null;
}
@Override
public Object execute(CompiledScript compiledScript, Map<String, Object> vars) {
return null;
}
@Override
public Object unwrap(Object value) {
return null;
}
@Override
public void close() {
}
@Override
public void scriptRemoved(@Nullable CompiledScript script) {
}
}
}
|
|
/*
* Copyright 2012-2022 THALES.
*
* This file is part of AuthzForce CE.
*
* 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.ow2.authzforce.core.pdp.testutil.test.conformance;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.Request;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.Response;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.ow2.authzforce.core.pdp.api.XmlUtils.XmlnsFilteringParser;
import org.ow2.authzforce.core.pdp.api.XmlUtils.XmlnsFilteringParserFactory;
import org.ow2.authzforce.core.pdp.api.io.PdpEngineInoutAdapter;
import org.ow2.authzforce.core.pdp.api.io.XacmlJaxbParsingUtils;
import org.ow2.authzforce.core.pdp.impl.PdpEngineConfiguration;
import org.ow2.authzforce.core.pdp.impl.io.PdpEngineAdapters;
import org.ow2.authzforce.core.pdp.testutil.TestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;
import javax.xml.bind.JAXBException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Optional;
/**
* XACML 3.0 conformance tests (published on OASIS xacml-comments mailing list). For tests testing validation of XACML policy syntax, the PDP is expected to reject the policy before receiving any
* Request. For these tests, the Request.xml and Response.xml are absent to indicate to this test class, that an invalid policy syntax is expected.
* <p>
* For tests testing validation of XACML Request syntax, the PDP is expected to reject the request before evaluation. For these tests, the Response.xml is absent to indicate to this test class, that
* an invalid Request syntax is expected.
*/
@RunWith(value = Parameterized.class)
public class ConformanceV3FromV2
{
/**
* Suffix of filename of root XACML Policy(Set). The actual filename is the concatenation of the test ID and this suffix.
*/
public static final String ROOT_POLICY_FILENAME_SUFFIX = "Policy.xml";
/**
* Suffix of filename of XACML request to send to the PDP. The actual filename is the concatenation of the test ID and this suffix.
*/
public static final String REQUEST_FILENAME_SUFFIX = "Request.xml";
/**
* Suffix of filename of the expected XACML response from the PDP. The actual filename is the concatenation of the test ID and this suffix.
*/
public static final String EXPECTED_RESPONSE_FILENAME_SUFFIX = "Response.xml";
/**
* Suffix of name of directory containing files of XACML Policy(Set) that can be referenced from root policy via Policy(Set)IdReference. The actual directory name is the concatenation of the test
* ID and this suffix.
*/
public final static String POLICIES_DIRNAME_SUFFIX = "Policies";
/**
* Suffix of filename of an AttributeProvider configuration. The actual filename is the concatenation of the test ID and this suffix.
*/
public static final String ATTRIBUTE_PROVIDER_FILENAME_SUFFIX = "AttributeProvider.xml";
/**
* PDP Configuration file name
*/
public final static String PDP_CONF_FILENAME = "pdp.xml";
/**
* PDP extensions schema
*/
public final static String PDP_EXTENSION_XSD_LOCATION = "classpath:pdp-ext.xsd";
/**
* Spring-supported location to XML catalog (may be prefixed with classpath:, etc.)
*/
public final static String XML_CATALOG_LOCATION = "classpath:catalog.xml";
/**
* the logger we'll use for all messages
*/
private static final Logger LOGGER = LoggerFactory.getLogger(ConformanceV3FromV2.class);
protected static void setUp(final String testRootDirectoryLocation)
{
LOGGER.debug("Launching conformance tests for features in directory: {}", testRootDirectoryLocation);
}
/**
* For each test folder {@code testRootDir}/{@code testSubDirectoryName}, it creates the test parameters: path to the test directory containing Request.xml, Response.xml, etc., and the ID of request filter to be applied (null means the default lax variant of the single-decision request preprocessor
*
* @param testRootDir
* path to root directory of all test data
* @param requestFilterId
* PDP request filter ID to be used for the tests
* @return test data
*/
public static Collection<Object[]> getTestData(final String testRootDir, DirectoryStream.Filter<? super Path> fileFilter, final String requestFilterId) throws IOException
{
final Collection<Object[]> testData = new ArrayList<>();
/*
* Each sub-directory of the root directory is data for a specific test. So we configure a test for each directory
*/
final Path testRootDirPath = Paths.get(testRootDir);
try (DirectoryStream<Path> stream = Files.newDirectoryStream(testRootDirPath, fileFilter))
{
for (final Path testDirPath: stream)
{
// specific test's resources directory location and request filter ID, used as parameters to test(...)
testData.add(new Object[]{testDirPath, requestFilterId });
}
}
return testData;
}
private final Path testDirectoryPath;
private final boolean enableXPath;
private final XmlnsFilteringParserFactory xacmlParserFactory;
private final String reqFilterId;
public ConformanceV3FromV2(final Path testDir, final boolean enableXPath, final String requestFilter)
{
this.testDirectoryPath = testDir;
this.enableXPath = enableXPath;
this.reqFilterId = requestFilter;
this.xacmlParserFactory = XacmlJaxbParsingUtils.getXacmlParserFactory(enableXPath);
}
@Test
public void test() throws Exception
{
LOGGER.debug("******************************");
LOGGER.debug("Starting PDP test in directory: '{}'", testDirectoryPath);
// Response file
final XmlnsFilteringParser respUnmarshaller = xacmlParserFactory.getInstance();
final Path expectedRespFilepath = testDirectoryPath.resolve(EXPECTED_RESPONSE_FILENAME_SUFFIX);
// If no Response file, it is just a static policy or request syntax error check
final Response expectedResponse;
if (Files.exists(expectedRespFilepath))
{
expectedResponse = TestUtils.createResponse(expectedRespFilepath, respUnmarshaller);
}
else
{
expectedResponse = null;
// Do nothing except logging -> request = null
LOGGER.debug("Response file '{}' does not exist -> Static Policy/Request syntax error check", expectedRespFilepath);
}
// Request file
final XmlnsFilteringParser reqUnmarshaller = xacmlParserFactory.getInstance();
final Path reqFilepath = testDirectoryPath.resolve(REQUEST_FILENAME_SUFFIX);
// If no Request file, it is just a static policy syntax error check
final Request request;
if (Files.exists(reqFilepath))
{
try
{
request = TestUtils.createRequest(reqFilepath, reqUnmarshaller);
}
catch (final JAXBException e)
{
// we found a syntax error in request
if (expectedResponse == null)
{
// this is a Request syntax error check and we found the syntax error as
// expected -> success
LOGGER.debug("Successfully found syntax error as expected in Request located at: {}", reqFilepath);
return;
}
// Unexpected error
throw e;
}
}
else
{
request = null;
// do nothing except logging -> request = null
LOGGER.debug("Request file '{}' does not exist -> Static policy syntax error check (Request/Response ignored)", reqFilepath);
}
/*
* Create PDP
*/
final PdpEngineConfiguration pdpEngineConf;
final Path pdpConfFile = testDirectoryPath.resolve(PDP_CONF_FILENAME);
if (Files.notExists(pdpConfFile))
{
/*
* Policies directory. If it exists, root Policy file is expected to be in there. This is the case for IIE*** conformance tests
*/
final Path policiesDir = testDirectoryPath.resolve(POLICIES_DIRNAME_SUFFIX);
/*
Attribute Provider config
*/
final Path attributeProviderConfFile = testDirectoryPath.resolve(ATTRIBUTE_PROVIDER_FILENAME_SUFFIX);
final Optional<Path> optAttributeProviderConfFile = Files.isRegularFile(attributeProviderConfFile) ? Optional.of(attributeProviderConfFile) : Optional.empty();
try
{
if (Files.isDirectory(policiesDir))
{
final Path rootPolicyFile = policiesDir.resolve(ROOT_POLICY_FILENAME_SUFFIX);
pdpEngineConf = TestUtils.newPdpEngineConfiguration(TestUtils.getPolicyRef(rootPolicyFile), policiesDir, enableXPath, optAttributeProviderConfFile, this.reqFilterId, null);
} else
{
final Path rootPolicyFile = testDirectoryPath.resolve(ROOT_POLICY_FILENAME_SUFFIX);
pdpEngineConf = TestUtils.newPdpEngineConfiguration(rootPolicyFile, enableXPath, optAttributeProviderConfFile, this.reqFilterId, null);
}
} catch (final IllegalArgumentException e)
{
// we found syntax error in policy
if (request == null)
{
// this is a policy syntax error check and we found the syntax error as
// expected -> success
LOGGER.debug("Successfully found syntax error as expected in policy(ies) with path: {}*", testDirectoryPath);
return;
}
// Unexpected error
throw e;
}
} else
{
/*
* PDP configuration filename found in test directory -> create PDP from it
*/
// final String pdpExtXsdLocation = testResourceLocationPrefix + PDP_EXTENSION_XSD_FILENAME;
File pdpExtXsdFile = null;
try
{
pdpExtXsdFile = ResourceUtils.getFile(PDP_EXTENSION_XSD_LOCATION);
} catch (final FileNotFoundException e)
{
LOGGER.debug("No PDP extension configuration file '{}' found -> JAXB-bound PDP extensions not allowed.", PDP_EXTENSION_XSD_LOCATION);
}
try
{
/*
* Load the PDP configuration from the configuration, and optionally, the PDP extension XSD if this file exists, and the XML catalog required to resolve these extension XSDs
*/
pdpEngineConf = pdpExtXsdFile == null ? PdpEngineConfiguration.getInstance(pdpConfFile.toString())
: PdpEngineConfiguration.getInstance(pdpConfFile.toString(), XML_CATALOG_LOCATION, PDP_EXTENSION_XSD_LOCATION);
} catch (final IOException e)
{
throw new RuntimeException("Error parsing PDP configuration from file '" + pdpConfFile + "' with extension XSD '" + PDP_EXTENSION_XSD_LOCATION + "' and XML catalog file '"
+ XML_CATALOG_LOCATION + "'", e);
}
}
try (PdpEngineInoutAdapter<Request, Response> pdp = PdpEngineAdapters.newXacmlJaxbInoutAdapter(pdpEngineConf))
{
if (request == null)
{
// this is a policy syntax error check and we didn't found the syntax error as
// expected
Assert.fail("Failed to find syntax error as expected in policy(ies) with path: " + testDirectoryPath + "*");
}
else if (expectedResponse == null)
{
/*
* No expected response, so it is not a PDP evaluation test, but request or policy syntax error check. We got here, so request and policy OK. This is unexpected.
*/
Assert.fail("Missing response file '" + expectedRespFilepath + "' or failed to find syntax error as expected in either request located at '" + reqFilepath
+ "' or policy(ies) with path '" + testDirectoryPath + "*'");
}
else
{
// this is an evaluation test with request/response (not a policy syntax check)
LOGGER.debug("Request that is sent to the PDP: {}", request);
final Response actualResponse = pdp.evaluate(request, reqUnmarshaller.getNamespacePrefixUriMap());
if (LOGGER.isDebugEnabled())
{
LOGGER.debug("Response that is received from the PDP : {}", TestUtils.printResponse(actualResponse));
}
TestUtils.assertNormalizedEquals("Test failed for directory "+ testDirectoryPath, expectedResponse, actualResponse);
}
}
catch (final IllegalArgumentException e)
{
// we found syntax error in policy
if (request == null)
{
// this is a policy syntax error check and we found the syntax error as
// expected -> success
LOGGER.debug("Successfully found syntax error as expected in policy(ies) with path: {}*", testDirectoryPath);
return;
}
// Unexpected error
throw e;
}
}
/* public static void main(String[] args) throws IOException
{
final String testsDir = "pdp-testutils/src/test/resources/conformance/xacml-3.0-from-2.0-ct/optional/xml";
final Path testsDirPath = Paths.get(testsDir);
for(final Path testdir: Files.newDirectoryStream(testsDirPath)) {
if(Files.isDirectory(testdir)) {
for(final Path testFile: Files.newDirectoryStream(testdir)) {
final String testFilename = testFile.getFileName().toString();
String prefix = testFilename.substring(0, 6);
Path newTestDirPath = testsDirPath.resolve(prefix);
if(Files.notExists(newTestDirPath)) {
System.out.println("Creating directory: " + newTestDirPath);
Files.createDirectory(newTestDirPath);
}
String suffix = testFilename.substring(6);
Path newFilepath = newTestDirPath.resolve(suffix);
System.out.println("Moving file: " + testFile + " -> "+ newFilepath);
Files.move(testFile, newFilepath);
}
}
}
}*/
}
|
|
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.providers.transfers;
import android.app.DownloadManager;
import android.app.DownloadManager.Request;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.UriMatcher;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import android.os.Binder;
import android.os.Environment;
import android.os.Handler;
import android.os.ParcelFileDescriptor;
import android.os.ParcelFileDescriptor.OnCloseListener;
import android.os.Process;
import android.os.SELinux;
import android.provider.BaseColumns;
import android.provider.Downloads;
import android.provider.OpenableColumns;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.util.Log;
import com.android.internal.util.IndentingPrintWriter;
import com.google.android.collect.Maps;
import com.google.common.annotations.VisibleForTesting;
import libcore.io.IoUtils;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* Allows application to interact with the transfer manager.
*/
public final class TransferProvider extends ContentProvider {
/** Database filename */
private static final String DB_NAME = "transfers.db";
/** Current database version */
private static final int DB_VERSION = 109;
/** Name of table in the database */
private static final String DB_TABLE = "transfers";
/** MIME type for the entire transfer list */
private static final String DOWNLOAD_LIST_TYPE = "vnd.android.cursor.dir/transfer";
/** MIME type for an individual transfer */
private static final String DOWNLOAD_TYPE = "vnd.android.cursor.item/transfer";
/** URI matcher used to recognize URIs sent by applications */
private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH);
/** URI matcher constant for the URI of all transfers belonging to the calling UID */
private static final int MY_DOWNLOADS = 1;
/** URI matcher constant for the URI of an individual transfer belonging to the calling UID */
private static final int MY_DOWNLOADS_ID = 2;
/** URI matcher constant for the URI of all transfers in the system */
private static final int ALL_DOWNLOADS = 3;
/** URI matcher constant for the URI of an individual transfer */
private static final int ALL_DOWNLOADS_ID = 4;
/** URI matcher constant for the URI of a transfer's request headers */
private static final int REQUEST_HEADERS_URI = 5;
/** URI matcher constant for the public URI returned by
* {@link TransferManager#getUriForTransferedFile(long)} if the given transfered file
* is publicly accessible.
*/
private static final int PUBLIC_DOWNLOAD_ID = 6;
static {
sURIMatcher.addURI("transfers", "my_transfers", MY_DOWNLOADS);
sURIMatcher.addURI("transfers", "my_transfers/#", MY_DOWNLOADS_ID);
sURIMatcher.addURI("transfers", "all_transfers", ALL_DOWNLOADS);
sURIMatcher.addURI("transfers", "all_transfers/#", ALL_DOWNLOADS_ID);
sURIMatcher.addURI("transfers",
"my_transfers/#/" + Downloads.Impl.RequestHeaders.URI_SEGMENT,
REQUEST_HEADERS_URI);
sURIMatcher.addURI("transfers",
"all_transfers/#/" + Downloads.Impl.RequestHeaders.URI_SEGMENT,
REQUEST_HEADERS_URI);
// temporary, for backwards compatibility
sURIMatcher.addURI("transfers", "transfer", MY_DOWNLOADS);
sURIMatcher.addURI("transfers", "transfer/#", MY_DOWNLOADS_ID);
sURIMatcher.addURI("transfers",
"transfer/#/" + Downloads.Impl.RequestHeaders.URI_SEGMENT,
REQUEST_HEADERS_URI);
sURIMatcher.addURI("transfers",
Downloads.Impl.PUBLICLY_ACCESSIBLE_DOWNLOADS_URI_SEGMENT + "/#",
PUBLIC_DOWNLOAD_ID);
}
/** Different base URIs that could be used to access an individual transfer */
private static final Uri[] BASE_URIS = new Uri[] {
Downloads.Impl.CONTENT_URI,
Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI,
};
private static final String[] sAppReadableColumnsArray = new String[] {
Downloads.Impl._ID,
Downloads.Impl.COLUMN_APP_DATA,
Downloads.Impl._DATA,
Downloads.Impl.COLUMN_MIME_TYPE,
Downloads.Impl.COLUMN_VISIBILITY,
Downloads.Impl.COLUMN_DESTINATION,
Downloads.Impl.COLUMN_CONTROL,
Downloads.Impl.COLUMN_STATUS,
Downloads.Impl.COLUMN_LAST_MODIFICATION,
Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
Downloads.Impl.COLUMN_TOTAL_BYTES,
Downloads.Impl.COLUMN_CURRENT_BYTES,
Downloads.Impl.COLUMN_TITLE,
Downloads.Impl.COLUMN_DESCRIPTION,
Downloads.Impl.COLUMN_URI,
Downloads.Impl.COLUMN_IS_VISIBLE_IN_DOWNLOADS_UI,
Downloads.Impl.COLUMN_FILE_NAME_HINT,
Downloads.Impl.COLUMN_MEDIAPROVIDER_URI,
Downloads.Impl.COLUMN_DELETED,
Downloads.Impl.COLUMN_IS_TYPE_UPLOAD, //ml
Downloads.Impl.COLUMN_IS_USING_TOR,
OpenableColumns.DISPLAY_NAME,
OpenableColumns.SIZE,
};
private static final HashSet<String> sAppReadableColumnsSet;
private static final HashMap<String, String> sColumnsMap;
static {
sAppReadableColumnsSet = new HashSet<String>();
for (int i = 0; i < sAppReadableColumnsArray.length; ++i) {
sAppReadableColumnsSet.add(sAppReadableColumnsArray[i]);
}
sColumnsMap = Maps.newHashMap();
sColumnsMap.put(OpenableColumns.DISPLAY_NAME,
Downloads.Impl.COLUMN_TITLE + " AS " + OpenableColumns.DISPLAY_NAME);
sColumnsMap.put(OpenableColumns.SIZE,
Downloads.Impl.COLUMN_TOTAL_BYTES + " AS " + OpenableColumns.SIZE);
}
private static final List<String> transferManagerColumnsList =
Arrays.asList(DownloadManager.UNDERLYING_COLUMNS);
private Handler mHandler;
/** The database that lies underneath this content provider */
private SQLiteOpenHelper mOpenHelper = null;
/** List of uids that can access the transfers */
private int mSystemUid = -1;
private int mDefContainerUid = -1;
private File mDownloadsDataDir;
@VisibleForTesting
SystemFacade mSystemFacade;
/**
* This class encapsulates a SQL where clause and its parameters. It makes it possible for
* shared methods (like {@link TransferProvider#getWhereClause(Uri, String, String[], int)})
* to return both pieces of information, and provides some utility logic to ease piece-by-piece
* construction of selections.
*/
private static class SqlSelection {
public StringBuilder mWhereClause = new StringBuilder();
public List<String> mParameters = new ArrayList<String>();
public <T> void appendClause(String newClause, final T... parameters) {
if (newClause == null || newClause.isEmpty()) {
return;
}
if (mWhereClause.length() != 0) {
mWhereClause.append(" AND ");
}
mWhereClause.append("(");
mWhereClause.append(newClause);
mWhereClause.append(")");
if (parameters != null) {
for (Object parameter : parameters) {
mParameters.add(parameter.toString());
}
}
}
public String getSelection() {
return mWhereClause.toString();
}
public String[] getParameters() {
String[] array = new String[mParameters.size()];
return mParameters.toArray(array);
}
}
/**
* Creates and updated database on demand when opening it.
* Helper class to create database the first time the provider is
* initialized and upgrade it when a new version of the provider needs
* an updated version of the database.
*/
private final class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(final Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
/**
* Creates database the first time we try to open it.
*/
@Override
public void onCreate(final SQLiteDatabase db) {
if (Constants.LOGVV) {
Log.v(Constants.TAG, "populating new database");
}
onUpgrade(db, 0, DB_VERSION);
}
/**
* Updates the database format when a content provider is used
* with a database that was created with a different format.
*
* Note: to support downgrades, creating a table should always drop it first if it already
* exists.
*/
@Override
public void onUpgrade(final SQLiteDatabase db, int oldV, final int newV) {
if (oldV == 31) {
// 31 and 100 are identical, just in different codelines. Upgrading from 31 is the
// same as upgrading from 100.
oldV = 100;
} else if (oldV < 100) {
// no logic to upgrade from these older version, just recreate the DB
Log.i(Constants.TAG, "Upgrading transfers database from version " + oldV
+ " to version " + newV + ", which will destroy all old data");
oldV = 99;
} else if (oldV > newV) {
// user must have downgraded software; we have no way to know how to downgrade the
// DB, so just recreate it
Log.i(Constants.TAG, "Downgrading transfers database from version " + oldV
+ " (current version is " + newV + "), destroying all old data");
oldV = 99;
}
for (int version = oldV + 1; version <= newV; version++) {
upgradeTo(db, version);
}
}
/**
* Upgrade database from (version - 1) to version.
*/
private void upgradeTo(SQLiteDatabase db, int version) {
switch (version) {
case 100:
createDownloadsTable(db);
break;
case 101:
createHeadersTable(db);
break;
case 102:
addColumn(db, DB_TABLE, Downloads.Impl.COLUMN_IS_PUBLIC_API,
"INTEGER NOT NULL DEFAULT 0");
addColumn(db, DB_TABLE, Downloads.Impl.COLUMN_ALLOW_ROAMING,
"INTEGER NOT NULL DEFAULT 0");
addColumn(db, DB_TABLE, Downloads.Impl.COLUMN_ALLOWED_NETWORK_TYPES,
"INTEGER NOT NULL DEFAULT 0");
break;
case 103:
addColumn(db, DB_TABLE, Downloads.Impl.COLUMN_IS_VISIBLE_IN_DOWNLOADS_UI,
"INTEGER NOT NULL DEFAULT 1");
makeCacheDownloadsInvisible(db);
break;
case 104:
addColumn(db, DB_TABLE, Downloads.Impl.COLUMN_BYPASS_RECOMMENDED_SIZE_LIMIT,
"INTEGER NOT NULL DEFAULT 0");
break;
case 105:
fillNullValues(db);
break;
case 106:
addColumn(db, DB_TABLE, Downloads.Impl.COLUMN_MEDIAPROVIDER_URI, "TEXT");
addColumn(db, DB_TABLE, Downloads.Impl.COLUMN_DELETED,
"BOOLEAN NOT NULL DEFAULT 0");
break;
case 107:
addColumn(db, DB_TABLE, Downloads.Impl.COLUMN_ERROR_MSG, "TEXT");
break;
case 108:
addColumn(db, DB_TABLE, Downloads.Impl.COLUMN_ALLOW_METERED,
"INTEGER NOT NULL DEFAULT 1");
break;
case 109:
addColumn(db, DB_TABLE, Downloads.Impl.COLUMN_ALLOW_WRITE,
"BOOLEAN NOT NULL DEFAULT 0");
break;
default:
throw new IllegalStateException("Don't know how to upgrade to " + version);
}
}
/**
* insert() now ensures these four columns are never null for new transfers, so this method
* makes that true for existing columns, so that code can rely on this assumption.
*/
private void fillNullValues(SQLiteDatabase db) {
ContentValues values = new ContentValues();
values.put(Downloads.Impl.COLUMN_CURRENT_BYTES, 0);
fillNullValuesForColumn(db, values);
values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, -1);
fillNullValuesForColumn(db, values);
values.put(Downloads.Impl.COLUMN_TITLE, "");
fillNullValuesForColumn(db, values);
values.put(Downloads.Impl.COLUMN_DESCRIPTION, "");
fillNullValuesForColumn(db, values);
}
private void fillNullValuesForColumn(SQLiteDatabase db, ContentValues values) {
String column = values.valueSet().iterator().next().getKey();
db.update(DB_TABLE, values, column + " is null", null);
values.clear();
}
/**
* Set all existing transfers to the cache partition to be invisible in the transfers UI.
*/
private void makeCacheDownloadsInvisible(SQLiteDatabase db) {
ContentValues values = new ContentValues();
values.put(Downloads.Impl.COLUMN_IS_VISIBLE_IN_DOWNLOADS_UI, false);
String cacheSelection = Downloads.Impl.COLUMN_DESTINATION
+ " != " + Downloads.Impl.DESTINATION_EXTERNAL;
db.update(DB_TABLE, values, cacheSelection, null);
}
/**
* Add a column to a table using ALTER TABLE.
* @param dbTable name of the table
* @param columnName name of the column to add
* @param columnDefinition SQL for the column definition
*/
private void addColumn(SQLiteDatabase db, String dbTable, String columnName,
String columnDefinition) {
db.execSQL("ALTER TABLE " + dbTable + " ADD COLUMN " + columnName + " "
+ columnDefinition);
}
/**
* Creates the table that'll hold the transfer information.
*/
private void createDownloadsTable(SQLiteDatabase db) {
try {
db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE);
db.execSQL("CREATE TABLE " + DB_TABLE + "(" +
Downloads.Impl._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
Downloads.Impl.COLUMN_URI + " TEXT, " +
Constants.RETRY_AFTER_X_REDIRECT_COUNT + " INTEGER, " +
Downloads.Impl.COLUMN_APP_DATA + " TEXT, " +
Downloads.Impl.COLUMN_NO_INTEGRITY + " BOOLEAN, " +
Downloads.Impl.COLUMN_FILE_NAME_HINT + " TEXT, " +
Constants.OTA_UPDATE + " BOOLEAN, " +
Downloads.Impl._DATA + " TEXT, " +
Downloads.Impl.COLUMN_MIME_TYPE + " TEXT, " +
Downloads.Impl.COLUMN_DESTINATION + " INTEGER, " +
Constants.NO_SYSTEM_FILES + " BOOLEAN, " +
Downloads.Impl.COLUMN_VISIBILITY + " INTEGER, " +
Downloads.Impl.COLUMN_CONTROL + " INTEGER, " +
Downloads.Impl.COLUMN_STATUS + " INTEGER, " +
Downloads.Impl.COLUMN_FAILED_CONNECTIONS + " INTEGER, " +
Downloads.Impl.COLUMN_LAST_MODIFICATION + " BIGINT, " +
Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE + " TEXT, " +
Downloads.Impl.COLUMN_NOTIFICATION_CLASS + " TEXT, " +
Downloads.Impl.COLUMN_NOTIFICATION_EXTRAS + " TEXT, " +
Downloads.Impl.COLUMN_COOKIE_DATA + " TEXT, " +
Downloads.Impl.COLUMN_USER_AGENT + " TEXT, " +
Downloads.Impl.COLUMN_REFERER + " TEXT, " +
Downloads.Impl.COLUMN_TOTAL_BYTES + " INTEGER, " +
Downloads.Impl.COLUMN_CURRENT_BYTES + " INTEGER, " +
Constants.ETAG + " TEXT, " +
Constants.UID + " INTEGER, " +
Downloads.Impl.COLUMN_OTHER_UID + " INTEGER, " +
Downloads.Impl.COLUMN_TITLE + " TEXT, " +
Downloads.Impl.COLUMN_DESCRIPTION + " TEXT, " +
Downloads.Impl.COLUMN_IS_TYPE_UPLOAD + " BOOLEAN, " +//ml
Downloads.Impl.COLUMN_IS_USING_TOR + " BOOLEAN, " +
Constants.MEDIA_SCANNED + " BOOLEAN);");
} catch (SQLException ex) {
Log.e(Constants.TAG, "couldn't create table in transfers database");
throw ex;
}
}
private void createHeadersTable(SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS " + Downloads.Impl.RequestHeaders.HEADERS_DB_TABLE);
db.execSQL("CREATE TABLE " + Downloads.Impl.RequestHeaders.HEADERS_DB_TABLE + "(" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
Downloads.Impl.RequestHeaders.COLUMN_DOWNLOAD_ID + " INTEGER NOT NULL," +
Downloads.Impl.RequestHeaders.COLUMN_HEADER + " TEXT NOT NULL," +
Downloads.Impl.RequestHeaders.COLUMN_VALUE + " TEXT NOT NULL" +
");");
}
}
/**
* Initializes the content provider when it is created.
*/
@Override
public boolean onCreate() {
if (mSystemFacade == null) {
mSystemFacade = new RealSystemFacade(getContext());
}
mHandler = new Handler();
mOpenHelper = new DatabaseHelper(getContext());
// Initialize the system uid
mSystemUid = Process.SYSTEM_UID;
// Initialize the default container uid. Package name hardcoded
// for now.
ApplicationInfo appInfo = null;
try {
appInfo = getContext().getPackageManager().
getApplicationInfo("com.android.defcontainer", 0);
} catch (NameNotFoundException e) {
Log.wtf(Constants.TAG, "Could not get ApplicationInfo for com.android.defconatiner", e);
}
if (appInfo != null) {
mDefContainerUid = appInfo.uid;
}
// start the TransferService class. don't wait for the 1st transfer to be issued.
// saves us by getting some initialization code in TransferService out of the way.
Context context = getContext();
context.startService(new Intent(context, TransferService.class));
mDownloadsDataDir = StorageManager.getTransferDataDirectory(getContext());
try {
SELinux.restorecon(mDownloadsDataDir.getCanonicalPath());
} catch (IOException e) {
Log.wtf(Constants.TAG, "Could not get canonical path for transfer directory", e);
}
return true;
}
/**
* Returns the content-provider-style MIME types of the various
* types accessible through this content provider.
*/
@Override
public String getType(final Uri uri) {
int match = sURIMatcher.match(uri);
switch (match) {
case MY_DOWNLOADS:
case ALL_DOWNLOADS: {
return DOWNLOAD_LIST_TYPE;
}
case MY_DOWNLOADS_ID:
case ALL_DOWNLOADS_ID:
case PUBLIC_DOWNLOAD_ID: {
// return the mimetype of this id from the database
final String id = getTransferIdFromUri(uri);
final SQLiteDatabase db = mOpenHelper.getReadableDatabase();
final String mimeType = DatabaseUtils.stringForQuery(db,
"SELECT " + Downloads.Impl.COLUMN_MIME_TYPE + " FROM " + DB_TABLE +
" WHERE " + Downloads.Impl._ID + " = ?",
new String[]{id});
if (TextUtils.isEmpty(mimeType)) {
return DOWNLOAD_TYPE;
} else {
return mimeType;
}
}
default: {
if (Constants.LOGV) {
Log.v(Constants.TAG, "calling getType on an unknown URI: " + uri);
}
throw new IllegalArgumentException("Unknown URI: " + uri);
}
}
}
/**
* Inserts a row in the database
*/
@Override
public Uri insert(final Uri uri, final ContentValues values) {
checkInsertPermissions(values);
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
// note we disallow inserting into ALL_DOWNLOADS
int match = sURIMatcher.match(uri);
if (match != MY_DOWNLOADS) {
Log.d(Constants.TAG, "calling insert on an unknown/invalid URI: " + uri);
throw new IllegalArgumentException("Unknown/Invalid URI " + uri);
}
// copy some of the input values as it
ContentValues filteredValues = new ContentValues();
copyString(Downloads.Impl.COLUMN_URI, values, filteredValues);
copyString(Downloads.Impl.COLUMN_APP_DATA, values, filteredValues);
copyBoolean(Downloads.Impl.COLUMN_NO_INTEGRITY, values, filteredValues);
copyString(Downloads.Impl.COLUMN_FILE_NAME_HINT, values, filteredValues);
copyString(Downloads.Impl.COLUMN_MIME_TYPE, values, filteredValues);
copyBoolean(Downloads.Impl.COLUMN_IS_PUBLIC_API, values, filteredValues);
copyBoolean(Downloads.Impl.COLUMN_IS_TYPE_UPLOAD, values, filteredValues);//ml
copyBoolean(Downloads.Impl.COLUMN_IS_USING_TOR, values, filteredValues);
boolean isPublicApi =
values.getAsBoolean(Downloads.Impl.COLUMN_IS_PUBLIC_API) == Boolean.TRUE;
// validate the destination column
Integer dest = values.getAsInteger(Downloads.Impl.COLUMN_DESTINATION);
if (dest != null) {
if (getContext().checkCallingPermission(Downloads.Impl.PERMISSION_ACCESS_ADVANCED)
!= PackageManager.PERMISSION_GRANTED
&& (dest == Downloads.Impl.DESTINATION_CACHE_PARTITION
|| dest == Downloads.Impl.DESTINATION_CACHE_PARTITION_NOROAMING
|| dest == Downloads.Impl.DESTINATION_SYSTEMCACHE_PARTITION)) {
throw new SecurityException("setting destination to : " + dest +
" not allowed, unless PERMISSION_ACCESS_ADVANCED is granted");
}
// for public API behavior, if an app has CACHE_NON_PURGEABLE permission, automatically
// switch to non-purgeable transfer
boolean hasNonPurgeablePermission =
getContext().checkCallingPermission(
Downloads.Impl.PERMISSION_CACHE_NON_PURGEABLE)
== PackageManager.PERMISSION_GRANTED;
if (isPublicApi && dest == Downloads.Impl.DESTINATION_CACHE_PARTITION_PURGEABLE
&& hasNonPurgeablePermission) {
dest = Downloads.Impl.DESTINATION_CACHE_PARTITION;
}
if (dest == Downloads.Impl.DESTINATION_FILE_URI) {
getContext().enforcePermission(
android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
Binder.getCallingPid(), Binder.getCallingUid(),
"need WRITE_EXTERNAL_STORAGE permission to use DESTINATION_FILE_URI");
checkFileUriDestination(values);
} else if (dest == Downloads.Impl.DESTINATION_SYSTEMCACHE_PARTITION) {
getContext().enforcePermission(
android.Manifest.permission.ACCESS_CACHE_FILESYSTEM,
Binder.getCallingPid(), Binder.getCallingUid(),
"need ACCESS_CACHE_FILESYSTEM permission to use system cache");
}
filteredValues.put(Downloads.Impl.COLUMN_DESTINATION, dest);
}
// validate the visibility column
Integer vis = values.getAsInteger(Downloads.Impl.COLUMN_VISIBILITY);
if (vis == null) {
if (dest == Downloads.Impl.DESTINATION_EXTERNAL) {
filteredValues.put(Downloads.Impl.COLUMN_VISIBILITY,
Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
} else {
filteredValues.put(Downloads.Impl.COLUMN_VISIBILITY,
Downloads.Impl.VISIBILITY_HIDDEN);
}
} else {
filteredValues.put(Downloads.Impl.COLUMN_VISIBILITY, vis);
}
// copy the control column as is
copyInteger(Downloads.Impl.COLUMN_CONTROL, values, filteredValues);
/*
* requests coming from
* TransferManager.addCompletedTransfer(String, String, String,
* boolean, String, String, long) need special treatment
*/
if (values.getAsInteger(Downloads.Impl.COLUMN_DESTINATION) ==
Downloads.Impl.DESTINATION_NON_DOWNLOADMANAGER_DOWNLOAD) {
// these requests always are marked as 'completed'
filteredValues.put(Downloads.Impl.COLUMN_STATUS, Downloads.Impl.STATUS_SUCCESS);
filteredValues.put(Downloads.Impl.COLUMN_TOTAL_BYTES,
values.getAsLong(Downloads.Impl.COLUMN_TOTAL_BYTES));
filteredValues.put(Downloads.Impl.COLUMN_CURRENT_BYTES, 0);
copyInteger(Downloads.Impl.COLUMN_MEDIA_SCANNED, values, filteredValues);
copyString(Downloads.Impl._DATA, values, filteredValues);
copyBoolean(Downloads.Impl.COLUMN_ALLOW_WRITE, values, filteredValues);
} else {
filteredValues.put(Downloads.Impl.COLUMN_STATUS, Downloads.Impl.STATUS_PENDING);
filteredValues.put(Downloads.Impl.COLUMN_TOTAL_BYTES, -1);
filteredValues.put(Downloads.Impl.COLUMN_CURRENT_BYTES, 0);
}
// set lastupdate to current time
long lastMod = mSystemFacade.currentTimeMillis();
filteredValues.put(Downloads.Impl.COLUMN_LAST_MODIFICATION, lastMod);
// use packagename of the caller to set the notification columns
String pckg = values.getAsString(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE);
String clazz = values.getAsString(Downloads.Impl.COLUMN_NOTIFICATION_CLASS);
if (pckg != null && (clazz != null || isPublicApi)) {
int uid = Binder.getCallingUid();
try {
if (uid == 0 || mSystemFacade.userOwnsPackage(uid, pckg)) {
filteredValues.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE, pckg);
if (clazz != null) {
filteredValues.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS, clazz);
}
}
} catch (PackageManager.NameNotFoundException ex) {
/* ignored for now */
}
}
// copy some more columns as is
copyString(Downloads.Impl.COLUMN_NOTIFICATION_EXTRAS, values, filteredValues);
copyString(Downloads.Impl.COLUMN_COOKIE_DATA, values, filteredValues);
copyString(Downloads.Impl.COLUMN_USER_AGENT, values, filteredValues);
copyString(Downloads.Impl.COLUMN_REFERER, values, filteredValues);
// UID, PID columns
if (getContext().checkCallingPermission(Downloads.Impl.PERMISSION_ACCESS_ADVANCED)
== PackageManager.PERMISSION_GRANTED) {
copyInteger(Downloads.Impl.COLUMN_OTHER_UID, values, filteredValues);
}
filteredValues.put(Constants.UID, Binder.getCallingUid());
if (Binder.getCallingUid() == 0) {
copyInteger(Constants.UID, values, filteredValues);
}
// copy some more columns as is
copyStringWithDefault(Downloads.Impl.COLUMN_TITLE, values, filteredValues, "");
copyStringWithDefault(Downloads.Impl.COLUMN_DESCRIPTION, values, filteredValues, "");
// is_visible_in_transfers_ui column
if (values.containsKey(Downloads.Impl.COLUMN_IS_VISIBLE_IN_DOWNLOADS_UI)) {
copyBoolean(Downloads.Impl.COLUMN_IS_VISIBLE_IN_DOWNLOADS_UI, values, filteredValues);
} else {
// by default, make external transfers visible in the UI
boolean isExternal = (dest == null || dest == Downloads.Impl.DESTINATION_EXTERNAL);
filteredValues.put(Downloads.Impl.COLUMN_IS_VISIBLE_IN_DOWNLOADS_UI, isExternal);
}
// public api requests and networktypes/roaming columns
if (isPublicApi) {
copyInteger(Downloads.Impl.COLUMN_ALLOWED_NETWORK_TYPES, values, filteredValues);
copyBoolean(Downloads.Impl.COLUMN_ALLOW_ROAMING, values, filteredValues);
copyBoolean(Downloads.Impl.COLUMN_ALLOW_METERED, values, filteredValues);
}
if (Constants.LOGVV) {
Log.v(Constants.TAG, "initiating transfer with UID "
+ filteredValues.getAsInteger(Constants.UID));
if (filteredValues.containsKey(Downloads.Impl.COLUMN_OTHER_UID)) {
Log.v(Constants.TAG, "other UID " +
filteredValues.getAsInteger(Downloads.Impl.COLUMN_OTHER_UID));
}
}
long rowID = db.insert(DB_TABLE, null, filteredValues);
if (rowID == -1) {
Log.d(Constants.TAG, "couldn't insert into transfers database");
return null;
}
insertRequestHeaders(db, rowID, values);
notifyContentChanged(uri, match);
// Always start service to handle notifications and/or scanning
final Context context = getContext();
context.startService(new Intent(context, TransferService.class));
return ContentUris.withAppendedId(Downloads.Impl.CONTENT_URI, rowID);
}
/**
* Check that the file URI provided for DESTINATION_FILE_URI is valid.
*/
private void checkFileUriDestination(ContentValues values) {
String fileUri = values.getAsString(Downloads.Impl.COLUMN_FILE_NAME_HINT);
if (fileUri == null) {
throw new IllegalArgumentException(
"DESTINATION_FILE_URI must include a file URI under COLUMN_FILE_NAME_HINT");
}
Uri uri = Uri.parse(fileUri);
String scheme = uri.getScheme();
if (scheme == null || !scheme.equals("file")) {
throw new IllegalArgumentException("Not a file URI: " + uri);
}
final String path = uri.getPath();
if (path == null) {
throw new IllegalArgumentException("Invalid file URI: " + uri);
}
try {
final String canonicalPath = new File(path).getCanonicalPath();
final String externalPath = Environment.getExternalStorageDirectory().getAbsolutePath();
if (!canonicalPath.startsWith(externalPath)) {
throw new SecurityException("Destination must be on external storage: " + uri);
}
} catch (IOException e) {
throw new SecurityException("Problem resolving path: " + uri);
}
}
/**
* Apps with the ACCESS_DOWNLOAD_MANAGER permission can access this provider freely, subject to
* constraints in the rest of the code. Apps without that may still access this provider through
* the public API, but additional restrictions are imposed. We check those restrictions here.
*
* @param values ContentValues provided to insert()
* @throws SecurityException if the caller has insufficient permissions
*/
private void checkInsertPermissions(ContentValues values) {
if (getContext().checkCallingOrSelfPermission(Downloads.Impl.PERMISSION_ACCESS)
== PackageManager.PERMISSION_GRANTED) {
return;
}
getContext().enforceCallingOrSelfPermission(android.Manifest.permission.INTERNET,
"INTERNET permission is required to use the transfer manager");
// ensure the request fits within the bounds of a public API request
// first copy so we can remove values
values = new ContentValues(values);
// check columns whose values are restricted
enforceAllowedValues(values, Downloads.Impl.COLUMN_IS_PUBLIC_API, Boolean.TRUE);
// validate the destination column
if (values.getAsInteger(Downloads.Impl.COLUMN_DESTINATION) ==
Downloads.Impl.DESTINATION_NON_DOWNLOADMANAGER_DOWNLOAD) {
/* this row is inserted by
* TransferManager.addCompletedTransfer(String, String, String,
* boolean, String, String, long)
*/
values.remove(Downloads.Impl.COLUMN_TOTAL_BYTES);
values.remove(Downloads.Impl._DATA);
values.remove(Downloads.Impl.COLUMN_STATUS);
}
enforceAllowedValues(values, Downloads.Impl.COLUMN_DESTINATION,
Downloads.Impl.DESTINATION_CACHE_PARTITION_PURGEABLE,
Downloads.Impl.DESTINATION_FILE_URI,
Downloads.Impl.DESTINATION_NON_DOWNLOADMANAGER_DOWNLOAD);
if (getContext().checkCallingOrSelfPermission(Downloads.Impl.PERMISSION_NO_NOTIFICATION)
== PackageManager.PERMISSION_GRANTED) {
enforceAllowedValues(values, Downloads.Impl.COLUMN_VISIBILITY,
Request.VISIBILITY_HIDDEN,
Request.VISIBILITY_VISIBLE,
Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED,
Request.VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION);
} else {
enforceAllowedValues(values, Downloads.Impl.COLUMN_VISIBILITY,
Request.VISIBILITY_VISIBLE,
Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED,
Request.VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION);
}
// remove the rest of the columns that are allowed (with any value)
values.remove(Downloads.Impl.COLUMN_URI);
values.remove(Downloads.Impl.COLUMN_TITLE);
values.remove(Downloads.Impl.COLUMN_DESCRIPTION);
values.remove(Downloads.Impl.COLUMN_MIME_TYPE);
values.remove(Downloads.Impl.COLUMN_FILE_NAME_HINT); // checked later in insert()
values.remove(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE); // checked later in insert()
values.remove(Downloads.Impl.COLUMN_ALLOWED_NETWORK_TYPES);
values.remove(Downloads.Impl.COLUMN_ALLOW_ROAMING);
values.remove(Downloads.Impl.COLUMN_ALLOW_METERED);
values.remove(Downloads.Impl.COLUMN_IS_VISIBLE_IN_DOWNLOADS_UI);
values.remove(Downloads.Impl.COLUMN_MEDIA_SCANNED);
values.remove(Downloads.Impl.COLUMN_ALLOW_WRITE);
values.remove(Downloads.Impl.COLUMN_IS_TYPE_UPLOAD);//ml
values.remove(Downloads.Impl.COLUMN_IS_USING_TOR);
Iterator<Map.Entry<String, Object>> iterator = values.valueSet().iterator();
while (iterator.hasNext()) {
String key = iterator.next().getKey();
if (key.startsWith(Downloads.Impl.RequestHeaders.INSERT_KEY_PREFIX)) {
iterator.remove();
}
}
// any extra columns are extraneous and disallowed
if (values.size() > 0) {
StringBuilder error = new StringBuilder("Invalid columns in request: ");
boolean first = true;
for (Map.Entry<String, Object> entry : values.valueSet()) {
if (!first) {
error.append(", ");
}
error.append(entry.getKey());
}
throw new SecurityException(error.toString());
}
}
/**
* Remove column from values, and throw a SecurityException if the value isn't within the
* specified allowedValues.
*/
private void enforceAllowedValues(ContentValues values, String column,
Object... allowedValues) {
Object value = values.get(column);
values.remove(column);
for (Object allowedValue : allowedValues) {
if (value == null && allowedValue == null) {
return;
}
if (value != null && value.equals(allowedValue)) {
return;
}
}
throw new SecurityException("Invalid value for " + column + ": " + value);
}
/**
* Starts a database query
*/
@Override
public Cursor query(final Uri uri, String[] projection,
final String selection, final String[] selectionArgs,
final String sort) {
Helpers.validateSelection(selection, sAppReadableColumnsSet);
SQLiteDatabase db = mOpenHelper.getReadableDatabase();
int match = sURIMatcher.match(uri);
if (match == -1) {
if (Constants.LOGV) {
Log.v(Constants.TAG, "querying unknown URI: " + uri);
}
throw new IllegalArgumentException("Unknown URI: " + uri);
}
if (match == REQUEST_HEADERS_URI) {
if (projection != null || selection != null || sort != null) {
throw new UnsupportedOperationException("Request header queries do not support "
+ "projections, selections or sorting");
}
return queryRequestHeaders(db, uri);
}
SqlSelection fullSelection = getWhereClause(uri, selection, selectionArgs, match);
if (shouldRestrictVisibility()) {
if (projection == null) {
projection = sAppReadableColumnsArray.clone();
} else {
// check the validity of the columns in projection
for (int i = 0; i < projection.length; ++i) {
if (!sAppReadableColumnsSet.contains(projection[i]) &&
!transferManagerColumnsList.contains(projection[i])) {
throw new IllegalArgumentException(
"column " + projection[i] + " is not allowed in queries");
}
}
}
for (int i = 0; i < projection.length; i++) {
final String newColumn = sColumnsMap.get(projection[i]);
if (newColumn != null) {
projection[i] = newColumn;
}
}
}
if (Constants.LOGVV) {
logVerboseQueryInfo(projection, selection, selectionArgs, sort, db);
}
Cursor ret = db.query(DB_TABLE, projection, fullSelection.getSelection(),
fullSelection.getParameters(), null, null, sort);
if (ret != null) {
ret.setNotificationUri(getContext().getContentResolver(), uri);
if (Constants.LOGVV) {
Log.v(Constants.TAG,
"created cursor " + ret + " on behalf of " + Binder.getCallingPid());
}
} else {
if (Constants.LOGV) {
Log.v(Constants.TAG, "query failed in transfers database");
}
}
return ret;
}
private void logVerboseQueryInfo(String[] projection, final String selection,
final String[] selectionArgs, final String sort, SQLiteDatabase db) {
java.lang.StringBuilder sb = new java.lang.StringBuilder();
sb.append("starting query, database is ");
if (db != null) {
sb.append("not ");
}
sb.append("null; ");
if (projection == null) {
sb.append("projection is null; ");
} else if (projection.length == 0) {
sb.append("projection is empty; ");
} else {
for (int i = 0; i < projection.length; ++i) {
sb.append("projection[");
sb.append(i);
sb.append("] is ");
sb.append(projection[i]);
sb.append("; ");
}
}
sb.append("selection is ");
sb.append(selection);
sb.append("; ");
if (selectionArgs == null) {
sb.append("selectionArgs is null; ");
} else if (selectionArgs.length == 0) {
sb.append("selectionArgs is empty; ");
} else {
for (int i = 0; i < selectionArgs.length; ++i) {
sb.append("selectionArgs[");
sb.append(i);
sb.append("] is ");
sb.append(selectionArgs[i]);
sb.append("; ");
}
}
sb.append("sort is ");
sb.append(sort);
sb.append(".");
Log.v(Constants.TAG, sb.toString());
}
private String getTransferIdFromUri(final Uri uri) {
return uri.getPathSegments().get(1);
}
/**
* Insert request headers for a transfer into the DB.
*/
private void insertRequestHeaders(SQLiteDatabase db, long transferId, ContentValues values) {
ContentValues rowValues = new ContentValues();
rowValues.put(Downloads.Impl.RequestHeaders.COLUMN_DOWNLOAD_ID, transferId);
for (Map.Entry<String, Object> entry : values.valueSet()) {
String key = entry.getKey();
if (key.startsWith(Downloads.Impl.RequestHeaders.INSERT_KEY_PREFIX)) {
String headerLine = entry.getValue().toString();
if (!headerLine.contains(":")) {
throw new IllegalArgumentException("Invalid HTTP header line: " + headerLine);
}
String[] parts = headerLine.split(":", 2);
rowValues.put(Downloads.Impl.RequestHeaders.COLUMN_HEADER, parts[0].trim());
rowValues.put(Downloads.Impl.RequestHeaders.COLUMN_VALUE, parts[1].trim());
db.insert(Downloads.Impl.RequestHeaders.HEADERS_DB_TABLE, null, rowValues);
}
}
}
/**
* Handle a query for the custom request headers registered for a transfer.
*/
private Cursor queryRequestHeaders(SQLiteDatabase db, Uri uri) {
String where = Downloads.Impl.RequestHeaders.COLUMN_DOWNLOAD_ID + "="
+ getTransferIdFromUri(uri);
String[] projection = new String[] {Downloads.Impl.RequestHeaders.COLUMN_HEADER,
Downloads.Impl.RequestHeaders.COLUMN_VALUE};
return db.query(Downloads.Impl.RequestHeaders.HEADERS_DB_TABLE, projection, where,
null, null, null, null);
}
/**
* Delete request headers for transfers matching the given query.
*/
private void deleteRequestHeaders(SQLiteDatabase db, String where, String[] whereArgs) {
String[] projection = new String[] {Downloads.Impl._ID};
Cursor cursor = db.query(DB_TABLE, projection, where, whereArgs, null, null, null, null);
try {
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
long id = cursor.getLong(0);
String idWhere = Downloads.Impl.RequestHeaders.COLUMN_DOWNLOAD_ID + "=" + id;
db.delete(Downloads.Impl.RequestHeaders.HEADERS_DB_TABLE, idWhere, null);
}
} finally {
cursor.close();
}
}
/**
* @return true if we should restrict the columns readable by this caller
*/
private boolean shouldRestrictVisibility() {
int callingUid = Binder.getCallingUid();
return Binder.getCallingPid() != Process.myPid() &&
callingUid != mSystemUid &&
callingUid != mDefContainerUid;
}
/**
* Updates a row in the database
*/
@Override
public int update(final Uri uri, final ContentValues values,
final String where, final String[] whereArgs) {
Helpers.validateSelection(where, sAppReadableColumnsSet);
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
int count;
boolean startService = false;
if (values.containsKey(Downloads.Impl.COLUMN_DELETED)) {
if (values.getAsInteger(Downloads.Impl.COLUMN_DELETED) == 1) {
// some rows are to be 'deleted'. need to start TransferService.
startService = true;
}
}
ContentValues filteredValues;
if (Binder.getCallingPid() != Process.myPid()) {
filteredValues = new ContentValues();
copyString(Downloads.Impl.COLUMN_APP_DATA, values, filteredValues);
copyInteger(Downloads.Impl.COLUMN_VISIBILITY, values, filteredValues);
Integer i = values.getAsInteger(Downloads.Impl.COLUMN_CONTROL);
if (i != null) {
filteredValues.put(Downloads.Impl.COLUMN_CONTROL, i);
startService = true;
}
copyInteger(Downloads.Impl.COLUMN_CONTROL, values, filteredValues);
copyString(Downloads.Impl.COLUMN_TITLE, values, filteredValues);
copyString(Downloads.Impl.COLUMN_MEDIAPROVIDER_URI, values, filteredValues);
copyString(Downloads.Impl.COLUMN_DESCRIPTION, values, filteredValues);
copyInteger(Downloads.Impl.COLUMN_DELETED, values, filteredValues);
copyBoolean(Downloads.Impl.COLUMN_IS_TYPE_UPLOAD, values, filteredValues);//ml
copyBoolean(Downloads.Impl.COLUMN_IS_USING_TOR, values, filteredValues);
} else {
filteredValues = values;
String filename = values.getAsString(Downloads.Impl._DATA);
if (filename != null) {
Cursor c = query(uri, new String[]
{ Downloads.Impl.COLUMN_TITLE }, null, null, null);
if (!c.moveToFirst() || c.getString(0).isEmpty()) {
values.put(Downloads.Impl.COLUMN_TITLE, new File(filename).getName());
}
c.close();
}
Integer status = values.getAsInteger(Downloads.Impl.COLUMN_STATUS);
boolean isRestart = status != null && status == Downloads.Impl.STATUS_PENDING;
boolean isUserBypassingSizeLimit =
values.containsKey(Downloads.Impl.COLUMN_BYPASS_RECOMMENDED_SIZE_LIMIT);
if (isRestart || isUserBypassingSizeLimit) {
startService = true;
}
}
int match = sURIMatcher.match(uri);
switch (match) {
case MY_DOWNLOADS:
case MY_DOWNLOADS_ID:
case ALL_DOWNLOADS:
case ALL_DOWNLOADS_ID:
SqlSelection selection = getWhereClause(uri, where, whereArgs, match);
if (filteredValues.size() > 0) {
count = db.update(DB_TABLE, filteredValues, selection.getSelection(),
selection.getParameters());
} else {
count = 0;
}
break;
default:
Log.d(Constants.TAG, "updating unknown/invalid URI: " + uri);
throw new UnsupportedOperationException("Cannot update URI: " + uri);
}
notifyContentChanged(uri, match);
if (startService) {
Context context = getContext();
context.startService(new Intent(context, TransferService.class));
}
return count;
}
/**
* Notify of a change through both URIs (/my_transfers and /all_transfers)
* @param uri either URI for the changed transfer(s)
* @param uriMatch the match ID from {@link #sURIMatcher}
*/
private void notifyContentChanged(final Uri uri, int uriMatch) {
Long transferId = null;
if (uriMatch == MY_DOWNLOADS_ID || uriMatch == ALL_DOWNLOADS_ID) {
transferId = Long.parseLong(getTransferIdFromUri(uri));
}
for (Uri uriToNotify : BASE_URIS) {
if (transferId != null) {
uriToNotify = ContentUris.withAppendedId(uriToNotify, transferId);
}
getContext().getContentResolver().notifyChange(uriToNotify, null);
}
}
private SqlSelection getWhereClause(final Uri uri, final String where, final String[] whereArgs,
int uriMatch) {
SqlSelection selection = new SqlSelection();
selection.appendClause(where, whereArgs);
if (uriMatch == MY_DOWNLOADS_ID || uriMatch == ALL_DOWNLOADS_ID ||
uriMatch == PUBLIC_DOWNLOAD_ID) {
selection.appendClause(Downloads.Impl._ID + " = ?", getTransferIdFromUri(uri));
}
if ((uriMatch == MY_DOWNLOADS || uriMatch == MY_DOWNLOADS_ID)
&& getContext().checkCallingPermission(Downloads.Impl.PERMISSION_ACCESS_ALL)
!= PackageManager.PERMISSION_GRANTED) {
selection.appendClause(
Constants.UID + "= ? OR " + Downloads.Impl.COLUMN_OTHER_UID + "= ?",
Binder.getCallingUid(), Binder.getCallingUid());
}
return selection;
}
/**
* Deletes a row in the database
*/
@Override
public int delete(final Uri uri, final String where,
final String[] whereArgs) {
Helpers.validateSelection(where, sAppReadableColumnsSet);
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
int count;
int match = sURIMatcher.match(uri);
switch (match) {
case MY_DOWNLOADS:
case MY_DOWNLOADS_ID:
case ALL_DOWNLOADS:
case ALL_DOWNLOADS_ID:
SqlSelection selection = getWhereClause(uri, where, whereArgs, match);
deleteRequestHeaders(db, selection.getSelection(), selection.getParameters());
final Cursor cursor = db.query(DB_TABLE, new String[] {
Downloads.Impl._ID }, selection.getSelection(), selection.getParameters(),
null, null, null);
try {
while (cursor.moveToNext()) {
final long id = cursor.getLong(0);
TransferStorageProvider.onTransferProviderDelete(getContext(), id);
}
} finally {
IoUtils.closeQuietly(cursor);
}
count = db.delete(DB_TABLE, selection.getSelection(), selection.getParameters());
break;
default:
Log.d(Constants.TAG, "deleting unknown/invalid URI: " + uri);
throw new UnsupportedOperationException("Cannot delete URI: " + uri);
}
notifyContentChanged(uri, match);
return count;
}
/**
* Remotely opens a file
*/
@Override
public ParcelFileDescriptor openFile(final Uri uri, String mode) throws FileNotFoundException {
if (Constants.LOGVV) {
logVerboseOpenFileInfo(uri, mode);
}
final Cursor cursor = query(uri, new String[] { Downloads.Impl._DATA }, null, null, null);
String path;
try {
int count = (cursor != null) ? cursor.getCount() : 0;
if (count != 1) {
// If there is not exactly one result, throw an appropriate exception.
if (count == 0) {
throw new FileNotFoundException("No entry for " + uri);
}
throw new FileNotFoundException("Multiple items at " + uri);
}
cursor.moveToFirst();
path = cursor.getString(0);
} finally {
IoUtils.closeQuietly(cursor);
}
if (path == null) {
throw new FileNotFoundException("No filename found.");
}
if (!Helpers.isFilenameValid(path, mDownloadsDataDir)) {
throw new FileNotFoundException("Invalid filename: " + path);
}
final File file = new File(path);
if ("r".equals(mode)) {
return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
} else {
try {
// When finished writing, update size and timestamp
return ParcelFileDescriptor.open(file, ParcelFileDescriptor.parseMode(mode),
mHandler, new OnCloseListener() {
@Override
public void onClose(IOException e) {
final ContentValues values = new ContentValues();
values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, file.length());
values.put(Downloads.Impl.COLUMN_LAST_MODIFICATION,
System.currentTimeMillis());
update(uri, values, null, null);
}
});
} catch (IOException e) {
throw new FileNotFoundException("Failed to open for writing: " + e);
}
}
}
@Override
public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ", 120);
pw.println("Downloads updated in last hour:");
pw.increaseIndent();
final SQLiteDatabase db = mOpenHelper.getReadableDatabase();
final long modifiedAfter = mSystemFacade.currentTimeMillis() - DateUtils.HOUR_IN_MILLIS;
final Cursor cursor = db.query(DB_TABLE, null,
Downloads.Impl.COLUMN_LAST_MODIFICATION + ">" + modifiedAfter, null, null, null,
Downloads.Impl._ID + " ASC");
try {
final String[] cols = cursor.getColumnNames();
final int idCol = cursor.getColumnIndex(BaseColumns._ID);
while (cursor.moveToNext()) {
pw.println("Transfer #" + cursor.getInt(idCol) + ":");
pw.increaseIndent();
for (int i = 0; i < cols.length; i++) {
// Omit sensitive data when dumping
if (Downloads.Impl.COLUMN_COOKIE_DATA.equals(cols[i])) {
continue;
}
pw.printPair(cols[i], cursor.getString(i));
}
pw.println();
pw.decreaseIndent();
}
} finally {
cursor.close();
}
pw.decreaseIndent();
}
private void logVerboseOpenFileInfo(Uri uri, String mode) {
Log.v(Constants.TAG, "openFile uri: " + uri + ", mode: " + mode
+ ", uid: " + Binder.getCallingUid());
Cursor cursor = query(Downloads.Impl.CONTENT_URI,
new String[] { "_id" }, null, null, "_id");
if (cursor == null) {
Log.v(Constants.TAG, "null cursor in openFile");
} else {
if (!cursor.moveToFirst()) {
Log.v(Constants.TAG, "empty cursor in openFile");
} else {
do {
Log.v(Constants.TAG, "row " + cursor.getInt(0) + " available");
} while(cursor.moveToNext());
}
cursor.close();
}
cursor = query(uri, new String[] { "_data" }, null, null, null);
if (cursor == null) {
Log.v(Constants.TAG, "null cursor in openFile");
} else {
if (!cursor.moveToFirst()) {
Log.v(Constants.TAG, "empty cursor in openFile");
} else {
String filename = cursor.getString(0);
Log.v(Constants.TAG, "filename in openFile: " + filename);
if (new java.io.File(filename).isFile()) {
Log.v(Constants.TAG, "file exists in openFile");
}
}
cursor.close();
}
}
private static final void copyInteger(String key, ContentValues from, ContentValues to) {
Integer i = from.getAsInteger(key);
if (i != null) {
to.put(key, i);
}
}
private static final void copyBoolean(String key, ContentValues from, ContentValues to) {
Boolean b = from.getAsBoolean(key);
if (b != null) {
to.put(key, b);
}
}
private static final void copyString(String key, ContentValues from, ContentValues to) {
String s = from.getAsString(key);
if (s != null) {
to.put(key, s);
}
}
private static final void copyStringWithDefault(String key, ContentValues from,
ContentValues to, String defaultValue) {
copyString(key, from, to);
if (!to.containsKey(key)) {
to.put(key, defaultValue);
}
}
}
|
|
/*
* $Id$
* This file is a part of the Arakhne Foundation Classes, http://www.arakhne.org/afc
*
* Copyright (c) 2000-2012 Stephane GALLAND.
* Copyright (c) 2005-10, Multiagent Team, Laboratoire Systemes et Transports,
* Universite de Technologie de Belfort-Montbeliard.
* Copyright (c) 2013-2016 The original authors, and other 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.arakhne.afc.ui.vector.android;
import java.io.IOError;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import org.arakhne.afc.math.continous.object2d.Shape2f;
import org.arakhne.afc.math.matrix.Transform2D;
import org.arakhne.afc.ui.vector.Color;
import org.arakhne.afc.ui.vector.Composite;
import org.arakhne.afc.ui.vector.Dimension;
import org.arakhne.afc.ui.vector.Font;
import org.arakhne.afc.ui.vector.FontMetrics;
import org.arakhne.afc.ui.vector.FontStyle;
import org.arakhne.afc.ui.vector.Image;
import org.arakhne.afc.ui.vector.Margins;
import org.arakhne.afc.ui.vector.Stroke;
import org.arakhne.afc.ui.vector.Stroke.EndCap;
import org.arakhne.afc.ui.vector.Stroke.LineJoin;
import org.arakhne.afc.ui.vector.VectorGraphics2D;
import org.arakhne.afc.ui.vector.VectorToolkit;
import org.arakhne.afc.vmutil.OperatingSystem;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
/** Android implementation of the generic Window toolkit.
*
* @author $Author: sgalland$
* @version $FullVersion$
* @mavengroupid $GroupId$
* @mavenartifactid $ArtifactId$
* @deprecated see JavaFX API
*/
@Deprecated
public class AndroidVectorToolkit extends VectorToolkit {
/**
*/
public AndroidVectorToolkit() {
//
}
@Override
protected boolean isSupported() {
return OperatingSystem.ANDROID.isCurrentOS();
}
@Override
protected void postDrawing(VectorGraphics2D context) {
// do not call super function to avoid to reset the current context.
}
@Override
protected <T> T toNativeUIObject(Class<T> type, Object o) {
if (o instanceof NativeWrapper) {
return ((NativeWrapper)o).getNativeObject(type);
}
return type.cast(o);
}
@Override
protected Shape2f createShape(Object nativeObject) {
throw new UnsupportedOperationException();
}
@Override
protected Transform2D createTransform(Object affineTransform) {
if (affineTransform==null) return null;
Matrix matrix = (Matrix)affineTransform;
float[] values = new float[9];
matrix.getValues(values);
return new Transform2D(
values[0], values[1], values[2],
values[3], values[4], values[5]);
}
@Override
protected Dimension createDimension(float width, float height) {
return new AndroidDimension(width, height);
}
@Override
protected Margins createMargins(float top, float left, float right,
float bottom) {
return new AndroidMargins(top, left, right, bottom);
}
@Override
protected Composite createComposite(Object compositeObject) {
if (compositeObject==null) return null;
return new AndroidComposite((Paint)compositeObject);
}
@Override
protected Composite createComposite(float alpha) {
return new AndroidComposite(alpha);
}
@Override
protected org.arakhne.afc.ui.vector.Paint createPaint(Object paintObject) {
return new AndroidPaint((Paint)paintObject);
}
@Override
protected Font createFont(String name, FontStyle style, float size) {
return AndroidPaint.getFont(name, style, size, getCurrentDrawingContext());
}
@Override
protected Font createFont(Object fontObject) {
if (fontObject==null) return null;
return new AndroidPaint((android.graphics.Paint)fontObject);
}
@Override
protected Font getDefaultFont() {
return AndroidPaint.getDefaultFont();
}
@Override
protected FontMetrics createFontMetrics(Object metricsObject) {
if (metricsObject==null) return null;
return new AndroidPaint((android.graphics.Paint)metricsObject);
}
@Override
protected FontMetrics createFontMetrics(Font font) {
if (font instanceof FontMetrics)
return (FontMetrics)font;
return new AndroidPaint(toNativeUIObject(Paint.class, font));
}
@Override
protected Image createImage(URL url) {
if (url==null) return null;
try {
return createImage(url.openStream());
}
catch (IOException e) {
throw new IOError(e);
}
}
@Override
protected Image createImage(InputStream stream) {
if (stream==null) return null;
AndroidImage img = new AndroidImage(stream);
if (img.getBitmap()==null) return null;
return img;
}
@Override
protected Image createImage(int width, int height, boolean isAlpha) {
AndroidImage img = new AndroidImage(width, height, isAlpha);
if (img.getBitmap()==null) return null;
return img;
}
@Override
protected Image createImage(Object imageObject) {
if (imageObject==null) return null;
AndroidImage img = new AndroidImage((Bitmap)imageObject);
if (img.getBitmap()==null) return null;
return img;
}
@Override
protected Image createTransparentImage(Image imageObject, float transparency) {
if (imageObject==null) return null;
Bitmap aImg = toNativeUIObject(Bitmap.class, imageObject);
Bitmap mutableBitmap = aImg.copy(Bitmap.Config.ARGB_8888, true);
Canvas canvas = new Canvas(mutableBitmap);
float t = 255f*(transparency+1f)/2f;
int colour = ((int)t & 0xFF) << 24;
canvas.drawColor(colour, PorterDuff.Mode.DST_OUT);
return new AndroidImage(mutableBitmap);
}
@Override
protected Image makeTransparentImage(Image imageObject, float transparency) {
if (imageObject==null) return null;
Bitmap aImg = toNativeUIObject(Bitmap.class, imageObject);
Bitmap mutableBitmap = aImg.isMutable() ?
aImg : aImg.copy(Bitmap.Config.ARGB_8888, true);
Canvas canvas = new Canvas(mutableBitmap);
float t = 255f*(transparency+1f)/2f;
int colour = ((int)t & 0xFF) << 24;
canvas.drawColor(colour, PorterDuff.Mode.DST_OUT);
return new AndroidImage(mutableBitmap);
}
@Override
protected void write(Image image, String type, OutputStream stream)
throws IOException {
String lt = type.toLowerCase();
Bitmap aImg = toNativeUIObject(Bitmap.class, image);
CompressFormat format;
if (lt.equals("png")) {
format = CompressFormat.PNG;
}
else if (lt.equals("jpeg") || lt.equals("jpg")) {
format = CompressFormat.JPEG;
}
else if (lt.equals("webp")) {
format = CompressFormat.WEBP;
}
else {
throw new IOException("Unsupported image type: "+type);
}
if (!aImg.compress(format, 100, stream)) {
throw new IOException("Unable to write the Android image for type: "+type);
}
}
@Override
protected Stroke createStroke(float width, LineJoin join, EndCap endCap,
float mitterLimit, float[] dashes, float dashPhase) {
return new AndroidPaint(width, join, endCap, mitterLimit, dashes, dashPhase);
}
@Override
protected Stroke createStroke(Object strokeObject) {
if (strokeObject==null) return null;
return new AndroidPaint((Paint)strokeObject);
}
@Override
protected Color createColor(int red, int green, int blue, int alpha) {
return new AndroidColor(red, green, blue, alpha);
}
@Override
protected Color createColor(Object rawColorObject) {
if (rawColorObject==null) return null;
if (rawColorObject instanceof Drawable) {
return new AndroidColor((Drawable)rawColorObject);
}
return new AndroidColor(((Number)rawColorObject).intValue());
}
@Override
protected <T> T findObjectWithId(int id, Class<T> type) {
Object o = null;
if (id==0) {
o = AndroidPaint.getDefaultFont();
}
if (o!=null && type.isInstance(o)) return type.cast(o);
return null;
}
@Override
protected int HSBtoRGB(float hue, float saturation, float brightness) {
float[] t = new float[] {hue, saturation, brightness};
return android.graphics.Color.HSVToColor(t);
}
@Override
protected Image createColorizedImage(Image imageObject,
Color filtering_color, float alpha) {
if (filtering_color==null || imageObject==null) return imageObject;
Bitmap img = toNativeUIObject(Bitmap.class, imageObject);
Bitmap mutableBitmap = img.copy(Bitmap.Config.ARGB_8888, true);
int[] pixels = new int[mutableBitmap.getHeight()*mutableBitmap.getWidth()];
mutableBitmap.getPixels(pixels, 0, mutableBitmap.getWidth(), 0, 0, mutableBitmap.getWidth(), mutableBitmap.getHeight());
int color_r, color_g, color_b;
for(int i=0; i<pixels.length; ++i) {
color_r = ((pixels[i] >> 16) & 0xff);
color_g = ((pixels[i] >> 8) & 0xff);
color_b = (pixels[i] & 0xff);
color_r = (int)((filtering_color.getRed() + color_r) * alpha);
if (color_r<0) color_r = 0;
if (color_r>255) color_r = 0;
color_g = (int)((filtering_color.getGreen() + color_g) * alpha);
if (color_g<0) color_g = 0;
if (color_g>255) color_g = 0;
color_b = (int)((filtering_color.getBlue() + color_b) * alpha);
if (color_b<0) color_b = 0;
if (color_b>255) color_b = 0;
pixels[i] = (pixels[i] & 0xff000000) | (color_r << 16) | (color_g << 8) | color_b;
}
mutableBitmap.setPixels(pixels, 0, mutableBitmap.getWidth(), 0, 0, mutableBitmap.getWidth(), mutableBitmap.getHeight());
return new AndroidImage(mutableBitmap);
}
@Override
protected Color createSelectionBackground() {
return color(0xFF9ccf00);
}
@Override
protected Color createSelectionForeground() {
return color(0xFF000000);
}
}
|
|
/*
* Copyright 2013-2016 Uncharted Software Inc.
*
* Property of Uncharted(TM), formerly Oculus Info Inc.
* https://uncharted.software/
*
* 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 influent.server.clustering;
import influent.idl.FL_Cluster;
import influent.idl.FL_Entity;
import influent.idl.FL_Geocoding;
import influent.server.clustering.utils.EntityClusterFactory;
import influent.server.clustering.utils.ClustererProperties;
import influent.server.utilities.InfluentId;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import oculus.aperture.spi.common.Properties;
public class GeneralEntityClusterer extends BaseEntityClusterer {
private FL_Geocoding geoCoder;
private EntityClusterFactory clusterFactory;
private Properties pMgr;
private List<EntityClusterer> clusterStages;
private int MAX_CLUSTER_SIZE = 10;
@Override
public void init(Object[] args) {
try {
this.clusterFactory = (EntityClusterFactory)args[0];
this.geoCoder = (FL_Geocoding)args[1];
this.pMgr = (Properties)args[2];
this.MAX_CLUSTER_SIZE = pMgr.getInteger(ClustererProperties.MAX_CLUSTER_SIZE, 10);
this.clusterStages = createClusterStages(pMgr);
}
catch (Exception e) {
throw new IllegalArgumentException("Invalid initialization parameters.", e);
}
}
private List<EntityClusterer> createClusterStages(Properties pMgr) throws Exception{
List<EntityClusterer> clusterStages = new ArrayList<EntityClusterer>();
try {
String[] clusterFields = pMgr.getString(ClustererProperties.CLUSTER_FIELDS, "GEO:geo,TYPE:categorical,LABEL:label").split(",");
for (String field : clusterFields) {
String[] tokens = field.split(":"); // TagOrFieldName, Type, Fuzzy (if label feature)
if (tokens.length > 1) {
String tagOrFieldName = tokens[0];
String type = tokens[1];
if (type.equalsIgnoreCase("categorical")) {
CategoricalEntityClusterer clusterer = new CategoricalEntityClusterer();
Object[] params = {clusterFactory, tagOrFieldName};
clusterer.init(params);
clusterStages.add(clusterer);
}
else if (type.equalsIgnoreCase("label")) {
// first group alphabetically - adjust alpha bucket size based upon max cluster size property
LabelEntityClusterer clusterer = new LabelEntityClusterer();
int bucketSize = Math.max((int)Math.ceil(26.0 / MAX_CLUSTER_SIZE), 1);
Object[] params = {clusterFactory, tagOrFieldName, true, pMgr, bucketSize};
clusterer.init(params);
clusterStages.add(clusterer);
// cluster again by alpha only if bucket size above was greater than 1
if (bucketSize > 1) {
clusterer = new LabelEntityClusterer();
Object[] params2 = {clusterFactory, tagOrFieldName, true, pMgr, 1};
clusterer.init(params2);
clusterStages.add(clusterer);
}
// next cluster by edit distance or finger print
clusterer = new LabelEntityClusterer();
Object[] params3 = {clusterFactory, tagOrFieldName, false, pMgr, MAX_CLUSTER_SIZE};
clusterer.init(params3);
clusterStages.add(clusterer);
}
else if (type.equalsIgnoreCase("geo")) {
GeoEntityClusterer clusterer = new GeoEntityClusterer();
Object[] params = {clusterFactory, tagOrFieldName, geoCoder, GeoEntityClusterer.GEO_LEVEL.Continent};
clusterer.init(params);
clusterStages.add(clusterer);
clusterer = new GeoEntityClusterer();
Object[] params2 = {clusterFactory, tagOrFieldName, geoCoder, GeoEntityClusterer.GEO_LEVEL.Region};
clusterer.init(params2);
clusterStages.add(clusterer);
clusterer = new GeoEntityClusterer();
Object[] params3 = {clusterFactory, tagOrFieldName, geoCoder, GeoEntityClusterer.GEO_LEVEL.Country};
clusterer.init(params3);
clusterStages.add(clusterer);
clusterer = new GeoEntityClusterer();
Object[] params4 = {clusterFactory, tagOrFieldName, geoCoder, GeoEntityClusterer.GEO_LEVEL.LatLon};
clusterer.init(params4);
clusterStages.add(clusterer);
}
else if (type.equalsIgnoreCase("topic")) {
Double k = tokens.length == 3 ? Double.parseDouble(tokens[2]) : 0.5;
TopicEntityClusterer clusterer = new TopicEntityClusterer();
Object[] params = {clusterFactory, tagOrFieldName, k};
clusterer.init(params);
clusterStages.add(clusterer);
}
else if (type.equalsIgnoreCase("numeric")) {
Double k = tokens.length == 3 ? Double.parseDouble(tokens[2]) : 100;
NumericEntityClusterer clusterer = new NumericEntityClusterer();
Object[] params = {clusterFactory, tagOrFieldName, k, MAX_CLUSTER_SIZE};
clusterer.init(params);
clusterStages.add(clusterer);
}
else {
log.error("Invalid cluster field type specified for '{}' in clusterer.properties - verify the value of entity.clusterer.clusterfields", tagOrFieldName);
}
}
else {
log.error("Invalid cluster field '{}' specified in clusterer.properties - verify the value of entity.clusterer.clusterfields", field);
}
}
} catch (Exception e) {
log.error("Invalid cluster field specified in clusterer.properties - verify the value of entity.clusterer.clusterfields");
}
if (clusterStages.isEmpty()) {
log.error("No valid cluster fields have been specified in clusterer.properties");
throw new Exception("No valid cluster fields have been specified in clusterer.properties");
}
// last stage ensures no leaf cluster contains more than max cluster size
MaxSizeEntityClusterer clusterer = new MaxSizeEntityClusterer();
Object[] params = {clusterFactory, MAX_CLUSTER_SIZE};
clusterer.init(params);
clusterStages.add(clusterer);
return clusterStages;
}
private List<FL_Cluster> getSubClusters(FL_Cluster cluster, ClusterContext context) {
List<FL_Cluster> subClusters = new LinkedList<FL_Cluster>();
for (String id : cluster.getSubclusters()) {
subClusters.add( context.clusters.get(id) );
}
return subClusters;
}
@Override
public ClusterContext clusterEntities(Collection<FL_Entity> entities,
Collection<FL_Cluster> immutableClusters,
Collection<FL_Cluster> clusters,
ClusterContext context) {
throw new UnsupportedOperationException();
}
@Override
public ClusterContext clusterEntities(Collection<FL_Entity> entities,
Collection<FL_Cluster> immutableClusters,
ClusterContext context) {
// sanity check that the clusterer has been configured and invoked with valid input
if (clusterStages == null || clusterStages.isEmpty() || context == null) return null;
// filter out immutable root clusters and re-cluster them to avoid being modified
Collection<FL_Cluster> allRoots = context.roots.values();
immutableClusters.addAll( filterImmutableClusters(allRoots) );
List<FL_Cluster> mutableRoots = filterMutableClusters(allRoots);
// first stage generates root objects in entity cluster hierarchy
ClusterContext results = clusterStages.get(0).clusterEntities(entities, immutableClusters, mutableRoots, context);
// add the new/modified roots to the context roots
context.roots.putAll(results.roots);
// keep track of the modified roots - only they need to have their summaries recomputed
Map<String, FL_Cluster> modifiedRoots = new HashMap<String, FL_Cluster>(results.roots);
// find the candidate clusters to split
Collection<FL_Cluster> clustersToSplit = new LinkedList<FL_Cluster>();
findClustersToSplit(results.roots, clustersToSplit);
// add the roots to the allClusters map in context
context.clusters.putAll(results.roots);
// keep track of a repeatable stages results to determine when it no longer is successful at clustering entities
int prevResultCount = 0;
//
// Top down Divisive hierarchical clustering using binning and k-means clustering - each stage clusters by a distinct feature
//
int currentStage = 1;
while (!clustersToSplit.isEmpty()) {
EntityClusterer clusterer = clusterStages.get(currentStage);
Map<String, FL_Cluster> stageResults = new HashMap<String, FL_Cluster>();
for (FL_Cluster cluster : clustersToSplit) {
// sub-cluster the entity cluster
results = clusterer.clusterEntities( getChildEntities(cluster, context, false), getSubClusters(cluster, context), context );
// update the cluster children to be the sub-clustering results
// and update the root and parent of the children
updateClusterReferences(cluster, results.roots);
// store the new/modified clusters in the context
context.clusters.putAll(results.roots);
// schedule the cluster for further splitting on another stage
stageResults.putAll(results.roots);
}
// update the clusters to split for next stage
clustersToSplit.clear();
findClustersToSplit(stageResults, clustersToSplit);
if ( isCompletedStage(currentStage, prevResultCount, stageResults.size()) ) {
currentStage = Math.min(clusterStages.size()-1, ++currentStage); // iterate through stages and stay on last stage until done
prevResultCount = 0; // reset prev result count since we are in a new stage
} else {
prevResultCount = stageResults.size(); // still in the current stage so update the results produced this iteration
}
}
// lastly update the modified clusters summaries
clusterFactory.updateClusterProperties(modifiedRoots, context, true);
// return back the modified context
return context;
}
private boolean isRepeatableStage(int currentStage) {
EntityClusterer clusterer = clusterStages.get(currentStage);
return (clusterer instanceof NumericEntityClusterer || clusterer instanceof LabelEntityClusterer);
}
private boolean isCompletedStage(int currentStage, int prevResultCount, int curResultCount) {
boolean completed = true;
// if the stage is repeatable and we are still producing more clusters than it's not complete
if ( isRepeatableStage(currentStage) && prevResultCount != curResultCount ) {
completed = false;
}
return completed;
}
private boolean isCandidate(FL_Cluster cluster) {
int numEntityMembers = cluster.getMembers().size();
int numMutables = InfluentId.filterInfluentIds(cluster.getSubclusters(), InfluentId.CLUSTER).size();
int numImmutables = numEntityMembers + cluster.getSubclusters().size() - numMutables;
boolean tooLarge = numImmutables > MAX_CLUSTER_SIZE;
boolean nonLeaf = (numImmutables > 0 && numMutables > 0);
boolean immutable = isImmutableCluster(cluster);
return ( !immutable && (tooLarge || nonLeaf) );
}
private void findClustersToSplit(Map<String, FL_Cluster> candidates, Collection<FL_Cluster> splitQueue) {
for (String id : candidates.keySet()) {
FL_Cluster c = candidates.get(id);
if (isCandidate(c)) {
splitQueue.add(c);
}
}
}
private void updateClusterReferences(FL_Cluster cluster, Map<String, FL_Cluster> children) {
List<String> childClusterIds = new LinkedList<String>();
String parentId = cluster.getUid();
String rootId = cluster.getRoot() == null ? parentId : cluster.getRoot();
for (String id : children.keySet()) {
FL_Cluster c = children.get(id);
c.setParent(parentId);
c.setRoot(rootId);
childClusterIds.add(c.getUid());
}
cluster.getMembers().clear();
List<String> mutableSubClusters = InfluentId.filterInfluentIds(cluster.getSubclusters(), InfluentId.CLUSTER);
Set<String> uniqueIds = new HashSet<String>(mutableSubClusters);
uniqueIds.addAll(childClusterIds);
cluster.setSubclusters(new LinkedList<String>(uniqueIds));
}
}
|
|
package de.geeksfactory.opacclient.networking;
//Based on
//http://stackoverflow.com/a/6378872/336784
//and
//http://download.oracle.com/javase/1.5.0/docs/guide/security/jsse/SSERefGuide.html#X509TrustManager
//and
//https://github.com/nelenkov/custom-cert-https
import android.annotation.TargetApi;
import android.os.Build;
import android.util.Log;
import org.apache.http.conn.scheme.LayeredSocketFactory;
import org.apache.http.conn.scheme.SocketFactory;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.ssl.BrowserCompatHostnameVerifier;
import org.apache.http.conn.ssl.BrowserCompatHostnameVerifierHC4;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.StrictHostnameVerifier;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HttpContext;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.GeneralSecurityException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import javax.security.auth.x500.X500Principal;
/**
* Allows you to trust certificates from additional KeyStores in addition to the default KeyStore
*/
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public class AdditionalKeyStoresSSLSocketFactory {
final static String TAG = "opacclient.tls";
public static ConnectionSocketFactory create(KeyStore keyStore, boolean tls_only)
throws NoSuchAlgorithmException, KeyManagementException {
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[]{new AdditionalKeyStoresTrustManager(keyStore)},
null);
return new TlsSniSocketFactory(sslContext, tls_only);
}
public static class TlsSniSocketFactory extends SSLConnectionSocketFactory {
private javax.net.ssl.SSLSocketFactory socketfactory;
private final X509HostnameVerifier hostnameVerifier;
private final boolean tls_only;
public TlsSniSocketFactory(final SSLContext sslContext, boolean tls_only) {
super(sslContext, BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
this.tls_only = tls_only;
socketfactory = sslContext.getSocketFactory();
hostnameVerifier = BROWSER_COMPATIBLE_HOSTNAME_VERIFIER;
}
@TargetApi(17)
public Socket createLayeredSocket(
final Socket socket,
final String target,
final int port,
final HttpContext context) throws IOException {
final SSLSocket sslsock = (SSLSocket) this.socketfactory.createSocket(
socket,
target,
port,
true);
// If supported protocols are not explicitly set, remove all SSL protocol versions
final String[] allProtocols = sslsock.getEnabledProtocols();
final List<String> enabledProtocols = new ArrayList<String>(allProtocols.length);
for (String protocol: allProtocols) {
if (!protocol.startsWith("SSL") || !tls_only) {
enabledProtocols.add(protocol);
}
}
if (!enabledProtocols.isEmpty()) {
sslsock.setEnabledProtocols(
enabledProtocols.toArray(new String[enabledProtocols.size()]));
}
Log.d(TAG, "Enabled protocols: " + Arrays.asList(sslsock.getEnabledProtocols()));
Log.d(TAG, "Enabled cipher suites:" + Arrays.asList(sslsock.getEnabledCipherSuites()));
prepareSocket(sslsock);
// Android specific code to enable SNI
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
Log.d(TAG, "Enabling SNI for " + target);
try {
Method method = sslsock.getClass().getMethod("setHostname", String.class);
method.invoke(sslsock, target);
} catch (Exception ex) {
Log.d(TAG, "SNI configuration failed", ex);
}
} else {
Log.d(TAG, "No documented SNI support on Android <4.2, trying with reflection");
try {
java.lang.reflect.Method setHostnameMethod = sslsock.getClass().getMethod("setHostname", String.class);
setHostnameMethod.invoke(sslsock, target);
} catch (Exception e) {
Log.w(TAG, "SNI not useable", e);
}
}
Log.d(TAG, "Starting handshake");
sslsock.startHandshake();
verifyHostname(sslsock, target);
return sslsock;
}
private void verifyHostname(final SSLSocket sslsock, final String hostname) throws IOException {
try {
if (Log.isLoggable(TAG, Log.DEBUG)) {
try {
final SSLSession session = sslsock.getSession();
Log.d(TAG, "Secure session established");
Log.d(TAG, " negotiated protocol: " + session.getProtocol());
Log.d(TAG, " negotiated cipher suite: " + session.getCipherSuite());
final Certificate[] certs = session.getPeerCertificates();
final X509Certificate x509 = (X509Certificate) certs[0];
final X500Principal peer = x509.getSubjectX500Principal();
Log.d(TAG, " peer principal: " + peer.toString());
final Collection<List<?>> altNames1 = x509.getSubjectAlternativeNames();
if (altNames1 != null) {
final List<String> altNames = new ArrayList<String>();
for (final List<?> aC : altNames1) {
if (!aC.isEmpty()) {
altNames.add((String) aC.get(1));
}
}
Log.d(TAG, " peer alternative names: " + altNames);
}
final X500Principal issuer = x509.getIssuerX500Principal();
Log.d(TAG, " issuer principal: " + issuer.toString());
final Collection<List<?>> altNames2 = x509.getIssuerAlternativeNames();
if (altNames2 != null) {
final List<String> altNames = new ArrayList<String>();
for (final List<?> aC : altNames2) {
if (!aC.isEmpty()) {
altNames.add((String) aC.get(1));
}
}
Log.d(TAG, " issuer alternative names: " + altNames);
}
} catch (Exception ignore) {
}
}
this.hostnameVerifier.verify(hostname, sslsock);
// verifyHostName() didn't blowup - good!
} catch (final IOException iox) {
// close the socket before re-throwing the exception
try { sslsock.close(); } catch (final Exception x) { /*ignore*/ }
throw iox;
}
}
}
public static class AdditionalKeyStoresTrustManager implements
X509TrustManager {
private X509TrustManager defaultTrustManager;
private X509TrustManager localTrustManager;
private X509Certificate[] acceptedIssuers;
public AdditionalKeyStoresTrustManager(KeyStore localKeyStore) {
try {
TrustManagerFactory tmf = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init((KeyStore) null);
defaultTrustManager = findX509TrustManager(tmf);
if (defaultTrustManager == null) {
throw new IllegalStateException(
"Couldn't find X509TrustManager");
}
localTrustManager = new LocalStoreX509TrustManager(
localKeyStore);
List<X509Certificate> allIssuers = new ArrayList<>();
Collections.addAll(allIssuers, defaultTrustManager
.getAcceptedIssuers());
Collections.addAll(allIssuers, localTrustManager
.getAcceptedIssuers());
acceptedIssuers = allIssuers
.toArray(new X509Certificate[allIssuers.size()]);
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
}
}
static X509TrustManager findX509TrustManager(TrustManagerFactory tmf) {
TrustManager tms[] = tmf.getTrustManagers();
for (TrustManager tm : tms) {
if (tm instanceof X509TrustManager) {
return (X509TrustManager) tm;
}
}
return null;
}
public static String getThumbPrint(X509Certificate cert)
throws NoSuchAlgorithmException, CertificateEncodingException {
MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] der = cert.getEncoded();
md.update(der);
byte[] digest = md.digest();
return hexify(digest);
}
public static String hexify(byte bytes[]) {
char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8',
'9', 'a', 'b', 'c', 'd', 'e', 'f'};
StringBuilder buf = new StringBuilder(bytes.length * 2);
for (byte aByte : bytes) {
buf.append(hexDigits[(aByte & 0xf0) >> 4]);
buf.append(hexDigits[aByte & 0x0f]);
}
return buf.toString();
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
try {
defaultTrustManager.checkClientTrusted(chain, authType);
} catch (CertificateException ce) {
localTrustManager.checkClientTrusted(
new X509Certificate[]{chain[0]}, authType);
}
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
try {
defaultTrustManager.checkServerTrusted(chain, authType);
} catch (CertificateException ce) {
localTrustManager.checkServerTrusted(
new X509Certificate[]{chain[0]}, authType);
}
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return acceptedIssuers;
}
static class LocalStoreX509TrustManager implements X509TrustManager {
private X509TrustManager trustManager;
LocalStoreX509TrustManager(KeyStore localTrustStore) {
try {
TrustManagerFactory tmf = TrustManagerFactory
.getInstance(TrustManagerFactory
.getDefaultAlgorithm());
tmf.init(localTrustStore);
trustManager = findX509TrustManager(tmf);
if (trustManager == null) {
throw new IllegalStateException(
"Couldn't find X509TrustManager");
}
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
}
}
@Override
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
trustManager.checkClientTrusted(chain, authType);
}
@Override
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
trustManager.checkServerTrusted(chain, authType);
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return trustManager.getAcceptedIssuers();
}
}
}
}
|
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.streaming.runtime.tasks;
import org.apache.flink.annotation.Internal;
import org.apache.flink.runtime.checkpoint.CheckpointMetaData;
import org.apache.flink.runtime.checkpoint.CheckpointOptions;
import org.apache.flink.runtime.checkpoint.CheckpointType;
import org.apache.flink.runtime.execution.CancelTaskException;
import org.apache.flink.runtime.execution.Environment;
import org.apache.flink.runtime.metrics.MetricNames;
import org.apache.flink.runtime.state.CheckpointStorageLocationReference;
import org.apache.flink.streaming.api.checkpoint.ExternallyInducedSource;
import org.apache.flink.streaming.api.functions.source.SourceFunction;
import org.apache.flink.streaming.api.operators.StreamSource;
import org.apache.flink.streaming.api.watermark.Watermark;
import org.apache.flink.streaming.runtime.tasks.mailbox.MailboxDefaultAction;
import org.apache.flink.util.ExceptionUtils;
import org.apache.flink.util.FatalExitExceptionHandler;
import org.apache.flink.util.FlinkException;
import org.apache.flink.util.Preconditions;
import javax.annotation.Nullable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* {@link StreamTask} for executing a {@link StreamSource}.
*
* <p>One important aspect of this is that the checkpointing and the emission of elements must never
* occur at the same time. The execution must be serial. This is achieved by having the contract
* with the {@link SourceFunction} that it must only modify its state or emit elements in a
* synchronized block that locks on the lock Object. Also, the modification of the state and the
* emission of elements must happen in the same block of code that is protected by the synchronized
* block.
*
* @param <OUT> Type of the output elements of this source.
* @param <SRC> Type of the source function for the stream source operator
* @param <OP> Type of the stream source operator
*/
@Internal
public class SourceStreamTask<
OUT, SRC extends SourceFunction<OUT>, OP extends StreamSource<OUT, SRC>>
extends StreamTask<OUT, OP> {
private final LegacySourceFunctionThread sourceThread;
private final Object lock;
private volatile boolean externallyInducedCheckpoints;
private final AtomicBoolean stopped = new AtomicBoolean(false);
private enum FinishingReason {
END_OF_DATA(true),
STOP_WITH_SAVEPOINT_DRAIN(true),
STOP_WITH_SAVEPOINT_NO_DRAIN(false);
private final boolean shouldCallFinish;
FinishingReason(boolean shouldCallFinish) {
this.shouldCallFinish = shouldCallFinish;
}
boolean shouldCallFinish() {
return this.shouldCallFinish;
}
}
/**
* Indicates whether this Task was purposefully finished, in this case we want to ignore
* exceptions thrown after finishing, to ensure shutdown works smoothly.
*
* <p>Moreover we differentiate drain and no drain cases to see if we need to call finish() on
* the operators.
*/
private volatile FinishingReason finishingReason = FinishingReason.END_OF_DATA;
public SourceStreamTask(Environment env) throws Exception {
this(env, new Object());
}
private SourceStreamTask(Environment env, Object lock) throws Exception {
super(
env,
null,
FatalExitExceptionHandler.INSTANCE,
StreamTaskActionExecutor.synchronizedExecutor(lock));
this.lock = Preconditions.checkNotNull(lock);
this.sourceThread = new LegacySourceFunctionThread();
getEnvironment().getMetricGroup().getIOMetricGroup().setEnableBusyTime(false);
}
@Override
protected void init() {
// we check if the source is actually inducing the checkpoints, rather
// than the trigger
SourceFunction<?> source = mainOperator.getUserFunction();
if (source instanceof ExternallyInducedSource) {
externallyInducedCheckpoints = true;
ExternallyInducedSource.CheckpointTrigger triggerHook =
new ExternallyInducedSource.CheckpointTrigger() {
@Override
public void triggerCheckpoint(long checkpointId) throws FlinkException {
// TODO - we need to see how to derive those. We should probably not
// encode this in the
// TODO - source's trigger message, but do a handshake in this task
// between the trigger
// TODO - message from the master, and the source's trigger
// notification
final CheckpointOptions checkpointOptions =
CheckpointOptions.forConfig(
CheckpointType.CHECKPOINT,
CheckpointStorageLocationReference.getDefault(),
configuration.isExactlyOnceCheckpointMode(),
configuration.isUnalignedCheckpointsEnabled(),
configuration.getAlignedCheckpointTimeout().toMillis());
final long timestamp = System.currentTimeMillis();
final CheckpointMetaData checkpointMetaData =
new CheckpointMetaData(checkpointId, timestamp, timestamp);
try {
SourceStreamTask.super
.triggerCheckpointAsync(
checkpointMetaData, checkpointOptions)
.get();
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new FlinkException(e.getMessage(), e);
}
}
};
((ExternallyInducedSource<?, ?>) source).setCheckpointTrigger(triggerHook);
}
getEnvironment()
.getMetricGroup()
.getIOMetricGroup()
.gauge(
MetricNames.CHECKPOINT_START_DELAY_TIME,
this::getAsyncCheckpointStartDelayNanos);
}
@Override
protected void advanceToEndOfEventTime() throws Exception {
operatorChain.getMainOperatorOutput().emitWatermark(Watermark.MAX_WATERMARK);
}
@Override
protected void cleanUpInternal() {
// does not hold any resources, so no cleanup needed
}
@Override
protected void processInput(MailboxDefaultAction.Controller controller) throws Exception {
controller.suspendDefaultAction();
// Against the usual contract of this method, this implementation is not step-wise but
// blocking instead for
// compatibility reasons with the current source interface (source functions run as a loop,
// not in steps).
sourceThread.setTaskDescription(getName());
sourceThread.start();
sourceThread
.getCompletionFuture()
.whenComplete(
(Void ignore, Throwable sourceThreadThrowable) -> {
if (sourceThreadThrowable != null) {
mailboxProcessor.reportThrowable(sourceThreadThrowable);
} else {
mailboxProcessor.suspend();
}
});
}
@Override
protected void cancelTask() {
if (stopped.compareAndSet(false, true)) {
cancelOperator(true);
}
}
@Override
protected void finishTask() {
this.finishingReason = FinishingReason.STOP_WITH_SAVEPOINT_NO_DRAIN;
/**
* Currently stop with savepoint relies on the EndOfPartitionEvents propagation and performs
* clean shutdown after the stop with savepoint (which can produce some records to process
* after the savepoint while stopping). If we interrupt source thread, we might leave the
* network stack in an inconsistent state. So, if we want to relay on the clean shutdown, we
* can not interrupt the source thread.
*/
cancelOperator(false);
}
private void cancelOperator(boolean interruptThread) {
try {
if (mainOperator != null) {
mainOperator.cancel();
}
} finally {
if (sourceThread.isAlive() && interruptThread) {
interruptSourceThread();
} else if (!sourceThread.isAlive() && !sourceThread.getCompletionFuture().isDone()) {
// sourceThread not alive and completion future not done means source thread
// didn't start and we need to manually complete the future
sourceThread.getCompletionFuture().complete(null);
}
}
}
@Override
public void maybeInterruptOnCancel(
Thread toInterrupt, @Nullable String taskName, @Nullable Long timeout) {
super.maybeInterruptOnCancel(toInterrupt, taskName, timeout);
interruptSourceThread();
}
private void interruptSourceThread() {
// Nothing need to do if the source is finished on restore
if (operatorChain != null && operatorChain.isTaskDeployedAsFinished()) {
return;
}
if (sourceThread.isAlive()) {
sourceThread.interrupt();
}
}
@Override
protected CompletableFuture<Void> getCompletionFuture() {
return sourceThread.getCompletionFuture();
}
// ------------------------------------------------------------------------
// Checkpointing
// ------------------------------------------------------------------------
@Override
public CompletableFuture<Boolean> triggerCheckpointAsync(
CheckpointMetaData checkpointMetaData, CheckpointOptions checkpointOptions) {
if (!externallyInducedCheckpoints) {
if (checkpointOptions.getCheckpointType().shouldDrain()) {
return triggerStopWithSavepointWithDrainAsync(
checkpointMetaData, checkpointOptions);
} else {
return super.triggerCheckpointAsync(checkpointMetaData, checkpointOptions);
}
} else {
// we do not trigger checkpoints here, we simply state whether we can trigger them
synchronized (lock) {
return CompletableFuture.completedFuture(isRunning());
}
}
}
private CompletableFuture<Boolean> triggerStopWithSavepointWithDrainAsync(
CheckpointMetaData checkpointMetaData, CheckpointOptions checkpointOptions) {
mainMailboxExecutor.execute(
() ->
stopOperatorForStopWithSavepointWithDrain(
checkpointMetaData.getCheckpointId()),
"stop legacy source for stop-with-savepoint --drain");
return assertTriggeringCheckpointExceptions(
sourceThread
.getCompletionFuture()
.thenCompose(
ignore ->
super.triggerCheckpointAsync(
checkpointMetaData, checkpointOptions)),
checkpointMetaData.getCheckpointId());
}
private void stopOperatorForStopWithSavepointWithDrain(long checkpointId) {
setSynchronousSavepoint(checkpointId, true);
finishingReason = FinishingReason.STOP_WITH_SAVEPOINT_DRAIN;
if (mainOperator != null) {
mainOperator.stop();
}
}
@Override
protected void declineCheckpoint(long checkpointId) {
if (!externallyInducedCheckpoints) {
super.declineCheckpoint(checkpointId);
}
}
/** Runnable that executes the source function in the head operator. */
private class LegacySourceFunctionThread extends Thread {
private final CompletableFuture<Void> completionFuture;
LegacySourceFunctionThread() {
this.completionFuture = new CompletableFuture<>();
}
@Override
public void run() {
try {
if (!operatorChain.isTaskDeployedAsFinished()) {
LOG.debug(
"Legacy source {} skip execution since the task is finished on restore",
getTaskNameWithSubtaskAndId());
mainOperator.run(lock, operatorChain);
}
completeProcessing();
completionFuture.complete(null);
} catch (Throwable t) {
// Note, t can be also an InterruptedException
if (isCanceled()
&& ExceptionUtils.findThrowable(t, InterruptedException.class)
.isPresent()) {
completionFuture.completeExceptionally(new CancelTaskException(t));
} else if (finishingReason == FinishingReason.STOP_WITH_SAVEPOINT_NO_DRAIN) {
// swallow all exceptions if the source was stopped without drain
completionFuture.complete(null);
} else {
completionFuture.completeExceptionally(t);
}
}
}
private void completeProcessing() throws InterruptedException, ExecutionException {
if (finishingReason.shouldCallFinish() && !isCanceled() && !isFailing()) {
mainMailboxExecutor
.submit(
() -> {
// theoretically the StreamSource can implement BoundedOneInput,
// so we
// need to call it here
operatorChain.endInput(1);
endData();
},
"SourceStreamTask finished processing data.")
.get();
}
}
public void setTaskDescription(final String taskDescription) {
setName("Legacy Source Thread - " + taskDescription);
}
/**
* @return future that is completed once this thread completes. If this task {@link
* #isFailing()} and this thread is not alive (e.g. not started) returns a normally
* completed future.
*/
CompletableFuture<Void> getCompletionFuture() {
return isFailing() && !isAlive()
? CompletableFuture.completedFuture(null)
: completionFuture;
}
}
}
|
|
/***
Copyright (c) 2013 CommonsWare, LLC
Licensed under the Apache License, Version 2.0 (the "License"); you may
not use this file except in compliance with the License. You may obtain
a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.commonsware.cwac.camera.acl;
import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.io.IOException;
import com.actionbarsherlock.app.SherlockFragment;
import com.commonsware.cwac.camera.CameraHost;
import com.commonsware.cwac.camera.CameraView;
import com.commonsware.cwac.camera.PictureTransaction;
import com.commonsware.cwac.camera.SimpleCameraHost;
import com.commonsware.cwac.camera.ZoomTransaction;
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public class CameraFragment extends SherlockFragment {
private CameraView cameraView=null;
private CameraHost host=null;
/*
* (non-Javadoc)
*
* @see android.app.Fragment#onCreateView(android.view.
* LayoutInflater, android.view.ViewGroup,
* android.os.Bundle)
*/
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
cameraView=new CameraView(getActivity());
cameraView.setHost(getHost());
return(cameraView);
}
/*
* (non-Javadoc)
*
* @see android.app.Fragment#onResume()
*/
@Override
public void onResume() {
super.onResume();
cameraView.onResume();
}
/*
* (non-Javadoc)
*
* @see android.app.Fragment#onPause()
*/
@Override
public void onPause() {
if (isRecording()) {
try {
stopRecording();
}
catch (IOException e) {
// TODO: get to developers
Log.e(getClass().getSimpleName(),
"Exception stopping recording in onPause()", e);
}
}
cameraView.onPause();
super.onPause();
}
/**
* Use this if you are overriding onCreateView() and are
* inflating a layout containing your CameraView, to tell
* the fragment the CameraView, so the fragment can help
* manage it. You do not need to call this if you are
* allowing the fragment to create its own CameraView
* instance.
*
* @param cameraView
* the CameraView from your inflated layout
*/
protected void setCameraView(CameraView cameraView) {
this.cameraView=cameraView;
}
/**
* @return the CameraHost instance you want to use for
* this fragment, where the default is an instance
* of the stock SimpleCameraHost.
*/
public CameraHost getHost() {
if (host == null) {
host=new SimpleCameraHost(getActivity());
}
return(host);
}
/**
* Call this (or override getCameraHost()) to supply the
* CameraHost used for most of the detailed interaction
* with the camera.
*
* @param host
* a CameraHost instance, such as a subclass of
* SimpleCameraHost
*/
public void setHost(CameraHost host) {
this.host=host;
}
/**
* Call this to take a picture and get access to a byte
* array of data as a result (e.g., to save or stream).
*/
public void takePicture() {
takePicture(false, true);
}
/**
* Call this to take a picture.
*
* @param needBitmap
* true if you need to be passed a Bitmap result,
* false otherwise
* @param needByteArray
* true if you need to be passed a byte array
* result, false otherwise
*/
public void takePicture(boolean needBitmap, boolean needByteArray) {
cameraView.takePicture(needBitmap, needByteArray);
}
/**
* Call this to take a picture.
*
* @param xact
* PictureTransaction with configuration data for
* the picture to be taken
*/
public void takePicture(PictureTransaction xact) {
cameraView.takePicture(xact);
}
/**
* @return true if we are recording video right now, false
* otherwise
*/
public boolean isRecording() {
return(cameraView == null ? false : cameraView.isRecording());
}
/**
* Call this to begin recording video.
*
* @throws Exception
* all sorts of things could go wrong
*/
public void record() throws Exception {
cameraView.record();
}
/**
* Call this to stop the recording triggered earlier by a
* call to record()
*
* @throws Exception
* all sorts of things could go wrong
*/
public void stopRecording() throws IOException {
cameraView.stopRecording();
}
/**
* @return the orientation of the screen, in degrees
* (0-360)
*/
public int getDisplayOrientation() {
return(cameraView.getDisplayOrientation());
}
/**
* Call this to lock the camera to landscape mode (with a
* parameter of true), regardless of what the actual
* screen orientation is.
*
* @param enable
* true to lock the camera to landscape, false to
* allow normal rotation
*/
public void lockToLandscape(boolean enable) {
cameraView.lockToLandscape(enable);
}
/**
* Call this to begin an auto-focus operation (e.g., in
* response to the user tapping something to focus the
* camera).
*/
public void autoFocus() {
cameraView.autoFocus();
}
/**
* Call this to cancel an auto-focus operation that had
* been started via a call to autoFocus().
*/
public void cancelAutoFocus() {
cameraView.cancelAutoFocus();
}
/**
* @return true if auto-focus is an option on this device,
* false otherwise
*/
public boolean isAutoFocusAvailable() {
return(cameraView.isAutoFocusAvailable());
}
/**
* If you are in single-shot mode and are done processing
* a previous picture, call this to restart the camera
* preview.
*/
public void restartPreview() {
cameraView.restartPreview();
}
/**
* @return the name of the current flash mode, as reported
* by Camera.Parameters
*/
public String getFlashMode() {
return(cameraView.getFlashMode());
}
/**
* Call this to begin populating a ZoomTransaction, with
* the eventual goal of changing the camera's zoom level.
*
* @param level
* a value from 0 to getMaxZoom() (called on
* Camera.Parameters), to indicate how tight the
* zoom should be (0 indicates no zoom)
* @return a ZoomTransaction to configure further and
* eventually call go() to actually do the zooming
*/
public ZoomTransaction zoomTo(int level) {
return(cameraView.zoomTo(level));
}
/**
* Calls startFaceDetection() on the CameraView, which in
* turn calls startFaceDetection() on the underlying
* camera.
*/
public void startFaceDetection() {
cameraView.startFaceDetection();
}
/**
* Calls stopFaceDetection() on the CameraView, which in
* turn calls startFaceDetection() on the underlying
* camera.
*/
public void stopFaceDetection() {
cameraView.stopFaceDetection();
}
public boolean doesZoomReallyWork() {
return(cameraView.doesZoomReallyWork());
}
public void setFlashMode(String mode) {
cameraView.setFlashMode(mode);
}
}
|
|
/*
* Copyright 2017 StreamSets 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.streamsets.datacollector.record;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.streamsets.pipeline.api.impl.ErrorMessage;
import com.streamsets.pipeline.api.impl.LocalizableString;
import com.streamsets.pipeline.api.Record;
import com.streamsets.pipeline.api.impl.Utils;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
public class HeaderImpl implements Record.Header, Predicate<String>, Cloneable, Serializable {
private static final String RESERVED_PREFIX = "_.";
private static final String STAGE_CREATOR_INSTANCE_ATTR = RESERVED_PREFIX + "stageCreator";
private static final String RECORD_SOURCE_ID_ATTR = RESERVED_PREFIX + "recordSourceId";
private static final String STAGES_PATH_ATTR = RESERVED_PREFIX + "stagePath";
private static final String RAW_DATA_ATTR = RESERVED_PREFIX + "rawData";
private static final String RAW_MIME_TYPE_ATTR = RESERVED_PREFIX + "rawMimeType";
private static final String TRACKING_ID_ATTR = RESERVED_PREFIX + "trackingId";
private static final String PREVIOUS_TRACKING_ID_ATTR = RESERVED_PREFIX + "previousTrackingId";
private static final String ERROR_CODE_ATTR = RESERVED_PREFIX + "errorCode";
private static final String ERROR_MESSAGE_ATTR = RESERVED_PREFIX + "errorMessage";
private static final String ERROR_STAGE_ATTR = RESERVED_PREFIX + "errorStage";
private static final String ERROR_STAGE_LABEL_ATTR = RESERVED_PREFIX + "errorStageLabel";
private static final String ERROR_TIMESTAMP_ATTR = RESERVED_PREFIX + "errorTimestamp";
private static final String SOURCE_RECORD_ATTR = RESERVED_PREFIX + "sourceRecord";
private static final String ERROR_DATACOLLECTOR_ID_ATTR = RESERVED_PREFIX + "dataCollectorId";
private static final String ERROR_PIPELINE_NAME_ATTR = RESERVED_PREFIX + "pipelineName";
private static final String ERROR_STACKTRACE = RESERVED_PREFIX + "errorStackTrace";
private static final String ERROR_JOB_ID = RESERVED_PREFIX + "errorJobId";
private static final List<String> REQUIRED_ATTRIBUTES = ImmutableList.of(STAGE_CREATOR_INSTANCE_ATTR,
RECORD_SOURCE_ID_ATTR);
//Note: additional fields should also define in ScriptRecord
private Map<String, Object> map;
public HeaderImpl() {
map = new HashMap<>();
map.put(SOURCE_RECORD_ATTR, null);
}
// for clone() purposes
private HeaderImpl(HeaderImpl header) {
this.map = new HashMap<>(header.map);
}
// Predicate interface
@Override
public boolean apply(String input) {
return !input.startsWith(RESERVED_PREFIX);
}
// Record.Header interface
@Override
public String getStageCreator() {
return (String) map.get(STAGE_CREATOR_INSTANCE_ATTR);
}
@Override
public String getSourceId() {
return (String) map.get(RECORD_SOURCE_ID_ATTR);
}
@Override
public String getStagesPath() {
return (String) map.get(STAGES_PATH_ATTR);
}
@Override
public String getTrackingId() {
return (String) map.get(TRACKING_ID_ATTR);
}
@Override
public String getPreviousTrackingId() {
return (String) map.get(PREVIOUS_TRACKING_ID_ATTR);
}
@Override
public byte[] getRaw() {
byte[] raw = (byte[]) map.get(RAW_DATA_ATTR);
return (raw != null) ? raw.clone() : null;
}
@Override
public String getRawMimeType() {
return (String) map.get(RAW_MIME_TYPE_ATTR);
}
@Override
public String getErrorDataCollectorId() {
return (String) map.get(ERROR_DATACOLLECTOR_ID_ATTR);
}
@Override
public String getErrorPipelineName() {
return (String) map.get(ERROR_PIPELINE_NAME_ATTR);
}
@Override
public String getErrorCode() {
return (String) map.get(ERROR_CODE_ATTR);
}
@Override
public String getErrorMessage() {
final Object error = map.get(ERROR_MESSAGE_ATTR);
return (error == null)
? null
: (error instanceof LocalizableString) ? ((LocalizableString) error).getLocalized() : (String) error;
}
@Override
public String getErrorStage() {
return (String) map.get(ERROR_STAGE_ATTR);
}
@Override
public String getErrorStageLabel() {
return (String) map.get(ERROR_STAGE_LABEL_ATTR);
}
@Override
public long getErrorTimestamp() {
final Object time = map.get(ERROR_TIMESTAMP_ATTR);
return (time != null) ? (long) time : 0;
}
@Override
public String getErrorStackTrace() {
return (String) map.get(ERROR_STACKTRACE);
}
@Override
public String getErrorJobId() {
return (String) map.get(ERROR_JOB_ID);
}
@Override
public Set<String> getAttributeNames() {
return ImmutableSet.copyOf(Sets.filter(map.keySet(), this));
}
private static final String REQUIRED_ATTR_EXCEPTION_MSG = "Does not have required attributes";
private static final String RESERVED_PREFIX_EXCEPTION_MSG = "Header attributes cannot start with '" +
RESERVED_PREFIX + "'";
@Override
public String getAttribute(String name) {
Preconditions.checkNotNull(name, "name cannot be null");
Preconditions.checkArgument(!name.startsWith(RESERVED_PREFIX), RESERVED_PREFIX_EXCEPTION_MSG);
return (String) map.get(name);
}
@Override
public void setAttribute(String name, String value) {
Preconditions.checkNotNull(name, "name cannot be null");
Preconditions.checkArgument(!name.startsWith(RESERVED_PREFIX), RESERVED_PREFIX_EXCEPTION_MSG);
Preconditions.checkNotNull(value, "value cannot be null");
map.put(name, value);
}
@Override
public void deleteAttribute(String name) {
Preconditions.checkNotNull(name, "name cannot be null");
Preconditions.checkArgument(!name.startsWith(RESERVED_PREFIX), RESERVED_PREFIX_EXCEPTION_MSG);
map.remove(name);
}
// For Json serialization
@SuppressWarnings("unchecked")
public Map<String, String> getValues() {
return (Map) Maps.filterKeys(map, this);
}
public HeaderImpl(
String stageCreator,
String sourceId,
String stagesPath,
String trackingId,
String previousTrackingId,
byte[] raw,
String rawMimeType,
String errorDataCollectorId,
String errorPipelineName,
String errorStage,
String errorStageName,
String errorCode,
String errorMessage,
long errorTimestamp,
String errorStackTrace,
Map<String, Object> map,
String errorJobId
) {
this.map = map;
setStageCreator(stageCreator);
setSourceId(sourceId);
if (stagesPath != null) {
setStagesPath(stagesPath);
}
if (trackingId != null) {
setTrackingId(trackingId);
}
if (errorDataCollectorId != null && errorPipelineName != null) {
setErrorContext(errorDataCollectorId, errorPipelineName);
}
if (errorCode != null) {
setError(errorStage, errorStageName, errorCode, errorMessage, errorTimestamp, errorStackTrace);
}
if (previousTrackingId != null) {
setPreviousTrackingId(previousTrackingId);
}
if (raw != null) {
setRaw(raw);
setRawMimeType(rawMimeType);
}
map.put(SOURCE_RECORD_ATTR, null);
if (errorJobId != null) {
setErrorJobId(errorJobId);
}
}
// HeaderImpl setter methods
public void setStageCreator(String stateCreator) {
Preconditions.checkNotNull(stateCreator, "stateCreator cannot be null");
map.put(STAGE_CREATOR_INSTANCE_ATTR, stateCreator);
}
public void setSourceId(String sourceId) {
Preconditions.checkNotNull(sourceId, "sourceId cannot be null");
map.put(RECORD_SOURCE_ID_ATTR, sourceId);
}
public void setStagesPath(String stagePath) {
Preconditions.checkNotNull(stagePath, "stagePath cannot be null");
map.put(STAGES_PATH_ATTR, stagePath);
}
public void setTrackingId(String trackingId) {
Preconditions.checkNotNull(trackingId, "trackingId cannot be null");
map.put(TRACKING_ID_ATTR, trackingId);
}
public void setPreviousTrackingId(String previousTrackingId) {
Preconditions.checkNotNull(previousTrackingId, "previousTrackingId cannot be null");
map.put(PREVIOUS_TRACKING_ID_ATTR, previousTrackingId);
}
public void setRaw(byte[] raw) {
Preconditions.checkNotNull(raw, "raw cannot be null");
map.put(RAW_DATA_ATTR, raw.clone());
}
public void setRawMimeType(String rawMime) {
Preconditions.checkNotNull(rawMime, "rawMime cannot be null");
map.put(RAW_MIME_TYPE_ATTR, rawMime);
}
public void setErrorJobId(String errorJobId) {
Preconditions.checkNotNull(errorJobId, "errorJobId cannot be null");
map.put(ERROR_JOB_ID, errorJobId);
}
public void setError(String errorStage, String errorStageName, ErrorMessage errorMessage) {
Preconditions.checkNotNull(errorMessage, "errorCode cannot be null");
setError(
errorStage,
errorStageName,
errorMessage.getErrorCode(),
errorMessage.getNonLocalized(),
System.currentTimeMillis(),
errorMessage.getErrorStackTrace()
);
}
public void copyErrorFrom(Record record) {
Record.Header header = record.getHeader();
setError(
header.getErrorStage(),
header.getErrorStageLabel(),
header.getErrorCode(),
header.getErrorMessage(),
header.getErrorTimestamp(),
header.getErrorStackTrace()
);
}
public void setErrorContext(String datacollector, String pipelineName) {
map.put(ERROR_DATACOLLECTOR_ID_ATTR, datacollector);
map.put(ERROR_PIPELINE_NAME_ATTR, pipelineName);
}
private void setError(
String errorStage,
String errorStageName,
String errorCode,
String errorMessage,
long errorTimestamp,
String errorStackTrace
) {
map.put(ERROR_STAGE_ATTR, errorStage);
map.put(ERROR_STAGE_LABEL_ATTR, errorStageName);
map.put(ERROR_CODE_ATTR, errorCode);
map.put(ERROR_MESSAGE_ATTR, errorMessage);
map.put(ERROR_TIMESTAMP_ATTR, errorTimestamp);
map.put(ERROR_STACKTRACE, errorStackTrace);
}
public void setSourceRecord(Record record) {
map.put(SOURCE_RECORD_ATTR, record);
}
public Record getSourceRecord() {
return (Record) map.get(SOURCE_RECORD_ATTR);
}
// Object methods
@Override
public int hashCode() {
return map.hashCode();
}
@Override
public boolean equals(Object obj) {
boolean eq = this == obj;
if (!eq && obj != null && obj instanceof HeaderImpl) {
Map<String, Object> otherMap = ((HeaderImpl) obj).map;
eq = map.size() == otherMap.size();
if (eq) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
Object otherValue = otherMap.get(key);
switch (key) {
case SOURCE_RECORD_ATTR:
break;
case RAW_DATA_ATTR:
eq = value == otherValue;
if (!eq && value != null && otherValue != null) {
byte[] arr = (byte[]) value;
byte[] otherArr = (byte[]) otherValue;
eq = arr.length == otherArr.length;
for (int i = 0; eq && i < arr.length; i++) {
eq = arr[i] == otherArr[i];
}
}
break;
default:
eq = (value == otherValue) || (value != null && value.equals(otherValue));
break;
}
if (!eq) {
break;
}
}
}
}
return eq;
}
@Override
public HeaderImpl clone() {
return new HeaderImpl(this);
}
@Override
public String toString() {
return Utils.format("HeaderImpl[{}]", getSourceId());
}
// ImmutableMap can't have null values and our map could have, so use unmodifiable map
public Map<String, Object> getAllAttributes() {
return Collections.unmodifiableMap(map);
}
private Map<String, Object> getSystemAttributes() {
Map<String, Object> existingSystemAttr = new HashMap<>();
//Need to do this way due to valid null values
List<String> existingReservedKeys = map.keySet()
.stream()
.filter(key -> key.startsWith(RESERVED_PREFIX))
.collect(Collectors.toList());
existingReservedKeys.forEach( (key) -> existingSystemAttr.put(key, map.get(key)));
return existingSystemAttr;
}
private boolean hasRequiredAttributes(Set<String> keys) {
/* Any new header map MUST have the MINIMUM required reserved header attributes AND if any
reserved attributes exist in existing map the MUST exist in new map's keys
*/
// Check that new map's keys have the minimum required attributes of a header impl.
if(!keys.containsAll(REQUIRED_ATTRIBUTES)) {
return false;
}
// Check that new map's keys also contain any existing reserved attributes.
Set<String> existingReservedKeys = getSystemAttributes().keySet();
if (!keys.containsAll(existingReservedKeys)) {
return false;
}
return true;
}
public Map<String, Object> overrideUserAndSystemAttributes(Map<String, Object> newAttrs) {
/* Any new header map MUST have the MINIMUM required reserved header attributes AND if any
reserved attributes exist in existing map the MUST exist in new map's keys
*/
if (!hasRequiredAttributes(newAttrs.keySet())) {
throw new IllegalArgumentException(REQUIRED_ATTR_EXCEPTION_MSG);
}
// ImmutableMap can't have null values and our map could have, so use unmodifiable map
Map<String, Object> old = Collections.unmodifiableMap(map);
map = new HashMap<>(newAttrs);
return old;
}
/** To be removed */
public Map<String, Object> getUserAttributes() {
return map.entrySet()
.stream()
.filter(map -> !map.getKey().startsWith(RESERVED_PREFIX))
.collect(Collectors.toMap(map -> map.getKey(), map -> map.getValue()));
}
/** To be removed */
public Map<String, Object> setUserAttributes(Map<String, Object> newAttributes) {
// ImmutableMap can't have null values and our map could have, so use unmodifiable map
Map<String, Object> old = Collections.unmodifiableMap(getUserAttributes());
//Set current map to just the Reserved System Attributes
map = getSystemAttributes();
// Add and validate each of the new user attributes
newAttributes.forEach((k,v) -> setAttribute(k, v.toString()));
return old;
}
}
|
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.jdbc.thin;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.cache.QueryEntity;
import org.apache.ignite.cache.QueryIndex;
import org.apache.ignite.cache.affinity.AffinityKey;
import org.apache.ignite.cache.query.annotations.QuerySqlField;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.internal.IgniteVersionUtils;
import org.apache.ignite.internal.jdbc2.JdbcUtils;
import org.apache.ignite.internal.processors.query.QueryEntityEx;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.spi.metric.sql.SqlViewMetricExporterSpi;
import org.apache.ignite.testframework.GridTestUtils;
import org.junit.Assert;
import org.junit.Test;
import static java.sql.Types.DATE;
import static java.sql.Types.DECIMAL;
import static java.sql.Types.INTEGER;
import static java.sql.Types.OTHER;
import static java.sql.Types.VARCHAR;
import static org.apache.ignite.cache.CacheMode.PARTITIONED;
import static org.apache.ignite.cache.CacheWriteSynchronizationMode.FULL_SYNC;
import static org.apache.ignite.internal.processors.query.QueryUtils.DFLT_SCHEMA;
import static org.apache.ignite.internal.processors.query.QueryUtils.SCHEMA_SYS;
/**
* Metadata tests.
*/
public class JdbcThinMetadataSelfTest extends JdbcThinAbstractSelfTest {
/** URL. */
private static final String URL = "jdbc:ignite:thin://127.0.0.1/";
/** URL with partition awareness enabled. */
public static final String URL_PARTITION_AWARENESS =
"jdbc:ignite:thin://127.0.0.1:10800..10801?partitionAwareness=true";
/** {@inheritDoc} */
@Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
return super.getConfiguration(igniteInstanceName)
.setSqlSchemas("PREDEFINED_SCHEMAS_1", "PREDEFINED_SCHEMAS_2")
.setMetricExporterSpi(new SqlViewMetricExporterSpi());
}
/**
* @param qryEntity Query entity.
* @return Cache configuration.
*/
protected CacheConfiguration cacheConfiguration(QueryEntity qryEntity) {
CacheConfiguration<?,?> cache = defaultCacheConfiguration();
cache.setCacheMode(PARTITIONED);
cache.setBackups(1);
cache.setWriteSynchronizationMode(FULL_SYNC);
cache.setQueryEntities(Collections.singletonList(qryEntity));
return cache;
}
/** {@inheritDoc} */
@Override protected void beforeTestsStarted() throws Exception {
super.beforeTestsStarted();
startGridsMultiThreaded(3);
Map<String, Integer> orgPrecision = new HashMap<>();
orgPrecision.put("name", 42);
IgniteCache<String, Organization> orgCache = jcache(grid(0),
cacheConfiguration(new QueryEntity(String.class.getName(), Organization.class.getName())
.addQueryField("id", Integer.class.getName(), null)
.addQueryField("name", String.class.getName(), null)
.setFieldsPrecision(orgPrecision)
.setIndexes(Arrays.asList(
new QueryIndex("id"),
new QueryIndex("name", false, "org_name_index")
))), "org");
assert orgCache != null;
orgCache.put("o1", new Organization(1, "A"));
orgCache.put("o2", new Organization(2, "B"));
LinkedHashMap<String, Boolean> persFields = new LinkedHashMap<>();
persFields.put("name", true);
persFields.put("age", false);
IgniteCache<AffinityKey, Person> personCache = jcache(grid(0), cacheConfiguration(
new QueryEntityEx(
new QueryEntity(AffinityKey.class.getName(), Person.class.getName())
.addQueryField("name", String.class.getName(), null)
.addQueryField("age", Integer.class.getName(), null)
.addQueryField("orgId", Integer.class.getName(), null)
.setIndexes(Arrays.asList(
new QueryIndex("orgId"),
new QueryIndex().setFields(persFields))))
.setNotNullFields(new HashSet<>(Arrays.asList("age", "name")))
), "pers");
assert personCache != null;
personCache.put(new AffinityKey<>("p1", "o1"), new Person("John White", 25, 1));
personCache.put(new AffinityKey<>("p2", "o1"), new Person("Joe Black", 35, 1));
personCache.put(new AffinityKey<>("p3", "o2"), new Person("Mike Green", 40, 2));
jcache(grid(0),
defaultCacheConfiguration().setIndexedTypes(Integer.class, Department.class),
"dep");
try (Connection conn = DriverManager.getConnection(URL)) {
Statement stmt = conn.createStatement();
stmt.execute("CREATE TABLE TEST (ID INT, NAME VARCHAR(50) default 'default name', " +
"age int default 21, VAL VARCHAR(50), PRIMARY KEY (ID, NAME))");
stmt.execute("CREATE TABLE \"Quoted\" (\"Id\" INT primary key, \"Name\" VARCHAR(50)) WITH WRAP_KEY");
stmt.execute("CREATE INDEX \"MyTestIndex quoted\" on \"Quoted\" (\"Id\" DESC)");
stmt.execute("CREATE INDEX IDX ON TEST (ID ASC)");
stmt.execute("CREATE TABLE TEST_DECIMAL_COLUMN (ID INT primary key, DEC_COL DECIMAL(8, 3))");
stmt.execute("CREATE TABLE TEST_DECIMAL_COLUMN_PRECISION (ID INT primary key, DEC_COL DECIMAL(8))");
stmt.execute("CREATE TABLE TEST_DECIMAL_DATE_COLUMN_META (ID INT primary key, DEC_COL DECIMAL(8), DATE_COL DATE)");
}
}
/**
* @throws Exception If failed.
*/
@Test
public void testResultSetMetaData() throws Exception {
Connection conn = DriverManager.getConnection(URL);
conn.setSchema("\"pers\"");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(
"select p.name, o.id as orgId from \"pers\".Person p, \"org\".Organization o where p.orgId = o.id");
assert rs != null;
ResultSetMetaData meta = rs.getMetaData();
assert meta != null;
assert meta.getColumnCount() == 2;
assert "Person".equalsIgnoreCase(meta.getTableName(1));
assert "name".equalsIgnoreCase(meta.getColumnName(1));
assert "name".equalsIgnoreCase(meta.getColumnLabel(1));
assert meta.getColumnType(1) == VARCHAR;
assert "VARCHAR".equals(meta.getColumnTypeName(1));
assert "java.lang.String".equals(meta.getColumnClassName(1));
assert "Organization".equalsIgnoreCase(meta.getTableName(2));
assert "orgId".equalsIgnoreCase(meta.getColumnName(2));
assert "orgId".equalsIgnoreCase(meta.getColumnLabel(2));
assert meta.getColumnType(2) == INTEGER;
assert "INTEGER".equals(meta.getColumnTypeName(2));
assert "java.lang.Integer".equals(meta.getColumnClassName(2));
}
/**
* @throws Exception If failed.
*/
@Test
public void testDecimalAndDateTypeMetaData() throws Exception {
try (Connection conn = DriverManager.getConnection(URL)) {
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(
"select t.dec_col, t.date_col from TEST_DECIMAL_DATE_COLUMN_META as t");
assert rs != null;
ResultSetMetaData meta = rs.getMetaData();
assert meta != null;
assert meta.getColumnCount() == 2;
assert "TEST_DECIMAL_DATE_COLUMN_META".equalsIgnoreCase(meta.getTableName(1));
assert "DEC_COL".equalsIgnoreCase(meta.getColumnName(1));
assert "DEC_COL".equalsIgnoreCase(meta.getColumnLabel(1));
assert meta.getColumnType(1) == DECIMAL;
assert "DECIMAL".equals(meta.getColumnTypeName(1));
assert "java.math.BigDecimal".equals(meta.getColumnClassName(1));
assert "TEST_DECIMAL_DATE_COLUMN_META".equalsIgnoreCase(meta.getTableName(2));
assert "DATE_COL".equalsIgnoreCase(meta.getColumnName(2));
assert "DATE_COL".equalsIgnoreCase(meta.getColumnLabel(2));
assert meta.getColumnType(2) == DATE;
assert "DATE".equals(meta.getColumnTypeName(2));
assert "java.sql.Date".equals(meta.getColumnClassName(2));
}
}
/**
* @throws Exception If failed.
*/
@Test
public void testGetTableTypes() throws Exception {
try (Connection conn = DriverManager.getConnection(URL)) {
DatabaseMetaData meta = conn.getMetaData();
ResultSet rs = meta.getTableTypes();
assertTrue(rs.next());
assertEquals("TABLE", rs.getString("TABLE_TYPE"));
assertTrue(rs.next());
assertEquals("VIEW", rs.getString("TABLE_TYPE"));
}
}
/**
* @throws Exception If failed.
*/
@Test
public void testGetTables() throws Exception {
try (Connection conn = DriverManager.getConnection(URL)) {
DatabaseMetaData meta = conn.getMetaData();
ResultSet rs = meta.getTables(null, "pers", "%", new String[]{"TABLE"});
assertNotNull(rs);
assertTrue(rs.next());
assertEquals("TABLE", rs.getString("TABLE_TYPE"));
assertEquals(JdbcUtils.CATALOG_NAME, rs.getString("TABLE_CAT"));
assertEquals("PERSON", rs.getString("TABLE_NAME"));
assertFalse(rs.next());
rs = meta.getTables(null, "org", "%", new String[]{"TABLE"});
assertNotNull(rs);
assertTrue(rs.next());
assertEquals("TABLE", rs.getString("TABLE_TYPE"));
assertEquals(JdbcUtils.CATALOG_NAME, rs.getString("TABLE_CAT"));
assertEquals("ORGANIZATION", rs.getString("TABLE_NAME"));
assertFalse(rs.next());
rs = meta.getTables(null, "pers", "%", null);
assertNotNull(rs);
assertTrue(rs.next());
assertEquals("TABLE", rs.getString("TABLE_TYPE"));
assertEquals(JdbcUtils.CATALOG_NAME, rs.getString("TABLE_CAT"));
assertEquals("PERSON", rs.getString("TABLE_NAME"));
assertFalse(rs.next());
rs = meta.getTables(null, "org", "%", null);
assertNotNull(rs);
assertTrue(rs.next());
assertEquals("TABLE", rs.getString("TABLE_TYPE"));
assertEquals(JdbcUtils.CATALOG_NAME, rs.getString("TABLE_CAT"));
assertEquals("ORGANIZATION", rs.getString("TABLE_NAME"));
assertFalse(rs.next());
rs = meta.getTables(null, "PUBLIC", "", new String[]{"WRONG"});
assertFalse(rs.next());
}
}
/**
* @throws Exception If failed.
*/
@Test
public void testGetAllTables() throws Exception {
testGetTables(
new String[] {"TABLE"},
new HashSet<>(Arrays.asList(
"org.ORGANIZATION",
"pers.PERSON",
"dep.DEPARTMENT",
"PUBLIC.TEST",
"PUBLIC.Quoted",
"PUBLIC.TEST_DECIMAL_COLUMN",
"PUBLIC.TEST_DECIMAL_COLUMN_PRECISION",
"PUBLIC.TEST_DECIMAL_DATE_COLUMN_META"))
);
}
/**
* @throws Exception If failed.
*/
@Test
public void testGetAllView() throws Exception {
testGetTables(
new String[] {"VIEW"},
new HashSet<>(Arrays.asList(
"SYS.METRICS",
"SYS.SERVICES",
"SYS.CACHE_GROUPS",
"SYS.CACHES",
"SYS.TASKS",
"SYS.SQL_QUERIES_HISTORY",
"SYS.NODES",
"SYS.SCHEMAS",
"SYS.NODE_METRICS",
"SYS.BASELINE_NODES",
"SYS.INDEXES",
"SYS.LOCAL_CACHE_GROUPS_IO",
"SYS.SQL_QUERIES",
"SYS.SCAN_QUERIES",
"SYS.NODE_ATTRIBUTES",
"SYS.TABLES",
"SYS.CLIENT_CONNECTIONS",
"SYS.TRANSACTIONS",
"SYS.VIEWS",
"SYS.TABLE_COLUMNS",
"SYS.VIEW_COLUMNS",
"SYS.CONTINUOUS_QUERIES",
"SYS.STRIPED_THREADPOOL_QUEUE",
"SYS.DATASTREAM_THREADPOOL_QUEUE",
"SYS.CACHE_GROUP_PAGE_LISTS",
"SYS.DATA_REGION_PAGE_LISTS"
))
);
}
/**
* @throws Exception If failed.
*/
private void testGetTables(String[] tblTypes, Set<String> expTbls) throws Exception {
try (Connection conn = DriverManager.getConnection(URL)) {
DatabaseMetaData meta = conn.getMetaData();
ResultSet rs = meta.getTables(null, null, null, tblTypes);
Set<String> actualTbls = new HashSet<>(expTbls.size());
while (rs.next()) {
actualTbls.add(rs.getString("TABLE_SCHEM") + '.'
+ rs.getString("TABLE_NAME"));
}
assert expTbls.equals(actualTbls) : "expectedTbls=" + expTbls +
", actualTbls" + actualTbls;
}
}
/**
* @throws Exception If failed.
*/
@Test
public void testGetColumns() throws Exception {
try (Connection conn = DriverManager.getConnection(URL)) {
conn.setSchema("pers");
DatabaseMetaData meta = conn.getMetaData();
ResultSet rs = meta.getColumns(null, "pers", "PERSON", "%");
ResultSetMetaData rsMeta = rs.getMetaData();
assert rsMeta.getColumnCount() == 24 : "Invalid columns count: " + rsMeta.getColumnCount();
assert rs != null;
Collection<String> names = new ArrayList<>(2);
names.add("NAME");
names.add("AGE");
names.add("ORGID");
int cnt = 0;
while (rs.next()) {
String name = rs.getString("COLUMN_NAME");
assert names.remove(name) : "Unexpected column name " + name;
if ("NAME".equals(name)) {
assert rs.getInt("DATA_TYPE") == VARCHAR;
assert "VARCHAR".equals(rs.getString("TYPE_NAME"));
assert rs.getInt("NULLABLE") == 0;
assert rs.getInt(11) == 0; // nullable column by index
assert rs.getString("IS_NULLABLE").equals("NO");
} else if ("ORGID".equals(name)) {
assert rs.getInt("DATA_TYPE") == INTEGER;
assert "INTEGER".equals(rs.getString("TYPE_NAME"));
assert rs.getInt("NULLABLE") == 1;
assert rs.getInt(11) == 1; // nullable column by index
assert rs.getString("IS_NULLABLE").equals("YES");
} else if ("AGE".equals(name)) {
assert rs.getInt("DATA_TYPE") == INTEGER;
assert "INTEGER".equals(rs.getString("TYPE_NAME"));
assert rs.getInt("NULLABLE") == 0;
assert rs.getInt(11) == 0; // nullable column by index
assert rs.getString("IS_NULLABLE").equals("NO");
}
else if ("_KEY".equals(name)) {
assert rs.getInt("DATA_TYPE") == OTHER;
assert "OTHER".equals(rs.getString("TYPE_NAME"));
assert rs.getInt("NULLABLE") == 0;
assert rs.getInt(11) == 0; // nullable column by index
assert rs.getString("IS_NULLABLE").equals("NO");
}
else if ("_VAL".equals(name)) {
assert rs.getInt("DATA_TYPE") == OTHER;
assert "OTHER".equals(rs.getString("TYPE_NAME"));
assert rs.getInt("NULLABLE") == 0;
assert rs.getInt(11) == 0; // nullable column by index
assert rs.getString("IS_NULLABLE").equals("NO");
}
cnt++;
}
assert names.isEmpty();
assert cnt == 3;
rs = meta.getColumns(null, "org", "ORGANIZATION", "%");
assert rs != null;
names.add("ID");
names.add("NAME");
cnt = 0;
while (rs.next()) {
String name = rs.getString("COLUMN_NAME");
assert names.remove(name);
if ("id".equals(name)) {
assert rs.getInt("DATA_TYPE") == INTEGER;
assert "INTEGER".equals(rs.getString("TYPE_NAME"));
assert rs.getInt("NULLABLE") == 0;
} else if ("name".equals(name)) {
assert rs.getInt("DATA_TYPE") == VARCHAR;
assert "VARCHAR".equals(rs.getString("TYPE_NAME"));
assert rs.getInt("NULLABLE") == 1;
}
if ("_KEY".equals(name)) {
assert rs.getInt("DATA_TYPE") == VARCHAR;
assert "VARCHAR".equals(rs.getString("TYPE_NAME"));
assert rs.getInt("NULLABLE") == 0;
}
if ("_VAL".equals(name)) {
assert rs.getInt("DATA_TYPE") == OTHER;
assert "OTHER".equals(rs.getString("TYPE_NAME"));
assert rs.getInt("NULLABLE") == 0;
}
cnt++;
}
assert names.isEmpty();
assert cnt == 2;
}
}
/**
* @throws Exception If failed.
*/
@Test
public void testGetAllColumns() throws Exception {
try (Connection conn = DriverManager.getConnection(URL)) {
DatabaseMetaData meta = conn.getMetaData();
ResultSet rs = meta.getColumns(null, null, null, null);
Set<String> expectedCols = new HashSet<>(Arrays.asList(
"PUBLIC.Quoted.Id.null",
"PUBLIC.Quoted.Name.null.50",
"PUBLIC.TEST.ID.null",
"PUBLIC.TEST.NAME.'default name'.50",
"PUBLIC.TEST.AGE.21",
"PUBLIC.TEST.VAL.null.50",
"PUBLIC.TEST_DECIMAL_COLUMN.ID.null",
"PUBLIC.TEST_DECIMAL_COLUMN.DEC_COL.null.8.3",
"PUBLIC.TEST_DECIMAL_COLUMN_PRECISION.ID.null",
"PUBLIC.TEST_DECIMAL_COLUMN_PRECISION.DEC_COL.null.8",
"PUBLIC.TEST_DECIMAL_DATE_COLUMN_META.ID.null",
"PUBLIC.TEST_DECIMAL_DATE_COLUMN_META.DEC_COL.null.8",
"PUBLIC.TEST_DECIMAL_DATE_COLUMN_META.DATE_COL.null",
"dep.DEPARTMENT.ID.null",
"dep.DEPARTMENT.NAME.null.43",
"org.ORGANIZATION.ID.null",
"org.ORGANIZATION.NAME.null.42",
"pers.PERSON.NAME.null",
"pers.PERSON.AGE.null",
"pers.PERSON.ORGID.null"
));
Set<String> actualUserCols = new HashSet<>(expectedCols.size());
Set<String> actualSystemCols = new HashSet<>();
while(rs.next()) {
int precision = rs.getInt("COLUMN_SIZE");
int scale = rs.getInt("DECIMAL_DIGITS");
String schemaName = rs.getString("TABLE_SCHEM");
String colDefinition = schemaName + '.'
+ rs.getString("TABLE_NAME") + "."
+ rs.getString("COLUMN_NAME") + "."
+ rs.getString("COLUMN_DEF")
+ (precision == 0 ? "" : ("." + precision))
+ (scale == 0 ? "" : ("." + scale));
if (!schemaName.equals(SCHEMA_SYS))
actualUserCols.add(colDefinition);
else
actualSystemCols.add(colDefinition);
}
Assert.assertEquals(expectedCols, actualUserCols);
expectedCols = new HashSet<>(Arrays.asList(
"SYS.BASELINE_NODES.CONSISTENT_ID.null.2147483647",
"SYS.BASELINE_NODES.ONLINE.null.1",
"SYS.CACHES.CACHE_GROUP_ID.null.10",
"SYS.CACHES.CACHE_GROUP_NAME.null.2147483647",
"SYS.CACHES.CACHE_ID.null.10",
"SYS.CACHES.CACHE_NAME.null.2147483647",
"SYS.CACHES.CACHE_TYPE.null.2147483647",
"SYS.CACHES.CACHE_MODE.null.2147483647",
"SYS.CACHES.ATOMICITY_MODE.null.2147483647",
"SYS.CACHES.IS_ONHEAP_CACHE_ENABLED.null.1",
"SYS.CACHES.IS_COPY_ON_READ.null.1",
"SYS.CACHES.IS_LOAD_PREVIOUS_VALUE.null.1",
"SYS.CACHES.IS_READ_FROM_BACKUP.null.1",
"SYS.CACHES.PARTITION_LOSS_POLICY.null.2147483647",
"SYS.CACHES.NODE_FILTER.null.2147483647",
"SYS.CACHES.TOPOLOGY_VALIDATOR.null.2147483647",
"SYS.CACHES.IS_EAGER_TTL.null.1",
"SYS.CACHES.WRITE_SYNCHRONIZATION_MODE.null.2147483647",
"SYS.CACHES.IS_INVALIDATE.null.1",
"SYS.CACHES.IS_EVENTS_DISABLED.null.1",
"SYS.CACHES.IS_STATISTICS_ENABLED.null.1",
"SYS.CACHES.IS_MANAGEMENT_ENABLED.null.1",
"SYS.CACHES.BACKUPS.null.10",
"SYS.CACHES.AFFINITY.null.2147483647",
"SYS.CACHES.AFFINITY_MAPPER.null.2147483647",
"SYS.CACHES.REBALANCE_MODE.null.2147483647",
"SYS.CACHES.REBALANCE_BATCH_SIZE.null.10",
"SYS.CACHES.REBALANCE_TIMEOUT.null.19",
"SYS.CACHES.REBALANCE_DELAY.null.19",
"SYS.CACHES.REBALANCE_THROTTLE.null.19",
"SYS.CACHES.REBALANCE_BATCHES_PREFETCH_COUNT.null.19",
"SYS.CACHES.REBALANCE_ORDER.null.10",
"SYS.CACHES.EVICTION_FILTER.null.2147483647",
"SYS.CACHES.EVICTION_POLICY_FACTORY.null.2147483647",
"SYS.CACHES.IS_NEAR_CACHE_ENABLED.null.1",
"SYS.CACHES.NEAR_CACHE_EVICTION_POLICY_FACTORY.null.2147483647",
"SYS.CACHES.NEAR_CACHE_START_SIZE.null.10",
"SYS.CACHES.DEFAULT_LOCK_TIMEOUT.null.19",
"SYS.CACHES.INTERCEPTOR.null.2147483647",
"SYS.CACHES.CACHE_STORE_FACTORY.null.2147483647",
"SYS.CACHES.IS_STORE_KEEP_BINARY.null.1",
"SYS.CACHES.IS_READ_THROUGH.null.1",
"SYS.CACHES.IS_WRITE_THROUGH.null.1",
"SYS.CACHES.IS_WRITE_BEHIND_ENABLED.null.1",
"SYS.CACHES.WRITE_BEHIND_COALESCING.null.1",
"SYS.CACHES.WRITE_BEHIND_FLUSH_SIZE.null.10",
"SYS.CACHES.WRITE_BEHIND_FLUSH_FREQUENCY.null.19",
"SYS.CACHES.WRITE_BEHIND_FLUSH_THREAD_COUNT.null.10",
"SYS.CACHES.WRITE_BEHIND_BATCH_SIZE.null.10",
"SYS.CACHES.MAX_CONCURRENT_ASYNC_OPERATIONS.null.10",
"SYS.CACHES.CACHE_LOADER_FACTORY.null.2147483647",
"SYS.CACHES.CACHE_WRITER_FACTORY.null.2147483647",
"SYS.CACHES.EXPIRY_POLICY_FACTORY.null.2147483647",
"SYS.CACHES.IS_SQL_ESCAPE_ALL.null.1",
"SYS.CACHES.IS_ENCRYPTION_ENABLED.null.1",
"SYS.CACHES.SQL_SCHEMA.null.2147483647",
"SYS.CACHES.SQL_INDEX_MAX_INLINE_SIZE.null.10",
"SYS.CACHES.IS_SQL_ONHEAP_CACHE_ENABLED.null.1",
"SYS.CACHES.SQL_ONHEAP_CACHE_MAX_SIZE.null.10",
"SYS.CACHES.QUERY_DETAIL_METRICS_SIZE.null.10",
"SYS.CACHES.QUERY_PARALLELISM.null.10",
"SYS.CACHES.MAX_QUERY_ITERATORS_COUNT.null.10",
"SYS.CACHES.DATA_REGION_NAME.null.2147483647",
"SYS.CACHE_GROUPS.CACHE_GROUP_ID.null.10",
"SYS.CACHE_GROUPS.CACHE_GROUP_NAME.null.2147483647",
"SYS.CACHE_GROUPS.IS_SHARED.null.1",
"SYS.CACHE_GROUPS.CACHE_COUNT.null.10",
"SYS.CACHE_GROUPS.CACHE_MODE.null.2147483647",
"SYS.CACHE_GROUPS.ATOMICITY_MODE.null.2147483647",
"SYS.CACHE_GROUPS.AFFINITY.null.2147483647",
"SYS.CACHE_GROUPS.PARTITIONS_COUNT.null.10",
"SYS.CACHE_GROUPS.NODE_FILTER.null.2147483647",
"SYS.CACHE_GROUPS.DATA_REGION_NAME.null.2147483647",
"SYS.CACHE_GROUPS.TOPOLOGY_VALIDATOR.null.2147483647",
"SYS.CACHE_GROUPS.PARTITION_LOSS_POLICY.null.2147483647",
"SYS.CACHE_GROUPS.REBALANCE_MODE.null.2147483647",
"SYS.CACHE_GROUPS.REBALANCE_DELAY.null.19",
"SYS.CACHE_GROUPS.REBALANCE_ORDER.null.10",
"SYS.CACHE_GROUPS.BACKUPS.null.10",
"SYS.INDEXES.CACHE_ID.null.10",
"SYS.INDEXES.CACHE_NAME.null.2147483647",
"SYS.INDEXES.SCHEMA_NAME.null.2147483647",
"SYS.INDEXES.TABLE_NAME.null.2147483647",
"SYS.INDEXES.INDEX_NAME.null.2147483647",
"SYS.INDEXES.INDEX_TYPE.null.2147483647",
"SYS.INDEXES.COLUMNS.null.2147483647",
"SYS.INDEXES.IS_PK.null.1",
"SYS.INDEXES.IS_UNIQUE.null.1",
"SYS.INDEXES.INLINE_SIZE.null.10",
"SYS.LOCAL_CACHE_GROUPS_IO.CACHE_GROUP_ID.null.10",
"SYS.LOCAL_CACHE_GROUPS_IO.CACHE_GROUP_NAME.null.2147483647",
"SYS.LOCAL_CACHE_GROUPS_IO.PHYSICAL_READS.null.19",
"SYS.LOCAL_CACHE_GROUPS_IO.LOGICAL_READS.null.19",
"SYS.SQL_QUERIES_HISTORY.SCHEMA_NAME.null.2147483647",
"SYS.SQL_QUERIES_HISTORY.SQL.null.2147483647",
"SYS.SQL_QUERIES_HISTORY.LOCAL.null.1",
"SYS.SQL_QUERIES_HISTORY.EXECUTIONS.null.19",
"SYS.SQL_QUERIES_HISTORY.FAILURES.null.19",
"SYS.SQL_QUERIES_HISTORY.DURATION_MIN.null.19",
"SYS.SQL_QUERIES_HISTORY.DURATION_MAX.null.19",
"SYS.SQL_QUERIES_HISTORY.LAST_START_TIME.null.26.6",
"SYS.SQL_QUERIES.QUERY_ID.null.2147483647",
"SYS.SQL_QUERIES.SQL.null.2147483647",
"SYS.SQL_QUERIES.SCHEMA_NAME.null.2147483647",
"SYS.SQL_QUERIES.LOCAL.null.1",
"SYS.SQL_QUERIES.START_TIME.null.26.6",
"SYS.SQL_QUERIES.DURATION.null.19",
"SYS.SQL_QUERIES.ORIGIN_NODE_ID.null.2147483647",
"SYS.SCAN_QUERIES.START_TIME.null.19",
"SYS.SCAN_QUERIES.TRANSFORMER.null.2147483647",
"SYS.SCAN_QUERIES.LOCAL.null.1",
"SYS.SCAN_QUERIES.QUERY_ID.null.19",
"SYS.SCAN_QUERIES.PARTITION.null.10",
"SYS.SCAN_QUERIES.CACHE_GROUP_ID.null.10",
"SYS.SCAN_QUERIES.CACHE_NAME.null.2147483647",
"SYS.SCAN_QUERIES.TOPOLOGY.null.2147483647",
"SYS.SCAN_QUERIES.CACHE_GROUP_NAME.null.2147483647",
"SYS.SCAN_QUERIES.TASK_NAME.null.2147483647",
"SYS.SCAN_QUERIES.DURATION.null.19",
"SYS.SCAN_QUERIES.KEEP_BINARY.null.1",
"SYS.SCAN_QUERIES.FILTER.null.2147483647",
"SYS.SCAN_QUERIES.SUBJECT_ID.null.2147483647",
"SYS.SCAN_QUERIES.CANCELED.null.1",
"SYS.SCAN_QUERIES.CACHE_ID.null.10",
"SYS.SCAN_QUERIES.PAGE_SIZE.null.10",
"SYS.SCAN_QUERIES.ORIGIN_NODE_ID.null.2147483647",
"SYS.NODES.NODE_ID.null.2147483647",
"SYS.NODES.CONSISTENT_ID.null.2147483647",
"SYS.NODES.VERSION.null.2147483647",
"SYS.NODES.IS_CLIENT.null.1",
"SYS.NODES.IS_DAEMON.null.1",
"SYS.NODES.IS_LOCAL.null.1",
"SYS.NODES.NODE_ORDER.null.19",
"SYS.NODES.ADDRESSES.null.2147483647",
"SYS.NODES.HOSTNAMES.null.2147483647",
"SYS.NODE_ATTRIBUTES.NODE_ID.null.2147483647",
"SYS.NODE_ATTRIBUTES.NAME.null.2147483647",
"SYS.NODE_ATTRIBUTES.VALUE.null.2147483647",
"SYS.NODE_METRICS.NODE_ID.null.2147483647",
"SYS.NODE_METRICS.LAST_UPDATE_TIME.null.26.6",
"SYS.NODE_METRICS.MAX_ACTIVE_JOBS.null.10",
"SYS.NODE_METRICS.CUR_ACTIVE_JOBS.null.10",
"SYS.NODE_METRICS.AVG_ACTIVE_JOBS.null.7",
"SYS.NODE_METRICS.MAX_WAITING_JOBS.null.10",
"SYS.NODE_METRICS.CUR_WAITING_JOBS.null.10",
"SYS.NODE_METRICS.AVG_WAITING_JOBS.null.7",
"SYS.NODE_METRICS.MAX_REJECTED_JOBS.null.10",
"SYS.NODE_METRICS.CUR_REJECTED_JOBS.null.10",
"SYS.NODE_METRICS.AVG_REJECTED_JOBS.null.7",
"SYS.NODE_METRICS.TOTAL_REJECTED_JOBS.null.10",
"SYS.NODE_METRICS.MAX_CANCELED_JOBS.null.10",
"SYS.NODE_METRICS.CUR_CANCELED_JOBS.null.10",
"SYS.NODE_METRICS.AVG_CANCELED_JOBS.null.7",
"SYS.NODE_METRICS.TOTAL_CANCELED_JOBS.null.10",
"SYS.NODE_METRICS.MAX_JOBS_WAIT_TIME.null.19",
"SYS.NODE_METRICS.CUR_JOBS_WAIT_TIME.null.19",
"SYS.NODE_METRICS.AVG_JOBS_WAIT_TIME.null.19",
"SYS.NODE_METRICS.MAX_JOBS_EXECUTE_TIME.null.19",
"SYS.NODE_METRICS.CUR_JOBS_EXECUTE_TIME.null.19",
"SYS.NODE_METRICS.AVG_JOBS_EXECUTE_TIME.null.19",
"SYS.NODE_METRICS.TOTAL_JOBS_EXECUTE_TIME.null.19",
"SYS.NODE_METRICS.TOTAL_EXECUTED_JOBS.null.10",
"SYS.NODE_METRICS.TOTAL_EXECUTED_TASKS.null.10",
"SYS.NODE_METRICS.TOTAL_BUSY_TIME.null.19",
"SYS.NODE_METRICS.TOTAL_IDLE_TIME.null.19",
"SYS.NODE_METRICS.CUR_IDLE_TIME.null.19",
"SYS.NODE_METRICS.BUSY_TIME_PERCENTAGE.null.7",
"SYS.NODE_METRICS.IDLE_TIME_PERCENTAGE.null.7",
"SYS.NODE_METRICS.TOTAL_CPU.null.10",
"SYS.NODE_METRICS.CUR_CPU_LOAD.null.17",
"SYS.NODE_METRICS.AVG_CPU_LOAD.null.17",
"SYS.NODE_METRICS.CUR_GC_CPU_LOAD.null.17",
"SYS.NODE_METRICS.HEAP_MEMORY_INIT.null.19",
"SYS.NODE_METRICS.HEAP_MEMORY_USED.null.19",
"SYS.NODE_METRICS.HEAP_MEMORY_COMMITED.null.19",
"SYS.NODE_METRICS.HEAP_MEMORY_MAX.null.19",
"SYS.NODE_METRICS.HEAP_MEMORY_TOTAL.null.19",
"SYS.NODE_METRICS.NONHEAP_MEMORY_INIT.null.19",
"SYS.NODE_METRICS.NONHEAP_MEMORY_USED.null.19",
"SYS.NODE_METRICS.NONHEAP_MEMORY_COMMITED.null.19",
"SYS.NODE_METRICS.NONHEAP_MEMORY_MAX.null.19",
"SYS.NODE_METRICS.NONHEAP_MEMORY_TOTAL.null.19",
"SYS.NODE_METRICS.UPTIME.null.19",
"SYS.NODE_METRICS.JVM_START_TIME.null.26.6",
"SYS.NODE_METRICS.NODE_START_TIME.null.26.6",
"SYS.NODE_METRICS.LAST_DATA_VERSION.null.19",
"SYS.NODE_METRICS.CUR_THREAD_COUNT.null.10",
"SYS.NODE_METRICS.MAX_THREAD_COUNT.null.10",
"SYS.NODE_METRICS.TOTAL_THREAD_COUNT.null.19",
"SYS.NODE_METRICS.CUR_DAEMON_THREAD_COUNT.null.10",
"SYS.NODE_METRICS.SENT_MESSAGES_COUNT.null.10",
"SYS.NODE_METRICS.SENT_BYTES_COUNT.null.19",
"SYS.NODE_METRICS.RECEIVED_MESSAGES_COUNT.null.10",
"SYS.NODE_METRICS.RECEIVED_BYTES_COUNT.null.19",
"SYS.NODE_METRICS.OUTBOUND_MESSAGES_QUEUE.null.10",
"SYS.TABLES.CACHE_ID.null.10",
"SYS.TABLES.CACHE_NAME.null.2147483647",
"SYS.TABLES.SCHEMA_NAME.null.2147483647",
"SYS.TABLES.TABLE_NAME.null.2147483647",
"SYS.TABLES.AFFINITY_KEY_COLUMN.null.2147483647",
"SYS.TABLES.KEY_ALIAS.null.2147483647",
"SYS.TABLES.VALUE_ALIAS.null.2147483647",
"SYS.TABLES.KEY_TYPE_NAME.null.2147483647",
"SYS.TABLES.VALUE_TYPE_NAME.null.2147483647",
"SYS.TABLES.IS_INDEX_REBUILD_IN_PROGRESS.null.1",
"SYS.METRICS.NAME.null.2147483647",
"SYS.METRICS.VALUE.null.2147483647",
"SYS.METRICS.DESCRIPTION.null.2147483647",
"SYS.SERVICES.SERVICE_ID.null.2147483647",
"SYS.SERVICES.NAME.null.2147483647",
"SYS.SERVICES.SERVICE_CLASS.null.2147483647",
"SYS.SERVICES.CACHE_NAME.null.2147483647",
"SYS.SERVICES.ORIGIN_NODE_ID.null.2147483647",
"SYS.SERVICES.TOTAL_COUNT.null.10",
"SYS.SERVICES.MAX_PER_NODE_COUNT.null.10",
"SYS.SERVICES.AFFINITY_KEY.null.2147483647",
"SYS.SERVICES.NODE_FILTER.null.2147483647",
"SYS.SERVICES.STATICALLY_CONFIGURED.null.1",
"SYS.SERVICES.SERVICE_ID.null.2147483647",
"SYS.TASKS.AFFINITY_CACHE_NAME.null.2147483647",
"SYS.TASKS.INTERNAL.null.1",
"SYS.TASKS.END_TIME.null.19",
"SYS.TASKS.START_TIME.null.19",
"SYS.TASKS.USER_VERSION.null.2147483647",
"SYS.TASKS.TASK_NAME.null.2147483647",
"SYS.TASKS.TASK_NODE_ID.null.2147483647",
"SYS.TASKS.JOB_ID.null.2147483647",
"SYS.TASKS.AFFINITY_PARTITION_ID.null.10",
"SYS.TASKS.TASK_CLASS_NAME.null.2147483647",
"SYS.TASKS.EXEC_NAME.null.2147483647",
"SYS.CLIENT_CONNECTIONS.CONNECTION_ID.null.19",
"SYS.CLIENT_CONNECTIONS.LOCAL_ADDRESS.null.2147483647",
"SYS.CLIENT_CONNECTIONS.REMOTE_ADDRESS.null.2147483647",
"SYS.CLIENT_CONNECTIONS.TYPE.null.2147483647",
"SYS.CLIENT_CONNECTIONS.USER.null.2147483647",
"SYS.CLIENT_CONNECTIONS.VERSION.null.2147483647",
"SYS.TASKS.EXEC_NAME.null.2147483647",
"SYS.TRANSACTIONS.LOCAL_NODE_ID.null.2147483647",
"SYS.TRANSACTIONS.STATE.null.2147483647",
"SYS.TRANSACTIONS.XID.null.2147483647",
"SYS.TRANSACTIONS.LABEL.null.2147483647",
"SYS.TRANSACTIONS.START_TIME.null.19",
"SYS.TRANSACTIONS.ISOLATION.null.2147483647",
"SYS.TRANSACTIONS.CONCURRENCY.null.2147483647",
"SYS.TRANSACTIONS.COLOCATED.null.1",
"SYS.TRANSACTIONS.DHT.null.1",
"SYS.TRANSACTIONS.IMPLICIT.null.1",
"SYS.TRANSACTIONS.IMPLICIT_SINGLE.null.1",
"SYS.TRANSACTIONS.INTERNAL.null.1",
"SYS.TRANSACTIONS.LOCAL.null.1",
"SYS.TRANSACTIONS.NEAR.null.1",
"SYS.TRANSACTIONS.ONE_PHASE_COMMIT.null.1",
"SYS.TRANSACTIONS.SUBJECT_ID.null.2147483647",
"SYS.TRANSACTIONS.SYSTEM.null.1",
"SYS.TRANSACTIONS.THREAD_ID.null.19",
"SYS.TRANSACTIONS.TIMEOUT.null.19",
"SYS.TRANSACTIONS.DURATION.null.19",
"SYS.TRANSACTIONS.ORIGINATING_NODE_ID.null.2147483647",
"SYS.TRANSACTIONS.OTHER_NODE_ID.null.2147483647",
"SYS.TRANSACTIONS.TOP_VER.null.2147483647",
"SYS.TRANSACTIONS.KEYS_COUNT.null.10",
"SYS.TRANSACTIONS.CACHE_IDS.null.2147483647",
"SYS.SCHEMAS.NAME.null.2147483647",
"SYS.SCHEMAS.PREDEFINED.null.1",
"SYS.VIEWS.NAME.null.2147483647",
"SYS.VIEWS.DESCRIPTION.null.2147483647",
"SYS.VIEWS.SCHEMA.null.2147483647",
"SYS.TABLE_COLUMNS.AFFINITY_COLUMN.null.1",
"SYS.TABLE_COLUMNS.COLUMN_NAME.null.2147483647",
"SYS.TABLE_COLUMNS.SCALE.null.10",
"SYS.TABLE_COLUMNS.PK.null.1",
"SYS.TABLE_COLUMNS.TYPE.null.2147483647",
"SYS.TABLE_COLUMNS.DEFAULT_VALUE.null.2147483647",
"SYS.TABLE_COLUMNS.SCHEMA_NAME.null.2147483647",
"SYS.TABLE_COLUMNS.TABLE_NAME.null.2147483647",
"SYS.TABLE_COLUMNS.NULLABLE.null.1",
"SYS.TABLE_COLUMNS.PRECISION.null.10",
"SYS.TABLE_COLUMNS.AUTO_INCREMENT.null.1",
"SYS.VIEW_COLUMNS.NULLABLE.null.1",
"SYS.VIEW_COLUMNS.SCHEMA_NAME.null.2147483647",
"SYS.VIEW_COLUMNS.COLUMN_NAME.null.2147483647",
"SYS.VIEW_COLUMNS.TYPE.null.2147483647",
"SYS.VIEW_COLUMNS.PRECISION.null.19",
"SYS.VIEW_COLUMNS.DEFAULT_VALUE.null.2147483647",
"SYS.VIEW_COLUMNS.SCALE.null.10",
"SYS.VIEW_COLUMNS.VIEW_NAME.null.2147483647",
"SYS.CONTINUOUS_QUERIES.NOTIFY_EXISTING.null.1",
"SYS.CONTINUOUS_QUERIES.OLD_VALUE_REQUIRED.null.1",
"SYS.CONTINUOUS_QUERIES.KEEP_BINARY.null.1",
"SYS.CONTINUOUS_QUERIES.IS_MESSAGING.null.1",
"SYS.CONTINUOUS_QUERIES.AUTO_UNSUBSCRIBE.null.1",
"SYS.CONTINUOUS_QUERIES.LAST_SEND_TIME.null.19",
"SYS.CONTINUOUS_QUERIES.LOCAL_TRANSFORMED_LISTENER.null.2147483647",
"SYS.CONTINUOUS_QUERIES.TOPIC.null.2147483647",
"SYS.CONTINUOUS_QUERIES.BUFFER_SIZE.null.10",
"SYS.CONTINUOUS_QUERIES.REMOTE_TRANSFORMER.null.2147483647",
"SYS.CONTINUOUS_QUERIES.DELAYED_REGISTER.null.1",
"SYS.CONTINUOUS_QUERIES.IS_QUERY.null.1",
"SYS.CONTINUOUS_QUERIES.NODE_ID.null.2147483647",
"SYS.CONTINUOUS_QUERIES.INTERVAL.null.19",
"SYS.CONTINUOUS_QUERIES.IS_EVENTS.null.1",
"SYS.CONTINUOUS_QUERIES.ROUTINE_ID.null.2147483647",
"SYS.CONTINUOUS_QUERIES.REMOTE_FILTER.null.2147483647",
"SYS.CONTINUOUS_QUERIES.CACHE_NAME.null.2147483647",
"SYS.CONTINUOUS_QUERIES.LOCAL_LISTENER.null.2147483647",
"SYS.STRIPED_THREADPOOL_QUEUE.STRIPE_INDEX.null.10",
"SYS.STRIPED_THREADPOOL_QUEUE.DESCRIPTION.null.2147483647",
"SYS.STRIPED_THREADPOOL_QUEUE.THREAD_NAME.null.2147483647",
"SYS.STRIPED_THREADPOOL_QUEUE.TASK_NAME.null.2147483647",
"SYS.DATASTREAM_THREADPOOL_QUEUE.STRIPE_INDEX.null.10",
"SYS.DATASTREAM_THREADPOOL_QUEUE.DESCRIPTION.null.2147483647",
"SYS.DATASTREAM_THREADPOOL_QUEUE.THREAD_NAME.null.2147483647",
"SYS.DATASTREAM_THREADPOOL_QUEUE.TASK_NAME.null.2147483647",
"SYS.CACHE_GROUP_PAGE_LISTS.CACHE_GROUP_ID.null.10",
"SYS.CACHE_GROUP_PAGE_LISTS.PARTITION_ID.null.10",
"SYS.CACHE_GROUP_PAGE_LISTS.NAME.null.2147483647",
"SYS.CACHE_GROUP_PAGE_LISTS.BUCKET_NUMBER.null.10",
"SYS.CACHE_GROUP_PAGE_LISTS.BUCKET_SIZE.null.19",
"SYS.CACHE_GROUP_PAGE_LISTS.STRIPES_COUNT.null.10",
"SYS.CACHE_GROUP_PAGE_LISTS.CACHED_PAGES_COUNT.null.10",
"SYS.DATA_REGION_PAGE_LISTS.NAME.null.2147483647",
"SYS.DATA_REGION_PAGE_LISTS.BUCKET_NUMBER.null.10",
"SYS.DATA_REGION_PAGE_LISTS.BUCKET_SIZE.null.19",
"SYS.DATA_REGION_PAGE_LISTS.STRIPES_COUNT.null.10",
"SYS.DATA_REGION_PAGE_LISTS.CACHED_PAGES_COUNT.null.10"
));
Assert.assertEquals(expectedCols, actualSystemCols);
}
}
/**
* @throws Exception If failed.
*/
@Test
public void testInvalidCatalog() throws Exception {
try (Connection conn = DriverManager.getConnection(URL)) {
DatabaseMetaData meta = conn.getMetaData();
ResultSet rs = meta.getSchemas("q", null);
assert !rs.next() : "Results must be empty";
rs = meta.getTables("q", null, null, null);
assert !rs.next() : "Results must be empty";
rs = meta.getColumns("q", null, null, null);
assert !rs.next() : "Results must be empty";
rs = meta.getIndexInfo("q", null, null, false, false);
assert !rs.next() : "Results must be empty";
rs = meta.getPrimaryKeys("q", null, null);
assert !rs.next() : "Results must be empty";
}
}
/**
* @throws Exception If failed.
*/
@Test
public void testIndexMetadata() throws Exception {
try (Connection conn = DriverManager.getConnection(URL);
ResultSet rs = conn.getMetaData().getIndexInfo(null, "pers", "PERSON", false, false)) {
int cnt = 0;
while (rs.next()) {
String idxName = rs.getString("INDEX_NAME");
String field = rs.getString("COLUMN_NAME");
String ascOrDesc = rs.getString("ASC_OR_DESC");
assert rs.getShort("TYPE") == DatabaseMetaData.tableIndexOther;
if ("PERSON_ORGID_ASC_IDX".equals(idxName)) {
assert "ORGID".equals(field);
assert "A".equals(ascOrDesc);
}
else if ("PERSON_NAME_ASC_AGE_DESC_IDX".equals(idxName)) {
if ("NAME".equals(field))
assert "A".equals(ascOrDesc);
else if ("AGE".equals(field))
assert "D".equals(ascOrDesc);
else
fail("Unexpected field: " + field);
}
else
fail("Unexpected index: " + idxName);
cnt++;
}
assert cnt == 3;
}
}
/**
* @throws Exception If failed.
*/
@Test
public void testGetAllIndexes() throws Exception {
try (Connection conn = DriverManager.getConnection(URL)) {
ResultSet rs = conn.getMetaData().getIndexInfo(null, null, null, false, false);
Set<String> expectedIdxs = new HashSet<>(Arrays.asList(
"org.ORGANIZATION.ORGANIZATION_ID_ASC_IDX",
"org.ORGANIZATION.ORG_NAME_INDEX",
"pers.PERSON.PERSON_ORGID_ASC_IDX",
"pers.PERSON.PERSON_NAME_ASC_AGE_DESC_IDX",
"PUBLIC.TEST.IDX",
"PUBLIC.Quoted.MyTestIndex quoted"));
Set<String> actualIdxs = new HashSet<>(expectedIdxs.size());
while(rs.next()) {
actualIdxs.add(rs.getString("TABLE_SCHEM") +
'.' + rs.getString("TABLE_NAME") +
'.' + rs.getString("INDEX_NAME"));
}
assert expectedIdxs.equals(actualIdxs) : "expectedIdxs=" + expectedIdxs +
", actualIdxs" + actualIdxs;
}
}
/**
* @throws Exception If failed.
*/
@Test
public void testPrimaryKeyMetadata() throws Exception {
try (Connection conn = DriverManager.getConnection(URL);
ResultSet rs = conn.getMetaData().getPrimaryKeys(null, "pers", "PERSON")) {
int cnt = 0;
while (rs.next()) {
assert "_KEY".equals(rs.getString("COLUMN_NAME"));
cnt++;
}
assert cnt == 1;
}
}
/**
* @throws Exception If failed.
*/
@Test
public void testGetAllPrimaryKeys() throws Exception {
try (Connection conn = DriverManager.getConnection(URL)) {
ResultSet rs = conn.getMetaData().getPrimaryKeys(null, null, null);
Set<String> expectedPks = new HashSet<>(Arrays.asList(
"org.ORGANIZATION.PK_org_ORGANIZATION._KEY",
"pers.PERSON.PK_pers_PERSON._KEY",
"dep.DEPARTMENT.PK_dep_DEPARTMENT._KEY",
"PUBLIC.TEST.PK_PUBLIC_TEST.ID",
"PUBLIC.TEST.PK_PUBLIC_TEST.NAME",
"PUBLIC.Quoted.PK_PUBLIC_Quoted.Id",
"PUBLIC.TEST_DECIMAL_COLUMN.ID.ID",
"PUBLIC.TEST_DECIMAL_COLUMN_PRECISION.ID.ID",
"PUBLIC.TEST_DECIMAL_DATE_COLUMN_META.ID.ID"));
Set<String> actualPks = new HashSet<>(expectedPks.size());
while(rs.next()) {
actualPks.add(rs.getString("TABLE_SCHEM") +
'.' + rs.getString("TABLE_NAME") +
'.' + rs.getString("PK_NAME") +
'.' + rs.getString("COLUMN_NAME"));
}
assertEquals("Metadata contains unexpected primary keys info.", expectedPks, actualPks);
}
}
/**
* @throws Exception If failed.
*/
@Test
public void testParametersMetadata() throws Exception {
// Perform checks few times due to query/plan caching.
for (int i = 0; i < 3; i++) {
// No parameters statement.
try(Connection conn = DriverManager.getConnection(URL)) {
conn.setSchema("\"pers\"");
PreparedStatement noParams = conn.prepareStatement("select * from Person;");
ParameterMetaData params = noParams.getParameterMetaData();
assertEquals("Parameters should be empty.", 0, params.getParameterCount());
}
// Selects.
try (Connection conn = DriverManager.getConnection(URL)) {
conn.setSchema("\"pers\"");
PreparedStatement selectStmt = conn.prepareStatement("select orgId from Person p where p.name > ? and p.orgId > ?");
ParameterMetaData meta = selectStmt.getParameterMetaData();
assertNotNull(meta);
assertEquals(2, meta.getParameterCount());
assertEquals(Types.VARCHAR, meta.getParameterType(1));
assertEquals(ParameterMetaData.parameterNullableUnknown, meta.isNullable(1));
assertEquals(Integer.MAX_VALUE, meta.getPrecision(1));
assertEquals(Types.INTEGER, meta.getParameterType(2));
assertEquals(ParameterMetaData.parameterNullableUnknown, meta.isNullable(2));
}
// Updates.
try (Connection conn = DriverManager.getConnection(URL)) {
conn.setSchema("\"pers\"");
PreparedStatement updateStmt = conn.prepareStatement("update Person p set orgId = 42 where p.name > ? and p.orgId > ?");
ParameterMetaData meta = updateStmt.getParameterMetaData();
assertNotNull(meta);
assertEquals(2, meta.getParameterCount());
assertEquals(Types.VARCHAR, meta.getParameterType(1));
assertEquals(ParameterMetaData.parameterNullableUnknown, meta.isNullable(1));
assertEquals(Integer.MAX_VALUE, meta.getPrecision(1));
assertEquals(Types.INTEGER, meta.getParameterType(2));
assertEquals(ParameterMetaData.parameterNullableUnknown, meta.isNullable(2));
}
// Multistatement
try (Connection conn = DriverManager.getConnection(URL)) {
conn.setSchema("\"pers\"");
PreparedStatement updateStmt = conn.prepareStatement(
"update Person p set orgId = 42 where p.name > ? and p.orgId > ?;" +
"select orgId from Person p where p.name > ? and p.orgId > ?");
ParameterMetaData meta = updateStmt.getParameterMetaData();
assertNotNull(meta);
assertEquals(4, meta.getParameterCount());
assertEquals(Types.VARCHAR, meta.getParameterType(1));
assertEquals(ParameterMetaData.parameterNullableUnknown, meta.isNullable(1));
assertEquals(Integer.MAX_VALUE, meta.getPrecision(1));
assertEquals(Types.INTEGER, meta.getParameterType(2));
assertEquals(ParameterMetaData.parameterNullableUnknown, meta.isNullable(2));
assertEquals(Types.VARCHAR, meta.getParameterType(3));
assertEquals(ParameterMetaData.parameterNullableUnknown, meta.isNullable(3));
assertEquals(Integer.MAX_VALUE, meta.getPrecision(3));
assertEquals(Types.INTEGER, meta.getParameterType(4));
assertEquals(ParameterMetaData.parameterNullableUnknown, meta.isNullable(4));
}
}
}
/**
* Check that parameters metadata throws correct exception on non-parsable statement.
*/
@Test
public void testParametersMetadataNegative() throws Exception {
try (Connection conn = DriverManager.getConnection(URL)) {
conn.setSchema("\"pers\"");
PreparedStatement notCorrect = conn.prepareStatement("select * from NotExistingTable;");
GridTestUtils.assertThrows(log(), notCorrect::getParameterMetaData, SQLException.class,
"Table \"NOTEXISTINGTABLE\" not found");
}
}
/**
* @throws Exception If failed.
*/
@Test
public void testSchemasMetadata() throws Exception {
try (Connection conn = DriverManager.getConnection(URL)) {
ResultSet rs = conn.getMetaData().getSchemas();
Set<String> expectedSchemas = new HashSet<>(Arrays.asList(SCHEMA_SYS, DFLT_SCHEMA,
"pers", "org", "dep", "PREDEFINED_SCHEMAS_1", "PREDEFINED_SCHEMAS_2"));
Set<String> schemas = new HashSet<>();
while (rs.next()) {
schemas.add(rs.getString(1));
assertEquals("There is only one possible catalog.",
JdbcUtils.CATALOG_NAME, rs.getString(2));
}
assert expectedSchemas.equals(schemas) : "Unexpected schemas: " + schemas +
". Expected schemas: " + expectedSchemas;
}
}
/**
* Negative scenarios for catalog name.
* Perform metadata lookups, that use incorrect catalog names.
*/
@Test
public void testCatalogWithNotExistingName() throws SQLException {
checkNoEntitiesFoundForCatalog("");
checkNoEntitiesFoundForCatalog("NOT_EXISTING_CATALOG");
}
/**
* Check that lookup in the metadata have been performed using specified catalog name (that is neither {@code null}
* nor correct catalog name), empty result set is returned.
*
* @param invalidCat catalog name that is not either
*/
private void checkNoEntitiesFoundForCatalog(String invalidCat) throws SQLException {
try (Connection conn = DriverManager.getConnection(URL)) {
DatabaseMetaData meta = conn.getMetaData();
// Intention: we set the other arguments that way, the values to have as many results as possible.
assertIsEmpty(meta.getTables(invalidCat, null, "%", new String[] {"TABLE"}));
assertIsEmpty(meta.getColumns(invalidCat, null, "%", "%"));
assertIsEmpty(meta.getColumnPrivileges(invalidCat, "pers", "PERSON", "%"));
assertIsEmpty(meta.getTablePrivileges(invalidCat, null, "%"));
assertIsEmpty(meta.getPrimaryKeys(invalidCat, "pers", "PERSON"));
assertIsEmpty(meta.getImportedKeys(invalidCat, "pers", "PERSON"));
assertIsEmpty(meta.getExportedKeys(invalidCat, "pers", "PERSON"));
// meta.getCrossReference(...) doesn't make sense because we don't have FK constraint.
assertIsEmpty(meta.getIndexInfo(invalidCat, null, "%", false, true));
assertIsEmpty(meta.getSuperTables(invalidCat, "%", "%"));
assertIsEmpty(meta.getSchemas(invalidCat, null));
assertIsEmpty(meta.getPseudoColumns(invalidCat, null, "%", ""));
}
}
/**
* Assert that specified ResultSet contains no rows.
*
* @param rs result set to check.
* @throws SQLException on error.
*/
private static void assertIsEmpty(ResultSet rs) throws SQLException {
try {
boolean empty = !rs.next();
assertTrue("Result should be empty because invalid catalog is specified.", empty);
}
finally {
rs.close();
}
}
/**
* @throws Exception If failed.
*/
@Test
public void testEmptySchemasMetadata() throws Exception {
try (Connection conn = DriverManager.getConnection(URL)) {
ResultSet rs = conn.getMetaData().getSchemas(null, "qqq");
assert !rs.next() : "Empty result set is expected";
}
}
/**
* @throws Exception If failed.
*/
@Test
public void testVersions() throws Exception {
try (Connection conn = DriverManager.getConnection(URL)) {
assertEquals("Unexpected ignite database product version.",
conn.getMetaData().getDatabaseProductVersion(), IgniteVersionUtils.VER.toString());
assertEquals("Unexpected ignite driver version.",
conn.getMetaData().getDriverVersion(), IgniteVersionUtils.VER.toString());
}
try (Connection conn = DriverManager.getConnection(URL_PARTITION_AWARENESS)) {
assertEquals("Unexpected ignite database product version.",
conn.getMetaData().getDatabaseProductVersion(), IgniteVersionUtils.VER.toString());
assertEquals("Unexpected ignite driver version.",
conn.getMetaData().getDriverVersion(), IgniteVersionUtils.VER.toString());
}
}
/**
* Person.
*/
private static class Person implements Serializable {
/** Name. */
private final String name;
/** Age. */
private final int age;
/** Organization ID. */
private final int orgId;
/**
* @param name Name.
* @param age Age.
* @param orgId Organization ID.
*/
private Person(String name, int age, int orgId) {
assert !F.isEmpty(name);
assert age > 0;
assert orgId > 0;
this.name = name;
this.age = age;
this.orgId = orgId;
}
}
/**
* Organization.
*/
private static class Organization implements Serializable {
/** ID. */
private final int id;
/** Name. */
private final String name;
/**
* @param id ID.
* @param name Name.
*/
private Organization(int id, String name) {
this.id = id;
this.name = name;
}
}
/**
* Organization.
*/
private static class Department implements Serializable {
/** ID. */
@QuerySqlField
private final int id;
/** Name. */
@QuerySqlField(precision = 43)
private final String name;
/**
* @param id ID.
* @param name Name.
*/
private Department(int id, String name) {
this.id = id;
this.name = name;
}
}
}
|
|
package com.finance.iso.iso8583.mediator;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.xml.stream.XMLStreamException;
import junit.framework.TestCase;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.util.AXIOMUtil;
import org.apache.axiom.soap.SOAPEnvelope;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.engine.AxisConfiguration;
import org.apache.synapse.MessageContext;
import org.apache.synapse.config.Entry;
import org.apache.synapse.config.SynapseConfiguration;
import org.apache.synapse.core.SynapseEnvironment;
import org.apache.synapse.core.axis2.Axis2MessageContext;
import org.apache.synapse.core.axis2.Axis2SynapseEnvironment;
public class XLinkISO8583MediatorTest extends TestCase {
private final Map<String, Entry> entries = new HashMap<String, Entry>();
public void testXLinkSignOn() {
XLinkISO8583Mediator linkISO8583Mediator = new XLinkISO8583Mediator();
linkISO8583Mediator.init(null);
linkISO8583Mediator.setHost("localhost");
linkISO8583Mediator.setPort("8000");
MessageContext msgCtx = null;
try {
msgCtx = this.generateMessage(msgCtx,null,null); // message # 1 ISO
setupAccountInfo(msgCtx);
linkISO8583Mediator.mediate(msgCtx);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (Exception e) {
fail("failed to perform sign-on for XLink");
}
}
/* {
"APIRequest": {
"InquiryType": "30",
"UserData": "Enc(PAN|CARDNO|PIN)",
"TrxId": "xx",
"Currency": "IDR|VND"
}
}
XML...
<APIRequest>
<OperationType>30</OperationType>
<UserData>Enc(PAN|CARDNO|PIN)</UserData>
<TrxId>xx</TrxId>
<Currency>IDR|VND</Currency>
</APIRequest>
*/
public void testDoTransaction() {
String payload = "<APIRequest> " + "<OperationType>30</OperationType>"
+ "<TrxId>123456789</TrxId>" + "<Currency>IDR</Currency>"
+ "</APIRequest>";
XLinkISO8583Mediator linkISO8583Mediator = new XLinkISO8583Mediator();
linkISO8583Mediator.init(null);
linkISO8583Mediator.setHost("localhost");
linkISO8583Mediator.setPort("8000");
MessageContext msgCtx = null;
try {
OMElement payloadOM = AXIOMUtil.stringToOM(payload);
msgCtx = this.generateMessage(msgCtx, payloadOM,null); // message # 1 ISO
setupAccountInfo(msgCtx);
linkISO8583Mediator.mediate(msgCtx);
org.apache.axis2.context.MessageContext axis2msgCtx = ((Axis2MessageContext) msgCtx)
.getAxis2MessageContext();
System.out.println(axis2msgCtx.getEnvelope());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (Exception e) {
fail("failed to perform sign-on for XLink");
}
}
/*if JSON, once converting it
<jsonObject>
<APIRequest>
<OperationType>30</OperationType>
<UserData>Enc(PAN|CARDNO|PIN)</UserData>
<TrxId>xx</TrxId><Currency>IDR|VND</Currency>
</APIRequest>
</jsonObject>*/
public void testTransactionMultiple() {
String payload = "<jsonObject><APIRequest> " + "<OperationType>30</OperationType>"
+ "<TrxId>xx</TrxId>" + "<Currency>IDR</Currency>"
+ "</APIRequest></jsonObject>";
XLinkISO8583Mediator linkISO8583Mediator = new XLinkISO8583Mediator();
linkISO8583Mediator.init(null);
linkISO8583Mediator.setHost("localhost");
linkISO8583Mediator.setPort("8000");
MessageContext msgCtx = null;
String msisdn = UUID.randomUUID().toString();
try {
OMElement payloadOM = AXIOMUtil.stringToOM(payload);
msgCtx = this.generateMessage(msgCtx, payloadOM,msisdn); // message # 1 ISO
setupAccountInfo(msgCtx);
linkISO8583Mediator.mediate(msgCtx);
org.apache.axis2.context.MessageContext axis2msgCtx = ((Axis2MessageContext) msgCtx)
.getAxis2MessageContext();
System.out.println(axis2msgCtx.getEnvelope());
try {
Thread.sleep(20000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i < 3; i++) {
System.out.println("iterating ####"+i);
echoMesg(payload, linkISO8583Mediator, msgCtx, msisdn);
}
} catch (Exception e) {
fail("failed to perform sign-on for XLink");
}
}
private void echoMesg(String payload,
XLinkISO8583Mediator linkISO8583Mediator, MessageContext msgCtx,
String msisdn) throws XMLStreamException {
OMElement payloadOM;
org.apache.axis2.context.MessageContext axis2msgCtx;
payloadOM = AXIOMUtil.stringToOM(payload);
msgCtx = this.generateMessage(msgCtx, payloadOM,msisdn); // message # 1 ISO
setupAccountInfo(msgCtx);
linkISO8583Mediator.mediate(msgCtx);
axis2msgCtx = ((Axis2MessageContext) msgCtx)
.getAxis2MessageContext();
System.out.println(axis2msgCtx.getEnvelope());
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*if JSON, once converting it
<jsonObject>
<APIRequest>
<OperationType>50</OperationType>
<UserData>MTIzOjQ1Njo3ODk=</UserData>
<TrxId>12345678</TrxId>
<Currency>IDR</Currency>
<Amount>999999</Amount>
</APIRequest>
</jsonObject>*/
public void testPaymentJSON() {
String payload = "<jsonObject><APIRequest> " + "<OperationType>50</OperationType>"
+ "<UserData>MTIzNDU2OjEyMzQ1NjoxMjM0NTYxMjM0NTYxMjM0</UserData>" //base 64encode
+ "<TrxId>123213999</TrxId>"
+ "<Currency>LKR</Currency>"
+ "<Amount>20000</Amount>"
+ "</APIRequest></jsonObject>";
XLinkISO8583Mediator linkISO8583Mediator = new XLinkISO8583Mediator();
linkISO8583Mediator.init(null);
linkISO8583Mediator.setHost("localhost");
linkISO8583Mediator.setPort("8000");
MessageContext msgCtx = null;
try {
OMElement payloadOM = AXIOMUtil.stringToOM(payload);
msgCtx = this.generateMessage(msgCtx, payloadOM,null); // message # 1 ISO
setupAccountInfo(msgCtx);
linkISO8583Mediator.mediate(msgCtx);
org.apache.axis2.context.MessageContext axis2msgCtx = ((Axis2MessageContext) msgCtx)
.getAxis2MessageContext();
System.out.println(axis2msgCtx.getEnvelope());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (Exception e) {
fail("failed to perform sign-on for XLink");
}
}
private void setupAccountInfo(MessageContext msgCtx) {
msgCtx.setProperty("cardno", "card123");
msgCtx.setProperty("accountno", "accountno123");
msgCtx.setProperty("pinno", "1234567890123456");
}
/*if JSON, once converting it
<jsonObject>
<APIRequest>
<OperationType>50</OperationType>
<UserData>MTIzOjQ1Njo3ODk=</UserData>
<TrxId>12345678</TrxId>
<Currency>IDR</Currency>
<Amount>999999</Amount>
</APIRequest>
</jsonObject>*/
public void testPaymentJSONThenSignOff() {
String payload = "<jsonObject><APIRequest> " + "<OperationType>50</OperationType>"
+ "<UserData>MTIzNDU2OjEyMzQ1NjoxMjM0NTYxMjM0NTYxMjM0</UserData>" //base 64encode
+ "<TrxId>123213999</TrxId>"
+ "<Currency>LKR</Currency>"
+ "<Amount>20000</Amount>"
+ "</APIRequest></jsonObject>";
XLinkISO8583Mediator linkISO8583Mediator = new XLinkISO8583Mediator();
linkISO8583Mediator.init(null);
linkISO8583Mediator.setHost("localhost");
linkISO8583Mediator.setPort("8000");
MessageContext msgCtx = null;
String msisdn = UUID.randomUUID().toString();
try {
OMElement payloadOM = AXIOMUtil.stringToOM(payload);
msgCtx = this.generateMessage(msgCtx, payloadOM,msisdn); // message # 1 ISO
setupAccountInfo(msgCtx);
linkISO8583Mediator.mediate(msgCtx);
org.apache.axis2.context.MessageContext axis2msgCtx = ((Axis2MessageContext) msgCtx)
.getAxis2MessageContext();
System.out.println(axis2msgCtx.getEnvelope());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//signOff Request.
payload = "<jsonObject><APIRequest> " + "<OperationType>02</OperationType>"
+ "</APIRequest></jsonObject>";
payloadOM = AXIOMUtil.stringToOM(payload);
msgCtx = this.generateMessage(msgCtx, payloadOM,msisdn);
linkISO8583Mediator.mediate(msgCtx);
Thread.sleep(10000);
} catch (Exception e) {
fail("failed to perform sign-on for XLink");
}
}
// msgCtx = this.generateMessage(msgCtx); // message # 2 ISO
// linkISO8583Mediator.mediate(msgCtx);
//
// Map<String, XLinkSessionWrapper> map = XLinkConnnector.getInstance()
// .getMap();
// assertEquals(2, map.size());
//
// try {
// Thread.sleep(60000);
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
//
// for (Map.Entry<String, XLinkSessionWrapper> entry : map.entrySet()) {
// msgCtx.setProperty(XLinkISO8583Constant.MOBILE_CONNECTION_KEY,
// entry.getKey());
// linkISO8583Mediator.mediate(msgCtx);
// }
// assertEquals(2, map.size());
private MessageContext generateMessage(MessageContext msgCtx,OMElement payload,String msisdn) {
try {
msgCtx = build();
org.apache.axis2.context.MessageContext axis2MsgCtx = ((Axis2MessageContext) msgCtx)
.getAxis2MessageContext();
OMElement payloadOM = AXIOMUtil.stringToOM(XML_PAYLOAD_A);
axis2MsgCtx.getEnvelope().getBody().addChild(payload !=null?payload:payloadOM);
msgCtx.setProperty(XLinkISO8583Constant.MOBILE_CONNECTION_KEY, msisdn ==null ?(UUID
.randomUUID().toString()):msisdn);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return msgCtx;
}
/**
* Build the test message context. This method returns a new (and
* independent) instance on every invocation.
*
* @return
* @throws Exception
*/
public MessageContext build() throws Exception {
SynapseConfiguration testConfig = new SynapseConfiguration();
// TODO: check whether we need a SynapseEnvironment in all cases
SynapseEnvironment synEnv = new Axis2SynapseEnvironment(
new ConfigurationContext(new AxisConfiguration()),
testConfig);
MessageContext synCtx = new Axis2MessageContext(
new org.apache.axis2.context.MessageContext(), testConfig,
synEnv);
for (Map.Entry<String, Entry> mapEntry : entries.entrySet()) {
testConfig.addEntry(mapEntry.getKey(), mapEntry.getValue());
}
;
SOAPEnvelope envelope = OMAbstractFactory.getSOAP11Factory()
.getDefaultEnvelope();
org.apache.axis2.context.MessageContext axis2MsgCtx = ((Axis2MessageContext) synCtx)
.getAxis2MessageContext();
axis2MsgCtx.setEnvelope(envelope);
return synCtx;
}
private static String XML_PAYLOAD_A = "<iso8583message>" + "<config>"
+ "<mti>1800</mti>" + "</config>" + "<data>"
+ "<field id=\"3\">110</field>" + "<field id=\"5\">4200.00</field>"
+ "<field id=\"48\">Simple Credit Transaction</field>"
+ "<field id=\"6\">645.23</field>"
+ "<field id=\"88\">66377125</field>" + "</data>"
+ "</iso8583message>";
}
|
|
package org.apache.helix.task;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.apache.helix.controller.stages.CurrentStateOutput;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.Message;
import org.apache.helix.model.Partition;
import org.apache.helix.model.ResourceAssignment;
import org.apache.helix.task.assigner.TaskAssignResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A TaskAssignmentCalculator for when a task group must be assigned according to partitions/states
* on a target
* resource. Here, tasks are co-located according to where a resource's partitions are, as well as
* (if desired) only where those partitions are in a given state.
*/
public class FixedTargetTaskAssignmentCalculator extends TaskAssignmentCalculator {
private static final Logger LOG =
LoggerFactory.getLogger(FixedTargetTaskAssignmentCalculator.class);
private AssignableInstanceManager _assignableInstanceManager;
/**
* Default constructor. Because of quota-based scheduling support, we need
* AssignableInstanceManager. This constructor should not be used.
*/
@Deprecated
public FixedTargetTaskAssignmentCalculator() {
}
/**
* Constructor for FixedTargetTaskAssignmentCalculator. Requires AssignableInstanceManager for
* "charging" resources per task.
* @param assignableInstanceManager
*/
public FixedTargetTaskAssignmentCalculator(AssignableInstanceManager assignableInstanceManager) {
_assignableInstanceManager = assignableInstanceManager;
}
@Override
public Set<Integer> getAllTaskPartitions(JobConfig jobCfg, JobContext jobCtx,
WorkflowConfig workflowCfg, WorkflowContext workflowCtx,
Map<String, IdealState> idealStateMap) {
IdealState tgtIs = idealStateMap.get(jobCfg.getTargetResource());
return getAllTaskPartitions(tgtIs, jobCfg, jobCtx);
}
@Override
public Map<String, SortedSet<Integer>> getTaskAssignment(CurrentStateOutput currStateOutput,
ResourceAssignment prevAssignment, Collection<String> instances, JobConfig jobCfg,
JobContext jobContext, WorkflowConfig workflowCfg, WorkflowContext workflowCtx,
Set<Integer> partitionSet, Map<String, IdealState> idealStateMap) {
return computeAssignmentAndChargeResource(currStateOutput, prevAssignment, instances,
workflowCfg, jobCfg, jobContext, partitionSet, idealStateMap);
}
/**
* Returns the set of all partition ids for a job.
* If a set of partition ids was explicitly specified in the config, that is used. Otherwise, we
* use the list of all partition ids from the target resource.
* return empty set if target resource does not exist.
*/
private static Set<Integer> getAllTaskPartitions(IdealState tgtResourceIs, JobConfig jobCfg,
JobContext taskCtx) {
Map<String, List<Integer>> currentTargets = taskCtx.getPartitionsByTarget();
SortedSet<String> targetPartitions = Sets.newTreeSet();
if (jobCfg.getTargetPartitions() != null) {
targetPartitions.addAll(jobCfg.getTargetPartitions());
} else {
if (tgtResourceIs != null) {
targetPartitions.addAll(tgtResourceIs.getPartitionSet());
} else {
LOG.warn("Missing target resource for the scheduled job!");
}
}
Set<Integer> taskPartitions = Sets.newTreeSet();
for (String targetPartition : targetPartitions) {
taskPartitions
.addAll(getPartitionsForTargetPartition(targetPartition, currentTargets, taskCtx));
}
return taskPartitions;
}
private static List<Integer> getPartitionsForTargetPartition(String targetPartition,
Map<String, List<Integer>> currentTargets, JobContext jobCtx) {
if (!currentTargets.containsKey(targetPartition)) {
int nextId = jobCtx.getPartitionSet().size();
jobCtx.setPartitionTarget(nextId, targetPartition);
return Lists.newArrayList(nextId);
} else {
return currentTargets.get(targetPartition);
}
}
/**
* NOTE: this method has been deprecated due to the addition of quota-based task scheduling.
* Get partition assignments for the target resource, but only for the partitions of interest.
* @param currStateOutput The current state of the instances in the cluster.
* @param instances The instances.
* @param tgtIs The ideal state of the target resource.
* @param tgtStates Only partitions in this set of states will be considered. If null, partitions
* do not need to
* be in any specific state to be considered.
* @param includeSet The set of partitions to consider.
* @return A map of instance vs set of partition ids assigned to that instance.
*/
@Deprecated
private static Map<String, SortedSet<Integer>> getTgtPartitionAssignment(
CurrentStateOutput currStateOutput, Iterable<String> instances, IdealState tgtIs,
Set<String> tgtStates, Set<Integer> includeSet, JobContext jobCtx) {
Map<String, SortedSet<Integer>> result = new HashMap<>();
for (String instance : instances) {
result.put(instance, new TreeSet<Integer>());
}
Map<String, List<Integer>> partitionsByTarget = jobCtx.getPartitionsByTarget();
for (String pName : tgtIs.getPartitionSet()) {
List<Integer> partitions = partitionsByTarget.get(pName);
if (partitions == null || partitions.size() < 1) {
continue;
}
int pId = partitions.get(0);
if (includeSet.contains(pId)) {
for (String instance : instances) {
Message pendingMessage = currStateOutput.getPendingMessage(tgtIs.getResourceName(),
new Partition(pName), instance);
if (pendingMessage != null) {
continue;
}
String s = currStateOutput.getCurrentState(tgtIs.getResourceName(), new Partition(pName),
instance);
if (s != null && (tgtStates == null || tgtStates.contains(s))) {
result.get(instance).add(pId);
}
}
}
}
return result;
}
/**
* Calculate the assignment for given tasks. This assignment also charges resources for each task
* and takes resource/quota availability into account while assigning.
* @param currStateOutput
* @param prevAssignment
* @param liveInstances
* @param jobCfg
* @param jobContext
* @param taskPartitionSet
* @param idealStateMap
* @return instance -> set of task partition numbers
*/
private Map<String, SortedSet<Integer>> computeAssignmentAndChargeResource(
CurrentStateOutput currStateOutput, ResourceAssignment prevAssignment,
Collection<String> liveInstances, WorkflowConfig workflowCfg, JobConfig jobCfg,
JobContext jobContext, Set<Integer> taskPartitionSet, Map<String, IdealState> idealStateMap) {
// Note: targeted jobs also take up capacity in quota-based scheduling
// "Charge" resources for the tasks
String quotaType = getQuotaType(workflowCfg, jobCfg);
// IdealState of the target resource
IdealState targetIdealState = idealStateMap.get(jobCfg.getTargetResource());
if (targetIdealState == null) {
LOG.warn("Missing target resource for the scheduled job!");
return Collections.emptyMap();
}
// The "states" you want to assign to. Assign to the partitions of the target resource if these
// partitions are in one of these states
Set<String> targetStates = jobCfg.getTargetPartitionStates();
Map<String, SortedSet<Integer>> result = new HashMap<>();
for (String instance : liveInstances) {
result.put(instance, new TreeSet<Integer>());
}
// <Target resource partition name -> list of task partition numbers> mapping
Map<String, List<Integer>> partitionsByTarget = jobContext.getPartitionsByTarget();
for (String targetResourcePartitionName : targetIdealState.getPartitionSet()) {
// Get all task partition numbers to be assigned to this targetResource partition
List<Integer> taskPartitions = partitionsByTarget.get(targetResourcePartitionName);
if (taskPartitions == null || taskPartitions.size() < 1) {
continue; // No tasks to assign, skip
}
// Get one task to be assigned to this targetResource partition
int targetPartitionId = taskPartitions.get(0);
// First, see if that task needs to be assigned at this time
if (taskPartitionSet.contains(targetPartitionId)) {
for (String instance : liveInstances) {
// See if there is a pending message on this instance on this partition for the target
// resource
// If there is, we should wait until the pending message gets processed, so skip
// assignment this time around
Message pendingMessage =
currStateOutput.getPendingMessage(targetIdealState.getResourceName(),
new Partition(targetResourcePartitionName), instance);
if (pendingMessage != null) {
continue;
}
// See if there a partition exists on this instance
String currentState = currStateOutput.getCurrentState(targetIdealState.getResourceName(),
new Partition(targetResourcePartitionName), instance);
if (currentState != null
&& (targetStates == null || targetStates.contains(currentState))) {
// Prepare pName and taskConfig for assignment
String pName = String.format("%s_%s", jobCfg.getJobId(), targetPartitionId);
if (!jobCfg.getTaskConfigMap().containsKey(pName)) {
jobCfg.getTaskConfigMap().put(pName,
new TaskConfig(null, null, pName, targetResourcePartitionName));
}
TaskConfig taskConfig = jobCfg.getTaskConfigMap().get(pName);
// On LiveInstance change, RUNNING or other non-terminal tasks might get re-assigned. If
// the new assignment differs from prevAssignment, release. If the assigned instances
// from old and new assignments are the same, then do nothing and let it keep running
// The following checks if two assignments (old and new) differ
Map<String, String> instanceMap = prevAssignment.getReplicaMap(new Partition(pName));
Iterator<String> itr = instanceMap.keySet().iterator();
// First, check if this taskPartition has been ever assigned before by checking
// prevAssignment
if (itr.hasNext()) {
String prevInstance = itr.next();
if (!prevInstance.equals(instance)) {
// Old and new assignments are different. We need to release from prevInstance, and
// this task will be assigned to a different instance
if (_assignableInstanceManager.getAssignableInstanceNames()
.contains(prevInstance)) {
_assignableInstanceManager.release(prevInstance, taskConfig, quotaType);
} else {
// This instance must be no longer live
LOG.warn(
"Task {} was reassigned from old instance: {} to new instance: {}. However, old instance: {} is not found in AssignableInstanceMap. The old instance is possibly no longer a LiveInstance. This task will not be released.",
pName, prevAssignment, instance);
}
} else {
// Old and new assignments are the same, so just skip assignment for this
// taskPartition so that it can just keep running
break;
}
}
// Actual assignment logic: try to charge resources first and assign if successful
if (_assignableInstanceManager.getAssignableInstanceNames().contains(instance)) {
// Try to assign first
TaskAssignResult taskAssignResult =
_assignableInstanceManager.tryAssign(instance, taskConfig, quotaType);
if (taskAssignResult.isSuccessful()) {
// There exists a partition, the states match up, and tryAssign successful. Assign!
_assignableInstanceManager.assign(instance, taskAssignResult);
result.get(instance).add(targetPartitionId);
// To prevent double assign of the tasks on other replicas of the targetResource
// partition
break;
} else if ((!taskAssignResult.isSuccessful() && taskAssignResult
.getFailureReason() == TaskAssignResult.FailureReason.TASK_ALREADY_ASSIGNED)) {
// In case of double assign, we can still include it in the assignment because
// RUNNING->RUNNING message will just be ignored by the participant
// AssignableInstance should already have it assigned, so do not double-charge
result.get(instance).add(targetPartitionId);
break;
} else {
LOG.warn(
"Unable to assign the task to this AssignableInstance. Skipping this instance. Task: {}, Instance: {}, TaskAssignResult: {}",
pName, instance, taskAssignResult);
}
} else {
LOG.error(
"AssignableInstance does not exist for this LiveInstance: {}. This should never happen! Will not assign to this instance.",
instance);
}
}
}
}
}
return result;
}
}
|
|
package com.iwisdomsky.resflux;
import android.app.*;
import android.content.*;
import android.content.pm.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import com.iwisdomsky.resflux.adapter.*;
import java.io.*;
import java.util.*;
import java.util.zip.*;
import android.text.*;
public class ExportActivity extends Activity implements View.OnClickListener
{
// progress bar shown when loading packages list
private LinearLayout mProgress;
// the listview which will be populated with
private ListView mListView;
// list of all export-able packages with mods
private ArrayList<String> mPackagesList;
// the export button
private Button mExport;
// the holder of user-selected packages to be exported
private ArrayList<String> mExportList;
// progress dialog shown when exporting is started
private ProgressDialog mExporting;
// the adapter to be used, ofcourse
private PackageListAdapter mAdapter;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.export);
// create the packages dir if not found
Utils.mkDirs(getFilesDir(),"packages");
// initializations
mExportList = new ArrayList<String>();
mPackagesList = new ArrayList<String>();
mProgress = new LinearLayout(this);
mProgress.setOrientation(LinearLayout.HORIZONTAL);
mProgress.setGravity(Gravity.CENTER);
mProgress.addView(new ProgressBar(this));
mListView = (ListView)findViewById(R.id.packagelist);
mListView.setFastScrollEnabled(true);
mListView.addFooterView(mProgress);
mAdapter = new PackageListAdapter(ExportActivity.this,mPackagesList);
mListView.setAdapter(mAdapter);
mExport = ((Button)findViewById(R.id.export));
mExport.setOnClickListener(this);
mExport.setEnabled(false);
((Button)findViewById(R.id.cancel)).setOnClickListener(new View.OnClickListener(){
public void onClick(View p1)
{
finish();
}
});
// start loading packages list
new Thread(loadPackagesList()).start();
}
// export button on click callback
public void onClick(View p1)
{
if ( mExportList.size() == 0 )
return;
final EditText et = new EditText(this);
et.setSingleLine(true);
et.setInputType(InputType.TYPE_TEXT_FLAG_CAP_WORDS);
new AlertDialog.Builder(this)
.setTitle("Set label:")
.setView(et)
.setNeutralButton("Export", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface p1, int p2)
{
final String file_name = et.getText().toString().trim();
new Thread(new Runnable(){
public void run()
{
exportModPackages(file_name);
runOnUiThread(new Runnable(){
public void run()
{
mExporting.dismiss();
}
});
}
}).start();
mExporting = new ProgressDialog(ExportActivity.this);
mExporting.setCancelable(false);
mExporting.setIndeterminate(true);
mExporting.setMessage("Exporting...");
mExporting.setOnDismissListener(new DialogInterface.OnDismissListener(){
public void onDismiss(DialogInterface p1)
{
Toast.makeText(ExportActivity.this,"Export complete!",Toast.LENGTH_SHORT).show();
finish();
}
});
mExporting.show();
}
}).create().show();
}
// export method
private void exportModPackages(String filename){
//Toast.makeText(this,mExportList.toString(),Toast.LENGTH_SHORT).show();
try
{
// get export dir handle
File export = new File(Environment.getExternalStorageDirectory(),"Resflux");
// be sure that the dirs exist
export.mkdirs();
// get export file handle
export = new File(export,filename.replaceAll("[^a-zA-Z0-9_\\.]","_")+".resflux.zip");
// get export file output stream for writing
FileOutputStream f = new FileOutputStream(export);
// get zip output stream for writing entries
ZipOutputStream zos = new ZipOutputStream(f);
// add icon
FileInputStream icon = new FileInputStream(new File(getFilesDir(),"icon.png"));
ZipEntry icon_entry = new ZipEntry("icon.png");
zos.putNextEntry(icon_entry);
int li;byte[] bufferi = new byte[Constants.BUFFER_SIZE];
while ( (li = icon.read(bufferi)) != -1 )
zos.write(bufferi,0,li);
zos.closeEntry();
icon.close();
// get script's input stream
InputStream in = getSerializedModPackagesStream(filename);
// create zip entry
ZipEntry script = new ZipEntry("Resflux.ini");
// put the zip entry
zos.putNextEntry(script);
// start writing to entry
int l;byte[] buffer = new byte[Constants.BUFFER_SIZE];
while ( (l = in.read(buffer)) != -1 )
zos.write(buffer,0,l);
// close the entry after writing
zos.closeEntry();
in.close();
// each packages
for ( int i=0;i<mExportList.size();i++) {
// get file handle
File drawable_dir = new File(getFilesDir(),"packages/"+mExportList.get(i)+"/drawable");
// list contents
File[] drawables = drawable_dir.listFiles();
// if not empty
if ( drawables.length>0 )
// each drawable
for ( File drawable : drawables )
// if a png drawable
if ( drawable.getName().endsWith(".png") ) {
FileInputStream din = new FileInputStream(drawable);
ZipEntry entry = new ZipEntry("packages/"+mExportList.get(i)+"/drawable/"+drawable.getName());
zos.putNextEntry(entry);
int dl;byte[] dbuffer = new byte[Constants.BUFFER_SIZE];
while ( (dl = din.read(dbuffer)) != -1 )
zos.write(dbuffer,0,dl);
zos.closeEntry();
din.close();
}
}
// close the zip file
zos.close();
}
catch (Exception e)
{
//Toast.makeText(this,e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
// Resflux.ini writer method
private InputStream getSerializedModPackagesStream(String file_name){
final StringBuilder script = new StringBuilder();
script.append("###########################################\n");
script.append("## ##\n");
script.append("## Resflux ##\n");
script.append("## Import Manifest File ##\n");
script.append("## ##\n");
script.append("## (Auto-generated. Do not modify) ##\n");
script.append("## ##\n");
script.append("## Developer: @WisdomSky of XDA-Devs ##\n");
script.append("## Contact: http://fb.me/WisdomSky ##\n");
script.append("## ##\n");
script.append("###########################################\n");
script.append("\n\n");
script.append("# set custom label\n");
script.append("resflux.label = \""+file_name+"\"\n");
script.append("# add icon\n");
script.append("resflux.icon = icon.png\n");
script.append("# set description\n");
script.append("resflux.desc = \"No description\"\n\n");
script.append("# magic directory\n");
script.append("ini.magic_dir = packages\n\n");
script.append("# start\n\n");
// each packages
for (int i=0;i<mExportList.size();i++){
// get package dir handle
File pkg = new File(getFilesDir(),"packages/"+mExportList.get(i));
// list package sub-dirs
File[] pkg_res = pkg.listFiles();
// check if there sub-dirs
if ( pkg_res.length > 0 ){
// write package name
script.append(" ["+pkg.getName()+"]\n");
// each of sub-dirs
for ( File ress : pkg_res){
// list sub-dir contents
File[] res_c = ress.listFiles();
// if sub-dir has contents
if ( res_c.length > 0) {
// each contents
for (File res : res_c ) {
// ignore png drawables
if ( ress.getName().equals("drawable") && res.getName().endsWith(".png") )
continue;
try
{
// write key value pairs
BufferedReader r = new BufferedReader(new FileReader(res));
script.append(" "+ress.getName()+"."+res.getName()+" = "+r.readLine()+"\n");
}
catch (Exception e)
{}
}
}
}
script.append("\n");
}
}
return new ByteArrayInputStream(script.toString().getBytes());
}
// load packages method
private Runnable loadPackagesList(){
return new Runnable(){
@Override
public void run(){
PackageManager pm = getPackageManager();
final List<ApplicationInfo> apps = new ArrayList<ApplicationInfo>();
File packages_dir = new File(getFilesDir(),"packages");
// each packages
for (File p : packages_dir.listFiles())
// if package has mods
if (isPackageDirHasContents(p))
try{
apps.add(pm.getApplicationInfo(p.getName(), 0));
} catch (PackageManager.NameNotFoundException e) {}
// if the dir has no existing mods then do some cleaning
else
Utils.deleteFile(p);
// sort packages alphabetically
Collections.sort(apps, new ApplicationInfo.DisplayNameComparator(pm));
for ( int i=0; i<apps.size(); i++ ) {
final int ii=i;
runOnUiThread(new Runnable(){
public void run(){
mPackagesList.add(apps.get(ii).packageName);
mAdapter.notifyDataSetChanged();
}
});
}
// callback
runOnUiThread(new Runnable(){
public void run(){
loadPackagesCallback();
}
});
}
};
}
// method invoked after loading packages
private void loadPackagesCallback(){
mExport.setEnabled(true);
mListView.removeFooterView(mProgress);
mAdapter.notifyDataSetChanged();
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
public void onItemClick(AdapterView<?> p1, View p2, int p3, long p4)
{
if ( p3==mPackagesList.size() )return;
if ( mExportList.contains(mPackagesList.get(p3)) ){
mExportList.remove(mPackagesList.get(p3));
p2.setBackgroundDrawable(null);
} else {
mExportList.add(mPackagesList.get(p3));
p2.setBackgroundColor(0xff444444);
}
}
});
mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener(){
public boolean onItemLongClick(AdapterView<?> p1, View p2, int p3, long p4)
{
final View item = p2;
final int i = p3;
new AlertDialog.Builder(ExportActivity.this)
.setTitle("Actions")
.setSingleChoiceItems(new ArrayAdapter<String>(ExportActivity.this,android.R.layout.simple_list_item_1, new String[]{"Clear Cache","Remove Mods"}), 0, new DialogInterface.OnClickListener(){
public void onClick(DialogInterface p1, int p2)
{
switch (p2) {
case 0:
Utils.deleteFile(new File(getCacheDir(),mPackagesList.get(i)+".bin"));
Toast.makeText(ExportActivity.this,"Cached resources list of this package has been cleared.",Toast.LENGTH_SHORT).show();
break;
case 1:
Utils.deleteFile(new File(getFilesDir(),"packages/"+mPackagesList.get(i)));
//Utils.deleteFile(new File(getCacheDir(),mPackagesList.get(i)+".bin"));
item.setBackgroundDrawable(null);
if ( mExportList.contains(mPackagesList.get(i)) ){
mExportList.remove(mPackagesList.get(i));
}
mPackagesList.remove(i);
mAdapter.notifyDataSetChanged();
Toast.makeText(ExportActivity.this,"All modifications applied to this package have been removed.",Toast.LENGTH_SHORT).show();
break;
}
p1.dismiss();
}
})
.create().show();
return false;
}
});
}
// check if the packages dir has packages with mods
public boolean isPackageDirHasContents(File package_dir){
for ( File sub : package_dir.listFiles() )
if ( sub.listFiles().length > 0) {
return true;
}
return false;
}
}
|
|
package crazypants.enderio.enchantment;
import java.util.ListIterator;
import javax.annotation.Nonnull;
import com.enderio.core.api.common.enchant.IAdvancedEnchant;
import crazypants.enderio.EnderIO;
import crazypants.enderio.Log;
import crazypants.enderio.config.Config;
import crazypants.enderio.integration.baubles.BaublesUtil;
import crazypants.enderio.integration.galacticraft.GalacticraftUtil;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.enchantment.EnumEnchantmentType;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.EntityEquipmentSlot;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemArmor;
import net.minecraft.item.ItemStack;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.util.FakePlayer;
import net.minecraftforge.event.entity.player.PlayerDropsEvent;
import net.minecraftforge.event.entity.player.PlayerEvent;
import net.minecraftforge.fml.common.eventhandler.EventPriority;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.registry.GameRegistry;
public class EnchantmentSoulBound extends Enchantment implements IAdvancedEnchant {
private static final @Nonnull String NAME = "soulBound";
public static EnchantmentSoulBound create() {
EnchantmentSoulBound res = new EnchantmentSoulBound();
MinecraftForge.EVENT_BUS.register(res);
GameRegistry.register(res);
return res;
}
private EnchantmentSoulBound() {
super(Config.enchantmentSoulBoundRarity, EnumEnchantmentType.ALL, EntityEquipmentSlot.values());
setName(NAME);
setRegistryName(NAME);
}
@Override
public int getMaxEnchantability(int level) {
return 60;
}
@Override
public int getMinEnchantability(int level) {
return 16;
}
@Override
public int getMaxLevel() {
return 1;
}
/*
* This is called the moment the player dies and drops his stuff.
*
* We go early, so we can get our items before other mods put them into some
* grave. Also remove them from the list so they won't get duped. If the
* inventory overflows, e.g. because everything there and the armor is
* soulbound, let the remainder be dropped/graved.
*/
@SubscribeEvent(priority = EventPriority.HIGHEST)
public void onPlayerDeath(PlayerDropsEvent evt) {
if (evt.getEntityPlayer() == null || evt.getEntityPlayer() instanceof FakePlayer || evt.isCanceled()) {
return;
}
if(evt.getEntityPlayer().worldObj.getGameRules().getBoolean("keepInventory")) {
return;
}
Log.debug("Running onPlayerDeathEarly logic for " + evt.getEntityPlayer().getName());
ListIterator<EntityItem> iter = evt.getDrops().listIterator();
while (iter.hasNext()) {
EntityItem ei = iter.next();
ItemStack item = ei.getEntityItem();
if(isSoulBound(item)) {
if (addToPlayerInventory(evt.getEntityPlayer(), item)) {
iter.remove();
}
}
}
// Note: Baubles will also add its items to evt.drops, but later. We cannot
// wait for that because gravestone mods also listen to this event. So we have
// to fetch Baubles items ourselves here.
// For the same reason we cannot put the items into Baubles slots.
IInventory baubles = BaublesUtil.instance().getBaubles(evt.getEntityPlayer());
if (baubles != null) {
for (int i = 0; i < baubles.getSizeInventory(); i++) {
ItemStack item = baubles.getStackInSlot(i);
if(isSoulBound(item)) {
if (addToPlayerInventory(evt.getEntityPlayer(), item)) {
baubles.setInventorySlotContents(i, null);
}
}
}
}
// Galacticraft. Again we are too early for those items. We just dump the
// stuff into the normal inventory to not have to keep a separate list.
if (evt.getEntityPlayer() instanceof EntityPlayerMP) {
IInventory galacticraft = GalacticraftUtil.getGCInventoryForPlayer((EntityPlayerMP) evt.getEntityPlayer());
if (galacticraft != null) {
for (int i = 0; i < galacticraft.getSizeInventory(); i++) {
ItemStack item = galacticraft.getStackInSlot(i);
if (isSoulBound(item)) {
if (addToPlayerInventory(evt.getEntityPlayer(), item)) {
galacticraft.setInventorySlotContents(i, null);
}
}
}
}
}
}
/*
* Do a second (late) pass. If any mod has added items to the list in the meantime, this gives us a chance to save them, too. If some gravestone mod has
* removed drops, we'll get nothing here.
*/
@SubscribeEvent(priority = EventPriority.LOWEST)
public void onPlayerDeathLate(PlayerDropsEvent evt) {
if (evt.getEntityPlayer() == null || evt.getEntityPlayer() instanceof FakePlayer || evt.isCanceled()) {
return;
}
if (evt.getEntityPlayer().worldObj.getGameRules().getBoolean("keepInventory")) {
return;
}
Log.debug("Running onPlayerDeathLate logic for " + evt.getEntityPlayer().getName());
ListIterator<EntityItem> iter = evt.getDrops().listIterator();
while (iter.hasNext()) {
EntityItem ei = iter.next();
ItemStack item = ei.getEntityItem();
if (isSoulBound(item)) {
if (addToPlayerInventory(evt.getEntityPlayer(), item)) {
iter.remove();
}
}
}
}
/*
* This is called when the user presses the "respawn" button. The original inventory would be empty, but onPlayerDeath() above placed items in it.
*
* Note: Without other death-modifying mods, the content of the old inventory would always fit into the new one (both being empty but for soulbound items in
* the old one) and the old one would be discarded just after this method. But better play it safe and assume that an overflow is possible and that another
* mod may move stuff out of the old inventory, too.
*/
@SubscribeEvent(priority = EventPriority.HIGHEST)
public void onPlayerClone(PlayerEvent.Clone evt) {
if (!evt.isWasDeath() || evt.isCanceled()) {
return;
}
if(evt.getOriginal() == null || evt.getEntityPlayer() == null || evt.getEntityPlayer() instanceof FakePlayer) {
return;
}
if(evt.getEntityPlayer().worldObj.getGameRules().getBoolean("keepInventory")) {
return;
}
if (evt.getOriginal() == evt.getEntityPlayer()
|| evt.getOriginal().inventory == evt.getEntityPlayer().inventory
|| (evt.getOriginal().inventory.armorInventory == evt.getEntityPlayer().inventory.armorInventory && evt.getOriginal().inventory.mainInventory == evt.getEntityPlayer().inventory.mainInventory)) {
Log.warn("Player " + evt.getEntityPlayer().getName() + " just died and respawned in their old body. Did someone fire a PlayerEvent.Clone(death=true) "
+ "for a teleportation? Supressing Soulbound enchantment for zombie player.");
return;
}
Log.debug("Running onPlayerCloneEarly logic for " + evt.getEntityPlayer().getName());
for (int i = 0; i < evt.getOriginal().inventory.armorInventory.length; i++) {
ItemStack item = evt.getOriginal().inventory.armorInventory[i];
if(isSoulBound(item)) {
if (addToPlayerInventory(evt.getEntityPlayer(), item)) {
evt.getOriginal().inventory.armorInventory[i] = null;
}
}
}
for (int i = 0; i < evt.getOriginal().inventory.mainInventory.length; i++) {
ItemStack item = evt.getOriginal().inventory.mainInventory[i];
if(isSoulBound(item)) {
if (addToPlayerInventory(evt.getEntityPlayer(), item)) {
evt.getOriginal().inventory.mainInventory[i] = null;
}
}
}
}
/*
* Do a second (late) pass and try to preserve any remaining items by spawning them into the world. They might end up nowhere, but if we do nothing they will
* be deleted. Note the dropping at the old location, because the new player object's location has not yet been set.
*/
@SubscribeEvent(priority = EventPriority.LOWEST)
public void onPlayerCloneLast(PlayerEvent.Clone evt) {
if (!evt.isWasDeath() || evt.isCanceled()) {
return;
}
if (evt.getOriginal() == null || evt.getEntityPlayer() == null || evt.getEntityPlayer() instanceof FakePlayer) {
return;
}
if (evt.getEntityPlayer().worldObj.getGameRules().getBoolean("keepInventory")) {
return;
}
if (evt.getOriginal() == evt.getEntityPlayer()
|| evt.getOriginal().inventory == evt.getEntityPlayer().inventory
|| (evt.getOriginal().inventory.armorInventory == evt.getEntityPlayer().inventory.armorInventory && evt.getOriginal().inventory.mainInventory == evt.getEntityPlayer().inventory.mainInventory)) {
return;
}
Log.debug("Running onPlayerCloneLate logic for " + evt.getEntityPlayer().getName());
for (int i = 0; i < evt.getOriginal().inventory.armorInventory.length; i++) {
ItemStack item = evt.getOriginal().inventory.armorInventory[i];
if (item != null && isSoulBound(item)) {
if (addToPlayerInventory(evt.getEntityPlayer(), item) || tryToSpawnItemInWorld(evt.getOriginal(), item)) {
evt.getOriginal().inventory.armorInventory[i] = null;
}
}
}
for (int i = 0; i < evt.getOriginal().inventory.mainInventory.length; i++) {
ItemStack item = evt.getOriginal().inventory.mainInventory[i];
if (item != null && isSoulBound(item)) {
if (addToPlayerInventory(evt.getEntityPlayer(), item) || tryToSpawnItemInWorld(evt.getOriginal(), item)) {
evt.getOriginal().inventory.mainInventory[i] = null;
}
}
}
}
private boolean tryToSpawnItemInWorld(EntityPlayer entityPlayer, @Nonnull ItemStack item) {
if (entityPlayer != null && entityPlayer.worldObj != null) {
EntityItem entityitem = new EntityItem(entityPlayer.worldObj, entityPlayer.posX, entityPlayer.posY + 0.5, entityPlayer.posZ, item);
entityitem.setPickupDelay(40);
entityitem.lifespan *= 2;
entityitem.motionX = 0;
entityitem.motionZ = 0;
entityPlayer.worldObj.spawnEntityInWorld(entityitem);
Log.debug("Running tryToSpawnItemInWorld logic for " + entityPlayer.getName() + ": " + item);
return true;
}
return false;
}
private boolean isSoulBound(ItemStack item) {
return EnchantmentHelper.getEnchantmentLevel(this, item) > 0;
}
private boolean addToPlayerInventory(EntityPlayer entityPlayer, ItemStack item) {
if(item == null || entityPlayer == null) {
return false;
}
if(item.getItem() instanceof ItemArmor) {
ItemArmor arm = (ItemArmor) item.getItem();
int index = arm.armorType.getIndex();
if (entityPlayer.inventory.armorInventory[index] == null) {
entityPlayer.inventory.armorInventory[index] = item;
Log.debug("Running addToPlayerInventory/armor logic for " + entityPlayer.getName() + ": " + item);
return true;
}
}
InventoryPlayer inv = entityPlayer.inventory;
for (int i = 0; i < inv.mainInventory.length; i++) {
if(inv.mainInventory[i] == null) {
inv.mainInventory[i] = item.copy();
Log.debug("Running addToPlayerInventory/main logic for " + entityPlayer.getName() + ": " + item);
return true;
}
}
Log.debug("Running addToPlayerInventory/fail logic for " + entityPlayer.getName() + ": " + item);
return false;
}
@Override
public String[] getTooltipDetails(ItemStack stack) {
return new String[] { EnderIO.lang.localizeExact("description.enchantment.enderio.soulBound") };
}
}
|
|
package org.jzy3d.maths;
import java.awt.geom.Point2D;
import java.io.Serializable;
/** A {@link Coord2d} stores a 2 dimensional coordinate for cartesian (x,y) or
* polar (a,r) mode, and provide operators allowing to add, substract,
* multiply and divises coordinate values, as well as computing the distance between
* two points, and converting polar and cartesian coordinates.
*
* @author Martin Pernollet
*/
public class Coord2d implements Serializable{
private static final long serialVersionUID = 3341791010864877760L;
/** The origin is a Coord2d having value 0 for each dimension.*/
public static final Coord2d ORIGIN = new Coord2d(0.0f, 0.0f);
/** An invalid Coord2d has value NaN for each dimension.*/
public static final Coord2d INVALID = new Coord2d(Float.NaN, Float.NaN);
/** Creates a 2d coordinate with the value 0 for each dimension.*/
public Coord2d(){
x = 0.0f;
y = 0.0f;
}
/** Creates a 2d coordinate.
* When using polar mode, x represents angle, and y represents distance.*/
public Coord2d(float xi, float yi){
x = xi;
y = yi;
}
/** Creates a 2d coordinate.
* When using polar mode, x represents angle, and y represents distance.*/
public Coord2d(double xi, double yi){
x = (float)xi;
y = (float)yi;
}
public Coord2d(Point2D point){
x = (float)point.getX();
y = (float)point.getY();
}
public boolean equals(Object o){
if(o instanceof Coord2d){
Coord2d c = (Coord2d)o;
return x==c.x && y==c.y;
}
else{
return false;
}
}
/** Return a duplicate of this 3d coordinate.*/
public Coord2d clone(){
return new Coord2d(x,y);
}
public Point2D cloneAsFloatPoint(){
return new Point2D.Float(x,y);
}
public Point2D cloneAsDoublePoint(){
return new Point2D.Double(x,y);
}
public void set(Coord2d c2){
x=c2.x;
y=c2.y;
}
/**************************************************************/
/** Add a Coord2d to the current one and return the result
* in a new Coord2d.
* @param c2
* @return the result Coord2d
*/
public Coord2d add(Coord2d c2){
return new Coord2d(x+c2.x, y+c2.y);
}
public void addSelf(Coord2d c2){
x+=c2.x;
y+=c2.y;
}
public void addSelf(float value){
x+=value;
y+=value;
}
public void addSelf(float x, float y){
this.x+=x;
this.y+=y;
}
public void addSelfX(float x){
this.x+=x;
}
public void addSelfY(float y){
this.y+=y;
}
/** Add a value to all components of the current Coord and return the result
* in a new Coord2d.
* @param value
* @return the result Coord2d
*/
public Coord2d add(float value){
return new Coord2d(x+value, y+value);
}
public Coord2d add(float x, float y){
return new Coord2d(this.x+x, this.y+y);
}
/** Substract a Coord2d to the current one and return the result
* in a new Coord2d.
* @param c2
* @return the result Coord2d
*/
public Coord2d sub(Coord2d c2){
return new Coord2d(x-c2.x, y-c2.y);
}
public void subSelf(Coord2d c2){
x-=c2.x;
y-=c2.y;
}
public void subSelf(float x, float y){
this.x-=x;
this.y-=y;
}
/** Substract a value to all components of the current Coord and return the result
* in a new Coord2d.
* @param value
* @return the result Coord2d
*/
public Coord2d sub(float value){
return new Coord2d(x-value, y-value);
}
public Coord2d sub(float x, float y){
return new Coord2d(this.x-x, this.y-y);
}
/** Multiply a Coord2d to the current one and return the result
* in a new Coord2d.
* @param c2
* @return the result Coord2d
*/
public Coord2d mul(Coord2d c2){
return new Coord2d(x*c2.x, y*c2.y);
}
public Coord2d mul(float x, float y){
return new Coord2d(this.x*x, this.y*y);
}
/** Multiply all components of the current Coord and return the result
* in a new Coord3d.
* @param value
* @return the result Coord3d
*/
public Coord2d mul(float value){
return new Coord2d(x*value, y*value);
}
public void mulSelf(float value){
x*=value;
y*=value;
}
/** Divise a Coord2d to the current one and return the result
* in a new Coord2d.
* @param c2
* @return the result Coord2d
*/
public Coord2d div(Coord2d c2){
return new Coord2d(x/c2.x, y/c2.y);
}
/** Divise all components of the current Coord by the same value and return the result
* in a new Coord3d.
* @param value
* @return the result Coord3d
*/
public Coord2d div(float value){
return new Coord2d(x/value, y/value);
}
public Coord2d div(float x, float y){
return new Coord2d(this.x/x, this.y/y);
}
public void divSelf(float value){
x/=value;
y/=value;
}
/** Converts the current Coord3d into cartesian coordinates
* and return the result in a new Coord3d.
* @return the result Coord3d
*/
public Coord2d cartesian(){
return new Coord2d(
Math.cos(x) * y,
Math.sin(x) * y);
}
/**
* Converts the current {@link Coord2d} into polar coordinates
* and return the result in a new {@link Coord2d} where X indicates
* angle, and Y indicates radius.
*
* Warning: If source X is 0, then output angle is NaN.
*
* Output angle is in [-PI/2; PI/2].
*
* @see {@link Coord2d.fullPolar()} for an angle value in [0;2*PI]
*/
public Coord2d polar(){
return new Coord2d(
Math.atan(y/x),
Math.sqrt(x*x + y*y));
}
/**
* Return a real polar value, with an angle in the range [0;2*PI]
* http://fr.wikipedia.org/wiki/Coordonn%C3%A9es_polaires
*/
public Coord2d fullPolar(){
double radius = Math.sqrt(x*x + y*y);
if(x<0){
return new Coord2d(Math.atan(y/x)+Math.PI, radius);
}
else if(x>0){
if(y>=0)
return new Coord2d(Math.atan(y/x), radius);
else
return new Coord2d(Math.atan(y/x)+2*Math.PI, radius);
}
else{ // x==0
if(y>0)
return new Coord2d(Math.PI/2,radius);
else if(y<0)
return new Coord2d(3*Math.PI/2,radius);
else // y==0
return new Coord2d(0,0);
}
}
/** Compute the distance between two coordinates.*/
public double distance(Coord2d c){
return Math.sqrt( Math.pow(x-c.x,2) + Math.pow(y-c.y,2) );
}
public double distanceSq(Coord2d c){
return Math.pow(x-c.x,2) + Math.pow(y-c.y,2);
}
/**
* Returns an interpolated point between the current and given point,
* according to an input ratio in [0;1] that indicates how near to the
* current point the new point will stand.
*
* A value of 1 will return a copy of the current point.
*/
public Coord2d interpolation(Coord2d c, float ratio){
float inv = 1-ratio;
float xx = x*ratio+c.x*inv;
float yy = y*ratio+c.y*inv;
return new Coord2d(xx,yy);
}
/**************************************************************/
/** Return a string representation of this coordinate.*/
public String toString(){
return ("x=" + x + " y=" + y);
}
/** Return an array representation of this coordinate.*/
public float[] toArray(){
float[] array = new float[2];
array[0] = x;
array[1] = y;
return array;
}
/**************************************************************/
public float x;
public float y;
}
|
|
/*
* Copyright 2011 The Closure Compiler 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.google.javascript.jscomp.parsing.parser;
import com.google.javascript.jscomp.parsing.parser.trees.Comment;
import com.google.javascript.jscomp.parsing.parser.util.ErrorReporter;
import com.google.javascript.jscomp.parsing.parser.util.SourcePosition;
import com.google.javascript.jscomp.parsing.parser.util.SourceRange;
import java.util.LinkedList;
/**
* Scans javascript source code into tokens. All entrypoints assume the
* caller is not expecting a regular expression literal except for
* nextRegularExpressionLiteralToken.
*
* <p>7 Lexical Conventions
*/
public class Scanner {
private final ErrorReporter errorReporter;
private final SourceFile source;
private final LinkedList<Token> currentTokens = new LinkedList<>();
private int index;
private final CommentRecorder commentRecorder;
public Scanner(ErrorReporter errorReporter, CommentRecorder commentRecorder,
SourceFile source) {
this(errorReporter, commentRecorder, source, 0);
}
public Scanner(ErrorReporter errorReporter, CommentRecorder commentRecorder,
SourceFile file, int offset) {
this.errorReporter = errorReporter;
this.commentRecorder = commentRecorder;
this.source = file;
this.index = offset;
}
public interface CommentRecorder {
void recordComment(Comment.Type type, SourceRange range, String value);
}
private LineNumberTable getLineNumberTable() {
return this.getFile().lineNumberTable;
}
public SourceFile getFile() {
return source;
}
public int getOffset() {
return currentTokens.isEmpty()
? index
: peekToken().location.start.offset;
}
public SourcePosition getPosition() {
return getPosition(getOffset());
}
private SourcePosition getPosition(int offset) {
return getLineNumberTable().getSourcePosition(offset);
}
private SourceRange getTokenRange(int startOffset) {
return getLineNumberTable().getSourceRange(startOffset, index);
}
public Token nextToken() {
peekToken();
return currentTokens.remove();
}
private void clearTokenLookahead() {
index = getOffset();
currentTokens.clear();
}
public LiteralToken nextRegularExpressionLiteralToken() {
clearTokenLookahead();
int beginToken = index;
// leading '/'
nextChar();
// body
if (!skipRegularExpressionBody()) {
return new LiteralToken(
TokenType.REGULAR_EXPRESSION,
getTokenString(beginToken),
getTokenRange(beginToken));
}
// separating '/'
if (peekChar() != '/') {
reportError("Expected '/' in regular expression literal");
return new LiteralToken(
TokenType.REGULAR_EXPRESSION,
getTokenString(beginToken),
getTokenRange(beginToken));
}
nextChar();
// flags
while (isIdentifierPart(peekChar())) {
nextChar();
}
return new LiteralToken(
TokenType.REGULAR_EXPRESSION,
getTokenString(beginToken),
getTokenRange(beginToken));
}
public LiteralToken nextTemplateLiteralToken() {
Token token = nextToken();
if (isAtEnd() || token.type != TokenType.CLOSE_CURLY) {
reportError(getPosition(index),
"Expected '}' after expression in template literal");
}
return nextTemplateLiteralTokenShared(
TokenType.TEMPLATE_TAIL, TokenType.TEMPLATE_MIDDLE);
}
private boolean skipRegularExpressionBody() {
if (!isRegularExpressionFirstChar(peekChar())) {
reportError("Expected regular expression first char");
return false;
}
if (!skipRegularExpressionChar()) {
return false;
}
while (!isAtEnd() && isRegularExpressionChar(peekChar())) {
if (!skipRegularExpressionChar()) {
return false;
}
}
return true;
}
private boolean skipRegularExpressionChar() {
switch (peekChar()) {
case '\\':
return skipRegularExpressionBackslashSequence();
case '[':
return skipRegularExpressionClass();
default:
nextChar();
return true;
}
}
private boolean skipRegularExpressionBackslashSequence() {
nextChar();
if (isLineTerminator(peekChar())) {
reportError("New line not allowed in regular expression literal");
return false;
}
nextChar();
return true;
}
private boolean skipRegularExpressionClass() {
nextChar();
while (!isAtEnd() && peekRegularExpressionClassChar()) {
if (!skipRegularExpressionClassChar()) {
return false;
}
}
if (peekChar() != ']') {
reportError("']' expected");
return false;
}
nextChar();
return true;
}
private boolean peekRegularExpressionClassChar() {
return peekChar() != ']' && !isLineTerminator(peekChar());
}
private boolean skipRegularExpressionClassChar() {
if (peek('\\')) {
return skipRegularExpressionBackslashSequence();
}
nextChar();
return true;
}
private boolean isRegularExpressionFirstChar(char ch) {
return isRegularExpressionChar(ch) && ch != '*';
}
private boolean isRegularExpressionChar(char ch) {
switch (ch) {
case '/':
return false;
case '\\':
case '[':
return true;
default:
return !isLineTerminator(ch);
}
}
public Token peekToken() {
return peekToken(0);
}
public Token peekToken(int index) {
while (currentTokens.size() <= index) {
currentTokens.add(scanToken());
}
return currentTokens.get(index);
}
private boolean isAtEnd() {
return !isValidIndex(index);
}
private boolean isValidIndex(int index) {
return index >= 0 && index < source.contents.length();
}
// 7.2 White Space
/**
* Returns true if the whitespace that was skipped included any
* line terminators.
*/
private boolean skipWhitespace() {
boolean foundLineTerminator = false;
while (!isAtEnd() && peekWhitespace()) {
if (isLineTerminator(nextChar())) {
foundLineTerminator = true;
}
}
return foundLineTerminator;
}
private boolean peekWhitespace() {
return isWhitespace(peekChar());
}
private static boolean isWhitespace(char ch) {
switch (ch) {
case '\u0009': // Tab
case '\u000B': // Vertical Tab
case '\u000C': // Form Feed
case '\u0020': // Space
case '\u00A0': // No-break space
case '\uFEFF': // Byte Order Mark
case '\n': // Line Feed
case '\r': // Carriage Return
case '\u2028': // Line Separator
case '\u2029': // Paragraph Separator
// TODO: there are other Unicode Category 'Zs' chars that should go here.
return true;
default:
return false;
}
}
// 7.3 Line Terminators
private static boolean isLineTerminator(char ch) {
switch (ch) {
case '\n': // Line Feed
case '\r': // Carriage Return
case '\u2028': // Line Separator
case '\u2029': // Paragraph Separator
return true;
default:
return false;
}
}
// 7.4 Comments
private void skipComments() {
while (skipComment())
{}
}
private boolean skipComment() {
boolean isStartOfLine = skipWhitespace();
if (!isAtEnd()) {
switch (peekChar(0)) {
case '/':
switch (peekChar(1)) {
case '/':
skipSingleLineComment();
return true;
case '*':
skipMultiLineComment();
return true;
}
break;
case '<':
// Check if this is the start of an HTML comment ("<!--").
// http://www.w3.org/TR/REC-html40/interact/scripts.html#h-18.3.2
if (peekChar(1) == '!' && peekChar(2) == '-' && peekChar(3) == '-') {
reportHtmlCommentWarning();
skipSingleLineComment();
return true;
}
break;
case '-':
// Check if this is the start of an HTML comment ("-->").
// Note that the spec does not require us to check for this case,
// but there is some legacy code that depends on this behavior.
if (isStartOfLine && peekChar(1) == '-' && peekChar(2) == '>') {
reportHtmlCommentWarning();
skipSingleLineComment();
return true;
}
break;
case '#':
if (index == 0 && peekChar(1) == '!') {
skipSingleLineComment(Comment.Type.SHEBANG);
return true;
}
break;
}
}
return false;
}
private void reportHtmlCommentWarning() {
reportWarning("In some cases, '<!--' and '-->' are treated as a '//' " +
"for legacy reasons. Removing this from your code is " +
"safe for all browsers currently in use.");
}
private void skipSingleLineComment() {
skipSingleLineComment(Comment.Type.LINE);
}
private void skipSingleLineComment(Comment.Type type) {
int startOffset = index;
while (!isAtEnd() && !isLineTerminator(peekChar())) {
nextChar();
}
SourceRange range = getLineNumberTable().getSourceRange(startOffset, index);
String value = this.source.contents.substring(startOffset, index);
recordComment(type, range, value);
}
private void recordComment(
Comment.Type type, SourceRange range, String value) {
commentRecorder.recordComment(type, range, value);
}
private void skipMultiLineComment() {
int startOffset = index;
nextChar(); // '/'
nextChar(); // '*'
while (!isAtEnd() && (peekChar() != '*' || peekChar(1) != '/')) {
nextChar();
}
if (!isAtEnd()) {
nextChar();
nextChar();
Comment.Type type = (index - startOffset > 4
&& this.source.contents.charAt(startOffset + 2) == '*')
? Comment.Type.JSDOC
: Comment.Type.BLOCK;
SourceRange range = getLineNumberTable().getSourceRange(
startOffset, index);
String value = this.source.contents.substring(
startOffset, index);
recordComment(type, range, value);
} else {
reportError("unterminated comment");
}
}
private Token scanToken() {
skipComments();
int beginToken = index;
if (isAtEnd()) {
return createToken(TokenType.END_OF_FILE, beginToken);
}
char ch = nextChar();
switch (ch) {
case '{': return createToken(TokenType.OPEN_CURLY, beginToken);
case '}': return createToken(TokenType.CLOSE_CURLY, beginToken);
case '(': return createToken(TokenType.OPEN_PAREN, beginToken);
case ')': return createToken(TokenType.CLOSE_PAREN, beginToken);
case '[': return createToken(TokenType.OPEN_SQUARE, beginToken);
case ']': return createToken(TokenType.CLOSE_SQUARE, beginToken);
case '.':
if (isDecimalDigit(peekChar())) {
return scanNumberPostPeriod(beginToken);
}
// Harmony spread operator
if (peek('.') && peekChar(1) == '.') {
nextChar();
nextChar();
return createToken(TokenType.SPREAD, beginToken);
}
return createToken(TokenType.PERIOD, beginToken);
case ';': return createToken(TokenType.SEMI_COLON, beginToken);
case ',': return createToken(TokenType.COMMA, beginToken);
case '~': return createToken(TokenType.TILDE, beginToken);
case '?': return createToken(TokenType.QUESTION, beginToken);
case ':': return createToken(TokenType.COLON, beginToken);
case '<':
switch (peekChar()) {
case '<':
nextChar();
if (peek('=')) {
nextChar();
return createToken(TokenType.LEFT_SHIFT_EQUAL, beginToken);
}
return createToken(TokenType.LEFT_SHIFT, beginToken);
case '=':
nextChar();
return createToken(TokenType.LESS_EQUAL, beginToken);
default:
return createToken(TokenType.OPEN_ANGLE, beginToken);
}
case '>':
switch (peekChar()) {
case '>':
nextChar();
switch (peekChar()) {
case '=':
nextChar();
return createToken(TokenType.RIGHT_SHIFT_EQUAL, beginToken);
case '>':
nextChar();
if (peek('=')) {
nextChar();
return createToken(TokenType.UNSIGNED_RIGHT_SHIFT_EQUAL, beginToken);
}
return createToken(TokenType.UNSIGNED_RIGHT_SHIFT, beginToken);
default:
return createToken(TokenType.RIGHT_SHIFT, beginToken);
}
case '=':
nextChar();
return createToken(TokenType.GREATER_EQUAL, beginToken);
default:
return createToken(TokenType.CLOSE_ANGLE, beginToken);
}
case '=':
switch (peekChar()) {
case '=':
nextChar();
if (peek('=')) {
nextChar();
return createToken(TokenType.EQUAL_EQUAL_EQUAL, beginToken);
}
return createToken(TokenType.EQUAL_EQUAL, beginToken);
case '>':
nextChar();
return createToken(TokenType.ARROW, beginToken);
default:
return createToken(TokenType.EQUAL, beginToken);
}
case '!':
if (peek('=')) {
nextChar();
if (peek('=')) {
nextChar();
return createToken(TokenType.NOT_EQUAL_EQUAL, beginToken);
}
return createToken(TokenType.NOT_EQUAL, beginToken);
}
return createToken(TokenType.BANG, beginToken);
case '*':
if (peek('=')) {
nextChar();
return createToken(TokenType.STAR_EQUAL, beginToken);
}
return createToken(TokenType.STAR, beginToken);
case '%':
if (peek('=')) {
nextChar();
return createToken(TokenType.PERCENT_EQUAL, beginToken);
}
return createToken(TokenType.PERCENT, beginToken);
case '^':
if (peek('=')) {
nextChar();
return createToken(TokenType.CARET_EQUAL, beginToken);
}
return createToken(TokenType.CARET, beginToken);
case '/':
if (peek('=')) {
nextChar();
return createToken(TokenType.SLASH_EQUAL, beginToken);
}
return createToken(TokenType.SLASH, beginToken);
case '+':
switch (peekChar()) {
case '+':
nextChar();
return createToken(TokenType.PLUS_PLUS, beginToken);
case '=':
nextChar();
return createToken(TokenType.PLUS_EQUAL, beginToken);
default:
return createToken(TokenType.PLUS, beginToken);
}
case '-':
switch (peekChar()) {
case '-':
nextChar();
return createToken(TokenType.MINUS_MINUS, beginToken);
case '=':
nextChar();
return createToken(TokenType.MINUS_EQUAL, beginToken);
default:
return createToken(TokenType.MINUS, beginToken);
}
case '&':
switch (peekChar()) {
case '&':
nextChar();
return createToken(TokenType.AND, beginToken);
case '=':
nextChar();
return createToken(TokenType.AMPERSAND_EQUAL, beginToken);
default:
return createToken(TokenType.AMPERSAND, beginToken);
}
case '|':
switch (peekChar()) {
case '|':
nextChar();
return createToken(TokenType.OR, beginToken);
case '=':
nextChar();
return createToken(TokenType.BAR_EQUAL, beginToken);
default:
return createToken(TokenType.BAR, beginToken);
}
case '#':
return createToken(TokenType.POUND, beginToken);
// TODO: add NumberToken
// TODO: character following NumericLiteral must not be an IdentifierStart or DecimalDigit
case '0':
return scanPostZero(beginToken);
case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
return scanPostDigit(beginToken);
case '"':
case '\'':
return scanStringLiteral(beginToken, ch);
case '`':
return scanTemplateLiteral(beginToken);
default:
return scanIdentifierOrKeyword(beginToken, ch);
}
}
private Token scanNumberPostPeriod(int beginToken) {
skipDecimalDigits();
return scanExponentOfNumericLiteral(beginToken);
}
private Token scanPostDigit(int beginToken) {
skipDecimalDigits();
return scanFractionalNumericLiteral(beginToken);
}
private Token scanPostZero(int beginToken) {
switch (peekChar()) {
case 'b':
case 'B':
// binary
nextChar();
if (!isBinaryDigit(peekChar())) {
reportError("Binary Integer Literal must contain at least one digit");
}
skipBinaryDigits();
return new LiteralToken(
TokenType.NUMBER, getTokenString(beginToken), getTokenRange(beginToken));
case 'o':
case 'O':
// octal
nextChar();
if (!isOctalDigit(peekChar())) {
reportError("Octal Integer Literal must contain at least one digit");
}
skipOctalDigits();
return new LiteralToken(
TokenType.NUMBER, getTokenString(beginToken), getTokenRange(beginToken));
case 'x':
case 'X':
nextChar();
if (!peekHexDigit()) {
reportError("Hex Integer Literal must contain at least one digit");
}
skipHexDigits();
return new LiteralToken(
TokenType.NUMBER, getTokenString(beginToken), getTokenRange(beginToken));
case 'e':
case 'E':
return scanExponentOfNumericLiteral(beginToken);
case '.':
return scanFractionalNumericLiteral(beginToken);
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
skipDecimalDigits();
if (peek('.')) {
nextChar();
skipDecimalDigits();
}
return new LiteralToken(
TokenType.NUMBER, getTokenString(beginToken), getTokenRange(beginToken));
default:
return new LiteralToken(
TokenType.NUMBER, getTokenString(beginToken), getTokenRange(beginToken));
}
}
private Token createToken(TokenType type, int beginToken) {
return new Token(type, getTokenRange(beginToken));
}
private Token scanIdentifierOrKeyword(int beginToken, char ch) {
StringBuilder valueBuilder = new StringBuilder();
valueBuilder.append(ch);
boolean containsUnicodeEscape = ch == '\\';
ch = peekChar();
while (isIdentifierPart(ch)
|| ch == '\\'
|| (ch == '{' && containsUnicodeEscape)
|| (ch == '}' && containsUnicodeEscape)) {
if (ch == '\\') {
containsUnicodeEscape = true;
}
valueBuilder.append(nextChar());
ch = peekChar();
}
String value = valueBuilder.toString();
// Process unicode escapes.
if (containsUnicodeEscape) {
value = processUnicodeEscapes(value);
if (value == null) {
reportError(
getPosition(index),
"Invalid escape sequence");
return createToken(TokenType.ERROR, beginToken);
}
}
// Check to make sure the first character (or the unicode escape at the
// beginning of the identifier) is a valid identifier start character.
char start = value.charAt(0);
if (!isIdentifierStart(start)) {
reportError(
getPosition(beginToken),
"Character '%c' (U+%04X) is not a valid identifier start char",
start, (int) start);
return createToken(TokenType.ERROR, beginToken);
}
if (Keywords.isKeyword(value)) {
return new Token(Keywords.getTokenType(value), getTokenRange(beginToken));
}
// Intern the value to avoid creating lots of copies of the same string.
return new IdentifierToken(getTokenRange(beginToken), value.intern());
}
/**
* Converts unicode escapes in the given string to the equivalent unicode character.
* If there are no escapes, returns the input unchanged.
* If there is an invalid escape sequence, returns null.
*/
private String processUnicodeEscapes(String value) {
while (value.contains("\\")) {
int escapeStart = value.indexOf('\\');
try {
if (value.charAt(escapeStart + 1) != 'u') {
return null;
}
String hexDigits;
int escapeEnd;
if (value.charAt(escapeStart + 2) != '{') {
// Simple escape with exactly four hex digits: \\uXXXX
escapeEnd = escapeStart + 6;
hexDigits = value.substring(escapeStart + 2, escapeEnd);
} else {
// Escape with braces can have any number of hex digits: \\u{XXXXXXX}
escapeEnd = escapeStart + 3;
while (Character.digit(value.charAt(escapeEnd), 0x10) >= 0) {
escapeEnd++;
}
if (value.charAt(escapeEnd) != '}') {
return null;
}
hexDigits = value.substring(escapeStart + 3, escapeEnd);
escapeEnd++;
}
//TODO(mattloring): Allow code points greater than the size of a char
char ch = (char) Integer.parseInt(hexDigits, 0x10);
if (!isIdentifierPart(ch)) {
return null;
}
value = value.substring(0, escapeStart) + ch +
value.substring(escapeEnd);
} catch (NumberFormatException|StringIndexOutOfBoundsException e) {
return null;
}
}
return value;
}
private boolean isIdentifierStart(char ch) {
switch (ch) {
case '$':
case '_':
return true;
default:
// TODO: UnicodeLetter also includes Letter Number (NI)
return Character.isLetter(ch);
}
}
private boolean isIdentifierPart(char ch) {
// TODO: identifier part character classes
// CombiningMark
// Non-Spacing mark (Mn)
// Combining spacing mark(Mc)
// Connector punctuation (Pc)
// Zero Width Non-Joiner
// Zero Width Joiner
return isIdentifierStart(ch) || Character.isDigit(ch);
}
private Token scanStringLiteral(int beginIndex, char terminator) {
while (peekStringLiteralChar(terminator)) {
if (!skipStringLiteralChar()) {
return new LiteralToken(
TokenType.STRING, getTokenString(beginIndex), getTokenRange(beginIndex));
}
}
if (peekChar() != terminator) {
reportError(getPosition(beginIndex), "Unterminated string literal");
} else {
nextChar();
}
return new LiteralToken(
TokenType.STRING, getTokenString(beginIndex), getTokenRange(beginIndex));
}
private Token scanTemplateLiteral(int beginIndex) {
if (isAtEnd()) {
reportError(getPosition(beginIndex), "Unterminated template literal");
}
return nextTemplateLiteralTokenShared(
TokenType.NO_SUBSTITUTION_TEMPLATE, TokenType.TEMPLATE_HEAD);
}
private LiteralToken nextTemplateLiteralTokenShared(TokenType endType,
TokenType middleType) {
int beginIndex = index;
skipTemplateCharacters();
if (isAtEnd()) {
reportError(getPosition(beginIndex), "Unterminated template literal");
}
String value = getTokenString(beginIndex);
switch (peekChar()) {
case '`':
nextChar();
return new LiteralToken(endType, value, getTokenRange(beginIndex - 1));
case '$':
nextChar(); // $
nextChar(); // {
return new LiteralToken(middleType, value, getTokenRange(beginIndex - 1));
default: // Should have reported error already
return new LiteralToken(endType, value, getTokenRange(beginIndex - 1));
}
}
private String getTokenString(int beginIndex) {
return this.source.contents.substring(beginIndex, index);
}
private boolean peekStringLiteralChar(char terminator) {
return !isAtEnd() && peekChar() != terminator && !isLineTerminator(peekChar());
}
private boolean skipStringLiteralChar() {
if (peek('\\')) {
return skipStringLiteralEscapeSequence();
}
nextChar();
return true;
}
private void skipTemplateCharacters() {
while (!isAtEnd()) {
switch(peekChar()) {
case '`':
return;
case '\\':
skipStringLiteralEscapeSequence();
break;
case '$':
if (peekChar(1) == '{') {
return;
}
// Fall through.
default:
nextChar();
}
}
}
private boolean skipStringLiteralEscapeSequence() {
nextChar();
if (isAtEnd()) {
reportError("Unterminated string literal escape sequence");
return false;
}
if (isLineTerminator(peekChar())) {
skipLineTerminator();
return true;
}
switch (nextChar()) {
case '\'':
case '"':
case '`':
case '\\':
case 'b':
case 'f':
case 'n':
case 'r':
case 't':
case 'v':
case '0':
return true;
case 'x':
return skipHexDigit() && skipHexDigit();
case 'u':
if (peek('{')) {
nextChar();
if (peek('}')) {
reportError("Empty unicode escape");
return false;
}
boolean allHexDigits = true;
while (!peek('}') && allHexDigits) {
allHexDigits = allHexDigits && skipHexDigit();
}
nextChar();
return allHexDigits;
} else {
return skipHexDigit() && skipHexDigit() && skipHexDigit() && skipHexDigit();
}
default:
return true;
}
}
private boolean skipHexDigit() {
if (!peekHexDigit()) {
reportError("Hex digit expected");
return false;
}
nextChar();
return true;
}
private void skipLineTerminator() {
char first = nextChar();
if (first == '\r' && peek('\n')) {
nextChar();
}
}
private LiteralToken scanFractionalNumericLiteral(int beginToken) {
if (peek('.')) {
nextChar();
skipDecimalDigits();
}
return scanExponentOfNumericLiteral(beginToken);
}
private LiteralToken scanExponentOfNumericLiteral(int beginToken) {
switch (peekChar()) {
case 'e':
case 'E':
nextChar();
switch (peekChar()) {
case '+':
case '-':
nextChar();
break;
}
if (!isDecimalDigit(peekChar())) {
reportError("Exponent part must contain at least one digit");
}
skipDecimalDigits();
break;
default:
break;
}
return new LiteralToken(
TokenType.NUMBER, getTokenString(beginToken), getTokenRange(beginToken));
}
private void skipDecimalDigits() {
while (isDecimalDigit(peekChar())) {
nextChar();
}
}
private static boolean isDecimalDigit(char ch) {
switch (ch) {
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
return true;
default:
return false;
}
}
private boolean peekHexDigit() {
return Character.digit(peekChar(), 0x10) >= 0;
}
private void skipHexDigits() {
while (peekHexDigit()) {
nextChar();
}
}
private void skipOctalDigits() {
while (isOctalDigit(peekChar())) {
nextChar();
}
}
private static boolean isOctalDigit(char ch) {
return valueOfOctalDigit(ch) >= 0;
}
private static int valueOfOctalDigit(char ch) {
switch (ch) {
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7':
return ch - '0';
default:
return -1;
}
}
private void skipBinaryDigits() {
while (isBinaryDigit(peekChar())) {
nextChar();
}
}
private static boolean isBinaryDigit(char ch) {
return valueOfBinaryDigit(ch) >= 0;
}
private static int valueOfBinaryDigit(char ch) {
switch (ch) {
case '0':
return 0;
case '1':
return 1;
default:
return -1;
}
}
private char nextChar() {
if (isAtEnd()) {
return '\0';
}
return source.contents.charAt(index++);
}
private boolean peek(char ch) {
return peekChar() == ch;
}
private char peekChar() {
return peekChar(0);
}
private char peekChar(int offset) {
return !isValidIndex(index + offset) ? '\0' : source.contents.charAt(index + offset);
}
private void reportError(String format, Object... arguments) {
reportError(getPosition(), format, arguments);
}
private void reportError(SourcePosition position, String format, Object... arguments) {
errorReporter.reportError(position, format, arguments);
}
private void reportWarning(String format, Object... arguments) {
errorReporter.reportWarning(getPosition(), format, arguments);
}
}
|
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase.master.procedure;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.hbase.CategoryBasedTimeout;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.TableNotDisabledException;
import org.apache.hadoop.hbase.TableNotFoundException;
import org.apache.hadoop.hbase.client.RegionInfo;
import org.apache.hadoop.hbase.procedure2.Procedure;
import org.apache.hadoop.hbase.procedure2.ProcedureExecutor;
import org.apache.hadoop.hbase.procedure2.ProcedureTestingUtility;
import org.apache.hadoop.hbase.testclassification.MasterTests;
import org.apache.hadoop.hbase.testclassification.MediumTests;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.TestName;
import org.junit.rules.TestRule;
@Category({MasterTests.class, MediumTests.class})
public class TestTruncateTableProcedure extends TestTableDDLProcedureBase {
private static final Log LOG = LogFactory.getLog(TestTruncateTableProcedure.class);
@Rule public final TestRule timeout = CategoryBasedTimeout.builder().withTimeout(this.getClass()).
withLookingForStuckThread(true).build();
@Rule
public TestName name = new TestName();
@Test(timeout=60000)
public void testTruncateNotExistentTable() throws Exception {
final TableName tableName = TableName.valueOf(name.getMethodName());
final ProcedureExecutor<MasterProcedureEnv> procExec = getMasterProcedureExecutor();
long procId = ProcedureTestingUtility.submitAndWait(procExec,
new TruncateTableProcedure(procExec.getEnvironment(), tableName, true));
// Second delete should fail with TableNotFound
Procedure<?> result = procExec.getResult(procId);
assertTrue(result.isFailed());
LOG.debug("Truncate failed with exception: " + result.getException());
assertTrue(ProcedureTestingUtility.getExceptionCause(result) instanceof TableNotFoundException);
}
@Test(timeout=60000)
public void testTruncateNotDisabledTable() throws Exception {
final TableName tableName = TableName.valueOf(name.getMethodName());
final ProcedureExecutor<MasterProcedureEnv> procExec = getMasterProcedureExecutor();
MasterProcedureTestingUtility.createTable(procExec, tableName, null, "f");
long procId = ProcedureTestingUtility.submitAndWait(procExec,
new TruncateTableProcedure(procExec.getEnvironment(), tableName, false));
// Second delete should fail with TableNotDisabled
Procedure<?> result = procExec.getResult(procId);
assertTrue(result.isFailed());
LOG.debug("Truncate failed with exception: " + result.getException());
assertTrue(
ProcedureTestingUtility.getExceptionCause(result) instanceof TableNotDisabledException);
}
@Test(timeout=60000)
public void testSimpleTruncatePreserveSplits() throws Exception {
final TableName tableName = TableName.valueOf(name.getMethodName());
testSimpleTruncate(tableName, true);
}
@Test(timeout=60000)
public void testSimpleTruncateNoPreserveSplits() throws Exception {
final TableName tableName = TableName.valueOf(name.getMethodName());
testSimpleTruncate(tableName, false);
}
private void testSimpleTruncate(final TableName tableName, final boolean preserveSplits)
throws Exception {
final String[] families = new String[] { "f1", "f2" };
final byte[][] splitKeys = new byte[][] {
Bytes.toBytes("a"), Bytes.toBytes("b"), Bytes.toBytes("c")
};
RegionInfo[] regions = MasterProcedureTestingUtility.createTable(
getMasterProcedureExecutor(), tableName, splitKeys, families);
// load and verify that there are rows in the table
MasterProcedureTestingUtility.loadData(
UTIL.getConnection(), tableName, 100, splitKeys, families);
assertEquals(100, UTIL.countRows(tableName));
// disable the table
UTIL.getAdmin().disableTable(tableName);
// truncate the table
final ProcedureExecutor<MasterProcedureEnv> procExec = getMasterProcedureExecutor();
long procId = ProcedureTestingUtility.submitAndWait(procExec,
new TruncateTableProcedure(procExec.getEnvironment(), tableName, preserveSplits));
ProcedureTestingUtility.assertProcNotFailed(procExec, procId);
UTIL.waitUntilAllRegionsAssigned(tableName);
// validate the table regions and layout
regions = UTIL.getAdmin().getTableRegions(tableName).toArray(new RegionInfo[0]);
if (preserveSplits) {
assertEquals(1 + splitKeys.length, regions.length);
} else {
assertEquals(1, regions.length);
}
MasterProcedureTestingUtility.validateTableCreation(
UTIL.getHBaseCluster().getMaster(), tableName, regions, families);
// verify that there are no rows in the table
assertEquals(0, UTIL.countRows(tableName));
// verify that the table is read/writable
MasterProcedureTestingUtility.loadData(
UTIL.getConnection(), tableName, 50, splitKeys, families);
assertEquals(50, UTIL.countRows(tableName));
}
@Test(timeout=60000)
public void testRecoveryAndDoubleExecutionPreserveSplits() throws Exception {
final TableName tableName = TableName.valueOf(name.getMethodName());
testRecoveryAndDoubleExecution(tableName, true);
}
@Test(timeout=60000)
public void testRecoveryAndDoubleExecutionNoPreserveSplits() throws Exception {
final TableName tableName = TableName.valueOf(name.getMethodName());
testRecoveryAndDoubleExecution(tableName, false);
}
private void testRecoveryAndDoubleExecution(final TableName tableName,
final boolean preserveSplits) throws Exception {
final String[] families = new String[] { "f1", "f2" };
// create the table
final byte[][] splitKeys = new byte[][] {
Bytes.toBytes("a"), Bytes.toBytes("b"), Bytes.toBytes("c")
};
RegionInfo[] regions = MasterProcedureTestingUtility.createTable(
getMasterProcedureExecutor(), tableName, splitKeys, families);
// load and verify that there are rows in the table
MasterProcedureTestingUtility.loadData(
UTIL.getConnection(), tableName, 100, splitKeys, families);
assertEquals(100, UTIL.countRows(tableName));
// disable the table
UTIL.getAdmin().disableTable(tableName);
final ProcedureExecutor<MasterProcedureEnv> procExec = getMasterProcedureExecutor();
ProcedureTestingUtility.waitNoProcedureRunning(procExec);
ProcedureTestingUtility.setKillAndToggleBeforeStoreUpdate(procExec, true);
// Start the Truncate procedure && kill the executor
long procId = procExec.submitProcedure(
new TruncateTableProcedure(procExec.getEnvironment(), tableName, preserveSplits));
// Restart the executor and execute the step twice
MasterProcedureTestingUtility.testRecoveryAndDoubleExecution(procExec, procId);
ProcedureTestingUtility.setKillAndToggleBeforeStoreUpdate(procExec, false);
UTIL.waitUntilAllRegionsAssigned(tableName);
// validate the table regions and layout
regions = UTIL.getAdmin().getTableRegions(tableName).toArray(new RegionInfo[0]);
if (preserveSplits) {
assertEquals(1 + splitKeys.length, regions.length);
} else {
assertEquals(1, regions.length);
}
MasterProcedureTestingUtility.validateTableCreation(
UTIL.getHBaseCluster().getMaster(), tableName, regions, families);
// verify that there are no rows in the table
assertEquals(0, UTIL.countRows(tableName));
// verify that the table is read/writable
MasterProcedureTestingUtility.loadData(
UTIL.getConnection(), tableName, 50, splitKeys, families);
assertEquals(50, UTIL.countRows(tableName));
}
}
|
|
/**
*
*/
package io.basic.ddf.content;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import io.basic.ddf.BasicDDF;
import io.ddf.DDF;
import io.ddf.content.APersistenceHandler;
import io.ddf.content.ISerializable;
import io.ddf.content.Schema;
import io.ddf.exception.DDFException;
import io.ddf.misc.Config;
import io.ddf.types.AGloballyAddressable;
import io.ddf.types.IGloballyAddressable;
import io.ddf.util.Utils;
import io.ddf.util.Utils.JsonSerDes;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
/**
* This {@link PersistenceHandler} loads and saves from/to a designated storage area.
*/
public class PersistenceHandler extends APersistenceHandler {
public PersistenceHandler(DDF theDDF) {
super(theDDF);
}
protected String locateOrCreatePersistenceDirectory() throws DDFException {
String result, path = null;
try {
result = Utils.locateOrCreateDirectory(Config.getBasicPersistenceDir());
} catch (Exception e) {
throw new DDFException(String.format("Unable to getPersistenceDirectory(%s)", path), e);
}
return result;
}
protected String locateOrCreatePersistenceSubdirectory(String subdir) throws DDFException {
String result = null, path = null;
try {
path = String.format("%s/%s", this.locateOrCreatePersistenceDirectory(), subdir);
result = Utils.locateOrCreateDirectory(path);
} catch (Exception e) {
throw new DDFException(String.format("Unable to getPersistenceSubdirectory(%s)", path), e);
}
return result;
}
// TODO (what's the namespace here)
protected String getDataFileName() throws DDFException {
// return this.getFilePath(this.getDDF().getNamespace(), this.getDDF().getName(), ".dat");
return this.getFilePath("adatao", this.getDDF().getName(), ".dat");
}
protected String getDataFileName(String namespace, String name) throws DDFException {
return this.getFilePath(namespace, name, ".dat");
}
protected String getSchemaFileName() throws DDFException {
// return this.getFilePath(this.getDDF().getNamespace(), this.getDDF().getName(), ".sch");
return this.getFilePath("adatao", this.getDDF().getName(), ".sch");
}
protected String getSchemaFileName(String namespace, String name) throws DDFException {
return this.getFilePath(namespace, name, ".sch");
}
protected String getFilePath(String namespace, String name, String postfix) throws DDFException {
String directory = locateOrCreatePersistenceSubdirectory(namespace);
return String.format("%s/%s%s", directory, name, postfix);
}
/*
* (non-Javadoc)
*
* @see io.ddf.content.IHandlePersistence#save(boolean)
*/
@Override
public APersistenceHandler.PersistenceUri persist(boolean doOverwrite) throws DDFException {
if (this.getDDF() == null) throw new DDFException("DDF cannot be null");
String dataFile = this.getDataFileName();
String schemaFile = this.getSchemaFileName();
try {
if (!doOverwrite && (Utils.fileExists(dataFile) || Utils.fileExists(schemaFile))) {
throw new DDFException("DDF already exists in persistence storage, and overwrite option is false");
}
} catch (IOException e) {
throw new DDFException(e);
}
try {
this.getDDF().beforePersisting();
//if overwrite and existed
if (doOverwrite && (Utils.fileExists(dataFile) || Utils.fileExists(schemaFile))) {
if(Utils.fileExists(dataFile)) Utils.deleteFile(dataFile);
if(Utils.fileExists(schemaFile)) Utils.deleteFile(schemaFile);
}
Utils.writeToFile(dataFile, JsonSerDes.serialize(this.getDDF()) + '\n');
Utils.writeToFile(schemaFile, JsonSerDes.serialize(this.getDDF().getSchema()) + '\n');
this.getDDF().afterPersisting();
} catch (Exception e) {
if (e instanceof DDFException) throw (DDFException) e;
else throw new DDFException(e);
}
return new PersistenceUri(this.getDDF().getEngine(), dataFile);
}
/*
* (non-Javadoc)
*
* @see io.ddf.content.IHandlePersistence#delete(java.lang.String, java.lang.String)
*/
@Override
public void unpersist(String namespace, String name) throws DDFException {
this.getDDF().beforeUnpersisting();
try {
Utils.deleteFile(this.getDataFileName(namespace, name));
Utils.deleteFile(this.getSchemaFileName(namespace, name));
} catch(Exception e) {
throw new DDFException(e);
}
this.getDDF().afterUnpersisting();
}
/*
* (non-Javadoc)
*
* @see io.ddf.content.IHandlePersistence#copy(java.lang.String, java.lang.String, java.lang.String,
* java.lang.String, boolean)
*/
@Override
public void duplicate(String fromNamespace, String fromName, String toNamespace, String toName, boolean doOverwrite)
throws DDFException {
IPersistible from = this.load(fromNamespace, fromName);
if (from instanceof DDF) {
DDF to = (DDF) from;
// to.setNamespace(toNamespace);
to.getManager().setDDFName(to, toName);
to.persist();
} else {
throw new DDFException("Can only duplicate DDFs");
}
}
@Override
public void rename(String fromNamespace, String fromName, String toNamespace, String toName, boolean doOverwrite)
throws DDFException {
this.duplicate(fromNamespace, fromName, toNamespace, toName, doOverwrite);
this.unpersist(fromNamespace, fromName);
}
@Override
public IPersistible load(String uri) throws DDFException {
return (DDF) this.load(new PersistenceUri(uri));
}
@Override
public IPersistible load(APersistenceHandler.PersistenceUri uri) throws DDFException {
return this.load(uri.getNamespace(), uri.getName());
}
/*
* (non-Javadoc)
*
* @see io.ddf.content.IHandlePersistence#load(java.lang.String, java.lang.String)
*/
@Override
public IPersistible load(String namespace, String name) throws DDFException {
Object loadedObject, schema = null;
loadedObject = JsonSerDes.loadFromFile(this.getFilePath(namespace, name, ".dat"));
if (loadedObject == null) throw new DDFException((String.format("Got null for IPersistible for %s/%s", namespace,
name)));
schema = JsonSerDes.loadFromFile(this.getFilePath(namespace, name, ".sch"));
if (schema == null) throw new DDFException((String.format("Got null for Schema for %s/%s", namespace, name)));
if (!(loadedObject instanceof IPersistible)) {
throw new DDFException("Expected object to be IPersistible, got " + loadedObject.getClass());
}
if (loadedObject instanceof DDF && schema instanceof Schema) {
((DDF) loadedObject).getSchemaHandler().setSchema((Schema) schema);
}
return (IPersistible) loadedObject;
}
@Override
public List<String> listNamespaces() throws DDFException {
return Utils.listSubdirectories(this.locateOrCreatePersistenceDirectory());
}
@Override
public List<String> listItems(String namespace) throws DDFException {
return Utils.listSubdirectories(this.locateOrCreatePersistenceSubdirectory(namespace));
}
/**
* Base class for objects that can persist themselves (e.g, Models) via the BasicObjectDDF persistence mechanism
*/
public static class BasicPersistible extends APersistible {
private static final long serialVersionUID = 5827603466305690244L;
@Override
protected DDF newContainerDDFImpl() throws DDFException {
List<Object[]> list = Lists.newArrayList();
list.add(new Object[] { this, this.getClass().getName() });
Schema schema = new Schema(this.getName(), "object BLOB, objectClass STRING");
BasicDDF ddf = new BasicDDF(list, Object[].class, this.getName(), schema);
return ddf;
}
/**
* Special case: if we hold a single object of type IPersistible, then some magic happens: we will return *that*
* object as a result of the deserialization, instead of this DDF itself. This makes it possible for clients to do
* things like<br/>
* <code>
* PersistenceUri uri = model.persist();
* Model model = (Model) ddfManager.load(uri);
* </code> instead of having to do this:<br/>
* <code>
* PersistenceUri uri = model.persist();
* BasicDDF ddf = (BasicDDF) ddfManager.load(uri);
* Model model = (Model) ddf.getList().get(0);
* </code>
*
* @throws DDFException
*/
public static ISerializable unwrapDeserializedObject(//
List<?> dataRows, ISerializable deserializedObject, JsonElement deserializedWrappedObject) throws DDFException {
if (dataRows.size() == 1 && deserializedWrappedObject instanceof JsonArray) {
JsonElement data = ((JsonArray) deserializedWrappedObject).get(0);
if (data instanceof JsonArray) {
JsonArray array = (JsonArray) data;
if (array.size() == 2) {
// Now we know it's very likely a two-column schema (object BLOB, objectClass STRING)
JsonElement object = ((JsonArray) data).get(0);
JsonElement objectClass = ((JsonArray) data).get(1);
if (objectClass instanceof JsonPrimitive) {
try {
Object embeddedObject = new Gson().fromJson(object.toString(),
Class.forName(objectClass.getAsString()));
if (embeddedObject instanceof ISerializable) {
// Yep, it's an ISerializable that we need to unwrap
deserializedObject = (ISerializable) embeddedObject;
}
} catch (Exception e) {
if (e instanceof DDFException) throw (DDFException) e;
else throw new DDFException(String.format("Unable to unwrap object from %s", object.toString()), e);
}
}
}
}
}
return deserializedObject;
}
}
}
|
|
// HSZendeskGear
//
//Copyright (c) 2014 HelpStack (http://helpstack.io)
//
//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.tenmiles.helpstack.gears;
import android.net.Uri;
import android.util.Base64;
import com.android.volley.AuthFailureError;
import com.android.volley.Cache;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.JsonObjectRequest;
import com.tenmiles.helpstack.logic.HSGear;
import com.tenmiles.helpstack.logic.OnFetchedArraySuccessListener;
import com.tenmiles.helpstack.logic.OnFetchedSuccessListener;
import com.tenmiles.helpstack.logic.OnNewTicketFetchedSuccessListener;
import com.tenmiles.helpstack.model.HSAttachment;
import com.tenmiles.helpstack.model.HSKBItem;
import com.tenmiles.helpstack.model.HSTicket;
import com.tenmiles.helpstack.model.HSTicketUpdate;
import com.tenmiles.helpstack.model.HSUploadAttachment;
import com.tenmiles.helpstack.model.HSUser;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
public class HSZendeskGear extends HSGear {
private String instanceUrl;
private String staff_email_address;
private String api_token;
private String section_id;
public HSZendeskGear(String instanceUrl, String staff_email_address, String api_token) {
if (!instanceUrl.endsWith("/")) {
instanceUrl = instanceUrl.concat("/");
}
this.instanceUrl = instanceUrl;
this.staff_email_address = staff_email_address;
this.api_token = api_token;
}
@Override
public void fetchKBArticle(String cancelTag, HSKBItem section, RequestQueue queue,
OnFetchedArraySuccessListener successListener, ErrorListener errorListener) {
if (section == null) {
// This is first request of sections
if (this.section_id == null) {
// Fetch all sections
String url = getApiUrl().concat("help_center/sections.json");
ZendeskJsonObjectRequest request = new ZendeskJsonObjectRequest(cancelTag, url,
new ZendeskArrayBaseListener<JSONObject>(successListener, errorListener) {
@Override
public void onResponse(JSONObject sectionsArray) {
HSKBItem[] array;
try {
array = retrieveSectionsFromData(sectionsArray);
successListener.onSuccess(array);
} catch (JSONException e) {
e.printStackTrace();
errorListener.onErrorResponse(new VolleyError("Parsing failed when getting sections from data"));
}
}
}, errorListener);
request.setTag(cancelTag);
request.setRetryPolicy(new DefaultRetryPolicy(ZendeskJsonObjectRequest.TIMEOUT_MS,
ZendeskJsonObjectRequest.MAX_RETRIES, ZendeskJsonObjectRequest.BACKOFF_MULT));
queue.add(request);
queue.start();
}
else {
showArticlesInSection(cancelTag,this.section_id, queue, successListener, errorListener);
}
}
else {
showArticlesInSection(cancelTag, section.getId(), queue, successListener, errorListener);
}
}
@Override
public void createNewTicket(String cancelTag, HSUser user, String message, String body, HSUploadAttachment[] attachments, RequestQueue queue,
OnNewTicketFetchedSuccessListener successListener,
ErrorListener errorListener) {
if (attachments != null && attachments.length > 0) {
createNewTicketWithAttachment(cancelTag, user, message, body, attachments, queue, successListener, errorListener);
}
else {
createTicket(cancelTag, user, message, body, null, queue, successListener, errorListener);
}
}
@Override
public void fetchAllUpdateOnTicket(String cancelTag, final HSTicket ticket, HSUser user, RequestQueue queue,
OnFetchedArraySuccessListener successListener, ErrorListener errorListener) {
ZendeskJsonObjectRequest fetchRequest = new ZendeskJsonObjectRequest(cancelTag,
getApiUrl().concat("tickets/").concat(ticket.getTicketId()).concat("/audits.json?include=users"),
new ZendeskArrayBaseListener<JSONObject>(successListener, errorListener) {
@Override
public void onResponse(JSONObject response) {
try {
JSONArray auditsArray = response.getJSONArray("audits");
JSONArray usersArray = response.getJSONArray("users");
ArrayList<HSTicketUpdate> ticketUpdates = new ArrayList<HSTicketUpdate>();
int auditsArrayLength = auditsArray.length();
for (int i = 0; i < auditsArrayLength; i++) {
JSONObject updateObject = auditsArray.getJSONObject(i);
HSTicketUpdate ticketUpdate = retrieveTicketUpdate(updateObject, usersArray);
if (ticketUpdate != null) {
ticketUpdates.add(ticketUpdate);
}
}
HSTicketUpdate[] array = new HSTicketUpdate[0];
array = ticketUpdates.toArray(array);
successListener.onSuccess(array);
} catch (JSONException e) {
e.printStackTrace();
errorListener.onErrorResponse(new VolleyError("Parsing failed when fetching all update for a ticket"));
}
}
}, errorListener);
fetchRequest.addCredential(staff_email_address, api_token);
fetchRequest.setTag(cancelTag);
fetchRequest.setRetryPolicy(new DefaultRetryPolicy(ZendeskJsonObjectRequest.TIMEOUT_MS,
ZendeskJsonObjectRequest.MAX_RETRIES, ZendeskJsonObjectRequest.BACKOFF_MULT));
queue.add(fetchRequest);
queue.start();
}
@Override
public void addReplyOnATicket(final String cancelTag, final String message, final HSUploadAttachment[] attachments, final HSTicket ticket, final HSUser user,
RequestQueue queue, final OnFetchedSuccessListener successListener, ErrorListener errorListener) {
if (attachments != null && attachments.length > 0) {
addReplyToTicketWithAttachment(cancelTag, ticket, user, message, attachments, queue, successListener, errorListener);
}
else {
addReplyToTicket(cancelTag, ticket, user, message, null, null, queue, successListener, errorListener);
}
}
public void setSectionId(String section_id) {
this.section_id = section_id;
}
public String getApiUrl() {
return this.instanceUrl.concat("api/v2/");
}
private void createNewTicketWithAttachment(final String cancelTag, final HSUser user, final String message, final String body, HSUploadAttachment[] attachments, final RequestQueue queue,
final OnNewTicketFetchedSuccessListener successListener, final ErrorListener errorListener) {
Uri.Builder builder = new Uri.Builder();
builder.encodedPath(getApiUrl());
builder.appendEncodedPath("uploads.json");
HSUploadAttachment attachmentObject = attachments[0]; // It is been handled in constructor, so hard coding here
String attachmentFileName = getAttachmentFileName(attachmentObject);
builder.appendQueryParameter("filename", attachmentFileName);
String attachmentUrl = builder.build().toString();
ZendeskObjectRequest attachmentRequest = new ZendeskObjectRequest(cancelTag, attachmentUrl, attachmentObject, new Listener<JSONObject>() {
@Override
public void onResponse(JSONObject jsonObject) {
try {
String attachmentToken = jsonObject.getJSONObject("upload").getString("token");
String[] attachmentTokenList = new String[1]; // It is been handled in constructor, so hard coding here
attachmentTokenList[0] = attachmentToken;
createTicket(cancelTag, user, message, body, attachmentTokenList, queue, successListener, errorListener);
} catch (JSONException e) {
e.printStackTrace();
errorListener.onErrorResponse(new VolleyError("Parsing failed when creating new ticket in Zendesk"));
}
}
}, errorListener);
attachmentRequest.addCredential(staff_email_address, api_token);
attachmentRequest.setTag(cancelTag);
attachmentRequest.setRetryPolicy(new DefaultRetryPolicy(ZendeskJsonObjectRequest.TIMEOUT_MS,
ZendeskJsonObjectRequest.MAX_RETRIES, ZendeskJsonObjectRequest.BACKOFF_MULT));
queue.add(attachmentRequest);
queue.start();
}
private void createTicket(String cancelTag, final HSUser user, String message, String body, String[] attachmentToken, RequestQueue queue, final OnNewTicketFetchedSuccessListener successListener, final Response.ErrorListener errorListener) {
JSONObject ticketJson = null;
try {
ticketJson = retrieveTicketProperties(user, body, attachmentToken, message);
} catch (JSONException e) {
e.printStackTrace();
errorListener.onErrorResponse(new VolleyError("Error when trying to retrieve ticket properties"));
}
ZendeskJsonObjectRequest request = new ZendeskJsonObjectRequest(cancelTag, getApiUrl().concat("tickets.json"), ticketJson, new CreateNewTicketSuccessListener(user, successListener, errorListener) {
@Override
public void onResponse(JSONObject response) {
try {
JSONObject responseTicket = response.getJSONObject("ticket");
HSTicket ticket = HSTicket.createATicket(responseTicket.getString("id"), responseTicket.getString("subject"));
HSUser user = HSUser.appendCredentialOnUserDetail(this.user, responseTicket.getString("submitter_id"), null);
successListener.onSuccess(user, ticket);
} catch (JSONException e) {
e.printStackTrace();
errorListener.onErrorResponse(new VolleyError("Parsing failed when creating a ticket"));
}
}
}, errorListener);
request.addCredential(staff_email_address, api_token);
request.setTag(cancelTag);
request.setRetryPolicy(new DefaultRetryPolicy(ZendeskJsonObjectRequest.TIMEOUT_MS,
ZendeskJsonObjectRequest.MAX_RETRIES, ZendeskJsonObjectRequest.BACKOFF_MULT));
queue.add(request);
queue.start();
}
private void addReplyToTicketWithAttachment(final String cancelTag, final HSTicket ticket, final HSUser user, final String message, HSUploadAttachment[] attachments, final RequestQueue queue,
final OnFetchedSuccessListener successListener, final ErrorListener errorListener) {
Uri.Builder builder = new Uri.Builder();
builder.encodedPath(getApiUrl());
builder.appendEncodedPath("uploads.json");
final HSUploadAttachment attachmentObject = attachments[0]; // It is been specified in constructor, so hard-coding the value. Can be changed later
String attachmentFileName = getAttachmentFileName(attachmentObject);
builder.appendQueryParameter("filename", attachmentFileName);
String attachmentUrl = builder.build().toString();
ZendeskObjectRequest attachmentRequest = new ZendeskObjectRequest(cancelTag, attachmentUrl, attachmentObject, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject jsonObject) {
try {
String attachmentToken = jsonObject.getJSONObject("upload").getString("token");
String[] attachmentTokenList = new String[1]; // It is been specified in constructor, so hard-coding the value. Can be changed later
attachmentTokenList[0] = attachmentToken;
HSAttachment[] attachmentObjectList = new HSAttachment[1]; // It is been specified in constructor, so hard-coding the value. Can be changed later
attachmentObjectList[0] = attachmentObject.getAttachment();
addReplyToTicket(cancelTag, ticket, user, message, attachmentTokenList, attachmentObjectList, queue, successListener, errorListener);
} catch (JSONException e) {
e.printStackTrace();
errorListener.onErrorResponse(new VolleyError("Parsing failed when reading attachment token from Zendesk"));
}
}
}, errorListener);
attachmentRequest.addCredential(staff_email_address, api_token);
attachmentRequest.setTag(cancelTag);
attachmentRequest.setRetryPolicy(new DefaultRetryPolicy(ZendeskJsonObjectRequest.TIMEOUT_MS,
ZendeskJsonObjectRequest.MAX_RETRIES, ZendeskJsonObjectRequest.BACKOFF_MULT));
queue.add(attachmentRequest);
queue.start();
}
private String getAttachmentFileName(HSUploadAttachment attachmentObject) {
return attachmentObject.getAttachment().getFileName() == null ? "picture":attachmentObject.getAttachment().getFileName();
}
private void addReplyToTicket(String cancelTag, HSTicket ticket, HSUser user, final String message, String[] attachmentToken, final HSAttachment[] attachmentObjectList, RequestQueue queue, final OnFetchedSuccessListener successListener, final Response.ErrorListener errorListener) {
JSONObject ticketJson = null;
try {
ticketJson = retrieveRequestProperties(message, attachmentToken);
} catch (JSONException e) {
e.printStackTrace();
errorListener.onErrorResponse(new VolleyError("Error when retrieving request properties"));
}
ZendeskJsonObjectRequest request = new ZendeskJsonObjectRequest(cancelTag, user.getEmail(), Request.Method.PUT,
getApiUrl().concat("requests/").concat(ticket.getTicketId()).concat(".json"),
ticketJson, new ZendeskBaseListener<JSONObject>(successListener, errorListener) {
@Override
public void onResponse(JSONObject response) {
if (response == null) {
this.errorListener.onErrorResponse(new VolleyError());
}
else {
HSTicketUpdate update;
String updateId = null;
String userName = null;
Date update_time = null;
HSAttachment[] attachmentList = attachmentObjectList;
try {
JSONObject requestObject= response.getJSONObject("request");
if (!requestObject.isNull("requester_id")) {
userName = requestObject.getString("requester_id");
}
if (!requestObject.isNull("updated_at")) {
update_time = parseTime(requestObject.getString("updated_at"));
}
update = HSTicketUpdate.createUpdateByUser(updateId, userName, message, update_time, attachmentList);
successListener.onSuccess(update);
} catch (JSONException e) {
e.printStackTrace();
errorListener.onErrorResponse(new VolleyError("Parse error with response when adding reply on ticket"));
}
}
}
}, errorListener);
request.addCredential(user.getEmail(), api_token);
request.setTag(cancelTag);
request.setRetryPolicy(new DefaultRetryPolicy(ZendeskJsonObjectRequest.TIMEOUT_MS,
ZendeskJsonObjectRequest.MAX_RETRIES, ZendeskJsonObjectRequest.BACKOFF_MULT));
queue.add(request);
queue.start();
}
private JSONObject retrieveTicketProperties(HSUser user, String body, String[] attachmentToken, String message) throws JSONException {
JSONObject requester = new JSONObject();
JSONObject comment = new JSONObject();
JSONObject ticketProperties = new JSONObject();
JSONObject ticket = new JSONObject();
requester.put("name", user.getFullName());
requester.put("email", user.getEmail());
requester.put("verified", true);
comment.put("body", body);
if (attachmentToken != null) {
JSONArray attachmentsArray = new JSONArray();
for (int i = 0; i < attachmentToken.length; i++) {
attachmentsArray.put(attachmentToken[i]);
}
comment.put("uploads", attachmentsArray);
}
ticketProperties.put("requester", requester);
ticketProperties.put("subject", message);
ticketProperties.put("comment", comment);
ticket.put("ticket", ticketProperties);
return ticket;
}
private JSONObject retrieveRequestProperties(String body, String[] attachmentToken) throws JSONException {
JSONObject comment = new JSONObject();
JSONObject requestProperties = new JSONObject();
JSONObject requestObject = new JSONObject();
comment.put("body", body);
if (attachmentToken != null) {
JSONArray attachmentsArray = new JSONArray();
for (int i = 0; i < attachmentToken.length; i++) {
attachmentsArray.put(attachmentToken[i]);
}
comment.put("uploads", attachmentsArray);
}
requestProperties.put("comment", comment);
requestObject.put("request", requestProperties);
return requestObject;
}
/**
*
* Note: Returns null if it is not pubic note.
*
*
*
* @param updateObject
* @param usersArray
* @return
* @throws JSONException
*/
private HSTicketUpdate retrieveTicketUpdate(JSONObject updateObject, JSONArray usersArray) throws JSONException {
int authorId = -1;
String content = null;
String updateId = null;
String from = null;
boolean publicNote = true;
Date update_time = null;
boolean isUpdateTypeUserReply = false;
HSAttachment[] attachments = null;
JSONArray eventsArray = updateObject.getJSONArray("events");
int eventsArrayLength = eventsArray.length();
for (int i = 0; i < eventsArrayLength; i++) { //else Nothing
JSONObject eventObject = eventsArray.getJSONObject(i);
if (eventObject.getString("type").equals("Comment")) {
publicNote = eventObject.getBoolean("public");
if (!publicNote) {
return null;
}
content = eventObject.getString("body");
if (!eventObject.isNull("author_id")) {
authorId = eventObject.getInt("author_id");
}
// authorId can be null here because of previous if loop. Make sure to handle it properly
JSONObject author = searchForUser(authorId, usersArray);
if (author != null) {
if (!author.isNull("name")) {
from = author.getString("name");
}
String role = author.getString("role");
if (role.equals("end-user")) {
isUpdateTypeUserReply = true;
}
}
if (!updateObject.isNull("created_at")) {
update_time = parseTime(updateObject.getString("created_at"));
}
JSONArray attachmentObjects = eventObject.getJSONArray("attachments");
if(attachmentObjects != null) {
int length = attachmentObjects.length();
ArrayList<HSAttachment> attachmentArray = new ArrayList<HSAttachment>();
for(int j = 0; j < length; j++) {
JSONObject attachmentData = attachmentObjects.getJSONObject(j);
String attachment_url = attachmentData.getString("mapped_content_url");
if (attachment_url.startsWith("/")) {
attachment_url = instanceUrl.concat(attachment_url.substring(1));
}
HSAttachment attachData = HSAttachment.createAttachment(attachment_url, attachmentData.getString("file_name"), attachmentData.getString("content_type"));
attachmentArray.add(attachData);
}
attachments = attachmentArray.toArray(new HSAttachment[length]);
}
break;
}
}
if (isUpdateTypeUserReply) {
return HSTicketUpdate.createUpdateByUser(updateId, from, content, update_time, attachments);
}
else {
return HSTicketUpdate.createUpdateByStaff(updateId, from, content, update_time, attachments);
}
}
private HSKBItem[] retrieveArticlesFromSectionArray(JSONArray articleArray) throws JSONException {
ArrayList<HSKBItem> kbArticleArray = new ArrayList<HSKBItem>();
for (int j = 0; j < articleArray.length(); j++) {
JSONObject arrayObject = articleArray.getJSONObject(j);
HSKBItem item = HSKBItem.createForArticle(arrayObject.getString("id"), arrayObject.getString("name").trim(), arrayObject.getString("body"));
kbArticleArray.add(item);
}
HSKBItem[] array = new HSKBItem[0];
array = kbArticleArray.toArray(array);
return array;
}
private HSKBItem[] retrieveSectionsFromData(JSONObject sectionsArray) throws JSONException {
JSONArray allSectionsArray = sectionsArray.getJSONArray("sections");
ArrayList<HSKBItem> kbSectionArray = new ArrayList<HSKBItem>();
int count = allSectionsArray.length();
for (int i = 0; i < count; i++) {
JSONObject sectionObject = allSectionsArray.getJSONObject(i);
if (sectionObject != null) {
HSKBItem item = HSKBItem.createForSection(sectionObject.getString("id"), sectionObject.getString("name"));
kbSectionArray.add(item);
}
}
HSKBItem[] array = new HSKBItem[0];
array = kbSectionArray.toArray(array);
return array;
}
private JSONObject searchForUser(int userId, JSONArray usersArray) throws JSONException {
JSONObject usersObject = null;
int usersArrayLength = usersArray.length();
for (int i = 0; i < usersArrayLength; i++) {
usersObject = usersArray.getJSONObject(i);
if (usersObject.getInt("id") == userId) {
return usersObject;
}
}
return null;
}
private void showArticlesInSection(String cancelTag, String section_id, RequestQueue queue, final OnFetchedArraySuccessListener successListener, final ErrorListener errorListener) {
// Fetch individual section
String url = getApiUrl().concat("help_center/sections/").concat(section_id).concat("/articles.json");
ZendeskJsonObjectRequest request = new ZendeskJsonObjectRequest(cancelTag, url, null, new ZendeskArrayBaseListener<JSONObject>(successListener, errorListener) {
@Override
public void onResponse(JSONObject sectionsObject) {
try {
HSKBItem[] array = retrieveArticlesFromSectionArray(sectionsObject.getJSONArray("articles"));
successListener.onSuccess(array);
} catch (JSONException e) {
e.printStackTrace();
errorListener.onErrorResponse(new VolleyError("Parse error when getting articles in section"));
}
}
}, errorListener);
request.addCredential(staff_email_address, api_token);
request.setTag(cancelTag);
request.setRetryPolicy(new DefaultRetryPolicy(ZendeskJsonObjectRequest.TIMEOUT_MS,
ZendeskJsonObjectRequest.MAX_RETRIES, ZendeskJsonObjectRequest.BACKOFF_MULT));
queue.add(request);
queue.start();
}
protected static Date parseTime(String dateString) {
Date givenTimeDate = null;
try {
givenTimeDate = parseUTCString(dateString,"yyyy-MM-dd'T'HH:mm:ss'Z'");
} catch (ParseException e) {
try {
givenTimeDate = parseUTCString(dateString,"yyyy-MM-dd");
} catch (ParseException e1) {
try {
givenTimeDate = parseUTCString(dateString,"yyyy-MM-dd HH:mm:ss.SSSSZ");
} catch (ParseException e2) {
e2.printStackTrace();
}
}
}
return givenTimeDate;
}
private static Date parseUTCString(String timeStr, String pattern) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat(pattern, Locale.getDefault());
format.setTimeZone(TimeZone.getTimeZone("UTC"));
return format.parse(timeStr);
}
private abstract class ZendeskArrayBaseListener<T> implements Listener<T> {
protected OnFetchedArraySuccessListener successListener;
protected ErrorListener errorListener;
public ZendeskArrayBaseListener(OnFetchedArraySuccessListener successListener,
ErrorListener errorListener) {
this.successListener = successListener;
this.errorListener = errorListener;
}
}
private abstract class ZendeskBaseListener<T> implements Listener<T> {
protected OnFetchedSuccessListener successListener;
protected Response.ErrorListener errorListener;
public ZendeskBaseListener(OnFetchedSuccessListener successListener,
ErrorListener errorListener) {
this.successListener = successListener;
this.errorListener = errorListener;
}
}
private class ZendeskJsonObjectRequest extends JsonObjectRequest {
protected static final int TIMEOUT_MS = 10000;
/** Default number of retries for image requests */
protected static final int MAX_RETRIES = 0;
/** Default backoff multiplier for image requests */
protected static final float BACKOFF_MULT = 1f;
HashMap<String, String> headers = new HashMap<String, String>();
public ZendeskJsonObjectRequest(String cancelTag, int method, String url, JSONObject jsonRequest, Listener<org.json.JSONObject> listener, ErrorListener errorListener) {
super(method, url, jsonRequest, listener, errorListener);
}
public ZendeskJsonObjectRequest(String cancelTag, String email_address, int method, String url, JSONObject jsonRequest, Listener<org.json.JSONObject> listener, Response.ErrorListener errorListener) {
super(method, url, jsonRequest, listener, errorListener);
}
public ZendeskJsonObjectRequest(String cancelTag, String url, JSONObject ticketJson, Listener<JSONObject> listener, ErrorListener errorListener) {
super(url, ticketJson, listener, errorListener);
}
public ZendeskJsonObjectRequest(String cancelTag, String url, Listener<JSONObject> listener, ErrorListener errorListener) {
super(url, null, listener, errorListener);
}
public void addCredential(String name, String api_token) {
String credentials = name.concat("/token:").concat(api_token);
String base64EncodedCredentials = Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
headers.put("Authorization", "Basic ".concat(base64EncodedCredentials));
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
return headers;
}
}
private class ZendeskObjectRequest extends Request<JSONObject> {
private byte[] content;
private Listener<JSONObject> mListener;
HashMap<String, String> headers = new HashMap<String, String>();
public ZendeskObjectRequest(String cancelTag, String attachmentUrl, HSUploadAttachment attachmentObject, Listener<JSONObject> listener, ErrorListener errorListener) {
super(Method.POST, attachmentUrl, errorListener);
mListener = listener;
InputStream inputStream = null;
try {
inputStream = attachmentObject.generateInputStreamToUpload();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// convert input stream to byte array and send that byte array in getBody
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[512];
try {
int n = 0;
while (-1 != (n = inputStream.read(buffer))) {
output.write(buffer, 0, n);
}
} catch (IOException e) {
e.printStackTrace();
}
this.content = output.toByteArray();
}
private void addCredential(String name, String api_token) {
String credentials = name.concat("/token:").concat(api_token);
String base64EncodedCredentials = Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
headers.put("Authorization", "Basic ".concat(base64EncodedCredentials));
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
return headers;
}
@Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
String jsonString = null;
try {
jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(jsonString);
} catch (JSONException e) {
e.printStackTrace();
}
Cache.Entry entry = HttpHeaderParser.parseCacheHeaders(response);
return Response.success(jsonObject, entry);
}
@Override
protected void deliverResponse(JSONObject response) {
mListener.onResponse(response);
}
@Override
public String getBodyContentType() {
return "application/binary";
}
@Override
public byte[] getBody() {
return this.content;
}
}
private abstract class CreateNewTicketSuccessListener implements Listener<JSONObject>
{
protected HSUser user;
protected OnNewTicketFetchedSuccessListener successListener;
protected ErrorListener errorListener;
public CreateNewTicketSuccessListener(HSUser user, OnNewTicketFetchedSuccessListener successListener,
ErrorListener errorListener) {
this.user = user;
this.successListener = successListener;
this.errorListener = errorListener;
}
}
}
|
|
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.elasticache.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
* <p>
* The status of the user group update.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/elasticache-2015-02-02/UserGroupsUpdateStatus" target="_top">AWS
* API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class UserGroupsUpdateStatus implements Serializable, Cloneable {
/**
* <p>
* The ID of the user group to add.
* </p>
*/
private com.amazonaws.internal.SdkInternalList<String> userGroupIdsToAdd;
/**
* <p>
* The ID of the user group to remove.
* </p>
*/
private com.amazonaws.internal.SdkInternalList<String> userGroupIdsToRemove;
/**
* <p>
* The ID of the user group to add.
* </p>
*
* @return The ID of the user group to add.
*/
public java.util.List<String> getUserGroupIdsToAdd() {
if (userGroupIdsToAdd == null) {
userGroupIdsToAdd = new com.amazonaws.internal.SdkInternalList<String>();
}
return userGroupIdsToAdd;
}
/**
* <p>
* The ID of the user group to add.
* </p>
*
* @param userGroupIdsToAdd
* The ID of the user group to add.
*/
public void setUserGroupIdsToAdd(java.util.Collection<String> userGroupIdsToAdd) {
if (userGroupIdsToAdd == null) {
this.userGroupIdsToAdd = null;
return;
}
this.userGroupIdsToAdd = new com.amazonaws.internal.SdkInternalList<String>(userGroupIdsToAdd);
}
/**
* <p>
* The ID of the user group to add.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setUserGroupIdsToAdd(java.util.Collection)} or {@link #withUserGroupIdsToAdd(java.util.Collection)} if
* you want to override the existing values.
* </p>
*
* @param userGroupIdsToAdd
* The ID of the user group to add.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public UserGroupsUpdateStatus withUserGroupIdsToAdd(String... userGroupIdsToAdd) {
if (this.userGroupIdsToAdd == null) {
setUserGroupIdsToAdd(new com.amazonaws.internal.SdkInternalList<String>(userGroupIdsToAdd.length));
}
for (String ele : userGroupIdsToAdd) {
this.userGroupIdsToAdd.add(ele);
}
return this;
}
/**
* <p>
* The ID of the user group to add.
* </p>
*
* @param userGroupIdsToAdd
* The ID of the user group to add.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public UserGroupsUpdateStatus withUserGroupIdsToAdd(java.util.Collection<String> userGroupIdsToAdd) {
setUserGroupIdsToAdd(userGroupIdsToAdd);
return this;
}
/**
* <p>
* The ID of the user group to remove.
* </p>
*
* @return The ID of the user group to remove.
*/
public java.util.List<String> getUserGroupIdsToRemove() {
if (userGroupIdsToRemove == null) {
userGroupIdsToRemove = new com.amazonaws.internal.SdkInternalList<String>();
}
return userGroupIdsToRemove;
}
/**
* <p>
* The ID of the user group to remove.
* </p>
*
* @param userGroupIdsToRemove
* The ID of the user group to remove.
*/
public void setUserGroupIdsToRemove(java.util.Collection<String> userGroupIdsToRemove) {
if (userGroupIdsToRemove == null) {
this.userGroupIdsToRemove = null;
return;
}
this.userGroupIdsToRemove = new com.amazonaws.internal.SdkInternalList<String>(userGroupIdsToRemove);
}
/**
* <p>
* The ID of the user group to remove.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setUserGroupIdsToRemove(java.util.Collection)} or {@link #withUserGroupIdsToRemove(java.util.Collection)}
* if you want to override the existing values.
* </p>
*
* @param userGroupIdsToRemove
* The ID of the user group to remove.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public UserGroupsUpdateStatus withUserGroupIdsToRemove(String... userGroupIdsToRemove) {
if (this.userGroupIdsToRemove == null) {
setUserGroupIdsToRemove(new com.amazonaws.internal.SdkInternalList<String>(userGroupIdsToRemove.length));
}
for (String ele : userGroupIdsToRemove) {
this.userGroupIdsToRemove.add(ele);
}
return this;
}
/**
* <p>
* The ID of the user group to remove.
* </p>
*
* @param userGroupIdsToRemove
* The ID of the user group to remove.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public UserGroupsUpdateStatus withUserGroupIdsToRemove(java.util.Collection<String> userGroupIdsToRemove) {
setUserGroupIdsToRemove(userGroupIdsToRemove);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getUserGroupIdsToAdd() != null)
sb.append("UserGroupIdsToAdd: ").append(getUserGroupIdsToAdd()).append(",");
if (getUserGroupIdsToRemove() != null)
sb.append("UserGroupIdsToRemove: ").append(getUserGroupIdsToRemove());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof UserGroupsUpdateStatus == false)
return false;
UserGroupsUpdateStatus other = (UserGroupsUpdateStatus) obj;
if (other.getUserGroupIdsToAdd() == null ^ this.getUserGroupIdsToAdd() == null)
return false;
if (other.getUserGroupIdsToAdd() != null && other.getUserGroupIdsToAdd().equals(this.getUserGroupIdsToAdd()) == false)
return false;
if (other.getUserGroupIdsToRemove() == null ^ this.getUserGroupIdsToRemove() == null)
return false;
if (other.getUserGroupIdsToRemove() != null && other.getUserGroupIdsToRemove().equals(this.getUserGroupIdsToRemove()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getUserGroupIdsToAdd() == null) ? 0 : getUserGroupIdsToAdd().hashCode());
hashCode = prime * hashCode + ((getUserGroupIdsToRemove() == null) ? 0 : getUserGroupIdsToRemove().hashCode());
return hashCode;
}
@Override
public UserGroupsUpdateStatus clone() {
try {
return (UserGroupsUpdateStatus) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
|
|
/* Generated by camel build tools - do NOT edit this file! */
package org.apache.camel.component.debezium;
import java.util.Map;
import org.apache.camel.CamelContext;
import org.apache.camel.spi.ExtendedPropertyConfigurerGetter;
import org.apache.camel.spi.PropertyConfigurerGetter;
import org.apache.camel.spi.ConfigurerStrategy;
import org.apache.camel.spi.GeneratedPropertyConfigurer;
import org.apache.camel.util.CaseInsensitiveMap;
import org.apache.camel.support.component.PropertyConfigurerSupport;
/**
* Generated by camel build tools - do NOT edit this file!
*/
@SuppressWarnings("unchecked")
public class DebeziumSqlserverEndpointConfigurer extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter {
@Override
public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
DebeziumSqlserverEndpoint target = (DebeziumSqlserverEndpoint) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "additionalproperties":
case "additionalProperties": target.getConfiguration().setAdditionalProperties(property(camelContext, java.util.Map.class, value)); return true;
case "bridgeerrorhandler":
case "bridgeErrorHandler": target.setBridgeErrorHandler(property(camelContext, boolean.class, value)); return true;
case "columnblacklist":
case "columnBlacklist": target.getConfiguration().setColumnBlacklist(property(camelContext, java.lang.String.class, value)); return true;
case "columnexcludelist":
case "columnExcludeList": target.getConfiguration().setColumnExcludeList(property(camelContext, java.lang.String.class, value)); return true;
case "columnincludelist":
case "columnIncludeList": target.getConfiguration().setColumnIncludeList(property(camelContext, java.lang.String.class, value)); return true;
case "columnpropagatesourcetype":
case "columnPropagateSourceType": target.getConfiguration().setColumnPropagateSourceType(property(camelContext, java.lang.String.class, value)); return true;
case "columnwhitelist":
case "columnWhitelist": target.getConfiguration().setColumnWhitelist(property(camelContext, java.lang.String.class, value)); return true;
case "converters": target.getConfiguration().setConverters(property(camelContext, java.lang.String.class, value)); return true;
case "databasedbname":
case "databaseDbname": target.getConfiguration().setDatabaseDbname(property(camelContext, java.lang.String.class, value)); return true;
case "databasehistory":
case "databaseHistory": target.getConfiguration().setDatabaseHistory(property(camelContext, java.lang.String.class, value)); return true;
case "databasehistoryfilefilename":
case "databaseHistoryFileFilename": target.getConfiguration().setDatabaseHistoryFileFilename(property(camelContext, java.lang.String.class, value)); return true;
case "databasehistorykafkabootstrapservers":
case "databaseHistoryKafkaBootstrapServers": target.getConfiguration().setDatabaseHistoryKafkaBootstrapServers(property(camelContext, java.lang.String.class, value)); return true;
case "databasehistorykafkarecoveryattempts":
case "databaseHistoryKafkaRecoveryAttempts": target.getConfiguration().setDatabaseHistoryKafkaRecoveryAttempts(property(camelContext, int.class, value)); return true;
case "databasehistorykafkarecoverypollintervalms":
case "databaseHistoryKafkaRecoveryPollIntervalMs": target.getConfiguration().setDatabaseHistoryKafkaRecoveryPollIntervalMs(property(camelContext, int.class, value)); return true;
case "databasehistorykafkatopic":
case "databaseHistoryKafkaTopic": target.getConfiguration().setDatabaseHistoryKafkaTopic(property(camelContext, java.lang.String.class, value)); return true;
case "databasehostname":
case "databaseHostname": target.getConfiguration().setDatabaseHostname(property(camelContext, java.lang.String.class, value)); return true;
case "databaseinstance":
case "databaseInstance": target.getConfiguration().setDatabaseInstance(property(camelContext, java.lang.String.class, value)); return true;
case "databasepassword":
case "databasePassword": target.getConfiguration().setDatabasePassword(property(camelContext, java.lang.String.class, value)); return true;
case "databaseport":
case "databasePort": target.getConfiguration().setDatabasePort(property(camelContext, int.class, value)); return true;
case "databaseservername":
case "databaseServerName": target.getConfiguration().setDatabaseServerName(property(camelContext, java.lang.String.class, value)); return true;
case "databaseservertimezone":
case "databaseServerTimezone": target.getConfiguration().setDatabaseServerTimezone(property(camelContext, java.lang.String.class, value)); return true;
case "databaseuser":
case "databaseUser": target.getConfiguration().setDatabaseUser(property(camelContext, java.lang.String.class, value)); return true;
case "datatypepropagatesourcetype":
case "datatypePropagateSourceType": target.getConfiguration().setDatatypePropagateSourceType(property(camelContext, java.lang.String.class, value)); return true;
case "decimalhandlingmode":
case "decimalHandlingMode": target.getConfiguration().setDecimalHandlingMode(property(camelContext, java.lang.String.class, value)); return true;
case "eventprocessingfailurehandlingmode":
case "eventProcessingFailureHandlingMode": target.getConfiguration().setEventProcessingFailureHandlingMode(property(camelContext, java.lang.String.class, value)); return true;
case "exceptionhandler":
case "exceptionHandler": target.setExceptionHandler(property(camelContext, org.apache.camel.spi.ExceptionHandler.class, value)); return true;
case "exchangepattern":
case "exchangePattern": target.setExchangePattern(property(camelContext, org.apache.camel.ExchangePattern.class, value)); return true;
case "heartbeatintervalms":
case "heartbeatIntervalMs": target.getConfiguration().setHeartbeatIntervalMs(property(camelContext, int.class, value)); return true;
case "heartbeattopicsprefix":
case "heartbeatTopicsPrefix": target.getConfiguration().setHeartbeatTopicsPrefix(property(camelContext, java.lang.String.class, value)); return true;
case "includeschemachanges":
case "includeSchemaChanges": target.getConfiguration().setIncludeSchemaChanges(property(camelContext, boolean.class, value)); return true;
case "internalkeyconverter":
case "internalKeyConverter": target.getConfiguration().setInternalKeyConverter(property(camelContext, java.lang.String.class, value)); return true;
case "internalvalueconverter":
case "internalValueConverter": target.getConfiguration().setInternalValueConverter(property(camelContext, java.lang.String.class, value)); return true;
case "maxbatchsize":
case "maxBatchSize": target.getConfiguration().setMaxBatchSize(property(camelContext, int.class, value)); return true;
case "maxqueuesize":
case "maxQueueSize": target.getConfiguration().setMaxQueueSize(property(camelContext, int.class, value)); return true;
case "messagekeycolumns":
case "messageKeyColumns": target.getConfiguration().setMessageKeyColumns(property(camelContext, java.lang.String.class, value)); return true;
case "offsetcommitpolicy":
case "offsetCommitPolicy": target.getConfiguration().setOffsetCommitPolicy(property(camelContext, java.lang.String.class, value)); return true;
case "offsetcommittimeoutms":
case "offsetCommitTimeoutMs": target.getConfiguration().setOffsetCommitTimeoutMs(property(camelContext, java.time.Duration.class, value).toMillis()); return true;
case "offsetflushintervalms":
case "offsetFlushIntervalMs": target.getConfiguration().setOffsetFlushIntervalMs(property(camelContext, java.time.Duration.class, value).toMillis()); return true;
case "offsetstorage":
case "offsetStorage": target.getConfiguration().setOffsetStorage(property(camelContext, java.lang.String.class, value)); return true;
case "offsetstoragefilename":
case "offsetStorageFileName": target.getConfiguration().setOffsetStorageFileName(property(camelContext, java.lang.String.class, value)); return true;
case "offsetstoragepartitions":
case "offsetStoragePartitions": target.getConfiguration().setOffsetStoragePartitions(property(camelContext, int.class, value)); return true;
case "offsetstoragereplicationfactor":
case "offsetStorageReplicationFactor": target.getConfiguration().setOffsetStorageReplicationFactor(property(camelContext, int.class, value)); return true;
case "offsetstoragetopic":
case "offsetStorageTopic": target.getConfiguration().setOffsetStorageTopic(property(camelContext, java.lang.String.class, value)); return true;
case "pollintervalms":
case "pollIntervalMs": target.getConfiguration().setPollIntervalMs(property(camelContext, java.time.Duration.class, value).toMillis()); return true;
case "providetransactionmetadata":
case "provideTransactionMetadata": target.getConfiguration().setProvideTransactionMetadata(property(camelContext, boolean.class, value)); return true;
case "queryfetchsize":
case "queryFetchSize": target.getConfiguration().setQueryFetchSize(property(camelContext, int.class, value)); return true;
case "retriablerestartconnectorwaitms":
case "retriableRestartConnectorWaitMs": target.getConfiguration().setRetriableRestartConnectorWaitMs(property(camelContext, java.time.Duration.class, value).toMillis()); return true;
case "sanitizefieldnames":
case "sanitizeFieldNames": target.getConfiguration().setSanitizeFieldNames(property(camelContext, boolean.class, value)); return true;
case "skippedoperations":
case "skippedOperations": target.getConfiguration().setSkippedOperations(property(camelContext, java.lang.String.class, value)); return true;
case "snapshotdelayms":
case "snapshotDelayMs": target.getConfiguration().setSnapshotDelayMs(property(camelContext, java.time.Duration.class, value).toMillis()); return true;
case "snapshotfetchsize":
case "snapshotFetchSize": target.getConfiguration().setSnapshotFetchSize(property(camelContext, int.class, value)); return true;
case "snapshotisolationmode":
case "snapshotIsolationMode": target.getConfiguration().setSnapshotIsolationMode(property(camelContext, java.lang.String.class, value)); return true;
case "snapshotlocktimeoutms":
case "snapshotLockTimeoutMs": target.getConfiguration().setSnapshotLockTimeoutMs(property(camelContext, java.time.Duration.class, value).toMillis()); return true;
case "snapshotmode":
case "snapshotMode": target.getConfiguration().setSnapshotMode(property(camelContext, java.lang.String.class, value)); return true;
case "snapshotselectstatementoverrides":
case "snapshotSelectStatementOverrides": target.getConfiguration().setSnapshotSelectStatementOverrides(property(camelContext, java.lang.String.class, value)); return true;
case "sourcestructversion":
case "sourceStructVersion": target.getConfiguration().setSourceStructVersion(property(camelContext, java.lang.String.class, value)); return true;
case "sourcetimestampmode":
case "sourceTimestampMode": target.getConfiguration().setSourceTimestampMode(property(camelContext, java.lang.String.class, value)); return true;
case "synchronous": target.setSynchronous(property(camelContext, boolean.class, value)); return true;
case "tableblacklist":
case "tableBlacklist": target.getConfiguration().setTableBlacklist(property(camelContext, java.lang.String.class, value)); return true;
case "tableexcludelist":
case "tableExcludeList": target.getConfiguration().setTableExcludeList(property(camelContext, java.lang.String.class, value)); return true;
case "tableignorebuiltin":
case "tableIgnoreBuiltin": target.getConfiguration().setTableIgnoreBuiltin(property(camelContext, boolean.class, value)); return true;
case "tableincludelist":
case "tableIncludeList": target.getConfiguration().setTableIncludeList(property(camelContext, java.lang.String.class, value)); return true;
case "tablewhitelist":
case "tableWhitelist": target.getConfiguration().setTableWhitelist(property(camelContext, java.lang.String.class, value)); return true;
case "timeprecisionmode":
case "timePrecisionMode": target.getConfiguration().setTimePrecisionMode(property(camelContext, java.lang.String.class, value)); return true;
case "tombstonesondelete":
case "tombstonesOnDelete": target.getConfiguration().setTombstonesOnDelete(property(camelContext, boolean.class, value)); return true;
default: return false;
}
}
@Override
public Class<?> getOptionType(String name, boolean ignoreCase) {
switch (ignoreCase ? name.toLowerCase() : name) {
case "additionalproperties":
case "additionalProperties": return java.util.Map.class;
case "bridgeerrorhandler":
case "bridgeErrorHandler": return boolean.class;
case "columnblacklist":
case "columnBlacklist": return java.lang.String.class;
case "columnexcludelist":
case "columnExcludeList": return java.lang.String.class;
case "columnincludelist":
case "columnIncludeList": return java.lang.String.class;
case "columnpropagatesourcetype":
case "columnPropagateSourceType": return java.lang.String.class;
case "columnwhitelist":
case "columnWhitelist": return java.lang.String.class;
case "converters": return java.lang.String.class;
case "databasedbname":
case "databaseDbname": return java.lang.String.class;
case "databasehistory":
case "databaseHistory": return java.lang.String.class;
case "databasehistoryfilefilename":
case "databaseHistoryFileFilename": return java.lang.String.class;
case "databasehistorykafkabootstrapservers":
case "databaseHistoryKafkaBootstrapServers": return java.lang.String.class;
case "databasehistorykafkarecoveryattempts":
case "databaseHistoryKafkaRecoveryAttempts": return int.class;
case "databasehistorykafkarecoverypollintervalms":
case "databaseHistoryKafkaRecoveryPollIntervalMs": return int.class;
case "databasehistorykafkatopic":
case "databaseHistoryKafkaTopic": return java.lang.String.class;
case "databasehostname":
case "databaseHostname": return java.lang.String.class;
case "databaseinstance":
case "databaseInstance": return java.lang.String.class;
case "databasepassword":
case "databasePassword": return java.lang.String.class;
case "databaseport":
case "databasePort": return int.class;
case "databaseservername":
case "databaseServerName": return java.lang.String.class;
case "databaseservertimezone":
case "databaseServerTimezone": return java.lang.String.class;
case "databaseuser":
case "databaseUser": return java.lang.String.class;
case "datatypepropagatesourcetype":
case "datatypePropagateSourceType": return java.lang.String.class;
case "decimalhandlingmode":
case "decimalHandlingMode": return java.lang.String.class;
case "eventprocessingfailurehandlingmode":
case "eventProcessingFailureHandlingMode": return java.lang.String.class;
case "exceptionhandler":
case "exceptionHandler": return org.apache.camel.spi.ExceptionHandler.class;
case "exchangepattern":
case "exchangePattern": return org.apache.camel.ExchangePattern.class;
case "heartbeatintervalms":
case "heartbeatIntervalMs": return int.class;
case "heartbeattopicsprefix":
case "heartbeatTopicsPrefix": return java.lang.String.class;
case "includeschemachanges":
case "includeSchemaChanges": return boolean.class;
case "internalkeyconverter":
case "internalKeyConverter": return java.lang.String.class;
case "internalvalueconverter":
case "internalValueConverter": return java.lang.String.class;
case "maxbatchsize":
case "maxBatchSize": return int.class;
case "maxqueuesize":
case "maxQueueSize": return int.class;
case "messagekeycolumns":
case "messageKeyColumns": return java.lang.String.class;
case "offsetcommitpolicy":
case "offsetCommitPolicy": return java.lang.String.class;
case "offsetcommittimeoutms":
case "offsetCommitTimeoutMs": return long.class;
case "offsetflushintervalms":
case "offsetFlushIntervalMs": return long.class;
case "offsetstorage":
case "offsetStorage": return java.lang.String.class;
case "offsetstoragefilename":
case "offsetStorageFileName": return java.lang.String.class;
case "offsetstoragepartitions":
case "offsetStoragePartitions": return int.class;
case "offsetstoragereplicationfactor":
case "offsetStorageReplicationFactor": return int.class;
case "offsetstoragetopic":
case "offsetStorageTopic": return java.lang.String.class;
case "pollintervalms":
case "pollIntervalMs": return long.class;
case "providetransactionmetadata":
case "provideTransactionMetadata": return boolean.class;
case "queryfetchsize":
case "queryFetchSize": return int.class;
case "retriablerestartconnectorwaitms":
case "retriableRestartConnectorWaitMs": return long.class;
case "sanitizefieldnames":
case "sanitizeFieldNames": return boolean.class;
case "skippedoperations":
case "skippedOperations": return java.lang.String.class;
case "snapshotdelayms":
case "snapshotDelayMs": return long.class;
case "snapshotfetchsize":
case "snapshotFetchSize": return int.class;
case "snapshotisolationmode":
case "snapshotIsolationMode": return java.lang.String.class;
case "snapshotlocktimeoutms":
case "snapshotLockTimeoutMs": return long.class;
case "snapshotmode":
case "snapshotMode": return java.lang.String.class;
case "snapshotselectstatementoverrides":
case "snapshotSelectStatementOverrides": return java.lang.String.class;
case "sourcestructversion":
case "sourceStructVersion": return java.lang.String.class;
case "sourcetimestampmode":
case "sourceTimestampMode": return java.lang.String.class;
case "synchronous": return boolean.class;
case "tableblacklist":
case "tableBlacklist": return java.lang.String.class;
case "tableexcludelist":
case "tableExcludeList": return java.lang.String.class;
case "tableignorebuiltin":
case "tableIgnoreBuiltin": return boolean.class;
case "tableincludelist":
case "tableIncludeList": return java.lang.String.class;
case "tablewhitelist":
case "tableWhitelist": return java.lang.String.class;
case "timeprecisionmode":
case "timePrecisionMode": return java.lang.String.class;
case "tombstonesondelete":
case "tombstonesOnDelete": return boolean.class;
default: return null;
}
}
@Override
public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
DebeziumSqlserverEndpoint target = (DebeziumSqlserverEndpoint) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "additionalproperties":
case "additionalProperties": return target.getConfiguration().getAdditionalProperties();
case "bridgeerrorhandler":
case "bridgeErrorHandler": return target.isBridgeErrorHandler();
case "columnblacklist":
case "columnBlacklist": return target.getConfiguration().getColumnBlacklist();
case "columnexcludelist":
case "columnExcludeList": return target.getConfiguration().getColumnExcludeList();
case "columnincludelist":
case "columnIncludeList": return target.getConfiguration().getColumnIncludeList();
case "columnpropagatesourcetype":
case "columnPropagateSourceType": return target.getConfiguration().getColumnPropagateSourceType();
case "columnwhitelist":
case "columnWhitelist": return target.getConfiguration().getColumnWhitelist();
case "converters": return target.getConfiguration().getConverters();
case "databasedbname":
case "databaseDbname": return target.getConfiguration().getDatabaseDbname();
case "databasehistory":
case "databaseHistory": return target.getConfiguration().getDatabaseHistory();
case "databasehistoryfilefilename":
case "databaseHistoryFileFilename": return target.getConfiguration().getDatabaseHistoryFileFilename();
case "databasehistorykafkabootstrapservers":
case "databaseHistoryKafkaBootstrapServers": return target.getConfiguration().getDatabaseHistoryKafkaBootstrapServers();
case "databasehistorykafkarecoveryattempts":
case "databaseHistoryKafkaRecoveryAttempts": return target.getConfiguration().getDatabaseHistoryKafkaRecoveryAttempts();
case "databasehistorykafkarecoverypollintervalms":
case "databaseHistoryKafkaRecoveryPollIntervalMs": return target.getConfiguration().getDatabaseHistoryKafkaRecoveryPollIntervalMs();
case "databasehistorykafkatopic":
case "databaseHistoryKafkaTopic": return target.getConfiguration().getDatabaseHistoryKafkaTopic();
case "databasehostname":
case "databaseHostname": return target.getConfiguration().getDatabaseHostname();
case "databaseinstance":
case "databaseInstance": return target.getConfiguration().getDatabaseInstance();
case "databasepassword":
case "databasePassword": return target.getConfiguration().getDatabasePassword();
case "databaseport":
case "databasePort": return target.getConfiguration().getDatabasePort();
case "databaseservername":
case "databaseServerName": return target.getConfiguration().getDatabaseServerName();
case "databaseservertimezone":
case "databaseServerTimezone": return target.getConfiguration().getDatabaseServerTimezone();
case "databaseuser":
case "databaseUser": return target.getConfiguration().getDatabaseUser();
case "datatypepropagatesourcetype":
case "datatypePropagateSourceType": return target.getConfiguration().getDatatypePropagateSourceType();
case "decimalhandlingmode":
case "decimalHandlingMode": return target.getConfiguration().getDecimalHandlingMode();
case "eventprocessingfailurehandlingmode":
case "eventProcessingFailureHandlingMode": return target.getConfiguration().getEventProcessingFailureHandlingMode();
case "exceptionhandler":
case "exceptionHandler": return target.getExceptionHandler();
case "exchangepattern":
case "exchangePattern": return target.getExchangePattern();
case "heartbeatintervalms":
case "heartbeatIntervalMs": return target.getConfiguration().getHeartbeatIntervalMs();
case "heartbeattopicsprefix":
case "heartbeatTopicsPrefix": return target.getConfiguration().getHeartbeatTopicsPrefix();
case "includeschemachanges":
case "includeSchemaChanges": return target.getConfiguration().isIncludeSchemaChanges();
case "internalkeyconverter":
case "internalKeyConverter": return target.getConfiguration().getInternalKeyConverter();
case "internalvalueconverter":
case "internalValueConverter": return target.getConfiguration().getInternalValueConverter();
case "maxbatchsize":
case "maxBatchSize": return target.getConfiguration().getMaxBatchSize();
case "maxqueuesize":
case "maxQueueSize": return target.getConfiguration().getMaxQueueSize();
case "messagekeycolumns":
case "messageKeyColumns": return target.getConfiguration().getMessageKeyColumns();
case "offsetcommitpolicy":
case "offsetCommitPolicy": return target.getConfiguration().getOffsetCommitPolicy();
case "offsetcommittimeoutms":
case "offsetCommitTimeoutMs": return target.getConfiguration().getOffsetCommitTimeoutMs();
case "offsetflushintervalms":
case "offsetFlushIntervalMs": return target.getConfiguration().getOffsetFlushIntervalMs();
case "offsetstorage":
case "offsetStorage": return target.getConfiguration().getOffsetStorage();
case "offsetstoragefilename":
case "offsetStorageFileName": return target.getConfiguration().getOffsetStorageFileName();
case "offsetstoragepartitions":
case "offsetStoragePartitions": return target.getConfiguration().getOffsetStoragePartitions();
case "offsetstoragereplicationfactor":
case "offsetStorageReplicationFactor": return target.getConfiguration().getOffsetStorageReplicationFactor();
case "offsetstoragetopic":
case "offsetStorageTopic": return target.getConfiguration().getOffsetStorageTopic();
case "pollintervalms":
case "pollIntervalMs": return target.getConfiguration().getPollIntervalMs();
case "providetransactionmetadata":
case "provideTransactionMetadata": return target.getConfiguration().isProvideTransactionMetadata();
case "queryfetchsize":
case "queryFetchSize": return target.getConfiguration().getQueryFetchSize();
case "retriablerestartconnectorwaitms":
case "retriableRestartConnectorWaitMs": return target.getConfiguration().getRetriableRestartConnectorWaitMs();
case "sanitizefieldnames":
case "sanitizeFieldNames": return target.getConfiguration().isSanitizeFieldNames();
case "skippedoperations":
case "skippedOperations": return target.getConfiguration().getSkippedOperations();
case "snapshotdelayms":
case "snapshotDelayMs": return target.getConfiguration().getSnapshotDelayMs();
case "snapshotfetchsize":
case "snapshotFetchSize": return target.getConfiguration().getSnapshotFetchSize();
case "snapshotisolationmode":
case "snapshotIsolationMode": return target.getConfiguration().getSnapshotIsolationMode();
case "snapshotlocktimeoutms":
case "snapshotLockTimeoutMs": return target.getConfiguration().getSnapshotLockTimeoutMs();
case "snapshotmode":
case "snapshotMode": return target.getConfiguration().getSnapshotMode();
case "snapshotselectstatementoverrides":
case "snapshotSelectStatementOverrides": return target.getConfiguration().getSnapshotSelectStatementOverrides();
case "sourcestructversion":
case "sourceStructVersion": return target.getConfiguration().getSourceStructVersion();
case "sourcetimestampmode":
case "sourceTimestampMode": return target.getConfiguration().getSourceTimestampMode();
case "synchronous": return target.isSynchronous();
case "tableblacklist":
case "tableBlacklist": return target.getConfiguration().getTableBlacklist();
case "tableexcludelist":
case "tableExcludeList": return target.getConfiguration().getTableExcludeList();
case "tableignorebuiltin":
case "tableIgnoreBuiltin": return target.getConfiguration().isTableIgnoreBuiltin();
case "tableincludelist":
case "tableIncludeList": return target.getConfiguration().getTableIncludeList();
case "tablewhitelist":
case "tableWhitelist": return target.getConfiguration().getTableWhitelist();
case "timeprecisionmode":
case "timePrecisionMode": return target.getConfiguration().getTimePrecisionMode();
case "tombstonesondelete":
case "tombstonesOnDelete": return target.getConfiguration().isTombstonesOnDelete();
default: return null;
}
}
}
|
|
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package git4idea.branch;
import com.google.common.collect.Maps;
import com.intellij.dvcs.DvcsUtil;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vcs.VcsNotifier;
import com.intellij.openapi.vcs.changes.Change;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.Function;
import com.intellij.util.containers.MultiMap;
import git4idea.GitUtil;
import git4idea.commands.Git;
import git4idea.commands.GitMessageWithFilesDetector;
import git4idea.config.GitVcsSettings;
import git4idea.repo.GitRepository;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import static com.intellij.openapi.application.ModalityState.defaultModalityState;
import static com.intellij.openapi.util.text.StringUtil.pluralize;
import static com.intellij.util.ObjectUtils.chooseNotNull;
/**
* Common class for Git operations with branches aware of multi-root configuration,
* which means showing combined error information, proposing to rollback, etc.
*/
abstract class GitBranchOperation {
protected static final Logger LOG = Logger.getInstance(GitBranchOperation.class);
@NotNull protected final Project myProject;
@NotNull protected final Git myGit;
@NotNull protected final GitBranchUiHandler myUiHandler;
@NotNull private final Collection<GitRepository> myRepositories;
@NotNull protected final Map<GitRepository, String> myCurrentHeads;
@NotNull protected final Map<GitRepository, String> myInitialRevisions;
@NotNull private final GitVcsSettings mySettings;
@NotNull private final Collection<GitRepository> mySuccessfulRepositories;
@NotNull private final Collection<GitRepository> mySkippedRepositories;
@NotNull private final Collection<GitRepository> myRemainingRepositories;
protected GitBranchOperation(@NotNull Project project, @NotNull Git git,
@NotNull GitBranchUiHandler uiHandler, @NotNull Collection<GitRepository> repositories) {
myProject = project;
myGit = git;
myUiHandler = uiHandler;
myRepositories = repositories;
myCurrentHeads = Maps.toMap(repositories, repo -> chooseNotNull(repo.getCurrentBranchName(), repo.getCurrentRevision()));
myInitialRevisions = Maps.toMap(repositories, GitRepository::getCurrentRevision);
mySuccessfulRepositories = new ArrayList<>();
mySkippedRepositories = new ArrayList<>();
myRemainingRepositories = new ArrayList<>(myRepositories);
mySettings = GitVcsSettings.getInstance(myProject);
}
protected abstract void execute();
protected abstract void rollback();
@NotNull
public abstract String getSuccessMessage();
@NotNull
protected abstract String getRollbackProposal();
/**
* Returns a short downcased name of the operation.
* It is used by some dialogs or notifications which are common to several operations.
* Some operations (like checkout new branch) can be not mentioned in these dialogs, so their operation names would be not used.
*/
@NotNull
protected abstract String getOperationName();
/**
* @return next repository that wasn't handled (e.g. checked out) yet.
*/
@NotNull
protected GitRepository next() {
return myRemainingRepositories.iterator().next();
}
/**
* @return true if there are more repositories on which the operation wasn't executed yet.
*/
protected boolean hasMoreRepositories() {
return !myRemainingRepositories.isEmpty();
}
/**
* Marks repositories as successful, i.e. they won't be handled again.
*/
protected void markSuccessful(GitRepository... repositories) {
for (GitRepository repository : repositories) {
mySuccessfulRepositories.add(repository);
myRemainingRepositories.remove(repository);
}
}
/**
* Marks repositories as successful, i.e. they won't be handled again.
*/
protected void markSkip(GitRepository... repositories) {
for (GitRepository repository : repositories) {
mySkippedRepositories.add(repository);
myRemainingRepositories.remove(repository);
}
}
/**
* @return true if the operation has already succeeded in at least one of repositories.
*/
protected boolean wereSuccessful() {
return !mySuccessfulRepositories.isEmpty();
}
protected boolean wereSkipped() {
return !mySkippedRepositories.isEmpty();
}
@NotNull
protected Collection<GitRepository> getSuccessfulRepositories() {
return mySuccessfulRepositories;
}
@NotNull
protected Collection<GitRepository> getSkippedRepositories() {
return mySkippedRepositories;
}
@NotNull
protected String successfulRepositoriesJoined() {
return GitUtil.joinToHtml(mySuccessfulRepositories);
}
@NotNull
protected Collection<GitRepository> getRepositories() {
return myRepositories;
}
@NotNull
protected Collection<GitRepository> getRemainingRepositories() {
return myRemainingRepositories;
}
@NotNull
protected List<GitRepository> getRemainingRepositoriesExceptGiven(@NotNull final GitRepository currentRepository) {
List<GitRepository> repositories = new ArrayList<>(myRemainingRepositories);
repositories.remove(currentRepository);
return repositories;
}
protected void notifySuccess(@NotNull String message) {
VcsNotifier.getInstance(myProject).notifySuccess(message);
}
protected void notifySuccess() {
notifySuccess(getSuccessMessage());
}
protected final void saveAllDocuments() {
ApplicationManager.getApplication().invokeAndWait(() -> FileDocumentManager.getInstance().saveAllDocuments(), defaultModalityState());
}
/**
* Show fatal error as a notification or as a dialog with rollback proposal.
*/
protected void fatalError(@NotNull String title, @NotNull String message) {
if (wereSuccessful()) {
showFatalErrorDialogWithRollback(title, message);
}
else {
showFatalNotification(title, message);
}
}
protected void showFatalErrorDialogWithRollback(@NotNull final String title, @NotNull final String message) {
boolean rollback = myUiHandler.notifyErrorWithRollbackProposal(title, message, getRollbackProposal());
if (rollback) {
rollback();
}
}
protected void showFatalNotification(@NotNull String title, @NotNull String message) {
notifyError(title, message);
}
protected void notifyError(@NotNull String title, @NotNull String message) {
VcsNotifier.getInstance(myProject).notifyError(title, message);
}
@NotNull
protected ProgressIndicator getIndicator() {
return myUiHandler.getProgressIndicator();
}
/**
* Display the error saying that the operation can't be performed because there are unmerged files in a repository.
* Such error prevents checking out and creating new branch.
*/
protected void fatalUnmergedFilesError() {
if (wereSuccessful()) {
showUnmergedFilesDialogWithRollback();
}
else {
showUnmergedFilesNotification();
}
}
@NotNull
protected String repositories() {
return pluralize("repository", getSuccessfulRepositories().size());
}
/**
* Updates the recently visited branch in the settings.
* This is to be performed after successful checkout operation.
*/
protected void updateRecentBranch() {
if (getRepositories().size() == 1) {
GitRepository repository = myRepositories.iterator().next();
String currentHead = myCurrentHeads.get(repository);
if (currentHead != null) {
mySettings.setRecentBranchOfRepository(repository.getRoot().getPath(), currentHead);
}
else {
LOG.error("Current head is not known for " + repository.getRoot().getPath());
}
}
else {
String recentCommonBranch = getRecentCommonBranch();
if (recentCommonBranch != null) {
mySettings.setRecentCommonBranch(recentCommonBranch);
}
}
}
/**
* Returns the hash of the revision which was current before the start of this GitBranchOperation.
*/
@NotNull
protected String getInitialRevision(@NotNull GitRepository repository) {
return myInitialRevisions.get(repository);
}
@Nullable
private String getRecentCommonBranch() {
String recentCommonBranch = null;
for (String branch : myCurrentHeads.values()) {
if (recentCommonBranch == null) {
recentCommonBranch = branch;
}
else if (!recentCommonBranch.equals(branch)) {
return null;
}
}
return recentCommonBranch;
}
private void showUnmergedFilesDialogWithRollback() {
boolean ok = myUiHandler.showUnmergedFilesMessageWithRollback(getOperationName(), getRollbackProposal());
if (ok) {
rollback();
}
}
private void showUnmergedFilesNotification() {
myUiHandler.showUnmergedFilesNotification(getOperationName(), getRepositories());
}
/**
* Asynchronously refreshes the VFS root directory of the given repository.
*/
protected void refreshRoot(@NotNull GitRepository repository) {
// marking all files dirty, because sometimes FileWatcher is unable to process such a large set of changes that can happen during
// checkout on a large repository: IDEA-89944
VfsUtil.markDirtyAndRefresh(false, true, false, repository.getRoot());
}
protected void fatalLocalChangesError(@NotNull String reference) {
String title = String.format("Couldn't %s %s", getOperationName(), reference);
if (wereSuccessful()) {
showFatalErrorDialogWithRollback(title, "");
}
}
/**
* Shows the error "The following untracked working tree files would be overwritten by checkout/merge".
* If there were no repositories that succeeded the operation, shows a notification with a link to the list of these untracked files.
* If some repositories succeeded, shows a dialog with the list of these files and a proposal to rollback the operation of those
* repositories.
*/
protected void fatalUntrackedFilesError(@NotNull VirtualFile root, @NotNull Collection<String> relativePaths) {
if (wereSuccessful()) {
showUntrackedFilesDialogWithRollback(root, relativePaths);
}
else {
showUntrackedFilesNotification(root, relativePaths);
}
}
private void showUntrackedFilesNotification(@NotNull VirtualFile root, @NotNull Collection<String> relativePaths) {
myUiHandler.showUntrackedFilesNotification(getOperationName(), root, relativePaths);
}
private void showUntrackedFilesDialogWithRollback(@NotNull VirtualFile root, @NotNull Collection<String> relativePaths) {
boolean ok = myUiHandler.showUntrackedFilesDialogWithRollback(getOperationName(), getRollbackProposal(), root, relativePaths);
if (ok) {
rollback();
}
}
/**
* TODO this is non-optimal and even incorrect, since such diff shows the difference between committed changes
* For each of the given repositories looks to the diff between current branch and the given branch and converts it to the list of
* local changes.
*/
@NotNull
Map<GitRepository, List<Change>> collectLocalChangesConflictingWithBranch(@NotNull Collection<GitRepository> repositories,
@NotNull String currentBranch, @NotNull String otherBranch) {
Map<GitRepository, List<Change>> changes = new HashMap<>();
for (GitRepository repository : repositories) {
try {
Collection<String> diff = GitUtil.getPathsDiffBetweenRefs(myGit, repository, currentBranch, otherBranch);
List<Change> changesInRepo = GitUtil.findLocalChangesForPaths(myProject, repository.getRoot(), diff, false);
if (!changesInRepo.isEmpty()) {
changes.put(repository, changesInRepo);
}
}
catch (VcsException e) {
// ignoring the exception: this is not fatal if we won't collect such a diff from other repositories.
// At worst, use will get double dialog proposing the smart checkout.
LOG.warn(String.format("Couldn't collect diff between %s and %s in %s", currentBranch, otherBranch, repository.getRoot()), e);
}
}
return changes;
}
/**
* When checkout or merge operation on a repository fails with the error "local changes would be overwritten by...",
* affected local files are captured by the {@link git4idea.commands.GitMessageWithFilesDetector detector}.
* Then all remaining (non successful repositories) are searched if they are about to fail with the same problem.
* All collected local changes which prevent the operation, together with these repositories, are returned.
* @param currentRepository The first repository which failed the operation.
* @param localChangesOverwrittenBy The detector of local changes would be overwritten by merge/checkout.
* @param currentBranch Current branch.
* @param nextBranch Branch to compare with (the branch to be checked out, or the branch to be merged).
* @return Repositories that have failed or would fail with the "local changes" error, together with these local changes.
*/
@NotNull
protected Pair<List<GitRepository>, List<Change>> getConflictingRepositoriesAndAffectedChanges(
@NotNull GitRepository currentRepository, @NotNull GitMessageWithFilesDetector localChangesOverwrittenBy,
String currentBranch, String nextBranch) {
// get changes overwritten by checkout from the error message captured from Git
List<Change> affectedChanges = GitUtil.findLocalChangesForPaths(myProject, currentRepository.getRoot(),
localChangesOverwrittenBy.getRelativeFilePaths(), true
);
// get all other conflicting changes
// get changes in all other repositories (except those which already have succeeded) to avoid multiple dialogs proposing smart checkout
Map<GitRepository, List<Change>> conflictingChangesInRepositories =
collectLocalChangesConflictingWithBranch(getRemainingRepositoriesExceptGiven(currentRepository), currentBranch, nextBranch);
Set<GitRepository> otherProblematicRepositories = conflictingChangesInRepositories.keySet();
List<GitRepository> allConflictingRepositories = new ArrayList<>(otherProblematicRepositories);
allConflictingRepositories.add(currentRepository);
for (List<Change> changes : conflictingChangesInRepositories.values()) {
affectedChanges.addAll(changes);
}
return Pair.create(allConflictingRepositories, affectedChanges);
}
@NotNull
protected static String stringifyBranchesByRepos(@NotNull Map<GitRepository, String> heads) {
MultiMap<String, VirtualFile> grouped = groupByBranches(heads);
if (grouped.size() == 1) {
return grouped.keySet().iterator().next();
}
return StringUtil.join(grouped.entrySet(), new Function<Map.Entry<String, Collection<VirtualFile>>, String>() {
@Override
public String fun(Map.Entry<String, Collection<VirtualFile>> entry) {
String roots = StringUtil.join(entry.getValue(), new Function<VirtualFile, String>() {
@Override
public String fun(VirtualFile file) {
return file.getName();
}
}, ", ");
return entry.getKey() + " (in " + roots + ")";
}
}, "<br/>");
}
@NotNull
private static MultiMap<String, VirtualFile> groupByBranches(@NotNull Map<GitRepository, String> heads) {
MultiMap<String, VirtualFile> result = MultiMap.createLinked();
List<GitRepository> sortedRepos = DvcsUtil.sortRepositories(heads.keySet());
for (GitRepository repo : sortedRepos) {
result.putValue(heads.get(repo), repo.getRoot());
}
return result;
}
}
|
|
/* 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.flowable.engine.delegate.event;
import java.util.Collection;
import java.util.Set;
import org.flowable.common.engine.api.delegate.event.AbstractFlowableEventListener;
import org.flowable.common.engine.api.delegate.event.FlowableEngineEntityEvent;
import org.flowable.common.engine.api.delegate.event.FlowableEngineEvent;
import org.flowable.common.engine.api.delegate.event.FlowableEngineEventType;
import org.flowable.common.engine.api.delegate.event.FlowableEvent;
import org.flowable.common.engine.api.delegate.event.FlowableEventType;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.impl.util.CommandContextUtil;
import org.flowable.variable.api.event.FlowableVariableEvent;
/**
* @author Robert Hafner
*/
public abstract class AbstractFlowableEngineEventListener extends AbstractFlowableEventListener {
protected Set<FlowableEngineEventType> types;
public AbstractFlowableEngineEventListener() {}
public AbstractFlowableEngineEventListener(Set<FlowableEngineEventType> types) {
this.types = types;
}
@Override
public void onEvent(FlowableEvent flowableEvent) {
if (flowableEvent instanceof FlowableEngineEvent) {
FlowableEngineEvent flowableEngineEvent = (FlowableEngineEvent) flowableEvent;
FlowableEngineEventType engineEventType = (FlowableEngineEventType) flowableEvent.getType();
if (types == null || types.contains(engineEventType)) {
switch (engineEventType) {
case ENTITY_CREATED:
entityCreated((FlowableEngineEntityEvent) flowableEngineEvent);
break;
case ENTITY_INITIALIZED:
entityInitialized((FlowableEngineEntityEvent) flowableEngineEvent);
break;
case ENTITY_UPDATED:
entityUpdated((FlowableEngineEntityEvent) flowableEngineEvent);
break;
case ENTITY_DELETED:
entityDeleted((FlowableEngineEntityEvent) flowableEngineEvent);
break;
case ENTITY_SUSPENDED:
entitySuspended((FlowableEngineEntityEvent) flowableEngineEvent);
break;
case ENTITY_ACTIVATED:
entityActivated((FlowableEngineEntityEvent) flowableEngineEvent);
break;
case TIMER_SCHEDULED:
timerScheduled((FlowableEngineEntityEvent) flowableEngineEvent);
break;
case TIMER_FIRED:
timerFired((FlowableEngineEntityEvent) flowableEngineEvent);
break;
case JOB_CANCELED:
jobCancelled((FlowableEngineEntityEvent) flowableEngineEvent);
break;
case JOB_EXECUTION_SUCCESS:
jobExecutionSuccess((FlowableEngineEntityEvent) flowableEngineEvent);
break;
case JOB_EXECUTION_FAILURE:
jobExecutionFailure((FlowableEngineEntityEvent) flowableEngineEvent);
break;
case JOB_RETRIES_DECREMENTED:
jobRetriesDecremented((FlowableEngineEntityEvent) flowableEngineEvent);
break;
case JOB_RESCHEDULED:
jobRescheduled((FlowableEngineEntityEvent) flowableEngineEvent);
break;
case CUSTOM:
custom(flowableEngineEvent);
break;
case ENGINE_CREATED:
engineCreated((FlowableProcessEngineEvent) flowableEngineEvent);
break;
case ENGINE_CLOSED:
engineClosed((FlowableProcessEngineEvent) flowableEngineEvent);
break;
case ACTIVITY_STARTED:
activityStarted((FlowableActivityEvent) flowableEngineEvent);
break;
case ACTIVITY_COMPLETED:
activityCompleted((FlowableActivityEvent) flowableEngineEvent);
break;
case ACTIVITY_CANCELLED:
activityCancelled((FlowableActivityCancelledEvent) flowableEngineEvent);
break;
case MULTI_INSTANCE_ACTIVITY_STARTED:
multiInstanceActivityStarted((FlowableMultiInstanceActivityEvent) flowableEngineEvent);
break;
case MULTI_INSTANCE_ACTIVITY_COMPLETED:
multiInstanceActivityCompleted((FlowableMultiInstanceActivityCompletedEvent) flowableEngineEvent);
break;
case MULTI_INSTANCE_ACTIVITY_COMPLETED_WITH_CONDITION:
multiInstanceActivityCompletedWithCondition((FlowableMultiInstanceActivityCompletedEvent) flowableEngineEvent);
break;
case MULTI_INSTANCE_ACTIVITY_CANCELLED:
multiInstanceActivityCancelled((FlowableMultiInstanceActivityCancelledEvent) flowableEngineEvent);
break;
case ACTIVITY_SIGNAL_WAITING:
activitySignalWaiting((FlowableSignalEvent) flowableEngineEvent);
break;
case ACTIVITY_SIGNALED:
activitySignaled((FlowableSignalEvent) flowableEngineEvent);
break;
case ACTIVITY_COMPENSATE:
activityCompensate((FlowableActivityEvent) flowableEngineEvent);
break;
case ACTIVITY_MESSAGE_WAITING:
activityMessageWaiting((FlowableMessageEvent) flowableEngineEvent);
break;
case ACTIVITY_MESSAGE_RECEIVED:
activityMessageReceived((FlowableMessageEvent) flowableEngineEvent);
break;
case ACTIVITY_MESSAGE_CANCELLED:
activityMessageCancelled((FlowableMessageEvent) flowableEngineEvent);
break;
case ACTIVITY_ERROR_RECEIVED:
activityErrorReceived((FlowableErrorEvent) flowableEngineEvent);
break;
case HISTORIC_ACTIVITY_INSTANCE_CREATED:
historicActivityInstanceCreated((FlowableEngineEntityEvent) flowableEngineEvent);
break;
case HISTORIC_ACTIVITY_INSTANCE_ENDED:
historicActivityInstanceEnded((FlowableEngineEntityEvent) flowableEngineEvent);
break;
case SEQUENCEFLOW_TAKEN:
sequenceFlowTaken((FlowableSequenceFlowTakenEvent) flowableEngineEvent);
break;
case VARIABLE_CREATED:
variableCreated((FlowableVariableEvent) flowableEngineEvent);
break;
case VARIABLE_UPDATED:
variableUpdatedEvent((FlowableVariableEvent) flowableEngineEvent);
break;
case VARIABLE_DELETED:
variableDeletedEvent((FlowableVariableEvent) flowableEngineEvent);
break;
case TASK_CREATED:
taskCreated((FlowableEngineEntityEvent) flowableEngineEvent);
break;
case TASK_ASSIGNED:
taskAssigned((FlowableEngineEntityEvent) flowableEngineEvent);
break;
case TASK_COMPLETED:
taskCompleted((FlowableEngineEntityEvent) flowableEngineEvent);
break;
case PROCESS_CREATED:
processCreated((FlowableEngineEntityEvent) flowableEngineEvent);
break;
case PROCESS_STARTED:
processStarted((FlowableProcessStartedEvent) flowableEngineEvent);
break;
case PROCESS_COMPLETED:
processCompleted((FlowableEngineEntityEvent) flowableEngineEvent);
break;
case PROCESS_COMPLETED_WITH_TERMINATE_END_EVENT:
processCompletedWithTerminateEnd((FlowableEngineEntityEvent) flowableEngineEvent);
break;
case PROCESS_COMPLETED_WITH_ERROR_END_EVENT:
processCompletedWithErrorEnd((FlowableEngineEntityEvent) flowableEngineEvent);
break;
case PROCESS_CANCELLED:
processCancelled((FlowableCancelledEvent) flowableEngineEvent);
break;
case HISTORIC_PROCESS_INSTANCE_CREATED:
historicProcessInstanceCreated((FlowableEngineEntityEvent) flowableEngineEvent);
break;
case HISTORIC_PROCESS_INSTANCE_ENDED:
historicProcessInstanceEnded((FlowableEngineEntityEvent) flowableEngineEvent);
break;
default:
break;
}
}
}
}
@Override
public boolean isFailOnException() {
return true;
}
@Override
public Collection<? extends FlowableEventType> getTypes() {
return types == null ? super.getTypes() : types;
}
protected void entityCreated(FlowableEngineEntityEvent event) {}
protected void entityInitialized(FlowableEngineEntityEvent event) {}
protected void entityUpdated(FlowableEngineEntityEvent event) {}
protected void entityDeleted(FlowableEngineEntityEvent event) {}
protected void entitySuspended(FlowableEngineEntityEvent event) {}
protected void entityActivated(FlowableEngineEntityEvent event) {}
protected void timerScheduled(FlowableEngineEntityEvent event) {}
protected void timerFired(FlowableEngineEntityEvent event) {}
protected void jobCancelled(FlowableEngineEntityEvent event) {}
protected void jobExecutionSuccess(FlowableEngineEntityEvent event) {}
protected void jobExecutionFailure(FlowableEngineEntityEvent event) {}
protected void jobRetriesDecremented(FlowableEngineEntityEvent event) {}
protected void jobRescheduled(FlowableEngineEntityEvent event) {}
protected void custom(FlowableEngineEvent event) {}
protected void engineCreated(FlowableProcessEngineEvent event) {}
protected void engineClosed(FlowableProcessEngineEvent flowableEngineEvent) {}
protected void activityStarted(FlowableActivityEvent event) {}
protected void activityCompleted(FlowableActivityEvent event) {}
protected void activityCancelled(FlowableActivityCancelledEvent event) {}
protected void multiInstanceActivityStarted(FlowableMultiInstanceActivityEvent event) {}
protected void multiInstanceActivityCompleted(FlowableMultiInstanceActivityCompletedEvent event) {}
protected void multiInstanceActivityCompletedWithCondition(FlowableMultiInstanceActivityCompletedEvent event) {}
protected void multiInstanceActivityCancelled(FlowableMultiInstanceActivityCancelledEvent event) {}
protected void activitySignalWaiting(FlowableSignalEvent event) {}
protected void activitySignaled(FlowableSignalEvent event) {}
protected void activityCompensate(FlowableActivityEvent event) {}
protected void activityMessageWaiting(FlowableMessageEvent event) {}
protected void activityMessageReceived(FlowableMessageEvent event) {}
protected void activityMessageCancelled(FlowableMessageEvent event) {}
protected void activityErrorReceived(FlowableErrorEvent event) {}
protected void historicActivityInstanceCreated(FlowableEngineEntityEvent event) {}
protected void historicActivityInstanceEnded(FlowableEngineEntityEvent event) {}
protected void sequenceFlowTaken(FlowableSequenceFlowTakenEvent event) {}
protected void variableCreated(FlowableVariableEvent event) {}
protected void variableUpdatedEvent(FlowableVariableEvent event) {}
protected void variableDeletedEvent(FlowableVariableEvent event) {}
protected void taskCreated(FlowableEngineEntityEvent event) {}
protected void taskAssigned(FlowableEngineEntityEvent event) {}
protected void taskCompleted(FlowableEngineEntityEvent event) {}
protected void processCreated(FlowableEngineEntityEvent event) {}
protected void processStarted(FlowableProcessStartedEvent event) {}
protected void processCompleted(FlowableEngineEntityEvent event) {}
protected void processCompletedWithTerminateEnd(FlowableEngineEntityEvent event) {}
protected void processCompletedWithErrorEnd(FlowableEngineEntityEvent event) {}
protected void processCancelled(FlowableCancelledEvent event) {}
protected void historicProcessInstanceCreated(FlowableEngineEntityEvent event) {}
protected void historicProcessInstanceEnded(FlowableEngineEntityEvent event) {}
protected DelegateExecution getExecution(FlowableEngineEvent event) {
String executionId = event.getExecutionId();
if (executionId != null) {
CommandContext commandContext = CommandContextUtil.getCommandContext();
if (commandContext != null) {
return CommandContextUtil.getExecutionEntityManager(commandContext).findById(executionId);
}
}
return null;
}
}
|
|
package org.hisp.dhis.webapi.controller;
/*
* Copyright (c) 2004-2016, University of Oslo
* 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 HISP project 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.
*/
import org.hisp.dhis.common.Grid;
import org.hisp.dhis.dxf2.webmessage.WebMessageException;
import org.hisp.dhis.schema.descriptors.SqlViewSchemaDescriptor;
import org.hisp.dhis.sqlview.SqlView;
import org.hisp.dhis.sqlview.SqlViewService;
import org.hisp.dhis.system.grid.GridUtils;
import org.hisp.dhis.system.util.CodecUtils;
import org.hisp.dhis.webapi.utils.ContextUtils;
import org.hisp.dhis.webapi.utils.WebMessageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Set;
/**
* @author Morten Olav Hansen <[email protected]>
*/
@Controller
@RequestMapping( value = SqlViewSchemaDescriptor.API_ENDPOINT )
public class SqlViewController
extends AbstractCrudController<SqlView>
{
@Autowired
private SqlViewService sqlViewService;
@Autowired
private ContextUtils contextUtils;
@RequestMapping( value = "/{uid}/data", method = RequestMethod.GET, produces = ContextUtils.CONTENT_TYPE_JSON )
public @ResponseBody Grid getViewJson( @PathVariable( "uid" ) String uid,
@RequestParam( required = false ) Set<String> criteria, @RequestParam( required = false ) Set<String> var,
HttpServletResponse response ) throws WebMessageException
{
SqlView sqlView = sqlViewService.getSqlViewByUid( uid );
if ( sqlView == null )
{
throw new WebMessageException( WebMessageUtils.notFound( "SQL view does not exist: " + uid ) );
}
Grid grid = sqlViewService.getSqlViewGrid( sqlView, SqlView.getCriteria( criteria ), SqlView.getCriteria( var ) );
contextUtils.configureResponse( response, ContextUtils.CONTENT_TYPE_JSON, sqlView.getCacheStrategy() );
return grid;
}
@RequestMapping( value = "/{uid}/data.xml", method = RequestMethod.GET )
public void getViewXml( @PathVariable( "uid" ) String uid,
@RequestParam( required = false ) Set<String> criteria, @RequestParam( required = false ) Set<String> var,
HttpServletResponse response ) throws WebMessageException, IOException
{
SqlView sqlView = sqlViewService.getSqlViewByUid( uid );
if ( sqlView == null )
{
throw new WebMessageException( WebMessageUtils.notFound( "SQL view does not exist: " + uid ) );
}
Grid grid = sqlViewService.getSqlViewGrid( sqlView, SqlView.getCriteria( criteria ), SqlView.getCriteria( var ) );
contextUtils.configureResponse( response, ContextUtils.CONTENT_TYPE_XML, sqlView.getCacheStrategy() );
GridUtils.toXml( grid, response.getOutputStream() );
}
@RequestMapping( value = "/{uid}/data.csv", method = RequestMethod.GET )
public void getViewCsv( @PathVariable( "uid" ) String uid,
@RequestParam( required = false ) Set<String> criteria, @RequestParam( required = false ) Set<String> var,
HttpServletResponse response ) throws Exception
{
SqlView sqlView = sqlViewService.getSqlViewByUid( uid );
if ( sqlView == null )
{
throw new WebMessageException( WebMessageUtils.notFound( "SQL view does not exist: " + uid ) );
}
Grid grid = sqlViewService.getSqlViewGrid( sqlView, SqlView.getCriteria( criteria ), SqlView.getCriteria( var ) );
String filename = CodecUtils.filenameEncode( grid.getTitle() ) + ".csv";
contextUtils.configureResponse( response, ContextUtils.CONTENT_TYPE_CSV, sqlView.getCacheStrategy(), filename, true );
GridUtils.toCsv( grid, response.getWriter() );
}
@RequestMapping( value = "/{uid}/data.xls", method = RequestMethod.GET )
public void getViewXls( @PathVariable( "uid" ) String uid,
@RequestParam( required = false ) Set<String> criteria, @RequestParam( required = false ) Set<String> var,
HttpServletResponse response ) throws Exception
{
SqlView sqlView = sqlViewService.getSqlViewByUid( uid );
if ( sqlView == null )
{
throw new WebMessageException( WebMessageUtils.notFound( "SQL view does not exist: " + uid ) );
}
Grid grid = sqlViewService.getSqlViewGrid( sqlView, SqlView.getCriteria( criteria ), SqlView.getCriteria( var ) );
String filename = CodecUtils.filenameEncode( grid.getTitle() ) + ".xls";
contextUtils.configureResponse( response, ContextUtils.CONTENT_TYPE_EXCEL, sqlView.getCacheStrategy(), filename, true );
GridUtils.toXls( grid, response.getOutputStream() );
}
@RequestMapping( value = "/{uid}/data.html", method = RequestMethod.GET )
public void getViewHtml( @PathVariable( "uid" ) String uid,
@RequestParam( required = false ) Set<String> criteria, @RequestParam( required = false ) Set<String> var,
HttpServletResponse response ) throws Exception
{
SqlView sqlView = sqlViewService.getSqlViewByUid( uid );
if ( sqlView == null )
{
throw new WebMessageException( WebMessageUtils.notFound( "SQL view does not exist: " + uid ) );
}
Grid grid = sqlViewService.getSqlViewGrid( sqlView, SqlView.getCriteria( criteria ), SqlView.getCriteria( var ) );
contextUtils.configureResponse( response, ContextUtils.CONTENT_TYPE_HTML, sqlView.getCacheStrategy() );
GridUtils.toHtml( grid, response.getWriter() );
}
@RequestMapping( value = "/{uid}/data.html+css", method = RequestMethod.GET )
public void getViewHtmlCss( @PathVariable( "uid" ) String uid,
@RequestParam( required = false ) Set<String> criteria, @RequestParam( required = false ) Set<String> var,
HttpServletResponse response ) throws Exception
{
SqlView sqlView = sqlViewService.getSqlViewByUid( uid );
if ( sqlView == null )
{
throw new WebMessageException( WebMessageUtils.notFound( "SQL view does not exist: " + uid ) );
}
Grid grid = sqlViewService.getSqlViewGrid( sqlView, SqlView.getCriteria( criteria ), SqlView.getCriteria( var ) );
contextUtils.configureResponse( response, ContextUtils.CONTENT_TYPE_HTML, sqlView.getCacheStrategy() );
GridUtils.toHtmlCss( grid, response.getWriter() );
}
@RequestMapping( value = "/{uid}/data.pdf", method = RequestMethod.GET )
public void getViewPdf( @PathVariable( "uid" ) String uid,
@RequestParam( required = false ) Set<String> criteria, @RequestParam( required = false ) Set<String> var,
HttpServletResponse response ) throws Exception
{
SqlView sqlView = sqlViewService.getSqlViewByUid( uid );
if ( sqlView == null )
{
throw new WebMessageException( WebMessageUtils.notFound( "SQL view does not exist: " + uid ) );
}
Grid grid = sqlViewService.getSqlViewGrid( sqlView, SqlView.getCriteria( criteria ), SqlView.getCriteria( var ) );
contextUtils.configureResponse( response, ContextUtils.CONTENT_TYPE_PDF, sqlView.getCacheStrategy() );
GridUtils.toPdf( grid, response.getOutputStream() );
}
@RequestMapping( value = "/{uid}/execute", method = RequestMethod.POST )
public void executeView( @PathVariable( "uid" ) String uid, @RequestParam( required = false ) Set<String> var,
HttpServletResponse response, HttpServletRequest request ) throws WebMessageException
{
SqlView sqlView = sqlViewService.getSqlViewByUid( uid );
if ( sqlView == null )
{
throw new WebMessageException( WebMessageUtils.notFound( "SQL view not found" ) );
}
String result = sqlViewService.createViewTable( sqlView );
if ( result != null )
{
throw new WebMessageException( WebMessageUtils.conflict( result ) );
}
else
{
response.addHeader( "Location", SqlViewSchemaDescriptor.API_ENDPOINT + "/" + sqlView.getUid() );
webMessageService.send( WebMessageUtils.created( "SQL view created" ), response, request );
}
}
@RequestMapping( value = "/{uid}/refresh", method = RequestMethod.POST )
public void refreshMaterializedView( @PathVariable( "uid" ) String uid,
HttpServletResponse response, HttpServletRequest request ) throws WebMessageException
{
SqlView sqlView = sqlViewService.getSqlViewByUid( uid );
if ( sqlView == null )
{
throw new WebMessageException( WebMessageUtils.notFound( "SQL view not found" ) );
}
boolean result = sqlViewService.refreshMaterializedView( sqlView );
if ( !result )
{
throw new WebMessageException( WebMessageUtils.conflict( "View could not be refreshed" ) );
}
else
{
webMessageService.send( WebMessageUtils.ok( "Materialized view refreshed" ), response, request );
}
}
}
|
|
/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.telephony.cdma;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Message;
import android.os.SystemProperties;
import android.preference.PreferenceManager;
import android.provider.Telephony.Sms.Intents;
import android.telephony.SmsCbMessage;
import com.android.internal.telephony.CellBroadcastHandler;
import com.android.internal.telephony.CommandsInterface;
import com.android.internal.telephony.InboundSmsHandler;
import com.android.internal.telephony.InboundSmsTracker;
import com.android.internal.telephony.PhoneBase;
import com.android.internal.telephony.SmsConstants;
import com.android.internal.telephony.SmsMessageBase;
import com.android.internal.telephony.SmsStorageMonitor;
import com.android.internal.telephony.TelephonyProperties;
import com.android.internal.telephony.WspTypeDecoder;
import com.android.internal.telephony.cdma.sms.SmsEnvelope;
import java.util.Arrays;
/**
* Subclass of {@link InboundSmsHandler} for 3GPP2 type messages.
*/
public class CdmaInboundSmsHandler extends InboundSmsHandler {
private final PhoneBase mPhone;
private final CdmaSMSDispatcher mSmsDispatcher;
private final CellBroadcastHandler mCellBroadcastHandler;
private final CdmaServiceCategoryProgramHandler mServiceCategoryProgramHandler;
private byte[] mLastDispatchedSmsFingerprint;
private byte[] mLastAcknowledgedSmsFingerprint;
private final boolean mCheckForDuplicatePortsInOmadmWapPush = Resources.getSystem().getBoolean(
com.android.internal.R.bool.config_duplicate_port_omadm_wappush);
/**
* Create a new inbound SMS handler for CDMA.
*/
private CdmaInboundSmsHandler(Context context, SmsStorageMonitor storageMonitor,
PhoneBase phone, CdmaSMSDispatcher smsDispatcher) {
super("CdmaInboundSmsHandler", context, storageMonitor);
mSmsDispatcher = smsDispatcher;
mCellBroadcastHandler = CellBroadcastHandler.makeCellBroadcastHandler(context);
mServiceCategoryProgramHandler = CdmaServiceCategoryProgramHandler.makeScpHandler(context,
phone.mCi);
mPhone = phone;
phone.mCi.setOnNewCdmaSms(getHandler(), EVENT_NEW_SMS, null);
}
/**
* Unregister for CDMA SMS.
*/
@Override
protected void onQuitting() {
mPhone.mCi.unSetOnNewCdmaSms(getHandler());
mCellBroadcastHandler.dispose();
if (DBG) log("unregistered for 3GPP2 SMS");
super.onQuitting();
}
/**
* Wait for state machine to enter startup state. We can't send any messages until then.
*/
public static CdmaInboundSmsHandler makeInboundSmsHandler(Context context,
SmsStorageMonitor storageMonitor, PhoneBase phone, CdmaSMSDispatcher smsDispatcher) {
CdmaInboundSmsHandler handler = new CdmaInboundSmsHandler(context, storageMonitor,
phone, smsDispatcher);
handler.start();
return handler;
}
/**
* Return whether the device is in Emergency Call Mode (only for 3GPP2).
* @return true if the device is in ECM; false otherwise
*/
private static boolean isInEmergencyCallMode() {
String inEcm = SystemProperties.get(TelephonyProperties.PROPERTY_INECM_MODE, "false");
return "true".equals(inEcm);
}
/**
* Return true if this handler is for 3GPP2 messages; false for 3GPP format.
* @return true (3GPP2)
*/
@Override
protected boolean is3gpp2() {
return true;
}
/**
* Process Cell Broadcast, Voicemail Notification, and other 3GPP/3GPP2-specific messages.
* @param smsb the SmsMessageBase object from the RIL
* @return true if the message was handled here; false to continue processing
*/
@Override
protected int dispatchMessageRadioSpecific(SmsMessageBase smsb) {
if (isInEmergencyCallMode()) {
return Activity.RESULT_OK;
}
SmsMessage sms = (SmsMessage) smsb;
boolean isBroadcastType = (SmsEnvelope.MESSAGE_TYPE_BROADCAST == sms.getMessageType());
// Handle CMAS emergency broadcast messages.
if (isBroadcastType) {
log("Broadcast type message");
SmsCbMessage cbMessage = sms.parseBroadcastSms();
if (cbMessage != null) {
mCellBroadcastHandler.dispatchSmsMessage(cbMessage);
} else {
loge("error trying to parse broadcast SMS");
}
return Intents.RESULT_SMS_HANDLED;
}
// Initialize fingerprint field, and see if we have a network duplicate SMS.
mLastDispatchedSmsFingerprint = sms.getIncomingSmsFingerprint();
if (mLastAcknowledgedSmsFingerprint != null &&
Arrays.equals(mLastDispatchedSmsFingerprint, mLastAcknowledgedSmsFingerprint)) {
return Intents.RESULT_SMS_HANDLED;
}
// Decode BD stream and set sms variables.
sms.parseSms();
int teleService = sms.getTeleService();
switch (teleService) {
case SmsEnvelope.TELESERVICE_VMN:
case SmsEnvelope.TELESERVICE_MWI:
// handle voicemail indication
handleVoicemailTeleservice(sms);
return Intents.RESULT_SMS_HANDLED;
case SmsEnvelope.TELESERVICE_WMT:
case SmsEnvelope.TELESERVICE_WEMT:
if (sms.isStatusReportMessage()) {
mSmsDispatcher.sendStatusReportMessage(sms);
return Intents.RESULT_SMS_HANDLED;
}
break;
case SmsEnvelope.TELESERVICE_SCPT:
mServiceCategoryProgramHandler.dispatchSmsMessage(sms);
return Intents.RESULT_SMS_HANDLED;
case SmsEnvelope.TELESERVICE_WAP:
// handled below, after storage check
break;
default:
loge("unsupported teleservice 0x" + Integer.toHexString(teleService));
return Intents.RESULT_SMS_UNSUPPORTED;
}
if (!mStorageMonitor.isStorageAvailable() &&
sms.getMessageClass() != SmsConstants.MessageClass.CLASS_0) {
// It's a storable message and there's no storage available. Bail.
// (See C.S0015-B v2.0 for a description of "Immediate Display"
// messages, which we represent as CLASS_0.)
return Intents.RESULT_SMS_OUT_OF_MEMORY;
}
if (SmsEnvelope.TELESERVICE_WAP == teleService) {
return processCdmaWapPdu(sms.getUserData(), sms.mMessageRef,
sms.getOriginatingAddress(), sms.getTimestampMillis());
}
return dispatchNormalMessage(smsb);
}
/**
* Send an acknowledge message.
* @param success indicates that last message was successfully received.
* @param result result code indicating any error
* @param response callback message sent when operation completes.
*/
@Override
protected void acknowledgeLastIncomingSms(boolean success, int result, Message response) {
if (isInEmergencyCallMode()) {
return;
}
int causeCode = resultToCause(result);
mPhone.mCi.acknowledgeLastIncomingCdmaSms(success, causeCode, response);
if (causeCode == 0) {
mLastAcknowledgedSmsFingerprint = mLastDispatchedSmsFingerprint;
}
mLastDispatchedSmsFingerprint = null;
}
/**
* Convert Android result code to CDMA SMS failure cause.
* @param rc the Android SMS intent result value
* @return 0 for success, or a CDMA SMS failure cause value
*/
private static int resultToCause(int rc) {
switch (rc) {
case Activity.RESULT_OK:
case Intents.RESULT_SMS_HANDLED:
// Cause code is ignored on success.
return 0;
case Intents.RESULT_SMS_OUT_OF_MEMORY:
return CommandsInterface.CDMA_SMS_FAIL_CAUSE_RESOURCE_SHORTAGE;
case Intents.RESULT_SMS_UNSUPPORTED:
return CommandsInterface.CDMA_SMS_FAIL_CAUSE_INVALID_TELESERVICE_ID;
case Intents.RESULT_SMS_GENERIC_ERROR:
default:
return CommandsInterface.CDMA_SMS_FAIL_CAUSE_ENCODING_PROBLEM;
}
}
/**
* Handle {@link SmsEnvelope#TELESERVICE_VMN} and {@link SmsEnvelope#TELESERVICE_MWI}.
* @param sms the message to process
*/
private void handleVoicemailTeleservice(SmsMessage sms) {
int voicemailCount = sms.getNumOfVoicemails();
if (DBG) log("Voicemail count=" + voicemailCount);
// Store the voicemail count in preferences.
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(mContext);
SharedPreferences.Editor editor = sp.edit();
editor.putInt(CDMAPhone.VM_COUNT_CDMA, voicemailCount);
editor.apply();
mPhone.setVoiceMessageWaiting(1, voicemailCount);
}
/**
* Processes inbound messages that are in the WAP-WDP PDU format. See
* wap-259-wdp-20010614-a section 6.5 for details on the WAP-WDP PDU format.
* WDP segments are gathered until a datagram completes and gets dispatched.
*
* @param pdu The WAP-WDP PDU segment
* @return a result code from {@link android.provider.Telephony.Sms.Intents}, or
* {@link Activity#RESULT_OK} if the message has been broadcast
* to applications
*/
private int processCdmaWapPdu(byte[] pdu, int referenceNumber, String address,
long timestamp) {
int index = 0;
int msgType = (0xFF & pdu[index++]);
if (msgType != 0) {
log("Received a WAP SMS which is not WDP. Discard.");
return Intents.RESULT_SMS_HANDLED;
}
int totalSegments = (0xFF & pdu[index++]); // >= 1
int segment = (0xFF & pdu[index++]); // >= 0
if (segment >= totalSegments) {
loge("WDP bad segment #" + segment + " expecting 0-" + (totalSegments - 1));
return Intents.RESULT_SMS_HANDLED;
}
// Only the first segment contains sourcePort and destination Port
int sourcePort = 0;
int destinationPort = 0;
if (segment == 0) {
//process WDP segment
sourcePort = (0xFF & pdu[index++]) << 8;
sourcePort |= 0xFF & pdu[index++];
destinationPort = (0xFF & pdu[index++]) << 8;
destinationPort |= 0xFF & pdu[index++];
// Some carriers incorrectly send duplicate port fields in omadm wap pushes.
// If configured, check for that here
if (mCheckForDuplicatePortsInOmadmWapPush) {
if (checkDuplicatePortOmadmWapPush(pdu, index)) {
index = index + 4; // skip duplicate port fields
}
}
}
// Lookup all other related parts
log("Received WAP PDU. Type = " + msgType + ", originator = " + address
+ ", src-port = " + sourcePort + ", dst-port = " + destinationPort
+ ", ID = " + referenceNumber + ", segment# = " + segment + '/' + totalSegments);
// pass the user data portion of the PDU to the shared handler in SMSDispatcher
byte[] userData = new byte[pdu.length - index];
System.arraycopy(pdu, index, userData, 0, pdu.length - index);
InboundSmsTracker tracker = new InboundSmsTracker(userData, timestamp, destinationPort,
true, address, referenceNumber, segment, totalSegments, true);
return addTrackerToRawTableAndSendMessage(tracker);
}
/**
* Optional check to see if the received WapPush is an OMADM notification with erroneous
* extra port fields.
* - Some carriers make this mistake.
* ex: MSGTYPE-TotalSegments-CurrentSegment
* -SourcePortDestPort-SourcePortDestPort-OMADM PDU
* @param origPdu The WAP-WDP PDU segment
* @param index Current Index while parsing the PDU.
* @return True if OrigPdu is OmaDM Push Message which has duplicate ports.
* False if OrigPdu is NOT OmaDM Push Message which has duplicate ports.
*/
private static boolean checkDuplicatePortOmadmWapPush(byte[] origPdu, int index) {
index += 4;
byte[] omaPdu = new byte[origPdu.length - index];
System.arraycopy(origPdu, index, omaPdu, 0, omaPdu.length);
WspTypeDecoder pduDecoder = new WspTypeDecoder(omaPdu);
int wspIndex = 2;
// Process header length field
if (!pduDecoder.decodeUintvarInteger(wspIndex)) {
return false;
}
wspIndex += pduDecoder.getDecodedDataLength(); // advance to next field
// Process content type field
if (!pduDecoder.decodeContentType(wspIndex)) {
return false;
}
String mimeType = pduDecoder.getValueString();
return (WspTypeDecoder.CONTENT_TYPE_B_PUSH_SYNCML_NOTI.equals(mimeType));
}
}
|
|
/*
* 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.stratos.manager.internal;
import com.hazelcast.core.HazelcastInstance;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.stratos.common.Component;
import org.apache.stratos.common.services.ComponentActivationEventListener;
import org.apache.stratos.common.services.ComponentStartUpSynchronizer;
import org.apache.stratos.common.services.DistributedObjectProvider;
import org.apache.stratos.common.threading.StratosThreadPool;
import org.apache.stratos.manager.context.StratosManagerContext;
import org.apache.stratos.manager.messaging.publisher.TenantEventPublisher;
import org.apache.stratos.manager.messaging.publisher.synchronizer.ApplicationSignUpEventSynchronizer;
import org.apache.stratos.manager.messaging.publisher.synchronizer.TenantEventSynchronizer;
import org.apache.stratos.manager.messaging.receiver.StratosManagerApplicationEventReceiver;
import org.apache.stratos.manager.messaging.receiver.StratosManagerInstanceStatusEventReceiver;
import org.apache.stratos.manager.messaging.receiver.StratosManagerTopologyEventReceiver;
import org.apache.stratos.manager.user.management.TenantUserRoleManager;
import org.apache.stratos.manager.user.management.exception.UserManagerException;
import org.apache.stratos.manager.utils.CartridgeConfigFileReader;
import org.apache.stratos.manager.utils.UserRoleCreator;
import org.apache.stratos.messaging.broker.publish.EventPublisherPool;
import org.apache.stratos.messaging.util.MessagingUtil;
import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.ntask.core.service.TaskService;
import org.wso2.carbon.registry.core.service.RegistryService;
import org.wso2.carbon.user.api.UserStoreManager;
import org.wso2.carbon.user.core.UserRealm;
import org.wso2.carbon.user.core.UserStoreException;
import org.wso2.carbon.user.core.service.RealmService;
import org.wso2.carbon.utils.ConfigurationContextService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* @scr.component name="org.wso2.carbon.hosting.mgt.internal.StratosManagerServiceComponent"
* immediate="true"
* @scr.reference name="hazelcast.instance.service" interface="com.hazelcast.core.HazelcastInstance"
* cardinality="0..1"policy="dynamic" bind="setHazelcastInstance" unbind="unsetHazelcastInstance"
* @scr.reference name="config.context.service"
* interface="org.wso2.carbon.utils.ConfigurationContextService"
* cardinality="1..1" policy="dynamic"
* bind="setConfigurationContextService"
* unbind="unsetConfigurationContextService"
* @scr.reference name="user.realmservice.default"
* interface="org.wso2.carbon.user.core.service.RealmService"
* cardinality="1..1" policy="dynamic" bind="setRealmService"
* unbind="unsetRealmService"
* @scr.reference name="registry.service"
* interface="org.wso2.carbon.registry.core.service.RegistryService"
* cardinality="1..1" policy="dynamic" bind="setRegistryService"
* unbind="unsetRegistryService"
* @scr.reference name="ntask.component" interface="org.wso2.carbon.ntask.core.service.TaskService"
* cardinality="1..1" policy="dynamic" bind="setTaskService"
* unbind="unsetTaskService"
* @scr.reference name="distributedObjectProvider" interface="org.apache.stratos.common.services.DistributedObjectProvider"
* cardinality="1..1" policy="dynamic" bind="setDistributedObjectProvider" unbind="unsetDistributedObjectProvider"
* @scr.reference name="componentStartUpSynchronizer" interface="org.apache.stratos.common.services.ComponentStartUpSynchronizer"
* cardinality="1..1" policy="dynamic" bind="setComponentStartUpSynchronizer" unbind="unsetComponentStartUpSynchronizer"
*/
public class StratosManagerServiceComponent {
private static final Log log = LogFactory.getLog(StratosManagerServiceComponent.class);
private static final String THREAD_POOL_ID = "stratos.manager.thread.pool";
private static final String SCHEDULER_THREAD_POOL_ID = "stratos.manager.scheduler.thread.pool";
private static final String STRATOS_MANAGER_COORDINATOR_LOCK = "stratos.manager.coordinator.lock";
private static final int THREAD_POOL_SIZE = 20;
private static final int SCHEDULER_THREAD_POOL_SIZE = 5;
private StratosManagerTopologyEventReceiver topologyEventReceiver;
private StratosManagerInstanceStatusEventReceiver instanceStatusEventReceiver;
private StratosManagerApplicationEventReceiver applicationEventReceiver;
private ExecutorService executorService;
private ScheduledExecutorService scheduler;
protected void activate(final ComponentContext componentContext) throws Exception {
try {
executorService = StratosThreadPool.getExecutorService(THREAD_POOL_ID, THREAD_POOL_SIZE);
scheduler = StratosThreadPool.getScheduledExecutorService(SCHEDULER_THREAD_POOL_ID,
SCHEDULER_THREAD_POOL_SIZE);
Runnable stratosManagerActivator = new Runnable() {
@Override
public void run() {
try {
ComponentStartUpSynchronizer componentStartUpSynchronizer =
ServiceReferenceHolder.getInstance().getComponentStartUpSynchronizer();
// Wait for cloud controller and autoscaler components to be activated
componentStartUpSynchronizer.waitForComponentActivation(Component.StratosManager,
Component.CloudController);
componentStartUpSynchronizer.waitForComponentActivation(Component.StratosManager,
Component.Autoscaler);
CartridgeConfigFileReader.readProperties();
if (StratosManagerContext.getInstance().isClustered()) {
Thread coordinatorElectorThread = new Thread() {
@Override
public void run() {
try {
ServiceReferenceHolder.getInstance().getHazelcastInstance()
.getLock(STRATOS_MANAGER_COORDINATOR_LOCK).lock();
String localMemberId = ServiceReferenceHolder.getInstance().getHazelcastInstance()
.getCluster().getLocalMember().getUuid();
log.info("Elected this member [" + localMemberId + "] " +
"as the stratos manager coordinator for the cluster");
StratosManagerContext.getInstance().setCoordinator(true);
executeCoordinatorTasks(componentContext);
} catch (Exception e) {
if (log.isErrorEnabled()) {
log.error("Could not execute coordinator tasks", e);
}
}
}
};
coordinatorElectorThread.setName("Stratos manager coordinator elector thread");
executorService.submit(coordinatorElectorThread);
} else {
executeCoordinatorTasks(componentContext);
}
// Initialize topology event receiver
initializeTopologyEventReceiver();
// Initialize application event receiver
initializeApplicationEventReceiver();
componentStartUpSynchronizer.waitForWebServiceActivation("StratosManagerService");
componentStartUpSynchronizer.setComponentStatus(Component.StratosManager, true);
if (log.isInfoEnabled()) {
log.info("Stratos manager component is activated");
}
} catch (Exception e) {
log.error("Could not activate stratos manager service component", e);
}
}
};
Thread stratosManagerActivatorThread = new Thread(stratosManagerActivator);
stratosManagerActivatorThread.start();
} catch (Exception e) {
log.error("Could not activate stratos manager service component", e);
}
}
/**
* Execute coordinator tasks
*
* @param componentContext
* @throws UserStoreException
* @throws UserManagerException
*/
private void executeCoordinatorTasks(ComponentContext componentContext) throws UserStoreException,
UserManagerException {
initializeTenantEventPublisher(componentContext);
initializeInstanceStatusEventReceiver();
registerComponentStartUpEventListeners();
// Create internal/user Role at server start-up
createInternalUserRole(componentContext);
}
/**
* Initialize instance status event receiver
*/
private void initializeInstanceStatusEventReceiver() {
instanceStatusEventReceiver = new StratosManagerInstanceStatusEventReceiver();
instanceStatusEventReceiver.setExecutorService(executorService);
instanceStatusEventReceiver.execute();
}
/**
* Initialize topology event receiver
*/
private void initializeTopologyEventReceiver() {
topologyEventReceiver = new StratosManagerTopologyEventReceiver();
topologyEventReceiver.setExecutorService(executorService);
topologyEventReceiver.execute();
}
/**
* Initialize application event receiver
*/
private void initializeApplicationEventReceiver() {
applicationEventReceiver = new StratosManagerApplicationEventReceiver();
applicationEventReceiver.setExecutorService(executorService);
applicationEventReceiver.execute();
}
/**
* Create internal user role if not exists.
*
* @param componentContext
* @throws UserStoreException
* @throws UserManagerException
*/
private void createInternalUserRole(ComponentContext componentContext) throws UserStoreException, UserManagerException {
RealmService realmService = ServiceReferenceHolder.getRealmService();
UserRealm realm = realmService.getBootstrapRealm();
UserStoreManager userStoreManager = realm.getUserStoreManager();
UserRoleCreator.createInternalUserRole(userStoreManager);
TenantUserRoleManager tenantUserRoleManager = new TenantUserRoleManager();
componentContext.getBundleContext().registerService(
org.wso2.carbon.stratos.common.listeners.TenantMgtListener.class.getName(),
tenantUserRoleManager, null);
}
/**
* Schedule complete tenant event synchronizer and initialize tenant event publisher
*
* @param componentContext
*/
private void initializeTenantEventPublisher(ComponentContext componentContext) {
// Register tenant event publisher
if (log.isDebugEnabled()) {
log.debug("Initializing tenant event publisher...");
}
final TenantEventPublisher tenantEventPublisher = new TenantEventPublisher();
componentContext.getBundleContext().registerService(
org.wso2.carbon.stratos.common.listeners.TenantMgtListener.class.getName(),
tenantEventPublisher, null);
if (log.isInfoEnabled()) {
log.info("Tenant event publisher initialized");
}
}
private void registerComponentStartUpEventListeners() {
ComponentStartUpSynchronizer componentStartUpSynchronizer =
ServiceReferenceHolder.getInstance().getComponentStartUpSynchronizer();
if (componentStartUpSynchronizer.isEnabled()) {
componentStartUpSynchronizer.addEventListener(new ComponentActivationEventListener() {
@Override
public void activated(Component component) {
if (component == Component.StratosManager) {
scheduleEventSynchronizers();
}
}
});
} else {
scheduleEventSynchronizers();
}
}
private void scheduleEventSynchronizers() {
Runnable tenantSynchronizer = new TenantEventSynchronizer();
scheduler.scheduleAtFixedRate(tenantSynchronizer, 0, 1, TimeUnit.MINUTES);
Runnable applicationSignUpSynchronizer = new ApplicationSignUpEventSynchronizer();
scheduler.scheduleAtFixedRate(applicationSignUpSynchronizer, 0, 1, TimeUnit.MINUTES);
}
protected void setConfigurationContextService(ConfigurationContextService contextService) {
ServiceReferenceHolder.setClientConfigContext(contextService.getClientConfigContext());
ServiceReferenceHolder.setServerConfigContext(contextService.getServerConfigContext());
ServiceReferenceHolder.getInstance().setAxisConfiguration(
contextService.getServerConfigContext().getAxisConfiguration());
}
protected void unsetConfigurationContextService(ConfigurationContextService contextService) {
ServiceReferenceHolder.setClientConfigContext(null);
ServiceReferenceHolder.setServerConfigContext(null);
ServiceReferenceHolder.getInstance().setAxisConfiguration(null);
}
public void setHazelcastInstance(HazelcastInstance hazelcastInstance) {
ServiceReferenceHolder.getInstance().setHazelcastInstance(hazelcastInstance);
}
public void unsetHazelcastInstance(HazelcastInstance hazelcastInstance) {
ServiceReferenceHolder.getInstance().setHazelcastInstance(null);
}
protected void setRealmService(RealmService realmService) {
ServiceReferenceHolder.setRealmService(realmService);
}
protected void unsetRealmService(RealmService realmService) {
}
protected void setRegistryService(RegistryService registryService) {
try {
ServiceReferenceHolder.setRegistryService(registryService);
} catch (Exception e) {
log.error("Cannot retrieve governance registry", e);
}
}
protected void unsetRegistryService(RegistryService registryService) {
}
protected void setTaskService(TaskService taskService) {
if (log.isDebugEnabled()) {
log.debug("Setting the task service");
}
ServiceReferenceHolder.getInstance().setTaskService(taskService);
}
protected void unsetTaskService(TaskService taskService) {
if (log.isDebugEnabled()) {
log.debug("Un-setting the task service");
}
ServiceReferenceHolder.getInstance().setTaskService(null);
}
protected void setDistributedObjectProvider(DistributedObjectProvider distributedObjectProvider) {
ServiceReferenceHolder.getInstance().setDistributedObjectProvider(distributedObjectProvider);
}
protected void unsetDistributedObjectProvider(DistributedObjectProvider distributedObjectProvider) {
ServiceReferenceHolder.getInstance().setDistributedObjectProvider(null);
}
protected void setComponentStartUpSynchronizer(ComponentStartUpSynchronizer componentStartUpSynchronizer) {
ServiceReferenceHolder.getInstance().setComponentStartUpSynchronizer(componentStartUpSynchronizer);
}
protected void unsetComponentStartUpSynchronizer(ComponentStartUpSynchronizer componentStartUpSynchronizer) {
ServiceReferenceHolder.getInstance().setComponentStartUpSynchronizer(null);
}
protected void deactivate(ComponentContext context) {
// Close event publisher connections to message broker
EventPublisherPool.close(MessagingUtil.Topics.INSTANCE_NOTIFIER_TOPIC.getTopicName());
EventPublisherPool.close(MessagingUtil.Topics.TENANT_TOPIC.getTopicName());
shutdownExecutorService(THREAD_POOL_ID);
shutdownScheduledExecutorService(SCHEDULER_THREAD_POOL_ID);
}
private void shutdownExecutorService(String executorServiceId) {
ExecutorService executorService = StratosThreadPool.getExecutorService(executorServiceId, 1);
if (executorService != null) {
shutdownExecutorService(executorService);
}
}
private void shutdownScheduledExecutorService(String executorServiceId) {
ExecutorService executorService = StratosThreadPool.getScheduledExecutorService(executorServiceId, 1);
if (executorService != null) {
shutdownExecutorService(executorService);
}
}
private void shutdownExecutorService(ExecutorService executorService) {
try {
executorService.shutdownNow();
} catch (Exception e) {
log.warn("An error occurred while shutting down executor service", e);
}
}
}
|
|
/*
* Copyright 2017 Netflix, 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.netflix.spinnaker.orca.pipelinetemplate.v1schema;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.spinnaker.orca.front50.PipelineModelMutator;
import com.netflix.spinnaker.orca.pipelinetemplate.exceptions.TemplateLoaderException;
import com.netflix.spinnaker.orca.pipelinetemplate.loader.TemplateLoader;
import com.netflix.spinnaker.orca.pipelinetemplate.v1schema.model.NamedHashMap;
import com.netflix.spinnaker.orca.pipelinetemplate.v1schema.model.PipelineTemplate;
import com.netflix.spinnaker.orca.pipelinetemplate.v1schema.model.PipelineTemplate.Configuration;
import com.netflix.spinnaker.orca.pipelinetemplate.v1schema.model.TemplateConfiguration;
import com.netflix.spinnaker.orca.pipelinetemplate.v1schema.model.TemplateConfiguration.PipelineConfiguration;
import com.netflix.spinnaker.orca.pipelinetemplate.v1schema.render.RenderContext;
import com.netflix.spinnaker.orca.pipelinetemplate.v1schema.render.RenderUtil;
import com.netflix.spinnaker.orca.pipelinetemplate.v1schema.render.Renderer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Maps pipeline configurations of concurrency settings, notifications, triggers and parameters from
* the pipeline template schema to the original non-templated pipeline schema.
*/
public class TemplatedPipelineModelMutator implements PipelineModelMutator {
private static final Logger log = LoggerFactory.getLogger(TemplatedPipelineModelMutator.class);
private final ObjectMapper pipelineTemplateObjectMapper;
private final TemplateLoader templateLoader;
private final Renderer renderer;
public TemplatedPipelineModelMutator(
ObjectMapper pipelineTemplateObjectMapper, TemplateLoader templateLoader, Renderer renderer) {
this.pipelineTemplateObjectMapper = pipelineTemplateObjectMapper;
this.templateLoader = templateLoader;
this.renderer = renderer;
}
@Override
public boolean supports(Map<String, Object> pipeline) {
return "templatedPipeline".equals(pipeline.get("type")) && pipeline.containsKey("config");
}
@Override
public void mutate(Map<String, Object> pipeline) {
TemplateConfiguration configuration =
pipelineTemplateObjectMapper.convertValue(
pipeline.get("config"), TemplateConfiguration.class);
PipelineTemplate template = null;
// Dynamically sourced templates don't support configuration inheritance.
if (!sourceContainsExpressions(configuration)) {
template = getPipelineTemplate(configuration);
if (template != null) {
applyConfigurationsFromTemplate(
configuration.getConfiguration(), template.getConfiguration(), pipeline);
}
}
mapRootPipelineConfigs(pipeline, configuration);
applyConfigurations(configuration.getConfiguration(), pipeline);
renderConfigurations(
pipeline, RenderUtil.createDefaultRenderContext(template, configuration, null));
}
@SuppressWarnings("unchecked")
private void mapRootPipelineConfigs(
Map<String, Object> pipeline, TemplateConfiguration configuration) {
if (pipeline.containsKey("id")
&& pipeline.get("id") != configuration.getPipeline().getPipelineConfigId()) {
Map<String, Object> config = (Map<String, Object>) pipeline.get("config");
Map<String, Object> p = (Map<String, Object>) config.get("pipeline");
p.put("pipelineConfigId", pipeline.get("id"));
}
if (pipeline.containsKey("name")
&& pipeline.get("name") != configuration.getPipeline().getName()) {
Map<String, Object> config = (Map<String, Object>) pipeline.get("config");
Map<String, Object> p = (Map<String, Object>) config.get("pipeline");
p.put("name", pipeline.get("name"));
}
if (pipeline.containsKey("application")
&& pipeline.get("application") != configuration.getPipeline().getApplication()) {
Map<String, Object> config = (Map<String, Object>) pipeline.get("config");
Map<String, Object> p = (Map<String, Object>) config.get("pipeline");
p.put("application", pipeline.get("application"));
}
}
private void applyConfigurationsFromTemplate(
PipelineConfiguration configuration,
Configuration templateConfiguration,
Map<String, Object> pipeline) {
if (configuration.getInherit().contains("concurrentExecutions")
&& templateConfiguration.getConcurrentExecutions() != null) {
applyConcurrentExecutions(pipeline, templateConfiguration.getConcurrentExecutions());
}
if (configuration.getInherit().contains("triggers")) {
pipeline.put("triggers", templateConfiguration.getTriggers());
}
if (configuration.getInherit().contains("parameters")) {
pipeline.put("parameterConfig", templateConfiguration.getParameters());
}
if (configuration.getInherit().contains("notifications")) {
pipeline.put("notifications", templateConfiguration.getNotifications());
}
if (configuration.getInherit().contains("expectedArtifacts")) {
pipeline.put("expectedArtifacts", templateConfiguration.getExpectedArtifacts());
}
}
private void applyConfigurations(
PipelineConfiguration configuration, Map<String, Object> pipeline) {
if (configuration.getConcurrentExecutions() != null) {
applyConcurrentExecutions(pipeline, configuration.getConcurrentExecutions());
}
if (configuration.getTriggers() != null && !configuration.getTriggers().isEmpty()) {
pipeline.put(
"triggers",
TemplateMerge.mergeDistinct(
pipelineTemplateObjectMapper.convertValue(
pipeline.get("triggers"), new TypeReference<List<NamedHashMap>>() {}),
configuration.getTriggers()));
}
if (configuration.getParameters() != null && !configuration.getParameters().isEmpty()) {
pipeline.put(
"parameterConfig",
TemplateMerge.mergeNamedContent(
pipelineTemplateObjectMapper.convertValue(
pipeline.get("parameterConfig"), new TypeReference<List<NamedHashMap>>() {}),
configuration.getParameters()));
}
if (configuration.getNotifications() != null && !configuration.getNotifications().isEmpty()) {
pipeline.put(
"notifications",
TemplateMerge.mergeNamedContent(
pipelineTemplateObjectMapper.convertValue(
pipeline.get("notifications"), new TypeReference<List<NamedHashMap>>() {}),
configuration.getNotifications()));
}
if (configuration.getExpectedArtifacts() != null
&& !configuration.getExpectedArtifacts().isEmpty()) {
pipeline.put(
"expectedArtifacts",
TemplateMerge.mergeDistinct(
pipelineTemplateObjectMapper.convertValue(
pipeline.get("expectedArtifacts"),
new TypeReference<List<HashMap<String, Object>>>() {}),
configuration.getExpectedArtifacts()));
}
}
private void applyConcurrentExecutions(
Map<String, Object> pipeline, Map<String, Object> concurrentExecutions) {
if (concurrentExecutions.containsKey("limitConcurrent")) {
pipeline.put("limitConcurrent", concurrentExecutions.get("limitConcurrent"));
}
if (concurrentExecutions.containsKey("maxConcurrentExecutions")) {
pipeline.put("maxConcurrentExecutions", concurrentExecutions.get("maxConcurrentExecutions"));
}
if (concurrentExecutions.containsKey("keepWaitingPipelines")) {
pipeline.put("keepWaitingPipelines", concurrentExecutions.get("keepWaitingPipelines"));
}
if (concurrentExecutions.containsKey("parallel")) {
pipeline.put("parallel", concurrentExecutions.get("parallel"));
}
}
@SuppressWarnings("unchecked")
private void renderConfigurations(Map<String, Object> pipeline, RenderContext renderContext) {
if (pipeline.containsKey("triggers")) {
pipeline.put("triggers", renderList((List<Object>) pipeline.get("triggers"), renderContext));
}
if (pipeline.containsKey("parameterConfig")) {
pipeline.put(
"parameterConfig",
renderList((List<Object>) pipeline.get("parameterConfig"), renderContext));
}
if (pipeline.containsKey("notifications")) {
pipeline.put(
"notifications", renderList((List<Object>) pipeline.get("notifications"), renderContext));
}
if (pipeline.containsKey("expectedArtifacts")) {
pipeline.put(
"expectedArtifacts",
renderList((List<Object>) pipeline.get("expectedArtifacts"), renderContext));
}
}
private List<Object> renderList(List<Object> list, RenderContext renderContext) {
if (list == null) {
return null;
}
return list.stream()
.map(i -> RenderUtil.deepRender(renderer, i, renderContext))
.collect(Collectors.toList());
}
private boolean sourceContainsExpressions(TemplateConfiguration configuration) {
String source = configuration.getPipeline().getTemplate().getSource();
return source.contains("{{") || source.contains("{%");
}
private PipelineTemplate getPipelineTemplate(TemplateConfiguration configuration) {
try {
return TemplateMerge.merge(templateLoader.load(configuration.getPipeline().getTemplate()));
} catch (TemplateLoaderException e) {
log.error("Could not load template: {}", configuration.getPipeline().getTemplate(), e);
return null;
}
}
}
|
|
package org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.configure.ui;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Properties;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.axiom.om.util.AXIOMUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.synapse.SynapseConstants;
import org.apache.synapse.mediators.template.TemplateParam;
import org.eclipse.core.resources.IContainer;
import org.eclipse.emf.edit.command.SetCommand;
import org.eclipse.emf.transaction.util.TransactionUtil;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IMessageProvider;
import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.TableEditor;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Link;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.wso2.developerstudio.eclipse.gmf.esb.CallTemplateParameter;
import org.wso2.developerstudio.eclipse.gmf.esb.CloudConnectorOperation;
import org.wso2.developerstudio.eclipse.gmf.esb.EsbFactory;
import org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage;
import org.wso2.developerstudio.eclipse.gmf.esb.NamespacedProperty;
import org.wso2.developerstudio.eclipse.gmf.esb.RuleOptionType;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.Activator;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.EditorUtils;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.factory.LocalEntryFileCreator;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.utils.DiagramImageUtils;
import org.wso2.developerstudio.eclipse.logging.core.IDeveloperStudioLog;
import org.wso2.developerstudio.eclipse.logging.core.Logger;
//import org.wso2.developerstudio.eclipse.artifact.localentry.model.LocalEntryModel;
public class CloudConnectorInitialConfigurationDialog extends TitleAreaDialog {
private String droppedCloudConnector;
private String droppedCloudConnectorComponentName;
/**
* Value type constant.
*/
private static final String VALUE_TYPE = "Value";
/**
* Expression type constant.
*/
private static final String EXPRESSION_TYPE = "Expression";
/**
* Table for add/edit/remove parameters.
*/
private Table paramTable;
protected static final OMFactory fac = OMAbstractFactory.getOMFactory();
protected static final OMNamespace synNS = SynapseConstants.SYNAPSE_OMNAMESPACE;
private final String connectorProperties = "cloudConnector.properties";
private final String configNameSeparator = "::";
private final String configExistsErrorMessage = "Connector configuration already exists";
private final String emptyNameErrorMessage = "Configuration name cannot be empty";
private static String operationName = "init";
private CloudConnectorOperation operation;
private String cloudConnectorAuthenticationInfo;
private TableEditor paramTypeEditor;
private TableEditor paramNameEditor;
private TableEditor paramValueEditor;
private Combo cmbParamType;
private Text txtParamName;
private PropertyText paramValue;
private Text nameText;
private Label configurationNameLabel;
private String configName;
private Collection<TemplateParam> parameters;
// private Label saveOptionLabel;
private Combo saveOptionCombo;
private List<String> availableConfigs;
private static IDeveloperStudioLog log = Logger.getLog(Activator.PLUGIN_ID);
public CloudConnectorInitialConfigurationDialog(Shell parent, CloudConnectorOperation operation,
Collection<TemplateParam> cloudConnectorConfigurationParameters, String cloudConnectorAuthenticationInfo) {
super(parent);
this.parameters = cloudConnectorConfigurationParameters;
this.operation = operation;
this.cloudConnectorAuthenticationInfo = cloudConnectorAuthenticationInfo;
setTitleImage(DiagramImageUtils.getInstance().getImageDescriptor("connectorInit.png").createImage());
// parent.setText("Connector Configuration.");
}
public String getDroppedCloudConnectorComponentName() {
return droppedCloudConnectorComponentName;
}
public void setDroppedCloudConnectorComponentName(String droppedCloudConnectorComponentName) {
this.droppedCloudConnectorComponentName = droppedCloudConnectorComponentName;
}
private String getDroppedCloudConnector() {
return droppedCloudConnector;
}
public void setDroppedCloudConnector(String droppedCloudConnector) {
this.droppedCloudConnector = droppedCloudConnector;
}
@Override
protected Control createDialogArea(Composite parent) {
Composite area = (Composite) super.createDialogArea(parent);
Composite container = new Composite(area, SWT.NONE);
GridLayout gridLayout = new GridLayout();
gridLayout.numColumns = 3;
gridLayout.verticalSpacing = 20;
container.setLayout(gridLayout);
configurationNameLabel = new Label(container, SWT.NONE);
{
configurationNameLabel.setText("Name: ");
configurationNameLabel.setBounds(10, 10, 50, 25);
}
// Text box for add new parameter.
nameText = new Text(container, SWT.BORDER);
{
/*
* FormData logCategoryLabelLayoutData = new FormData(160,SWT.DEFAULT);
* logCategoryLabelLayoutData.top = new FormAttachment(
* configurationNameLabel, 0, SWT.CENTER);
* logCategoryLabelLayoutData.left = new FormAttachment(
* configurationNameLabel, 5);
* nameText.setLayoutData(logCategoryLabelLayoutData);
*/
nameText.setBounds(65, 10, 100, 25);
GridData gridDataNameText2 = new GridData();
gridDataNameText2.horizontalAlignment = SWT.FILL;
gridDataNameText2.grabExcessHorizontalSpace = true;
nameText.setLayoutData(gridDataNameText2);
}
nameText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
configName = nameText.getText();
// CustomPaletteToolTransferDropTargetListener.definedName=nameText.getText();
if (StringUtils.isNotBlank(configName)) {
if (availableConfigs.contains(configName)) {
setErrorMessage(configExistsErrorMessage);
updateOKButtonStatus(false);
} else {
setErrorMessage(null);
updateOKButtonStatus(true);
}
} else {
setErrorMessage(emptyNameErrorMessage);
updateOKButtonStatus(false);
}
}
});
Link link = new Link(container, SWT.NONE);
if (cloudConnectorAuthenticationInfo != null && !cloudConnectorAuthenticationInfo.isEmpty()) {
link.setText("<a href=\"" + cloudConnectorAuthenticationInfo + "\">How to get Authentication info..</a>");
}
link.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
try {
// Open default external browser
PlatformUI.getWorkbench().getBrowserSupport().getExternalBrowser().openURL(new URL(e.text));
} catch (PartInitException | MalformedURLException ex) {
log.error("Error while opening URL : " + e.text, ex);
}
}
});
link.setSize(180, 10);
/*
* saveOptionLabel = new Label(container, SWT.NONE);
* {
* saveOptionLabel.setText("Save as : ");
* FormData logCategoryLabelLayoutData1 = new FormData(80,SWT.DEFAULT);
* logCategoryLabelLayoutData1.top = new FormAttachment(configurationNameLabel, 20);
* logCategoryLabelLayoutData1.left = new FormAttachment(0);
* saveOptionLabel.setLayoutData(logCategoryLabelLayoutData1);
* }
*
* saveOptionCombo = new Combo(container, SWT.DROP_DOWN | SWT.READ_ONLY);
* {
* saveOptionCombo.add("Inline Config");
* saveOptionCombo.add("Sequence Config");
* saveOptionCombo.select(0);
* FormData logCategoryComboLayoutData = new FormData(160,SWT.DEFAULT);
* logCategoryComboLayoutData.top = new FormAttachment(
* saveOptionLabel, 0, SWT.CENTER);
* logCategoryComboLayoutData.left = new FormAttachment(
* saveOptionLabel, 5);
* saveOptionCombo.setLayoutData(logCategoryComboLayoutData);
* }
*/
// Table for show the parameters.
paramTable = new Table(container, SWT.BORDER | SWT.FULL_SELECTION | SWT.HIDE_SELECTION);
paramTable.setBounds(10, 50, 600, 200);
GridData gridData3 = new GridData();
gridData3.horizontalSpan = 3;
gridData3.horizontalAlignment = SWT.FILL;
gridData3.grabExcessHorizontalSpace = true;
gridData3.verticalAlignment = SWT.FILL;
gridData3.grabExcessVerticalSpace = true;
paramTable.setLayoutData(gridData3);
TableColumn nameColumn = new TableColumn(paramTable, SWT.LEFT);
TableColumn valueColumn = new TableColumn(paramTable, SWT.LEFT);
TableColumn typeColumn = new TableColumn(paramTable, SWT.LEFT);
nameColumn.setText("Parameter Name");
nameColumn.setWidth(200);
valueColumn.setText("Value/Expression");
valueColumn.setWidth(250);
typeColumn.setText("Parameter Type");
typeColumn.setWidth(150);
paramTable.setHeaderVisible(true);
paramTable.setLinesVisible(true);
Listener tblPropertiesListener = new Listener() {
public void handleEvent(Event evt) {
if (null != evt.item) {
if (evt.item instanceof TableItem) {
TableItem item = (TableItem) evt.item;
editItem(item);
}
}
}
};
paramTable.addListener(SWT.Selection, tblPropertiesListener);
if (parameters != null) {
for (TemplateParam param : parameters) {
CallTemplateParameter callTemplateParameter = EsbFactory.eINSTANCE.createCallTemplateParameter();
callTemplateParameter.setParameterName(param.getName());
callTemplateParameter.setParameterValue("");
callTemplateParameter.setTemplateParameterType(RuleOptionType.VALUE);
bindPram(callTemplateParameter);
}
}
// setupTableEditor(paramTable);
/*
* FormData logPropertiesTableLayoutData = new FormData(SWT.DEFAULT, 150);
* logPropertiesTableLayoutData.top = new FormAttachment(configurationNameLabel, 20);
* logPropertiesTableLayoutData.left = new FormAttachment(0);
* logPropertiesTableLayoutData.bottom = new FormAttachment(100);
* paramTable.setLayoutData(logPropertiesTableLayoutData);
*/
availableConfigs = getAvailableConfigs();
return parent;
}
@Override
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
newShell.setText("Connector Configuration");
}
@Override
public void create() {
super.create();
setTitle("Enter authentication details");
setMessage("Please provide required parameters to authenticate user", IMessageProvider.INFORMATION);
}
/**
* Return the initial size of the dialog.
*/
@Override
protected Point getInitialSize() {
return new Point(630, 400);
}
private TableItem bindPram(CallTemplateParameter param) {
TableItem item = new TableItem(paramTable, SWT.NONE);
if (param.getTemplateParameterType().getLiteral().equals(VALUE_TYPE)) {
item.setText(new String[] { param.getParameterName(), param.getParameterValue(),
param.getTemplateParameterType().getLiteral() });
}
if (param.getTemplateParameterType().getLiteral().equals(EXPRESSION_TYPE)) {
item.setText(new String[] { param.getParameterName(), param.getParameterExpression().getPropertyValue(),
param.getTemplateParameterType().getLiteral() });
}
item.setData(param);
item.setData("exp", EsbFactory.eINSTANCE.copyNamespacedProperty(param.getParameterExpression()));
return item;
}
private TableEditor initTableEditor(TableEditor editor, Table table) {
if (null != editor) {
Control lastCtrl = editor.getEditor();
if (null != lastCtrl) {
lastCtrl.dispose();
}
}
editor = new TableEditor(table);
editor.horizontalAlignment = SWT.LEFT;
editor.grabHorizontal = true;
return editor;
}
private void editItem(final TableItem item) {
NamespacedProperty expression = (NamespacedProperty) item.getData("exp");
paramNameEditor = initTableEditor(paramNameEditor, item.getParent());
txtParamName = new Text(item.getParent(), SWT.NONE);
txtParamName.setText(item.getText(0));
paramNameEditor.setEditor(txtParamName, item, 0);
txtParamName.setEditable(false);
item.getParent().redraw();
item.getParent().layout();
txtParamName.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
item.setText(0, txtParamName.getText());
}
});
paramTypeEditor = initTableEditor(paramTypeEditor, item.getParent());
cmbParamType = new Combo(item.getParent(), SWT.READ_ONLY);
cmbParamType.setItems(new String[] { VALUE_TYPE, EXPRESSION_TYPE });
cmbParamType.setText(item.getText(2));
paramTypeEditor.setEditor(cmbParamType, item, 2);
item.getParent().redraw();
item.getParent().layout();
cmbParamType.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event evt) {
item.setText(2, cmbParamType.getText());
}
});
paramValueEditor = initTableEditor(paramValueEditor, item.getParent());
paramValue = new PropertyText(item.getParent(), SWT.NONE, cmbParamType);
paramValue.addProperties(item.getText(1), expression);
paramValueEditor.setEditor(paramValue, item, 1);
item.getParent().redraw();
item.getParent().layout();
paramValue.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
item.setText(1, paramValue.getText());
Object property = paramValue.getProperty();
if (property instanceof NamespacedProperty) {
item.setData("exp", (NamespacedProperty) property);
}
}
});
}
private void serializeParams(OMElement invokeElem) {
OMElement connectorEl = fac.createOMElement(getDroppedCloudConnectorComponentName() + "." + operationName,
synNS);
for (int i = 0; i < paramTable.getItems().length; ++i) {
TableItem tableItem = paramTable.getItems()[i];
CallTemplateParameter callTemplateParameter = (CallTemplateParameter) tableItem.getData();
if (!"".equals(callTemplateParameter.getParameterName())) {
OMElement paramEl = fac.createOMElement(callTemplateParameter.getParameterName(), synNS);
paramEl.setText(tableItem.getText(1));
// new ValueSerializer().serializeValue(value, "value", paramEl);
connectorEl.addChild(paramEl);
}
}
invokeElem.addChild(connectorEl);
}
/**
* Create contents of the button bar.
*
* @param parent
*/
protected void createButtonsForButtonBar(Composite parent) {
createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true);
createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false);
updateOKButtonStatus(false);
}
private void updateOKButtonStatus(boolean status) {
getButton(IDialogConstants.OK_ID).setEnabled(status);
}
@Override
protected void okPressed() {
IContainer location = EditorUtils.getActiveProject().getFolder(
"src" + File.separator + "main" + File.separator + "synapse-config" + File.separator + "local-entries");
try {
LocalEntryFileCreator localEntryFileCreator = new LocalEntryFileCreator();
String content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><localEntry xmlns=\"http://ws.apache.org/ns/synapse\" key=\""
+ configName + "\"/>";
OMElement payload = AXIOMUtil.stringToOM(content);
serializeParams(payload);
localEntryFileCreator.createLocalEntryFile(payload.toString(), location, configName);
} catch (Exception e) {
log.error("Error occured while creating the Local entry file", e);
}
/**
* put a entry in cloudConnector.properties file
*/
String pathName = EditorUtils.getActiveProject().getLocation().toOSString() + File.separator + "resources";
File resources = new File(pathName);
try {
resources.mkdir();
File cloudConnectorConfig = new File(pathName + File.separator + connectorProperties);
cloudConnectorConfig.createNewFile();
Properties prop = new Properties();
prop.load(new FileInputStream(pathName + File.separator + connectorProperties));
String localEntryConfigs = prop.getProperty("LOCAL_ENTRY_CONFIGS");
if (localEntryConfigs == null || "".equals(localEntryConfigs)) {
prop.setProperty("LOCAL_ENTRY_CONFIGS", configName + configNameSeparator + getDroppedCloudConnector());
} else {
prop.setProperty("LOCAL_ENTRY_CONFIGS",
localEntryConfigs + "," + configName + configNameSeparator + getDroppedCloudConnector());
}
prop.setProperty("INLINE_CONFIGS", "");
prop.store(new FileOutputStream(cloudConnectorConfig.getAbsolutePath()), null);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*
* Display.getCurrent().asyncExec(new Runnable() {
* public void run() {
* IEditorReference editorReferences[] = PlatformUI.getWorkbench().getActiveWorkbenchWindow()
* .getActivePage().getEditorReferences();
* IEditorPart activeEditor=PlatformUI.getWorkbench().getActiveWorkbenchWindow()
* .getActivePage().getActiveEditor();
* for (int i = 0; i < editorReferences.length; i++) {
* IEditorPart editor = editorReferences[i].getEditor(false);
* if ((editor instanceof EsbMultiPageEditor)) {
*
* This must be altered. 'addDefinedSequences' and 'addDefinedEndpoints' methods should not exist inside
* EsbPaletteFactory class.
* Creating new instance of 'EsbPaletteFactory' must be avoided.
*
* EsbPaletteFactory esbPaletteFactory=new EsbPaletteFactory();
* if(!editor.equals(activeEditor)){
* //esbPaletteFactory.addDefinedSequences(((EsbMultiPageEditor) editor).getGraphicalEditor());
* //esbPaletteFactory.addDefinedEndpoints(((EsbMultiPageEditor) editor).getGraphicalEditor());
* }else{
* //esbPaletteFactory.addCloudConnectorOperations(((EsbMultiPageEditor)
* editor).getGraphicalEditor(),configName,getDroppedCloudConnector());
* }
* }
* }
* }
* });
*/
SetCommand setCmd = new SetCommand(TransactionUtil.getEditingDomain(operation), operation,
EsbPackage.Literals.CLOUD_CONNECTOR_OPERATION__CONFIG_REF, configName);
if (setCmd.canExecute()) {
TransactionUtil.getEditingDomain(operation).getCommandStack().execute(setCmd);
}
super.okPressed();
}
/**
* Get available configurations for the given connector.
*
* @return available configurations
*/
private ArrayList<String> getAvailableConfigs() {
ArrayList<String> availableConfigs = new ArrayList<String>();
String pathName = EditorUtils.getActiveProject().getLocation().toOSString() + File.separator + "resources";
File resources = new File(pathName);
if (resources.exists()) {
File connectorConfig = new File(pathName + File.separator + connectorProperties);
if (connectorConfig.exists()) {
Properties prop = new Properties();
try {
prop.load(new FileInputStream(pathName + File.separator + connectorProperties));
String localEntryConfigs = prop.getProperty("LOCAL_ENTRY_CONFIGS");
if (localEntryConfigs != null) {
String[] configs = localEntryConfigs.split(",");
for (int i = 0; i < configs.length; ++i) {
if (!"".equals(configs[i])) {
availableConfigs.add(configs[i].split(configNameSeparator)[0]);
}
}
}
} catch (FileNotFoundException e) {
// e.printStackTrace();
} catch (IOException e) {
// e.printStackTrace();
}
}
}
return availableConfigs;
}
}
|
|
/*
* 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.util.cache;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import com.facebook.buck.io.ArchiveMemberPath;
import com.facebook.buck.io.HashingDeterministicJarWriter;
import com.facebook.buck.io.ProjectFilesystem;
import com.facebook.buck.testutil.FakeProjectFilesystem;
import com.facebook.buck.testutil.integration.TemporaryPaths;
import com.google.common.hash.HashCode;
import com.google.common.hash.Hashing;
import org.hamcrest.Matchers;
import org.hamcrest.junit.ExpectedException;
import org.junit.Rule;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Optional;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarOutputStream;
public class DefaultFileHashCacheTest {
@Rule
public TemporaryPaths tmp = new TemporaryPaths();
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Test
public void whenPathIsPutCacheContainsPath() {
ProjectFilesystem filesystem = new FakeProjectFilesystem();
DefaultFileHashCache cache = new DefaultFileHashCache(filesystem, Optional.empty());
Path path = new File("SomeClass.java").toPath();
HashCodeAndFileType value = HashCodeAndFileType.ofFile(HashCode.fromInt(42));
cache.loadingCache.put(path, value);
assertTrue("Cache should contain path", cache.willGet(filesystem.resolve(path)));
}
@Test
public void whenPathIsPutPathGetReturnsHash() throws IOException {
ProjectFilesystem filesystem = new FakeProjectFilesystem();
DefaultFileHashCache cache = new DefaultFileHashCache(filesystem, Optional.empty());
Path path = new File("SomeClass.java").toPath();
HashCodeAndFileType value = HashCodeAndFileType.ofFile(HashCode.fromInt(42));
cache.loadingCache.put(path, value);
assertEquals(
"Cache should contain hash",
value.getHashCode(),
cache.get(filesystem.resolve(path)));
}
@Test
public void whenPathIsPutThenInvalidatedCacheDoesNotContainPath() {
ProjectFilesystem filesystem = new FakeProjectFilesystem();
DefaultFileHashCache cache = new DefaultFileHashCache(filesystem, Optional.empty());
Path path = new File("SomeClass.java").toPath();
HashCodeAndFileType value = HashCodeAndFileType.ofFile(HashCode.fromInt(42));
cache.loadingCache.put(path, value);
assertTrue("Cache should contain path", cache.willGet(filesystem.resolve(path)));
cache.invalidate(filesystem.resolve(path));
assertFalse("Cache should not contain pain", cache.willGet(filesystem.resolve(path)));
}
@Test
public void invalidatingNonExistentEntryDoesNotThrow() {
ProjectFilesystem filesystem = new FakeProjectFilesystem();
DefaultFileHashCache cache = new DefaultFileHashCache(filesystem, Optional.empty());
Path path = new File("SomeClass.java").toPath();
assertFalse("Cache should not contain pain", cache.willGet(filesystem.resolve(path)));
cache.invalidate(filesystem.resolve(path));
assertFalse("Cache should not contain pain", cache.willGet(filesystem.resolve(path)));
}
@Test
public void missingEntryThrowsNoSuchFileException() throws IOException {
ProjectFilesystem filesystem = new FakeProjectFilesystem();
DefaultFileHashCache cache = new DefaultFileHashCache(filesystem, Optional.empty());
expectedException.expect(NoSuchFileException.class);
cache.get(filesystem.resolve(Paths.get("hello.java")));
}
@Test
public void whenPathsArePutThenInvalidateAllRemovesThem() throws IOException {
ProjectFilesystem filesystem = new FakeProjectFilesystem();
DefaultFileHashCache cache = new DefaultFileHashCache(filesystem, Optional.empty());
Path path1 = Paths.get("path1");
filesystem.writeContentsToPath("contenst1", path1);
cache.get(filesystem.resolve(path1));
assertTrue(cache.willGet(filesystem.resolve(path1)));
Path path2 = Paths.get("path2");
filesystem.writeContentsToPath("contenst2", path2);
cache.get(filesystem.resolve(path2));
assertTrue(cache.willGet(filesystem.resolve(path2)));
// Verify that `invalidateAll` clears everything from the cache.
assertFalse(cache.loadingCache.asMap().isEmpty());
cache.invalidateAll();
assertTrue(cache.loadingCache.asMap().isEmpty());
}
@Test
public void whenDirectoryIsPutThenInvalidatedCacheDoesNotContainPathOrChildren()
throws IOException {
ProjectFilesystem filesystem = new FakeProjectFilesystem();
DefaultFileHashCache cache = new DefaultFileHashCache(filesystem, Optional.empty());
Path dir = filesystem.getRootPath().getFileSystem().getPath("dir");
filesystem.mkdirs(dir);
Path child1 = dir.resolve("child1");
filesystem.touch(child1);
Path child2 = dir.resolve("child2");
filesystem.touch(child2);
cache.get(filesystem.resolve(dir));
assertTrue(cache.willGet(filesystem.resolve(dir)));
assertTrue(cache.willGet(filesystem.resolve(child1)));
assertTrue(cache.willGet(filesystem.resolve(child2)));
cache.invalidate(filesystem.resolve(dir));
assertNull(cache.loadingCache.getIfPresent(dir));
assertNull(cache.loadingCache.getIfPresent(child1));
assertNull(cache.loadingCache.getIfPresent(child2));
}
@Test
public void whenJarMemberWithHashInManifestIsQueriedThenCacheCorrectlyObtainsIt()
throws IOException {
ProjectFilesystem filesystem = new FakeProjectFilesystem();
DefaultFileHashCache cache = new DefaultFileHashCache(filesystem, Optional.empty());
Path abiJarPath = Paths.get("test-abi.jar");
Path memberPath = Paths.get("SomeClass.class");
String memberContents = "Some contents";
try (HashingDeterministicJarWriter jar = new HashingDeterministicJarWriter(
new JarOutputStream(filesystem.newFileOutputStream(abiJarPath)))) {
jar.writeEntry(
memberPath.toString(),
new ByteArrayInputStream(memberContents.getBytes(StandardCharsets.UTF_8)));
}
HashCode actual = cache.get(ArchiveMemberPath.of(filesystem.resolve(abiJarPath), memberPath));
HashCode expected = Hashing.murmur3_128().hashString(memberContents, StandardCharsets.UTF_8);
assertEquals(expected, actual);
}
@Test(expected = NoSuchFileException.class)
public void whenJarMemberWithoutHashInManifestIsQueriedThenThrow()
throws IOException {
ProjectFilesystem filesystem = new FakeProjectFilesystem();
DefaultFileHashCache cache = new DefaultFileHashCache(filesystem, Optional.empty());
Path abiJarPath = Paths.get("test-abi.jar");
Path memberPath = Paths.get("Unhashed.txt");
String memberContents = "Some contents";
try (HashingDeterministicJarWriter jar = new HashingDeterministicJarWriter(
new JarOutputStream(filesystem.newFileOutputStream(abiJarPath)))) {
jar
.writeEntry(
"SomeClass.class",
new ByteArrayInputStream(memberContents.getBytes(StandardCharsets.UTF_8)))
.writeUnhashedEntry(
memberPath.toString(),
new ByteArrayInputStream(memberContents.getBytes(StandardCharsets.UTF_8)));
}
cache.get(ArchiveMemberPath.of(filesystem.resolve(abiJarPath), memberPath));
}
@Test(expected = UnsupportedOperationException.class)
public void whenJarMemberWithoutManifestIsQueriedThenThrow() throws IOException {
ProjectFilesystem filesystem = new FakeProjectFilesystem();
DefaultFileHashCache cache = new DefaultFileHashCache(filesystem, Optional.empty());
Path abiJarPath = Paths.get("no-manifest.jar");
Path memberPath = Paths.get("Empty.class");
try (JarOutputStream jar = new JarOutputStream(filesystem.newFileOutputStream(abiJarPath))) {
jar.putNextEntry(new JarEntry(memberPath.toString()));
jar.write("Contents".getBytes(StandardCharsets.UTF_8));
jar.closeEntry();
}
cache.get(ArchiveMemberPath.of(filesystem.resolve(abiJarPath), memberPath));
}
@Test(expected = NoSuchFileException.class)
public void whenJarMemberWithEmptyManifestIsQueriedThenThrow() throws IOException {
ProjectFilesystem filesystem = new FakeProjectFilesystem();
DefaultFileHashCache cache = new DefaultFileHashCache(filesystem, Optional.empty());
Path abiJarPath = Paths.get("empty-manifest.jar");
Path memberPath = Paths.get("Empty.class");
try (HashingDeterministicJarWriter jar = new HashingDeterministicJarWriter(
new JarOutputStream(filesystem.newFileOutputStream(abiJarPath)))) {
jar
.writeUnhashedEntry(
JarFile.MANIFEST_NAME,
new ByteArrayInputStream(new byte[0]))
.writeUnhashedEntry(
memberPath.toString(),
new ByteArrayInputStream("Contents".getBytes(StandardCharsets.UTF_8)));
}
cache.get(ArchiveMemberPath.of(filesystem.resolve(abiJarPath), memberPath));
}
@Test
public void getSizeOfMissingPathThrows() throws IOException {
ProjectFilesystem filesystem = new FakeProjectFilesystem();
Path input = filesystem.getRootPath().getFileSystem().getPath("input");
DefaultFileHashCache cache = new DefaultFileHashCache(filesystem, Optional.empty());
expectedException.expect(FileNotFoundException.class);
cache.getSize(filesystem.resolve(input));
}
@Test
public void getSizeOfFile() throws IOException {
ProjectFilesystem filesystem = new FakeProjectFilesystem();
Path input = filesystem.getRootPath().getFileSystem().getPath("input");
filesystem.writeBytesToPath(new byte[123], input);
DefaultFileHashCache cache = new DefaultFileHashCache(filesystem, Optional.empty());
assertThat(
cache.getSize(filesystem.resolve(input)),
Matchers.equalTo(123L));
}
@Test
public void getSizeOfDirectory() throws IOException {
ProjectFilesystem filesystem = new FakeProjectFilesystem();
Path input = filesystem.getRootPath().getFileSystem().getPath("input");
filesystem.mkdirs(input);
filesystem.writeBytesToPath(new byte[123], input.resolve("file1"));
filesystem.writeBytesToPath(new byte[123], input.resolve("file2"));
DefaultFileHashCache cache = new DefaultFileHashCache(filesystem, Optional.empty());
assertThat(
cache.getSize(filesystem.resolve(input)),
Matchers.equalTo(246L));
}
@Test
public void getFileSizeInvalidation() throws IOException {
ProjectFilesystem filesystem = new FakeProjectFilesystem();
Path input = filesystem.getRootPath().getFileSystem().getPath("input");
filesystem.writeBytesToPath(new byte[123], input);
DefaultFileHashCache cache = new DefaultFileHashCache(filesystem, Optional.empty());
cache.getSize(filesystem.resolve(input));
cache.invalidate(filesystem.resolve(input));
assertNull(cache.sizeCache.getIfPresent(filesystem.resolve(input)));
}
}
|
|
package org.sakaiproject.evaluation.tool.locators;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.evaluation.constant.EvalConstants;
import org.sakaiproject.evaluation.logic.EvalCommonLogic;
import org.sakaiproject.evaluation.logic.EvalSettings;
import org.sakaiproject.evaluation.logic.model.EvalUser;
import org.sakaiproject.evaluation.model.EvalAdhocGroup;
import org.sakaiproject.evaluation.model.EvalAdhocUser;
import org.sakaiproject.evaluation.utils.EvalUtils;
import uk.org.ponder.messageutil.TargettedMessage;
import uk.org.ponder.messageutil.TargettedMessageList;
/**
* This is not a true Bean Locator. It's primary purpose is
* for handling the calls for adhoc groups from the
* modify_adhoc_groups page.
*
* @author Steven Githens
* @author Aaron Zeckoski (azeckoski @ gmail.com)
*/
public class AdhocGroupsBean {
private static Log log = LogFactory.getLog(AdhocGroupsBean.class);
public static final String SAVED_NEW_ADHOCGROUP = "added-adhoc-group";
public static final String UPDATED_ADHOCGROUP = "updated-adhoc-group";
public static final String DELETED_ADHOCGROUP = "deleted-adhoc-group";
// These three variables are for EL form binding.
private Long adhocGroupId;
private String adhocGroupTitle;
private String newAdhocGroupUsers;
// These are for keeping track of users. They may not all be used at the moment
// but would be needed if we want more detailed error/confirm dialogs.
public List<String> acceptedUsers = new ArrayList<String>();
public List<String> rejectedUsers = new ArrayList<String>();
public List<String> alreadyInGroupUsers = new ArrayList<String>();
/**
* Adds more users to an existing adhocgroup using the data entered with
* adhocGroupId and newAdhocGroupUsers.
*
* @return The UPDATED_ADHOCGROUP constant that could be used in ARI2 or
* other action return mechanisms.
*/
public String addUsersToAdHocGroup() {
String currentUserId = commonLogic.getCurrentUserId();
if (adhocGroupId == null) {
throw new IllegalArgumentException("Cannot add users to adhoc group without an id, adhocGroupId is null");
}
EvalAdhocGroup group = commonLogic.getAdhocGroupById( adhocGroupId );
adhocGroupId = group.getId();
/*
* You can only change the adhoc group if you are the owner.
*/
if (!currentUserId.equals(group.getOwner())) {
throw new SecurityException("Only EvalAdhocGroup owners can change their groups: " + group.getId() + " , " + currentUserId);
}
// put the new title in the adhoc group - https://bugs.caret.cam.ac.uk/browse/CTL-1305
if (adhocGroupTitle != null && ! "".equals(adhocGroupTitle)) {
group.setTitle(adhocGroupTitle);
}
// save the adhoc group
updateAdHocGroup(group);
return UPDATED_ADHOCGROUP;
}
/**
* Primarily for EL Button Binding when creating new adhoc groups.
*
* @return The action return SAVED_NEW_ADHOCGROUP for use in ARI2 primarily.
*/
public String addNewAdHocGroup() {
String currentUserId = commonLogic.getCurrentUserId();
/*
* At the moment we allow any registered user to create adhoc groups.
*/
if (commonLogic.isUserAnonymous(currentUserId)) {
throw new SecurityException("Anonymous users cannot create EvalAdhocGroups: " + currentUserId);
}
if (adhocGroupTitle == null || "".equals(adhocGroupTitle)) {
messages.addMessage(new TargettedMessage("modifyadhocgroup.message.notitle",
new Object[] {}, TargettedMessage.SEVERITY_ERROR));
return "noTitle";
}
EvalAdhocGroup group = new EvalAdhocGroup(currentUserId, adhocGroupTitle);
updateAdHocGroup(group);
return SAVED_NEW_ADHOCGROUP;
}
public String deleteAdHocGroup() {
if (adhocGroupId == null) {
throw new IllegalArgumentException("Cannot delete adhoc group without an id, adhocGroupId is null");
}
EvalAdhocGroup group = commonLogic.getAdhocGroupById( adhocGroupId );
commonLogic.deleteAdhocGroup(adhocGroupId);
messages.addMessage(new TargettedMessage("modifyadhocgroup.group.deleted",
new Object[] { group.getTitle() }, TargettedMessage.SEVERITY_INFO));
return DELETED_ADHOCGROUP;
}
/**
* Updates the Group by adding the newline seperated users in member
* variable newAdhocGroupUsers.
*
*/
private void updateAdHocGroup(EvalAdhocGroup group) {
String currentUserId = commonLogic.getCurrentUserId();
/*
* At the moment we allow any registered user to create adhoc groups.
*/
if (commonLogic.isUserAnonymous(currentUserId)) {
throw new SecurityException("Anonymous users cannot create EvalAdhocGroups: " + currentUserId);
}
Boolean useAdhocusers = (Boolean) settings.get(EvalSettings.ENABLE_ADHOC_USERS);
String[] existingParticipants = group.getParticipantIds();
if (existingParticipants == null) {
existingParticipants = new String[] {};
}
List<String> existingParticipantsList = new ArrayList<String>();
for (String particpant: existingParticipants) {
existingParticipantsList.add(particpant);
}
List<String> participants = new ArrayList<String>();
checkAndAddToParticipantsList(newAdhocGroupUsers, participants, existingParticipantsList);
List<String> allParticipants = new ArrayList<String>();
for (String particpant: existingParticipants) {
allParticipants.add(particpant);
}
allParticipants.addAll(participants);
group.setParticipantIds(allParticipants.toArray(new String[] {}));
commonLogic.saveAdhocGroup(group);
adhocGroupId = group.getId();
messages.addMessage(new TargettedMessage("modifyadhocgroup.message.savednewgroup",
new Object[] { group.getTitle() }, TargettedMessage.SEVERITY_INFO));
// Build the rejected users with no trailing commas
//String[] rejectedStringList = rejectedUsers.toArray(new String[]{});
StringBuilder rejectedUsersDisplayBuilder = new StringBuilder();
for (int i = 0; i < rejectedUsers.size(); i++) {
if (i == rejectedUsers.size()-1) {
rejectedUsersDisplayBuilder.append(rejectedUsers.get(i));
}
else {
rejectedUsersDisplayBuilder.append(rejectedUsers.get(i));
rejectedUsersDisplayBuilder.append(", ");
}
}
String rejectedUsersDisplay = rejectedUsersDisplayBuilder.toString();
if (rejectedUsers.size() > 0 && useAdhocusers) {
messages.addMessage(new TargettedMessage("modifyadhocgroup.message.badusers",
new Object[] { rejectedUsersDisplay }, TargettedMessage.SEVERITY_ERROR));
}
else if (rejectedUsers.size() > 0) {
messages.addMessage(new TargettedMessage("modifyadhocgroup.message.badusers.noadhocusers",
new Object[] { rejectedUsersDisplay }, TargettedMessage.SEVERITY_ERROR));
}
else {
log.info("Add entries added succesfully to new adhocGroup: " + adhocGroupId);
}
// Message for any users already in the group
if (alreadyInGroupUsers.size() > 0) {
StringBuilder alreadyInGroupUsersBuilder = new StringBuilder();
for (int i = 0; i < alreadyInGroupUsers.size(); i++) {
if (i == alreadyInGroupUsers.size()-1) {
alreadyInGroupUsersBuilder.append(alreadyInGroupUsers.get(i));
}
else {
alreadyInGroupUsersBuilder.append(alreadyInGroupUsers.get(i));
alreadyInGroupUsersBuilder.append(", ");
}
}
messages.addMessage(new TargettedMessage("modifyadhocgroup.message.existingusers",
new Object[] { alreadyInGroupUsersBuilder.toString() }, TargettedMessage.SEVERITY_INFO ));
}
}
/**
* Adds folks to the participants list and does validation.
*
* @param data The newline seperated list of adhoc users.
* @param participants The existing list we are adding more participants to.
*/
private void checkAndAddToParticipantsList(String data, List<String> participants,
List<String> existingParticipants) {
// If they didn't actually type anything in the window, don't throw up any
// errors or anything. Same if it's just all whitespace.
if ("".equals(data)
|| data == null
|| EvalUtils.isBlank(data.trim())
|| data.matches("[ \t\r\n]+")) {
messages.addMessage(new TargettedMessage("modifyadhocgroup.message.badusers",
new Object[] { "NONE" }, TargettedMessage.SEVERITY_ERROR ));
return;
}
String[] potentialMembers = data.split("\n");
Boolean useAdhocusers = (Boolean) settings.get(EvalSettings.ENABLE_ADHOC_USERS);
/*
* As we go through the newline separated list of users we look for these things:
* 1. Is this person already in the adhoc group?
* 2. Is the id for an existing user in the system?
* 3. If Adhoc users are allowed, is this a valid email address?
* 4. Otherwise add it to the garbage list.
*/
for (String next: potentialMembers) {
String potentialId = next.trim();
if (EvalUtils.isBlank(potentialId)) {
continue; // skip blank ones
}
String userId = null;
// check if this is a valid username for an existing user
String internalUserId = commonLogic.getUserId(potentialId);
if (internalUserId == null) {
internalUserId = potentialId;
}
// look up the username by their internal id
EvalUser user = commonLogic.getEvalUserById(internalUserId);
if (EvalConstants.USER_TYPE_EXTERNAL.equals(user.type)
|| EvalConstants.USER_TYPE_INTERNAL.equals(user.type)) {
userId = user.userId;
potentialId = user.displayName;
} else {
// check if this is an email belonging to an existing user
user = commonLogic.getEvalUserByEmail(potentialId);
if (EvalConstants.USER_TYPE_EXTERNAL.equals(user.type)
|| EvalConstants.USER_TYPE_INTERNAL.equals(user.type)) {
userId = user.userId;
potentialId = user.displayName;
} else {
// check if the email is valid and we are using adhoc users
if (useAdhocusers
&& EvalUtils.isValidEmail(potentialId)) {
EvalAdhocUser newUser = new EvalAdhocUser(commonLogic.getCurrentUserId(), potentialId);
commonLogic.saveAdhocUser(newUser);
userId = newUser.getUserId();
}
}
}
if (userId == null) {
// invalid entry
rejectedUsers.add(potentialId);
} else {
if (existingParticipants.contains(userId)) {
// check if user is already in the group
alreadyInGroupUsers.add(potentialId);
} else {
// add user to participants and put this user in the accepted list
participants.add(userId);
acceptedUsers.add(potentialId);
}
}
}
}
/*
* Boilerplate Getters and Setters below.
*/
public Long getAdhocGroupId() {
return adhocGroupId;
}
public void setAdhocGroupId(Long adhocGroupId) {
this.adhocGroupId = adhocGroupId;
}
public String getAdhocGroupTitle() {
return adhocGroupTitle;
}
public void setAdhocGroupTitle(String adhocGroupTitle) {
this.adhocGroupTitle = adhocGroupTitle;
}
public String getNewAdhocGroupUsers() {
return newAdhocGroupUsers;
}
public void setNewAdhocGroupUsers(String newAdhocGroupUsers) {
this.newAdhocGroupUsers = newAdhocGroupUsers;
}
private EvalCommonLogic commonLogic;
public void setCommonLogic(EvalCommonLogic bean) {
this.commonLogic = bean;
}
private EvalSettings settings;
public void setSettings(EvalSettings settings) {
this.settings = settings;
}
private TargettedMessageList messages;
public void setMessages(TargettedMessageList messages) {
this.messages = messages;
}
}
|
|
/*************************************************************************/
/* PaymentsManager.java */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md) */
/* */
/* 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.godotengine.godot.payments;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.text.TextUtils;
import android.util.Log;
import com.android.vending.billing.IInAppBillingService;
import org.godotengine.godot.Godot;
import org.godotengine.godot.GodotPaymentV3;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Arrays;
public class PaymentsManager {
public static final int BILLING_RESPONSE_RESULT_OK = 0;
public static final int REQUEST_CODE_FOR_PURCHASE = 0x1001;
private static boolean auto_consume = true;
private Activity activity;
IInAppBillingService mService;
public void setActivity(Activity activity) {
this.activity = activity;
}
public static PaymentsManager createManager(Activity activity) {
PaymentsManager manager = new PaymentsManager(activity);
return manager;
}
private PaymentsManager(Activity activity) {
this.activity = activity;
}
public PaymentsManager initService() {
Intent intent = new Intent("com.android.vending.billing.InAppBillingService.BIND");
intent.setPackage("com.android.vending");
activity.bindService(
intent,
mServiceConn,
Context.BIND_AUTO_CREATE);
return this;
}
public void destroy() {
if (mService != null) {
activity.unbindService(mServiceConn);
}
}
ServiceConnection mServiceConn = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
mService = null;
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mService = IInAppBillingService.Stub.asInterface(service);
}
};
public void requestPurchase(final String sku, String transactionId) {
new PurchaseTask(mService, Godot.getInstance()) {
@Override
protected void error(String message) {
godotPaymentV3.callbackFail();
}
@Override
protected void canceled() {
godotPaymentV3.callbackCancel();
}
@Override
protected void alreadyOwned() {
godotPaymentV3.callbackAlreadyOwned(sku);
}
}.purchase(sku, transactionId);
}
public void consumeUnconsumedPurchases() {
new ReleaseAllConsumablesTask(mService, activity) {
@Override
protected void success(String sku, String receipt, String signature, String token) {
godotPaymentV3.callbackSuccessProductMassConsumed(receipt, signature, sku);
}
@Override
protected void error(String message) {
Log.d("godot", "consumeUnconsumedPurchases :" + message);
godotPaymentV3.callbackFailConsume();
}
@Override
protected void notRequired() {
Log.d("godot", "callbackSuccessNoUnconsumedPurchases :");
godotPaymentV3.callbackSuccessNoUnconsumedPurchases();
}
}.consumeItAll();
}
public void requestPurchased() {
try {
PaymentsCache pc = new PaymentsCache(Godot.getInstance());
String continueToken = null;
do {
Bundle bundle = mService.getPurchases(3, activity.getPackageName(), "inapp", continueToken);
if (bundle.getInt("RESPONSE_CODE") == 0) {
final ArrayList<String> myPurchases = bundle.getStringArrayList("INAPP_PURCHASE_DATA_LIST");
final ArrayList<String> mySignatures = bundle.getStringArrayList("INAPP_DATA_SIGNATURE_LIST");
if (myPurchases == null || myPurchases.size() == 0) {
godotPaymentV3.callbackPurchased("", "", "");
return;
}
for (int i = 0; i < myPurchases.size(); i++) {
try {
String receipt = myPurchases.get(i);
JSONObject inappPurchaseData = new JSONObject(receipt);
String sku = inappPurchaseData.getString("productId");
String token = inappPurchaseData.getString("purchaseToken");
String signature = mySignatures.get(i);
pc.setConsumableValue("ticket_signautre", sku, signature);
pc.setConsumableValue("ticket", sku, receipt);
pc.setConsumableFlag("block", sku, true);
pc.setConsumableValue("token", sku, token);
godotPaymentV3.callbackPurchased(receipt, signature, sku);
} catch (JSONException e) {
}
}
}
continueToken = bundle.getString("INAPP_CONTINUATION_TOKEN");
Log.d("godot", "continue token = " + continueToken);
} while (!TextUtils.isEmpty(continueToken));
} catch (Exception e) {
Log.d("godot", "Error requesting purchased products:" + e.getClass().getName() + ":" + e.getMessage());
}
}
public void processPurchaseResponse(int resultCode, Intent data) {
new HandlePurchaseTask(activity) {
@Override
protected void success(final String sku, final String signature, final String ticket) {
godotPaymentV3.callbackSuccess(ticket, signature, sku);
if (auto_consume) {
new ConsumeTask(mService, activity) {
@Override
protected void success(String ticket) {
}
@Override
protected void error(String message) {
godotPaymentV3.callbackFail();
}
}.consume(sku);
}
}
@Override
protected void error(String message) {
godotPaymentV3.callbackFail();
}
@Override
protected void canceled() {
godotPaymentV3.callbackCancel();
}
}.handlePurchaseRequest(resultCode, data);
}
public void validatePurchase(String purchaseToken, final String sku) {
new ValidateTask(activity, godotPaymentV3) {
@Override
protected void success() {
new ConsumeTask(mService, activity) {
@Override
protected void success(String ticket) {
godotPaymentV3.callbackSuccess(ticket, null, sku);
}
@Override
protected void error(String message) {
godotPaymentV3.callbackFail();
}
}.consume(sku);
}
@Override
protected void error(String message) {
godotPaymentV3.callbackFail();
}
@Override
protected void canceled() {
godotPaymentV3.callbackCancel();
}
}.validatePurchase(sku);
}
public void setAutoConsume(boolean autoConsume) {
auto_consume = autoConsume;
}
public void consume(final String sku) {
new ConsumeTask(mService, activity) {
@Override
protected void success(String ticket) {
godotPaymentV3.callbackSuccessProductMassConsumed(ticket, "", sku);
}
@Override
protected void error(String message) {
godotPaymentV3.callbackFailConsume();
}
}.consume(sku);
}
// Workaround to bug where sometimes response codes come as Long instead of Integer
int getResponseCodeFromBundle(Bundle b) {
Object o = b.get("RESPONSE_CODE");
if (o == null) {
//logDebug("Bundle with null response code, assuming OK (known issue)");
return BILLING_RESPONSE_RESULT_OK;
} else if (o instanceof Integer) return ((Integer) o).intValue();
else if (o instanceof Long) return (int) ((Long) o).longValue();
else {
//logError("Unexpected type for bundle response code.");
//logError(o.getClass().getName());
throw new RuntimeException("Unexpected type for bundle response code: " + o.getClass().getName());
}
}
/**
* Returns a human-readable description for the given response code.
*
* @param code The response code
* @return A human-readable string explaining the result code.
* It also includes the result code numerically.
*/
public static String getResponseDesc(int code) {
String[] iab_msgs = ("0:OK/1:User Canceled/2:Unknown/" +
"3:Billing Unavailable/4:Item unavailable/" +
"5:Developer Error/6:Error/7:Item Already Owned/" +
"8:Item not owned").split("/");
String[] iabhelper_msgs = ("0:OK/-1001:Remote exception during initialization/" +
"-1002:Bad response received/" +
"-1003:Purchase signature verification failed/" +
"-1004:Send intent failed/" +
"-1005:User cancelled/" +
"-1006:Unknown purchase response/" +
"-1007:Missing token/" +
"-1008:Unknown error/" +
"-1009:Subscriptions not available/" +
"-1010:Invalid consumption attempt").split("/");
if (code <= -1000) {
int index = -1000 - code;
if (index >= 0 && index < iabhelper_msgs.length) return iabhelper_msgs[index];
else return String.valueOf(code) + ":Unknown IAB Helper Error";
} else if (code < 0 || code >= iab_msgs.length)
return String.valueOf(code) + ":Unknown";
else
return iab_msgs[code];
}
public void querySkuDetails(final String[] list) {
(new Thread(new Runnable() {
@Override
public void run() {
ArrayList<String> skuList = new ArrayList<String>(Arrays.asList(list));
if (skuList.size() == 0) {
return;
}
// Split the sku list in blocks of no more than 20 elements.
ArrayList<ArrayList<String>> packs = new ArrayList<ArrayList<String>>();
ArrayList<String> tempList;
int n = skuList.size() / 20;
int mod = skuList.size() % 20;
for (int i = 0; i < n; i++) {
tempList = new ArrayList<String>();
for (String s : skuList.subList(i * 20, i * 20 + 20)) {
tempList.add(s);
}
packs.add(tempList);
}
if (mod != 0) {
tempList = new ArrayList<String>();
for (String s : skuList.subList(n * 20, n * 20 + mod)) {
tempList.add(s);
}
packs.add(tempList);
}
for (ArrayList<String> skuPartList : packs) {
Bundle querySkus = new Bundle();
querySkus.putStringArrayList("ITEM_ID_LIST", skuPartList);
Bundle skuDetails = null;
try {
skuDetails = mService.getSkuDetails(3, activity.getPackageName(), "inapp", querySkus);
if (!skuDetails.containsKey("DETAILS_LIST")) {
int response = getResponseCodeFromBundle(skuDetails);
if (response != BILLING_RESPONSE_RESULT_OK) {
godotPaymentV3.errorSkuDetail(getResponseDesc(response));
} else {
godotPaymentV3.errorSkuDetail("No error but no detail list.");
}
return;
}
ArrayList<String> responseList = skuDetails.getStringArrayList("DETAILS_LIST");
for (String thisResponse : responseList) {
Log.d("godot", "response = "+thisResponse);
godotPaymentV3.addSkuDetail(thisResponse);
}
} catch (RemoteException e) {
e.printStackTrace();
godotPaymentV3.errorSkuDetail("RemoteException error!");
}
}
godotPaymentV3.completeSkuDetail();
}
})).start();
}
private GodotPaymentV3 godotPaymentV3;
public void setBaseSingleton(GodotPaymentV3 godotPaymentV3) {
this.godotPaymentV3 = godotPaymentV3;
}
}
|
|
package com.miscell.wiping.home;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import com.flurry.android.FlurryAgent;
import com.miscell.wiping.BaseActivity;
import com.miscell.wiping.R;
import com.miscell.wiping.raindrops.RainDropsView;
import com.miscell.wiping.utils.Blur;
import com.miscell.wiping.utils.DirectoryUtils;
import com.miscell.wiping.utils.Utils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
/**
* Created by chenjishi on 15/4/1.
*/
public class PhotoActivity extends BaseActivity implements View.OnClickListener {
private static final int MAX_IMAGE_WIDTH = 1080;
private static final String BLURRED_IMG_NAME = "blurred_image.png";
private static final int SCALED_WIDTH = 400;
public static final String IMAGE_PATH = "image_path";
private ImageView mImageView;
private FrameLayout mContentView;
private ImageButton mShareButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_photo, true);
Bundle extras = getIntent().getExtras();
if (null == extras) {
finish();
return;
}
String filePath = extras.getString(IMAGE_PATH);
mContentView = (FrameLayout) findViewById(android.R.id.content);
mImageView = (ImageView) findViewById(R.id.image_view);
setPreview(filePath);
}
private int setPreview(String filePath) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
int width = getResources().getDisplayMetrics().widthPixels;
int w = options.outWidth;
int h = options.outHeight;
int height = (int) (width * h * 1.0f / w);
options.inSampleSize = calculateInSampleSize(options, width, height);
options.inJustDecodeBounds = false;
final Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);
if (null != bitmap) {
mImageView.setImageBitmap(bitmap);
new Thread() {
@Override
public void run() {
blur(bitmap);
}
}.start();
}
return height;
}
private void blur(Bitmap bitmap) {
int width = SCALED_WIDTH;
int height = (int) (width * bitmap.getHeight() * 1.f / bitmap.getWidth());
Bitmap scaleBitmap = Bitmap.createScaledBitmap(bitmap, width, height, true);
Bitmap bmp = Bitmap.createBitmap(scaleBitmap.getWidth(), scaleBitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bmp);
canvas.drawBitmap(scaleBitmap, 0, 0, null);
scaleBitmap.recycle();
File file = new File(getFilesDir() + BLURRED_IMG_NAME);
Bitmap newImg = Blur.fastblur(this, bmp, 12);
Utils.storeImage(newImg, file);
runOnUiThread(new Runnable() {
@Override
public void run() {
RainDropsView rainView = new RainDropsView(PhotoActivity.this);
mContentView.addView(rainView, new FrameLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT));
rainView.setBlurredImagePath(getFilesDir() + BLURRED_IMG_NAME);
mImageView.setVisibility(View.VISIBLE);
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(dp2px(48), dp2px(48));
lp.gravity = Gravity.RIGHT;
mShareButton = new ImageButton(PhotoActivity.this);
mShareButton.setBackgroundResource(R.drawable.hightlight_bkg);
mShareButton.setImageResource(R.drawable.ic_social_share);
mShareButton.setOnClickListener(PhotoActivity.this);
mContentView.addView(mShareButton, lp);
}
});
}
private ProgressDialog mProgress;
private void generateImage() {
mContentView.destroyDrawingCache();
mContentView.setDrawingCacheEnabled(true);
Bitmap bitmap = mContentView.getDrawingCache();
if (null != bitmap) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int requiredWidth = MAX_IMAGE_WIDTH;
int requiredHeight = (int) (MAX_IMAGE_WIDTH * height * 1.f / width);
final Rect srcRect = new Rect(0, 0, width, height);
final Rect dstRect = new Rect(0, 0, requiredWidth, requiredHeight);
Bitmap newBitmap = Bitmap.createBitmap(requiredWidth, requiredHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(newBitmap);
canvas.drawBitmap(bitmap, srcRect, dstRect, null);
final String filePath = DirectoryUtils.getTempCacheDir() + "share.png";
File file = new File(filePath);
storeImage(newBitmap, file);
runOnUiThread(new Runnable() {
@Override
public void run() {
share(filePath);
}
});
}
mContentView.setDrawingCacheEnabled(false);
}
private void share(String filePath) {
if (null != mProgress && mProgress.isShowing()) mProgress.dismiss();
if (TextUtils.isEmpty(filePath)) return;
ShareOption shareOption = new ShareOption();
shareOption.title = getString(R.string.app_name);
shareOption.description = getString(R.string.share_description);
shareOption.imagePath = filePath;
shareOption.url = "http://www.u148.net/";
ShareDialog shareDialog = new ShareDialog(this, shareOption);
shareDialog.show();
mShareButton.setVisibility(View.VISIBLE);
}
private void storeImage(Bitmap image, File pictureFile) {
if (pictureFile == null) return;
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
@Override
public void onClick(View v) {
if (null == mProgress) {
mProgress = new ProgressDialog(this);
mProgress.setMessage(getString(R.string.generating_image));
}
mProgress.show();
mShareButton.setVisibility(View.GONE);
new Thread() {
@Override
public void run() {
generateImage();
}
}.start();
FlurryAgent.logEvent("share_button_click");
}
private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
}
|
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.bbva.kltt.apirest.core.parsed_info.common;
import com.bbva.kltt.apirest.core.parser.IItemFactory;
import com.bbva.kltt.apirest.core.util.APIRestGeneratorException;
import com.bbva.kltt.apirest.core.util.ConstantsCommon;
import com.bbva.kltt.apirest.core.util.ConstantsInput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* ------------------------------------------------
* @author Francisco Manuel Benitez Chico
* ------------------------------------------------
*/
public class ItemFactory implements IItemFactory
{
/** Logger of the class */
private static final Logger LOGGER = LoggerFactory.getLogger(ItemFactory.class) ;
/** Attribute - Main items map */
private final Map<String, Item> mainItemsMap ;
/**
* Public constructor
* @param mainItemsMap with the main items map
*/
public ItemFactory(final Map<String, Item> mainItemsMap)
{
this.mainItemsMap = mainItemsMap ;
}
/**
* @param type with the type
* @return true if the type is simple
*/
@Override
public boolean isSimpleItem(final String type)
{
boolean isSimpleItem = type == null ;
if (!isSimpleItem)
{
final boolean isSimpleItemG1 = type.equalsIgnoreCase(ConstantsInput.JSON_TYPE_STRING) || type.equalsIgnoreCase(ConstantsInput.JSON_TYPE_BOOLEAN) ;
final boolean isSimpleItemG2 = type.equalsIgnoreCase(ConstantsInput.JSON_TYPE_INTEGER) || type.equalsIgnoreCase(ConstantsInput.JSON_TYPE_NUMBER) ;
isSimpleItem = isSimpleItemG1 || isSimpleItemG2 ;
}
return isSimpleItem ;
}
/**
* @param name with the item name
* @param alias with the alias name
* @param description with the description
* @param required true if the item is required
* @param type with the type
* @param format with the format
* @return a new item
* @throws APIRestGeneratorException with an occurred exception
*/
@Override
public Item createNewSimpleItem(final String name,
final String alias,
final String description,
final String required,
final String type,
final String format) throws APIRestGeneratorException
{
Item item = this.createNewSimpleItemG1(name, alias, description, required, type, format) ;
if (item == null)
{
item = this.createNewSimpleItemG2(name, alias, description, required, type, format) ;
}
return item ;
}
/**
* @param name with the item name
* @param alias with the alias name
* @param description with the description
* @param required true if the item is required
* @param type with the type
* @param format with the format
* @return a new item
* @throws APIRestGeneratorException with an occurred exception
*/
private Item createNewSimpleItemG1(final String name,
final String alias,
final String description,
final String required,
final String type,
final String format) throws APIRestGeneratorException
{
Item item = null ;
if (type == null || type.equalsIgnoreCase(ConstantsInput.JSON_TYPE_STRING))
{
item = new ItemSimpleString(name, alias, description, required) ;
}
else if (type.equalsIgnoreCase(ConstantsInput.JSON_TYPE_BOOLEAN))
{
item = new ItemSimpleBoolean(name, alias, description, required) ;
}
else if (type.equalsIgnoreCase(ConstantsInput.JSON_TYPE_INTEGER) && (format == null || format.equalsIgnoreCase(ConstantsInput.JSON_FORMAT_INT32)))
{
item = new ItemSimpleInteger(name, alias, description, required) ;
}
else if (type.equalsIgnoreCase(ConstantsInput.JSON_TYPE_INTEGER) && (format != null && format.equalsIgnoreCase(ConstantsInput.JSON_FORMAT_INT64)))
{
item = new ItemSimpleLong(name, alias, description, required) ;
}
return item ;
}
/**
* @param name with the item name
* @param alias with the alias name
* @param description with the description
* @param required true if the item is required
* @param type with the type
* @param format with the format
* @return a new item
* @throws APIRestGeneratorException with an occurred exception
*/
private Item createNewSimpleItemG2(final String name,
final String alias,
final String description,
final String required,
final String type,
final String format) throws APIRestGeneratorException
{
Item item = null ;
if (type.equalsIgnoreCase(ConstantsInput.JSON_TYPE_NUMBER) && (format == null || format.equalsIgnoreCase(ConstantsInput.JSON_FORMAT_FLOAT)))
{
item = new ItemSimpleFloat(name, alias, description, required) ;
}
else if (type.equalsIgnoreCase(ConstantsInput.JSON_TYPE_NUMBER) && (format != null && format.equalsIgnoreCase(ConstantsInput.JSON_FORMAT_DOUBLE)))
{
item = new ItemSimpleDouble(name, alias, description, required) ;
}
else
{
String errorString = "'type' or 'format' values are invalid for the item values: " +
"[name: " + name + ", description: " + description + ", type: " + type + ", format: " + format + "]" ;
ItemFactory.LOGGER.error(errorString) ;
throw new APIRestGeneratorException(errorString) ;
}
return item ;
}
/**
* @param type with the type
* @return true if the type is array type
*/
@Override
public boolean isArrayItem(final String type)
{
return type != null && type.equalsIgnoreCase(ConstantsInput.JSON_TYPE_ARRAY) ;
}
/**
* @param name with the item name
* @param alias with the alias name
* @param description with the description
* @param required true if the item is required
* @return a new item array
* @throws APIRestGeneratorException with an occurred exception
*/
@Override
public ItemArray createNewArray(final String name, final String alias, final String description, final String required) throws APIRestGeneratorException
{
return new ItemArray(name, alias, description, required) ;
}
/**
* @param name with the item name
* @param alias with the alias name
* @param description with the description
* @param required true if the item is required
* @param reference with the reference
* @return a new instance of ItemRef
* @throws APIRestGeneratorException with an occurred exception
*/
@Override
public ItemRef createNewItemRef(final String name,
final String alias,
final String description,
final String required,
final String reference) throws APIRestGeneratorException
{
ItemRef itemRef = null ;
final Pattern pattern = Pattern.compile(ConstantsInput.PATT_DEFINITION_REF) ;
final Matcher matcher = pattern.matcher(reference) ;
if (matcher.matches())
{
final String itemRefString = matcher.group(1) ;
if (!this.mainItemsMap.containsKey(itemRefString))
{
final String errorString = "The following reference was not found in the items map: " + itemRefString ;
ItemFactory.LOGGER.error(errorString) ;
throw new APIRestGeneratorException(errorString) ;
}
itemRef = new ItemRef(name, alias, description, required, itemRefString) ;
}
else
{
final String errorString = "The following reference was not defined properly to be search in the items map: " + reference ;
ItemFactory.LOGGER.error(errorString) ;
throw new APIRestGeneratorException(errorString) ;
}
return itemRef ;
}
/**
* @param type with the type
* @return true if the type is complex type
*/
@Override
public boolean isComplexItem(final String type)
{
return type != null && type.equalsIgnoreCase(ConstantsInput.JSON_TYPE_OBJECT) ;
}
/**
* @param name with the name
* @param alias with the alias name
* @param description with the description
* @param required true if the item is required
* @return a new item complex
* @throws APIRestGeneratorException with an occurred exception
*/
@Override
public ItemComplex createNewItemComplex(final String name, final String alias, final String description, final String required) throws APIRestGeneratorException
{
return new ItemComplex(name, alias, description, required) ;
}
/**
* @param type with the type
* @return true if the type is file type
*/
@Override
public boolean isFileItem(final String type)
{
return type != null && type.equalsIgnoreCase(ConstantsCommon.TYPE_FILE) ;
}
/**
* @param name with the name
* @param description with the description
* @param required true if the item is required
* @return a new item file
* @throws APIRestGeneratorException with an occurred exception
*/
@Override
public ItemFile createNewItemFile(final String name, final String alias, final String description, final String required) throws APIRestGeneratorException
{
return new ItemFile(name, alias, description, required) ;
}
}
|
|
package com.socialsim.gui;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingWorker;
import javax.swing.border.LineBorder;
import com.socialsim.misc.Util;
import com.socialsim.overlay.TerrainOverlay;
import com.socialsim.regions.Terrain;
import com.socialsim.regions.World;
import com.socialsim.simulations.Simulation;
//MainFrame is the main GUI to our simulation!
public class MainFrame extends JFrame
{
private static final long serialVersionUID = 1L;
//Some of our global GUI variables
//GUI variables that we need to update from multiple plavces
private JFrame frmSocialsim;
JProgressBar simProgress = null;
private JTextField yearsField;
private JLabel lblYears;
private JButton startButton;
private JButton showBookBtn;
private Simulation s = null;
private Book book = null;
private MapFrame mapFrame = null;
private JLabel statusLabel;
private JButton stopButton;
private JTextArea statusArea;
//The "current" simulation thread
private SimTask currentSimTask = null;
private JButton showLogBtn;
private JButton showTreeBtn;
private JButton btnClearLog;
private JTextField rootFamiliesField;
/**
* Launch the application.
*/
//THE MAIN ENTRY POINT!
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
//Get a new MainFrame, and show it
new MainFrame().frmSocialsim.setVisible(true);
//Namer n = new Namer();
//See random crap
/*for(int i = 5; i < 200; i++)
{
Util.print(n.generate(5));
}*/
} catch (Exception e)
{
Util.print("MainFrame start-up error: " + e.toString());
}
}
});
}
/**
* Create the application.
*/
public MainFrame()
{
initialize();
frmSocialsim.setResizable(false);
}
/**
* Initialize the contents of the frame.
*/
//This is for GUI setup
//It also contains listener methods for all of the buttons
private void initialize()
{
//The frame that contains everything
frmSocialsim = new JFrame();
frmSocialsim.setTitle("SocialSim");
frmSocialsim.setSize(1078,732);
frmSocialsim.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//The menu bar at the top
JMenuBar menuBar = new JMenuBar();
frmSocialsim.setJMenuBar(menuBar);
frmSocialsim.getContentPane().setLayout(null);
//Our simulation progress bar
simProgress = new JProgressBar(0,100);
simProgress.setStringPainted(true);
simProgress.setBounds(12, 612, 1036, 27);
frmSocialsim.getContentPane().add(simProgress);
//The button that will show the complete book
showBookBtn = new JButton("Show Complete Book");
showBookBtn.setBounds(54, 13, 163, 25);
showBookBtn.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
if(book != null)
{
book.setVisible(true);
}
}
});
//The panel that contains parameter controls and the start/stop buttons
JPanel paramsPanel = new JPanel();
paramsPanel.setBorder(new LineBorder(new Color(0, 0, 0)));
paramsPanel.setBounds(12, 13, 490, 586);
frmSocialsim.getContentPane().add(paramsPanel);
paramsPanel.setLayout(null);
//The label that says "Years: "
lblYears = new JLabel("Years: ");
lblYears.setBounds(159, 54, 41, 16);
paramsPanel.add(lblYears);
//The textBox that inputs the number of years
yearsField = new JTextField();
yearsField.setBounds(212, 51, 116, 22);
yearsField.setText("100");
paramsPanel.add(yearsField);
yearsField.setColumns(10);
rootFamiliesField = new JTextField();
rootFamiliesField.setText("1");
rootFamiliesField.setColumns(10);
rootFamiliesField.setBounds(212, 88, 116, 22);
paramsPanel.add(rootFamiliesField);
//The button that starts the simulation, and it's ActionListener
startButton = new JButton("Start");
startButton.setBounds(159, 13, 80, 25);
/* This is where the user starts the simulation! */
startButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent arg0)
{
setButtons(false, showBookBtn,showLogBtn,showTreeBtn, btnClearLog);
stopButton.setEnabled(true);
startButton.setEnabled(false);
int years = Integer.parseInt(yearsField.getText());
int roots = Integer.parseInt(rootFamiliesField.getText());
statusLabel.setText("Simulating " + yearsField.getText() + " years (" + years*365 + " days) of civilization...");
setStatus("Running simulation...\n");
s = new Simulation(years);
s.rootFamilies = roots;
/* Called when the simulation ends */
s.setOnEndListener(new Simulation.onEndListener()
{
@Override
public void onEnd(World w, long time, double msPerDay, boolean endedEarly)
{
setStatus("Simulation done!");
if(endedEarly)
{
setStatus("Simulation ended early!");
}
else
{
simProgress.setValue(100);
}
book = new Book(w);
setButtons(true, showBookBtn,showLogBtn,showTreeBtn, startButton, btnClearLog);
String status = w.toString();
statusArea.append("Simulation done in " + time + "ms (" + time/1000 + " seconds)...\n");
statusArea.append("Ms per day: " + msPerDay + "\n");
statusArea.append(status);
statusArea.setCaretPosition(statusArea.getDocument().getLength());
stopButton.setEnabled(false);
}
});
/* Start the simulation in a thread, and set it to update our progress bar */
currentSimTask = new SimTask(s);
currentSimTask.addPropertyChangeListener(new PropertyChangeListener()
{
@Override
public void propertyChange(PropertyChangeEvent evt)
{
if ("progress" == evt.getPropertyName())
{
int progress = (Integer) evt.getNewValue();
simProgress.setValue(progress);
}
}
});
currentSimTask.execute();
}
});
paramsPanel.add(startButton);
//The button that stops the simulation, and its ActionListener
stopButton = new JButton("Stop");
stopButton.setBounds(244, 13, 80, 25);
paramsPanel.add(stopButton);
stopButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent arg0)
{
if(s != null)
{
s.stop();
setButtons(true, showBookBtn,showLogBtn,showTreeBtn, startButton);
stopButton.setEnabled(false);
book = new Book(s.getWorld());
setStatus("Simulation stopped!");
}
}
});
//The panel that holds all of the results components
JPanel resultsPanel = new JPanel();
resultsPanel.setBorder(new LineBorder(new Color(0, 0, 0)));
resultsPanel.setBounds(514, 13, 534, 586);
resultsPanel.setLayout(null);
resultsPanel.add(showBookBtn);
frmSocialsim.getContentPane().add(resultsPanel);
//The scroll pane that holds the end-of-sim basic log
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(12, 44, 510, 509);
resultsPanel.add(scrollPane);
//The text area that displays ending sim data
statusArea = new JTextArea();
scrollPane.setViewportView(statusArea);
//The button that will show the log window
showLogBtn = new JButton("Show Log");
showLogBtn.setBounds(229, 13, 97, 25);
showLogBtn.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent arg0)
{
if(s != null )
{
LogWindow log = new LogWindow(s.getWorld());
log.setVisible(true);
}
}
});
resultsPanel.add(showLogBtn);
//The button that will show the family tree
showTreeBtn = new JButton("Show Family Tree");
showTreeBtn.setBounds(338, 13, 137, 25);
showTreeBtn.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent arg0)
{
if(s != null )
{
FamilyTree tree =new FamilyTree(s.getWorld().people);
tree.setVisible(true);
}
}
});
resultsPanel.add(showTreeBtn);
//The button that will clear the small log window
btnClearLog = new JButton("Clear Log");
btnClearLog.setBounds(229, 556, 97, 25);
btnClearLog.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent arg0)
{
if(statusArea != null)
statusArea.setText("");
setStatus("Log cleared!");
}
});
resultsPanel.add(btnClearLog);
//The label that contains the status of the sim
statusLabel = new JLabel("Status label!");
statusLabel.setBounds(12, 644, 837, 16);
frmSocialsim.getContentPane().add(statusLabel);
stopButton.setEnabled(false);
JLabel lblRootFams = new JLabel("Root Couples:");
lblRootFams.setBounds(113, 91, 80, 16);
paramsPanel.add(lblRootFams);
}
//Set the status message
public void setStatus(String s)
{
if(statusLabel != null)
{
statusLabel.setText(s);
}
}
//Define the thread that will run the simulation in the background
class SimTask extends SwingWorker<Void, Void>
{
Simulation sim;
public SimTask(Simulation s)
{
sim = s;
}
@Override
protected Void doInBackground() throws Exception
{
if(s != null)
{
//Set the onProgressChanged listener
sim.setOnProgressChangedListener(new Simulation.onProgressChangedListener()
{
@Override
public void onProgressChanged(int progress)
{
setProgress(progress);
}
});
sim.start();
Util.print("Done!");
}
return null;
}
};
//Change the state of many buttons at once
public void setButtons(boolean flag, JButton... buttons )
{
for(JButton b : buttons)
{
b.setEnabled(flag);
}
}
}
|
|
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.vfs.newvfs.persistent;
import com.intellij.util.io.PagePool;
import com.intellij.util.io.storage.AbstractRecordsTable;
import com.intellij.util.io.storage.RecordIdIterator;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.IOException;
import java.util.BitSet;
// Twice as compact as AbstractRecordsTable: 8 bytes per record: int offset ([0..Integer.MAX_INT]), int ((capacity [0..0xFFFF) << 16) | (size [-1..0xFFFF)))
// if int offset is overflowed then new 8 byte record is created to
// hold long offset and original record contains negative new record number,
// same if size / capacity is overflowed: new record is created to hold integer offset / capacity and original record contains its
// negative number
class CompactRecordsTable extends AbstractRecordsTable {
private final byte[] zeroes;
private final boolean forceSplit;
public CompactRecordsTable(File recordsFile, PagePool pool, boolean forceSplit) throws IOException {
super(recordsFile, pool);
zeroes = new byte[getRecordSize()];
this.forceSplit = forceSplit;
}
@Override
protected int getImplVersion() {
return 1;
}
@Override
protected int getRecordSize() {
return 8;
}
@Override
protected byte[] getZeros() {
return zeroes;
}
private static final int ADDRESS_OFFSET = 0;
private static final int SIZE_AND_CAPACITY_OFFSET = 4;
private static final int SIZE_OFFSET_IN_INDIRECT_RECORD = 0;
private static final int CAPACITY_OFFSET_IN_INDIRECT_RECORD = 4;
@Override
public long getAddress(int record) {
int address = myStorage.getInt(getOffset(record, ADDRESS_OFFSET));
if (address < 0) { // read address from indirect record
return super.getAddress(-address);
}
return address;
}
@Override
public void setAddress(int record, long address) {
markDirty();
int addressOfRecordAbsoluteOffset = getOffset(record, ADDRESS_OFFSET);
int existing_address = myStorage.getInt(addressOfRecordAbsoluteOffset);
if (existing_address < 0) { // update address in indirect record
super.setAddress(-existing_address, address);
return;
}
if (address > Integer.MAX_VALUE || address < 0 || forceSplit) {
// nonnegative integer address is not enough and we introduce indirect record
int extendedRecord = doCreateNewRecord();
super.setAddress(extendedRecord, address);
myStorage.putInt(addressOfRecordAbsoluteOffset, -extendedRecord);
}
else {
myStorage.putInt(addressOfRecordAbsoluteOffset, (int)address);
}
}
private int doCreateNewRecord() {
try {
return createNewRecord();
}
catch (IOException ex) {
throw new RuntimeException(ex);
}
}
private static final int SIZE_MASK = 0xFFFF;
private static final int CAPACITY_MASK = 0x7FFF0000;
private static final int CAPACITY_SHIFT = 16;
private static final int SPECIAL_POSITIVE_VALUE_FOR_SPECIAL_NEGATIVE_SIZE = 0xFFFF;
@Override
public int getSize(int record) {
int currentValue = myStorage.getInt(getOffset(record, SIZE_AND_CAPACITY_OFFSET));
if (currentValue < 0) {
// read size from indirect record
return myStorage.getInt(getOffset(-currentValue, SIZE_OFFSET_IN_INDIRECT_RECORD));
}
int i = currentValue & SIZE_MASK;
if (i == SPECIAL_POSITIVE_VALUE_FOR_SPECIAL_NEGATIVE_SIZE) i = SPECIAL_NEGATIVE_SIZE_FOR_REMOVED_RECORD;
return i;
}
@Override
public void setSize(int record, int size) {
markDirty();
int sizeAndCapacityOfRecordAbsoluteOffset = getOffset(record, SIZE_AND_CAPACITY_OFFSET);
int currentValue = myStorage.getInt(sizeAndCapacityOfRecordAbsoluteOffset);
if (currentValue < 0) {
// update size in indirect record
myStorage.putInt(getOffset(-currentValue, SIZE_OFFSET_IN_INDIRECT_RECORD), size);
return;
}
// size to fit in normal record [-1 .. 0xFFFF)
if (size >= 0xFFFF || size < SPECIAL_NEGATIVE_SIZE_FOR_REMOVED_RECORD || forceSplit) {
// introduce indirect record able to hold larger size range
extendSizeAndCapacityRecord(record, size, getCapacity(record));
return;
}
if (size == SPECIAL_NEGATIVE_SIZE_FOR_REMOVED_RECORD) {
size = SPECIAL_POSITIVE_VALUE_FOR_SPECIAL_NEGATIVE_SIZE;
}
myStorage.putInt(sizeAndCapacityOfRecordAbsoluteOffset, size | (currentValue & CAPACITY_MASK));
}
private void extendSizeAndCapacityRecord(int record, int size, int capacity) {
int extendedRecord = doCreateNewRecord();
myStorage.putInt(getOffset(extendedRecord, SIZE_OFFSET_IN_INDIRECT_RECORD), size);
myStorage.putInt(getOffset(extendedRecord, CAPACITY_OFFSET_IN_INDIRECT_RECORD), capacity);
myStorage.putInt(getOffset(record, SIZE_AND_CAPACITY_OFFSET), -extendedRecord);
}
@Override
public int getCapacity(int record) {
int currentValue = myStorage.getInt(getOffset(record, SIZE_AND_CAPACITY_OFFSET));
if (currentValue < 0) {
// read capacity from indirect record
return myStorage.getInt(getOffset(-currentValue, CAPACITY_OFFSET_IN_INDIRECT_RECORD));
}
return (currentValue & CAPACITY_MASK) >> CAPACITY_SHIFT;
}
@Override
public void setCapacity(int record, int capacity) {
markDirty();
int sizeAndCapacityOfRecordAbsoluteOffset = getOffset(record, SIZE_AND_CAPACITY_OFFSET);
int currentValue = myStorage.getInt(sizeAndCapacityOfRecordAbsoluteOffset);
if (currentValue < 0) {
// update capacity in indirect record
myStorage.putInt(getOffset(-currentValue, CAPACITY_OFFSET_IN_INDIRECT_RECORD), capacity);
return;
}
// size to fit in normal record [0 .. 0x7FFF]
if (capacity > 0x7fff || capacity < 0 || forceSplit) {
// introduce indirect record able to hold larger capacity range
extendSizeAndCapacityRecord(record, getSize(record), capacity);
return;
}
myStorage.putInt(sizeAndCapacityOfRecordAbsoluteOffset, (currentValue & SIZE_MASK) | (capacity << CAPACITY_SHIFT));
}
@Override
public void deleteRecord(int record) throws IOException {
final int sizeAndCapacityOfRecordAbsoluteOffset = getOffset(record, SIZE_AND_CAPACITY_OFFSET);
final int sizeAndCapacityValue = myStorage.getInt(sizeAndCapacityOfRecordAbsoluteOffset);
final int addressOfRecordAbsoluteOffset = getOffset(record, ADDRESS_OFFSET);
final int existingAddressValue = myStorage.getInt(addressOfRecordAbsoluteOffset);
super.deleteRecord(record);
if (sizeAndCapacityValue < 0) {
super.deleteRecord(-sizeAndCapacityValue);
}
if (existingAddressValue < 0) {
super.deleteRecord(-existingAddressValue);
}
}
@Override
public RecordIdIterator createRecordIdIterator() throws IOException {
final BitSet extraRecordsIds = buildIdSetOfExtraRecords();
final RecordIdIterator iterator = super.createRecordIdIterator();
return new RecordIdIterator() {
int nextId = scanToNextId();
private int scanToNextId() {
while(iterator.hasNextId()) {
int next = iterator.nextId();
if ( !extraRecordsIds.get(next)) return next;
}
return -1;
}
@Override
public boolean hasNextId() {
return nextId != -1;
}
@Override
public int nextId() {
assert hasNextId();
int result = nextId;
nextId = scanToNextId();
return result;
}
@Override
public boolean validId() {
assert hasNextId();
return isSizeOfLiveRecord(getSize(nextId));
}
};
}
@NotNull
private BitSet buildIdSetOfExtraRecords() throws IOException {
final BitSet extraRecords = new BitSet();
final RecordIdIterator iterator = super.createRecordIdIterator();
while(iterator.hasNextId()) {
int recordId = iterator.nextId();
final int sizeAndCapacityOfRecordAbsoluteOffset = getOffset(recordId, SIZE_AND_CAPACITY_OFFSET);
final int sizeAndCapacityValue = myStorage.getInt(sizeAndCapacityOfRecordAbsoluteOffset);
final int addressOfRecordAbsoluteOffset = getOffset(recordId, ADDRESS_OFFSET);
final int existingAddressValue = myStorage.getInt(addressOfRecordAbsoluteOffset);
if (sizeAndCapacityValue < 0) {
extraRecords.set(-sizeAndCapacityValue);
}
if (existingAddressValue < 0) {
extraRecords.set(-existingAddressValue);
}
}
return extraRecords;
}
}
|
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.beanutils;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Locale;
import org.apache.commons.beanutils.converters.DateConverter;
import junit.framework.TestCase;
import junit.framework.Test;
import junit.framework.TestSuite;
/**
* <p>
* Test Case for the ConvertUtils class.
* </p>
*
* @author Craig R. McClanahan
* @version $Revision: 551047 $ $Date: 2007-06-27 07:34:15 +0200 (Wed, 27 Jun 2007) $
*/
public class ConvertUtilsTestCase extends TestCase {
// ---------------------------------------------------- Instance Variables
// ---------------------------------------------------------- Constructors
/**
* Construct a new instance of this test case.
*
* @param name Name of the test case
*/
public ConvertUtilsTestCase(String name) {
super(name);
}
// -------------------------------------------------- Overall Test Methods
/**
* Set up instance variables required by this test case.
*/
public void setUp() {
ConvertUtils.deregister();
}
/**
* Return the tests included in this test suite.
*/
public static Test suite() {
return (new TestSuite(ConvertUtilsTestCase.class));
}
/**
* Tear down instance variables required by this test case.
*/
public void tearDown() {
// No action required
}
// ------------------------------------------------ Individual Test Methods
/**
* Negative String to primitive integer array tests.
*/
public void testNegativeIntegerArray() {
Object value = null;
int intArray[] = new int[0];
value = ConvertUtils.convert((String) null, intArray.getClass());
checkIntegerArray(value, intArray);
value = ConvertUtils.convert("a", intArray.getClass());
checkIntegerArray(value, intArray);
value = ConvertUtils.convert("{ a }", intArray.getClass());
checkIntegerArray(value, intArray);
value = ConvertUtils.convert("1a3", intArray.getClass());
checkIntegerArray(value, intArray);
value = ConvertUtils.convert("{ 1a3 }", intArray.getClass());
checkIntegerArray(value, intArray);
value = ConvertUtils.convert("0,1a3", intArray.getClass());
checkIntegerArray(value, intArray);
value = ConvertUtils.convert("{ 0, 1a3 }", intArray.getClass());
checkIntegerArray(value, intArray);
}
/**
* Negative scalar conversion tests. These rely on the standard
* default value conversions in ConvertUtils.
*/
public void testNegativeScalar() {
Object value = null;
value = ConvertUtils.convert("foo", Boolean.TYPE);
assertTrue(value instanceof Boolean);
assertEquals(((Boolean) value).booleanValue(), false);
value = ConvertUtils.convert("foo", Boolean.class);
assertTrue(value instanceof Boolean);
assertEquals(((Boolean) value).booleanValue(), false);
value = ConvertUtils.convert("foo", Byte.TYPE);
assertTrue(value instanceof Byte);
assertEquals(((Byte) value).byteValue(), (byte) 0);
value = ConvertUtils.convert("foo", Byte.class);
assertTrue(value instanceof Byte);
assertEquals(((Byte) value).byteValue(), (byte) 0);
try {
value = ConvertUtils.convert
("org.apache.commons.beanutils.Undefined", Class.class);
fail("Should have thrown conversion exception");
} catch (ConversionException e) {
// Expected result
}
value = ConvertUtils.convert("foo", Double.TYPE);
assertTrue(value instanceof Double);
assertEquals(((Double) value).doubleValue(), 0.0,
0.005);
value = ConvertUtils.convert("foo", Double.class);
assertTrue(value instanceof Double);
assertEquals(((Double) value).doubleValue(), 0.0, 0.005);
value = ConvertUtils.convert("foo", Float.TYPE);
assertTrue(value instanceof Float);
assertEquals(((Float) value).floatValue(), (float) 0.0,
(float) 0.005);
value = ConvertUtils.convert("foo", Float.class);
assertTrue(value instanceof Float);
assertEquals(((Float) value).floatValue(), (float) 0.0,
(float) 0.005);
value = ConvertUtils.convert("foo", Integer.TYPE);
assertTrue(value instanceof Integer);
assertEquals(((Integer) value).intValue(), 0);
value = ConvertUtils.convert("foo", Integer.class);
assertTrue(value instanceof Integer);
assertEquals(((Integer) value).intValue(), 0);
value = ConvertUtils.convert("foo", Byte.TYPE);
assertTrue(value instanceof Byte);
assertEquals(((Byte) value).byteValue(), (byte) 0);
value = ConvertUtils.convert("foo", Long.class);
assertTrue(value instanceof Long);
assertEquals(((Long) value).longValue(), 0);
value = ConvertUtils.convert("foo", Short.TYPE);
assertTrue(value instanceof Short);
assertEquals(((Short) value).shortValue(), (short) 0);
value = ConvertUtils.convert("foo", Short.class);
assertTrue(value instanceof Short);
assertEquals(((Short) value).shortValue(), (short) 0);
}
/**
* Negative String to String array tests.
*/
public void testNegativeStringArray() {
Object value = null;
String stringArray[] = new String[0];
value = ConvertUtils.convert((String) null, stringArray.getClass());
checkStringArray(value, stringArray);
}
/**
* Test conversion of object to string for arrays.
*/
public void testObjectToStringArray() {
int intArray0[] = new int[0];
int intArray1[] = { 123 };
int intArray2[] = { 123, 456 };
String stringArray0[] = new String[0];
String stringArray1[] = { "abc" };
String stringArray2[] = { "abc", "def" };
assertEquals("intArray0", null,
ConvertUtils.convert(intArray0));
assertEquals("intArray1", "123",
ConvertUtils.convert(intArray1));
assertEquals("intArray2", "123",
ConvertUtils.convert(intArray2));
assertEquals("stringArray0", null,
ConvertUtils.convert(stringArray0));
assertEquals("stringArray1", "abc",
ConvertUtils.convert(stringArray1));
assertEquals("stringArray2", "abc",
ConvertUtils.convert(stringArray2));
}
/**
* Test conversion of object to string for scalars.
*/
public void testObjectToStringScalar() {
assertEquals("Boolean->String", "false",
ConvertUtils.convert(Boolean.FALSE));
assertEquals("Boolean->String", "true",
ConvertUtils.convert(Boolean.TRUE));
assertEquals("Byte->String", "123",
ConvertUtils.convert(new Byte((byte) 123)));
assertEquals("Character->String", "a",
ConvertUtils.convert(new Character('a')));
assertEquals("Double->String", "123.0",
ConvertUtils.convert(new Double(123.0)));
assertEquals("Float->String", "123.0",
ConvertUtils.convert(new Float((float) 123.0)));
assertEquals("Integer->String", "123",
ConvertUtils.convert(new Integer(123)));
assertEquals("Long->String", "123",
ConvertUtils.convert(new Long(123)));
assertEquals("Short->String", "123",
ConvertUtils.convert(new Short((short) 123)));
assertEquals("String->String", "abc",
ConvertUtils.convert("abc"));
assertEquals("String->String null", null,
ConvertUtils.convert(null));
}
/**
* Positive array conversion tests.
*/
public void testPositiveArray() {
String values1[] = { "10", "20", "30" };
Object value = ConvertUtils.convert(values1, Integer.TYPE);
int shape[] = new int[0];
assertEquals(shape.getClass(), value.getClass());
int results1[] = (int[]) value;
assertEquals(results1[0], 10);
assertEquals(results1[1], 20);
assertEquals(results1[2], 30);
String values2[] = { "100", "200", "300" };
value = ConvertUtils.convert(values2, shape.getClass());
assertEquals(shape.getClass(), value.getClass());
int results2[] = (int[]) value;
assertEquals(results2[0], 100);
assertEquals(results2[1], 200);
assertEquals(results2[2], 300);
}
/**
* Positive String to primitive integer array tests.
*/
public void testPositiveIntegerArray() {
Object value = null;
int intArray[] = new int[0];
int intArray1[] = new int[] { 0 };
int intArray2[] = new int[] { 0, 10 };
value = ConvertUtils.convert("{ }", intArray.getClass());
checkIntegerArray(value, intArray);
value = ConvertUtils.convert("0", intArray.getClass());
checkIntegerArray(value, intArray1);
value = ConvertUtils.convert(" 0 ", intArray.getClass());
checkIntegerArray(value, intArray1);
value = ConvertUtils.convert("{ 0 }", intArray.getClass());
checkIntegerArray(value, intArray1);
value = ConvertUtils.convert("0,10", intArray.getClass());
checkIntegerArray(value, intArray2);
value = ConvertUtils.convert("0 10", intArray.getClass());
checkIntegerArray(value, intArray2);
value = ConvertUtils.convert("{0,10}", intArray.getClass());
checkIntegerArray(value, intArray2);
value = ConvertUtils.convert("{0 10}", intArray.getClass());
checkIntegerArray(value, intArray2);
value = ConvertUtils.convert("{ 0, 10 }", intArray.getClass());
checkIntegerArray(value, intArray2);
value = ConvertUtils.convert("{ 0 10 }", intArray.getClass());
checkIntegerArray(value, intArray2);
}
/**
* Positive scalar conversion tests.
*/
public void testPositiveScalar() {
Object value = null;
value = ConvertUtils.convert("true", Boolean.TYPE);
assertTrue(value instanceof Boolean);
assertEquals(((Boolean) value).booleanValue(), true);
value = ConvertUtils.convert("true", Boolean.class);
assertTrue(value instanceof Boolean);
assertEquals(((Boolean) value).booleanValue(), true);
value = ConvertUtils.convert("yes", Boolean.TYPE);
assertTrue(value instanceof Boolean);
assertEquals(((Boolean) value).booleanValue(), true);
value = ConvertUtils.convert("yes", Boolean.class);
assertTrue(value instanceof Boolean);
assertEquals(((Boolean) value).booleanValue(), true);
value = ConvertUtils.convert("y", Boolean.TYPE);
assertTrue(value instanceof Boolean);
assertEquals(((Boolean) value).booleanValue(), true);
value = ConvertUtils.convert("y", Boolean.class);
assertTrue(value instanceof Boolean);
assertEquals(((Boolean) value).booleanValue(), true);
value = ConvertUtils.convert("on", Boolean.TYPE);
assertTrue(value instanceof Boolean);
assertEquals(((Boolean) value).booleanValue(), true);
value = ConvertUtils.convert("on", Boolean.class);
assertTrue(value instanceof Boolean);
assertEquals(((Boolean) value).booleanValue(), true);
value = ConvertUtils.convert("false", Boolean.TYPE);
assertTrue(value instanceof Boolean);
assertEquals(((Boolean) value).booleanValue(), false);
value = ConvertUtils.convert("false", Boolean.class);
assertTrue(value instanceof Boolean);
assertEquals(((Boolean) value).booleanValue(), false);
value = ConvertUtils.convert("no", Boolean.TYPE);
assertTrue(value instanceof Boolean);
assertEquals(((Boolean) value).booleanValue(), false);
value = ConvertUtils.convert("no", Boolean.class);
assertTrue(value instanceof Boolean);
assertEquals(((Boolean) value).booleanValue(), false);
value = ConvertUtils.convert("n", Boolean.TYPE);
assertTrue(value instanceof Boolean);
assertEquals(((Boolean) value).booleanValue(), false);
value = ConvertUtils.convert("n", Boolean.class);
assertTrue(value instanceof Boolean);
assertEquals(((Boolean) value).booleanValue(), false);
value = ConvertUtils.convert("off", Boolean.TYPE);
assertTrue(value instanceof Boolean);
assertEquals(((Boolean) value).booleanValue(), false);
value = ConvertUtils.convert("off", Boolean.class);
assertTrue(value instanceof Boolean);
assertEquals(((Boolean) value).booleanValue(), false);
value = ConvertUtils.convert("123", Byte.TYPE);
assertTrue(value instanceof Byte);
assertEquals(((Byte) value).byteValue(), (byte) 123);
value = ConvertUtils.convert("123", Byte.class);
assertTrue(value instanceof Byte);
assertEquals(((Byte) value).byteValue(), (byte) 123);
value = ConvertUtils.convert("a", Character.TYPE);
assertTrue(value instanceof Character);
assertEquals(((Character) value).charValue(), 'a');
value = ConvertUtils.convert("a", Character.class);
assertTrue(value instanceof Character);
assertEquals(((Character) value).charValue(), 'a');
value = ConvertUtils.convert("java.lang.String", Class.class);
assertTrue(value instanceof Class);
assertEquals(String.class, value);
value = ConvertUtils.convert("123.456", Double.TYPE);
assertTrue(value instanceof Double);
assertEquals(((Double) value).doubleValue(), 123.456, 0.005);
value = ConvertUtils.convert("123.456", Double.class);
assertTrue(value instanceof Double);
assertEquals(((Double) value).doubleValue(), 123.456, 0.005);
value = ConvertUtils.convert("123.456", Float.TYPE);
assertTrue(value instanceof Float);
assertEquals(((Float) value).floatValue(), (float) 123.456,
(float) 0.005);
value = ConvertUtils.convert("123.456", Float.class);
assertTrue(value instanceof Float);
assertEquals(((Float) value).floatValue(), (float) 123.456,
(float) 0.005);
value = ConvertUtils.convert("123", Integer.TYPE);
assertTrue(value instanceof Integer);
assertEquals(((Integer) value).intValue(), 123);
value = ConvertUtils.convert("123", Integer.class);
assertTrue(value instanceof Integer);
assertEquals(((Integer) value).intValue(), 123);
value = ConvertUtils.convert("123", Long.TYPE);
assertTrue(value instanceof Long);
assertEquals(((Long) value).longValue(), 123);
value = ConvertUtils.convert("123", Long.class);
assertTrue(value instanceof Long);
assertEquals(((Long) value).longValue(), 123);
value = ConvertUtils.convert("123", Short.TYPE);
assertTrue(value instanceof Short);
assertEquals(((Short) value).shortValue(), (short) 123);
value = ConvertUtils.convert("123", Short.class);
assertTrue(value instanceof Short);
assertEquals(((Short) value).shortValue(), (short) 123);
String input = null;
input = "2002-03-17";
value = ConvertUtils.convert(input, Date.class);
assertTrue(value instanceof Date);
assertEquals(input, value.toString());
input = "20:30:40";
value = ConvertUtils.convert(input, Time.class);
assertTrue(value instanceof Time);
assertEquals(input, value.toString());
input = "2002-03-17 20:30:40.0";
value = ConvertUtils.convert(input, Timestamp.class);
assertTrue(value instanceof Timestamp);
assertEquals(input, value.toString());
}
/**
* Positive String to String array tests.
*/
public void testPositiveStringArray() {
Object value = null;
String stringArray[] = new String[0];
String stringArray1[] = new String[]
{ "abc" };
String stringArray2[] = new String[]
{ "abc", "de,f" };
value = ConvertUtils.convert("", stringArray.getClass());
checkStringArray(value, stringArray);
value = ConvertUtils.convert(" ", stringArray.getClass());
checkStringArray(value, stringArray);
value = ConvertUtils.convert("{}", stringArray.getClass());
checkStringArray(value, stringArray);
value = ConvertUtils.convert("{ }", stringArray.getClass());
checkStringArray(value, stringArray);
value = ConvertUtils.convert("abc", stringArray.getClass());
checkStringArray(value, stringArray1);
value = ConvertUtils.convert("{abc}", stringArray.getClass());
checkStringArray(value, stringArray1);
value = ConvertUtils.convert("\"abc\"", stringArray.getClass());
checkStringArray(value, stringArray1);
value = ConvertUtils.convert("{\"abc\"}", stringArray.getClass());
checkStringArray(value, stringArray1);
value = ConvertUtils.convert("'abc'", stringArray.getClass());
checkStringArray(value, stringArray1);
value = ConvertUtils.convert("{'abc'}", stringArray.getClass());
checkStringArray(value, stringArray1);
value = ConvertUtils.convert("abc 'de,f'",
stringArray.getClass());
checkStringArray(value, stringArray2);
value = ConvertUtils.convert("{abc, 'de,f'}",
stringArray.getClass());
checkStringArray(value, stringArray2);
value = ConvertUtils.convert("\"abc\",\"de,f\"",
stringArray.getClass());
checkStringArray(value, stringArray2);
value = ConvertUtils.convert("{\"abc\" 'de,f'}",
stringArray.getClass());
checkStringArray(value, stringArray2);
value = ConvertUtils.convert("'abc' 'de,f'",
stringArray.getClass());
checkStringArray(value, stringArray2);
value = ConvertUtils.convert("{'abc', \"de,f\"}",
stringArray.getClass());
checkStringArray(value, stringArray2);
}
public void testSeparateConvertInstances() throws Exception {
ConvertUtilsBean utilsOne = new ConvertUtilsBean();
ConvertUtilsBean utilsTwo = new ConvertUtilsBean();
// make sure that the test work ok before anything's changed
Object
value = utilsOne.convert("true", Boolean.TYPE);
assertTrue(value instanceof Boolean);
assertEquals(
"Standard conversion failed (1)",
((Boolean) value).booleanValue(),
true);
value = utilsTwo.convert("true", Boolean.TYPE);
assertTrue(value instanceof Boolean);
assertEquals(
"Standard conversion failed (2)",
((Boolean) value).booleanValue(),
true);
// now register a test
utilsOne.register(new ThrowExceptionConverter(), Boolean.TYPE);
try {
utilsOne.convert("true", Boolean.TYPE);
fail("Register converter failed.");
} catch (PassTestException e) { /* This shows that the registration has worked */ }
try {
// nothing should have changed
value = utilsTwo.convert("true", Boolean.TYPE);
assertTrue(value instanceof Boolean);
assertEquals(
"Standard conversion failed (3)",
((Boolean) value).booleanValue(),
true);
} catch (PassTestException e) {
// This is a failure since utilsTwo should still have
// standard converters registered
fail("Registering a converter for an instance should not effect another instance.");
}
// nothing we'll test deregister
utilsOne.deregister();
value = utilsOne.convert("true", Boolean.TYPE);
assertTrue(value instanceof Boolean);
assertEquals("Instance deregister failed.", ((Boolean) value).booleanValue(), true);
value = utilsTwo.convert("true", Boolean.TYPE);
assertTrue(value instanceof Boolean);
assertEquals(
"Standard conversion failed (4)",
((Boolean) value).booleanValue(),
true);
}
public void testDeregisteringSingleConverter() throws Exception {
// make sure that the test work ok before anything's changed
Object
value = ConvertUtils.convert("true", Boolean.TYPE);
assertTrue(value instanceof Boolean);
assertEquals(
"Standard conversion failed (1)",
((Boolean) value).booleanValue(),
true);
// we'll test deregister
ConvertUtils.deregister(Boolean.TYPE);
assertNull("Converter should be null",ConvertUtils.lookup(Boolean.TYPE));
}
public void testConvertToString() throws Exception {
Converter dummyConverter = new Converter() {
public Object convert(Class type, Object value) {
return value;
}
};
Converter fooConverter = new Converter() {
public Object convert(Class type, Object value) {
return "Foo-Converter";
}
};
DateConverter dateConverter = new DateConverter();
dateConverter.setLocale(Locale.US);
ConvertUtilsBean utils = new ConvertUtilsBean();
utils.register(dateConverter, java.util.Date.class);
utils.register(fooConverter, String.class);
// Convert using registerd DateConverter
java.util.Date today = new java.util.Date();
DateFormat fmt = new SimpleDateFormat("M/d/yy"); /* US Short Format */
String expected = fmt.format(today);
assertEquals("DateConverter M/d/yy", expected, utils.convert(today, String.class));
// Date converter doesn't do String conversion - use String Converter
utils.register(dummyConverter, java.util.Date.class);
assertEquals("Date Converter doesn't do String conversion", "Foo-Converter", utils.convert(today, String.class));
// No registered Date converter - use String Converter
utils.deregister(java.util.Date.class);
assertEquals("No registered Date converter", "Foo-Converter", utils.convert(today, String.class));
// String Converter doesn't do Strings!!!
utils.register(dummyConverter, String.class);
assertEquals("String Converter doesn't do Strings!!!", today.toString(), utils.convert(today, String.class));
// No registered Date or String converter - use Object's toString()
utils.deregister(String.class);
assertEquals("Object's toString()", today.toString(), utils.convert(today, String.class));
}
// -------------------------------------------------------- Private Methods
private void checkIntegerArray(Object value, int intArray[]) {
assertNotNull("Returned value is not null", value);
assertEquals("Returned value is int[]",
intArray.getClass(), value.getClass());
int results[] = (int[]) value;
assertEquals("Returned array length", intArray.length, results.length);
for (int i = 0; i < intArray.length; i++) {
assertEquals("Returned array value " + i,
intArray[i], results[i]);
}
}
private void checkStringArray(Object value, String stringArray[]) {
assertNotNull("Returned value is not null", value);
assertEquals("Returned value is String[]",
stringArray.getClass(), value.getClass());
String results[] = (String[]) value;
assertEquals("Returned array length",
stringArray.length, results.length);
for (int i = 0; i < stringArray.length; i++) {
assertEquals("Returned array value " + i,
stringArray[i], results[i]);
}
}
}
|
|
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2016. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import edu.wpi.first.wpilibj.communication.FRCNetworkCommunicationsLibrary.tResourceType;
import edu.wpi.first.wpilibj.communication.UsageReporting;
import edu.wpi.first.wpilibj.hal.SerialPortJNI;
/**
* Driver for the RS-232 serial port on the RoboRIO.
*
* The current implementation uses the VISA formatted I/O mode. This means that
* all traffic goes through the formatted buffers. This allows the intermingled
* use of print(), readString(), and the raw buffer accessors read() and
* write().
*
* More information can be found in the NI-VISA User Manual here:
* http://www.ni.com/pdf/manuals/370423a.pdf and the NI-VISA Programmer's
* Reference Manual here: http://www.ni.com/pdf/manuals/370132c.pdf
*/
public class SerialPort {
private byte m_port;
public enum Port {
kOnboard(0), kMXP(1), kUSB(2);
private int value;
private Port(int value) {
this.value = value;
}
public int getValue() {
return this.value;
}
};
/**
* Represents the parity to use for serial communications
*/
public static class Parity {
/**
* The integer value representing this enumeration
*/
public final int value;
static final int kNone_val = 0;
static final int kOdd_val = 1;
static final int kEven_val = 2;
static final int kMark_val = 3;
static final int kSpace_val = 4;
/**
* parity: Use no parity
*/
public static final Parity kNone = new Parity(kNone_val);
/**
* parity: Use odd parity
*/
public static final Parity kOdd = new Parity(kOdd_val);
/**
* parity: Use even parity
*/
public static final Parity kEven = new Parity(kEven_val);
/**
* parity: Use mark parity
*/
public static final Parity kMark = new Parity(kMark_val);
/**
* parity: Use space parity
*/
public static final Parity kSpace = new Parity((kSpace_val));
private Parity(int value) {
this.value = value;
}
}
/**
* Represents the number of stop bits to use for Serial Communication
*/
public static class StopBits {
/**
* The integer value representing this enumeration
*/
public final int value;
static final int kOne_val = 10;
static final int kOnePointFive_val = 15;
static final int kTwo_val = 20;
/**
* stopBits: use 1
*/
public static final StopBits kOne = new StopBits(kOne_val);
/**
* stopBits: use 1.5
*/
public static final StopBits kOnePointFive = new StopBits(kOnePointFive_val);
/**
* stopBits: use 2
*/
public static final StopBits kTwo = new StopBits(kTwo_val);
private StopBits(int value) {
this.value = value;
}
}
/**
* Represents what type of flow control to use for serial communication
*/
public static class FlowControl {
/**
* The integer value representing this enumeration
*/
public final int value;
static final int kNone_val = 0;
static final int kXonXoff_val = 1;
static final int kRtsCts_val = 2;
static final int kDtrDsr_val = 4;
/**
* flowControl: use none
*/
public static final FlowControl kNone = new FlowControl(kNone_val);
/**
* flowcontrol: use on/off
*/
public static final FlowControl kXonXoff = new FlowControl(kXonXoff_val);
/**
* flowcontrol: use rts cts
*/
public static final FlowControl kRtsCts = new FlowControl(kRtsCts_val);
/**
* flowcontrol: use dts dsr
*/
public static final FlowControl kDtrDsr = new FlowControl(kDtrDsr_val);
private FlowControl(int value) {
this.value = value;
}
}
/**
* Represents which type of buffer mode to use when writing to a serial port
*/
public static class WriteBufferMode {
/**
* The integer value representing this enumeration
*/
public final int value;
static final int kFlushOnAccess_val = 1;
static final int kFlushWhenFull_val = 2;
/**
* Flush on access
*/
public static final WriteBufferMode kFlushOnAccess = new WriteBufferMode(kFlushOnAccess_val);
/**
* Flush when full
*/
public static final WriteBufferMode kFlushWhenFull = new WriteBufferMode(kFlushWhenFull_val);
private WriteBufferMode(int value) {
this.value = value;
}
}
/**
* Create an instance of a Serial Port class.
*
* @param baudRate The baud rate to configure the serial port.
* @param port The Serial port to use
* @param dataBits The number of data bits per transfer. Valid values are
* between 5 and 8 bits.
* @param parity Select the type of parity checking to use.
* @param stopBits The number of stop bits to use as defined by the enum
* StopBits.
*/
public SerialPort(final int baudRate, Port port, final int dataBits, Parity parity,
StopBits stopBits) {
m_port = (byte) port.getValue();
SerialPortJNI.serialInitializePort(m_port);
SerialPortJNI.serialSetBaudRate(m_port, baudRate);
SerialPortJNI.serialSetDataBits(m_port, (byte) dataBits);
SerialPortJNI.serialSetParity(m_port, (byte) parity.value);
SerialPortJNI.serialSetStopBits(m_port, (byte) stopBits.value);
// Set the default read buffer size to 1 to return bytes immediately
setReadBufferSize(1);
// Set the default timeout to 5 seconds.
setTimeout(5.0f);
// Don't wait until the buffer is full to transmit.
setWriteBufferMode(WriteBufferMode.kFlushOnAccess);
disableTermination();
UsageReporting.report(tResourceType.kResourceType_SerialPort, 0);
}
/**
* Create an instance of a Serial Port class. Defaults to one stop bit.
*
* @param baudRate The baud rate to configure the serial port.
* @param dataBits The number of data bits per transfer. Valid values are
* between 5 and 8 bits.
* @param parity Select the type of parity checking to use.
*/
public SerialPort(final int baudRate, Port port, final int dataBits, Parity parity) {
this(baudRate, port, dataBits, parity, StopBits.kOne);
}
/**
* Create an instance of a Serial Port class. Defaults to no parity and one
* stop bit.
*
* @param baudRate The baud rate to configure the serial port.
* @param dataBits The number of data bits per transfer. Valid values are
* between 5 and 8 bits.
*/
public SerialPort(final int baudRate, Port port, final int dataBits) {
this(baudRate, port, dataBits, Parity.kNone, StopBits.kOne);
}
/**
* Create an instance of a Serial Port class. Defaults to 8 databits, no
* parity, and one stop bit.
*
* @param baudRate The baud rate to configure the serial port.
*/
public SerialPort(final int baudRate, Port port) {
this(baudRate, port, 8, Parity.kNone, StopBits.kOne);
}
/**
* Destructor.
*/
public void free() {
SerialPortJNI.serialClose(m_port);
}
/**
* Set the type of flow control to enable on this port.
*
* By default, flow control is disabled.
*$
* @param flowControl the FlowControl value to use
*/
public void setFlowControl(FlowControl flowControl) {
SerialPortJNI.serialSetFlowControl(m_port, (byte) flowControl.value);
}
/**
* Enable termination and specify the termination character.
*
* Termination is currently only implemented for receive. When the the
* terminator is received, the read() or readString() will return fewer bytes
* than requested, stopping after the terminator.
*
* @param terminator The character to use for termination.
*/
public void enableTermination(char terminator) {
SerialPortJNI.serialEnableTermination(m_port, terminator);
}
/**
* Enable termination with the default terminator '\n'
*
* Termination is currently only implemented for receive. When the the
* terminator is received, the read() or readString() will return fewer bytes
* than requested, stopping after the terminator.
*
* The default terminator is '\n'
*/
public void enableTermination() {
this.enableTermination('\n');
}
/**
* Disable termination behavior.
*/
public void disableTermination() {
SerialPortJNI.serialDisableTermination(m_port);
}
/**
* Get the number of bytes currently available to read from the serial port.
*
* @return The number of bytes available to read.
*/
public int getBytesReceived() {
return SerialPortJNI.serialGetBytesRecieved(m_port);
}
/**
* Read a string out of the buffer. Reads the entire contents of the buffer
*
* @return The read string
*/
public String readString() {
return readString(getBytesReceived());
}
/**
* Read a string out of the buffer. Reads the entire contents of the buffer
*
* @param count the number of characters to read into the string
* @return The read string
*/
public String readString(int count) {
byte[] out = read(count);
try {
return new String(out, 0, out.length, "US-ASCII");
} catch (UnsupportedEncodingException ex) {
ex.printStackTrace();
return new String();
}
}
/**
* Read raw bytes out of the buffer.
*
* @param count The maximum number of bytes to read.
* @return An array of the read bytes
*/
public byte[] read(final int count) {
ByteBuffer dataReceivedBuffer = ByteBuffer.allocateDirect(count);
int gotten = SerialPortJNI.serialRead(m_port, dataReceivedBuffer, count);
byte[] retVal = new byte[gotten];
dataReceivedBuffer.get(retVal);
return retVal;
}
/**
* Write raw bytes to the serial port.
*
* @param buffer The buffer of bytes to write.
* @param count The maximum number of bytes to write.
* @return The number of bytes actually written into the port.
*/
public int write(byte[] buffer, int count) {
ByteBuffer dataToSendBuffer = ByteBuffer.allocateDirect(count);
dataToSendBuffer.put(buffer, 0, count);
return SerialPortJNI.serialWrite(m_port, dataToSendBuffer, count);
}
/**
* Write a string to the serial port
*
* @param data The string to write to the serial port.
* @return The number of bytes actually written into the port.
*/
public int writeString(String data) {
return write(data.getBytes(), data.length());
}
/**
* Configure the timeout of the serial port.
*
* This defines the timeout for transactions with the hardware. It will affect
* reads if less bytes are available than the read buffer size (defaults to 1)
* and very large writes.
*
* @param timeout The number of seconds to to wait for I/O.
*/
public void setTimeout(double timeout) {
SerialPortJNI.serialSetTimeout(m_port, (float) timeout);
}
/**
* Specify the size of the input buffer.
*
* Specify the amount of data that can be stored before data from the device
* is returned to Read. If you want data that is received to be returned
* immediately, set this to 1.
*
* It the buffer is not filled before the read timeout expires, all data that
* has been received so far will be returned.
*
* @param size The read buffer size.
*/
public void setReadBufferSize(int size) {
SerialPortJNI.serialSetReadBufferSize(m_port, size);
}
/**
* Specify the size of the output buffer.
*
* Specify the amount of data that can be stored before being transmitted to
* the device.
*
* @param size The write buffer size.
*/
public void setWriteBufferSize(int size) {
SerialPortJNI.serialSetWriteBufferSize(m_port, size);
}
/**
* Specify the flushing behavior of the output buffer.
*
* When set to kFlushOnAccess, data is synchronously written to the serial
* port after each call to either print() or write().
*
* When set to kFlushWhenFull, data will only be written to the serial port
* when the buffer is full or when flush() is called.
*
* @param mode The write buffer mode.
*/
public void setWriteBufferMode(WriteBufferMode mode) {
SerialPortJNI.serialSetWriteMode(m_port, (byte) mode.value);
}
/**
* Force the output buffer to be written to the port.
*
* This is used when setWriteBufferMode() is set to kFlushWhenFull to force a
* flush before the buffer is full.
*/
public void flush() {
SerialPortJNI.serialFlush(m_port);
}
/**
* Reset the serial port driver to a known state.
*
* Empty the transmit and receive buffers in the device and formatted I/O.
*/
public void reset() {
SerialPortJNI.serialClear(m_port);
}
}
|
|
package org.risk.logic;
import static com.google.common.base.Preconditions.checkArgument;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.risk.logic.GameApi.Operation;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
public final class GameResources {
private GameResources() {
}
public static final Map<Integer, Integer> PLAYERS_UNIT_MAP = ImmutableMap.<Integer, Integer>of(
2, 40,
3, 35,
4, 30,
5, 25,
6, 20);
public static final int MIN_ALLOCATED_UNITS = 3;
public static final int TOTAL_TERRITORIES = 42; // Number of territories
public static final int TOTAL_CONTINENTS = 6;
public static final int TOTAL_WILD_CARDS = 2;
public static final int TOTAL_RISK_CARDS = TOTAL_TERRITORIES + TOTAL_WILD_CARDS;
public static final int MAX_DICE_ROLL = 6;
public static final int MIN_DICE_ROLL = 1;
public static final String TURN_ORDER = "turnOrder";
public static final String TURN = "turn";
public static final String PHASE = "phase"; // reinforce, attack, fortify
public static final String RISK_CARD = "RC";
public static final String TERRITORY = "territory";
public static final String UNCLAIMED_TERRITORY = "unclaimedTerritory";
public static final String CONTINENT = "continent";
public static final String UNITS = "units";
public static final String ATTACK_OCCUPY = "attackOccupy";
public static final String ATTACK_RESULT = "attackResult";
public static final String END_ATTACK = "endAttack";
public static final String ATTACKER = "attacker";
public static final String DEFENDER = "defender";
public static final String TERRITORY_WINNER = "territoryWinner";
public static final String PLAYER = "player";
public static final String MESSAGE = "message";
public static final String ATTACK_TO_TERRITORY = "attackToTerritory";
public static final String LAST_ATTACKING_TERRITORY = "lastAttackingTerritory";
public static final String DICE_ROLL = "diceRoll";
public static final String WINNING_TERRITORY = "winningTerritory";
public static final String MOVEMENT_FROM_TERRITORY = "movementFromTerritory";
public static final String MOVEMENT_TO_TERRITORY = "movementFromTerritory";
public static final String UNITS_FROM_TERRITORY = "unitsFromTerritory";
public static final String UNITS_TO_TERRITORY = "unitsFromTerritory";
public static final String UNCLAIMED_UNITS = "unclaimedUnits";
public static final String CARDS = "cards";
public static final String CARDS_TRADED = "cards_traded";
public static final String DECK = "deck";
public static final String DEPLOYMENT = "deployment";
public static final String CLAIM_TERRITORY = "claimTerritory";
public static final String CARD_TRADE = "cardTrade";
public static final String ATTACK_PHASE = "attackPhase";
public static final String FORTIFY = "fortify";
public static final String END_GAME = "endGame";
public static final String SET_TURN_ORDER = "setTurnOrder";
public static final int START_PLAYER_ID_INDEX = 0;
public static final int MAX_PLAYERS = 6;
public static final String REINFORCE = "reinforce";
public static final String REINFORCE_UNITS = "reinforceUnits";
public static final String ADD_UNITS = "addUnits";
public static final String CARDS_BEING_TRADED = "cardsBeingTraded";
public static final String TRADE_NUMBER = "tradeNumber";
public static final String ATTACK_TRADE = "attackTrade";
public static final String ATTACK_REINFORCE = "attackReinforce";
public static final String CONTINUOUS_TRADE = "continuousTrade";
public static final Integer MIN_CARDS_IN_ATTACK_TRADE = 4;
public static final Integer MAX_CARDS_IN_ATTACK_TRADE = 6;
public static final String GAME_ENDED = "gameEnded";
public static final String AUTO_CLAIM = "autoClaim";
public static final String AUTO_DEPLOY = "autoDeploy";
public static final Map<String, Object> EMPTYSTATE = ImmutableMap.<String, Object>of();
public static final Map<String, Object> NONEMPTYSTATE = ImmutableMap.<String, Object>of(
"k", "v");
public static final Map<String, Object> EMPTYMAP = ImmutableMap.<String, Object>of();
public static final List<String> EMPTYLISTSTRING = ImmutableList.<String>of();
public static final List<Integer> EMPTYLISTINT = ImmutableList.<Integer>of();
public static final Map<Integer, Integer> EMPTYINTMAP = ImmutableMap.<Integer, Integer>of();
public static final int TOTAL_INITIAL_DICE_ROLL = 3;
public static final Map<String, String> UI_PHASE_MAPPING = ImmutableMap.<String, String>builder()
.put(SET_TURN_ORDER, "Decide Turn Order")
.put(CLAIM_TERRITORY, "Claim Territory")
.put(DEPLOYMENT, "Deploy Units")
.put(CARD_TRADE, "Trade Cards")
.put(ADD_UNITS, "Add units for Reinforcement")
.put(REINFORCE, "Reinforce Territories")
.put(ATTACK_PHASE, "Attack")
.put(ATTACK_TRADE, "Trade Cards in Attack Phase")
.put(ATTACK_REINFORCE, "Reinforce Territory in Attack Phase")
.put(ATTACK_RESULT, "Result of Attack")
.put(ATTACK_OCCUPY, "Occupy new territory")
.put(END_ATTACK, "End of attack")
.put(FORTIFY, "Fortify Territory")
.put(END_GAME, "End of Game")
.put(GAME_ENDED, "End of Game")
.build();
public static List<String> getNewTerritoryNameList(String newTerritoryName,
int totalLinesAvailable) {
String [] newTerritoryNameSplit = newTerritoryName.split(" ");
List<String> newTerritoryNameList = Arrays.asList(newTerritoryNameSplit);
if (newTerritoryNameList.size() > totalLinesAvailable) {
List<String> tempTerritoryNameList = new ArrayList<String>();
int oneSlotSize = newTerritoryNameList.size() / totalLinesAvailable;
int extras = newTerritoryNameList.size() % totalLinesAvailable;
int newTerritoryPointer = 0;
for (int j = 0; j < totalLinesAvailable; ++j) {
StringBuilder singleSlotTerritoryName = new StringBuilder();
for (int i = 0; i < oneSlotSize && newTerritoryPointer < newTerritoryNameList.size();
++i) {
singleSlotTerritoryName.append(newTerritoryNameList.get(newTerritoryPointer++));
singleSlotTerritoryName.append(" ");
}
if (extras > 0) {
singleSlotTerritoryName.append(newTerritoryNameList.get(newTerritoryPointer++));
singleSlotTerritoryName.append(" ");
extras--;
}
singleSlotTerritoryName.deleteCharAt(singleSlotTerritoryName.length() - 1);
tempTerritoryNameList.add(singleSlotTerritoryName.toString());
}
newTerritoryNameList = tempTerritoryNameList;
}
return newTerritoryNameList;
}
/*
* This is a helper method to get risk card value from its ID.
*/
public static String cardIdToString(int cardId) {
checkArgument(cardId >= 0 && cardId <= 43);
int category = cardId % 3;
String categoryString = cardId > 41 ? "W"
: category == 1 ? "I"
: category == 2 ? "C" : "A";
return categoryString + cardId;
}
/*
* This is a helper method which returns a list of RISK cards of given range.
*/
public static List<String> getCardsInRange(int fromInclusive, int toInclusive) {
List<String> keys = Lists.newArrayList();
for (int i = fromInclusive; i <= toInclusive; i++) {
keys.add(RISK_CARD + i);
}
return keys;
}
/*
* Helper method to get list of territory from given range.
*/
public static List<Integer> getTerritoriesInRange(int fromInclusive, int toInclusive) {
List<Integer> listOfTerritories = Lists.newArrayList();
for (int i = fromInclusive; i <= toInclusive; i++) {
listOfTerritories.add(i);
}
return listOfTerritories;
}
public static int getMaxDiceRollsForAttacker(int units) {
if (units < 2) {
return 0;
}
return (units - 1) >= 3 ? 3 : (units - 1);
}
public static int getMaxDiceRollsForDefender(int units) {
if (units < 1) {
return 0;
}
return units >= 2 ? 2 : 1;
}
public static int getMinUnitsToNewTerritory(int remainingUnits) {
if (remainingUnits < 2) {
return 0; //error
}
if (remainingUnits > 3) {
return 3;
}
return remainingUnits - 1;
}
public static int getNewUnits(int territories, List<String> continent) {
int newUnits = territories / 3;
if (newUnits < GameResources.MIN_ALLOCATED_UNITS) {
newUnits = GameResources.MIN_ALLOCATED_UNITS;
}
for (String continentId : continent) {
newUnits += Continent.UNITS_VALUE.get(continentId);
}
return newUnits;
}
//Assumes both map have equal size
public static Map<String, Integer> differenceTerritoryMap(
Map<String, Integer> oldTerritories, Map<String, Integer> newTerritories) {
Map<String, Integer> differenceMap = new HashMap<String, Integer>();
for (Map.Entry<String, Integer> oldEntry : oldTerritories.entrySet()) {
int difference = newTerritories.get(oldEntry.getKey()) - oldEntry.getValue();
if (difference != 0) {
differenceMap.put(oldEntry.getKey(), difference);
}
}
return differenceMap;
}
@SuppressWarnings("unchecked")
public static Map<String, Integer> differenceTerritoryMap(
Map<String, Object> currentPlayerState, RiskState lastPlayerState, String lastMovePlayerId) {
Map<String, Integer> territoryUnitMap =
(Map<String, Integer>) currentPlayerState.get(GameResources.TERRITORY);
Map<String, Integer> oldTerritoryMap = lastPlayerState.getPlayersMap().get(lastMovePlayerId)
.getTerritoryUnitMap();
Map<String, Integer> differenceTerritoryMap =
GameResources.differenceTerritoryMap(oldTerritoryMap, territoryUnitMap);
return differenceTerritoryMap;
}
//Finds the new territory in newTerritories otherwise returns null
public static String findNewTerritory(
Set<String> oldTerritories, Set<String> newTerritories) {
String newTerritory = null;
for (String territory : newTerritories) {
if (!oldTerritories.contains(territory)) {
if (newTerritory == null) {
newTerritory = territory;
} else {
return null;
}
}
}
return newTerritory;
}
public static List<Integer> getDiceRolls(Map<String, Object> lastApiState, String type) {
List<Integer> diceRolls = new ArrayList<Integer>();
boolean rolls = true;
int count = 0;
while (rolls) {
Integer diceRoll = (Integer) lastApiState.get(
type + GameResources.DICE_ROLL + (++count));
if (diceRoll != null) {
diceRolls.add(diceRoll);
} else {
rolls = false;
}
}
return diceRolls;
}
public static List<String> getDiceRollKeys(List<String> playerIds) {
List<String> diceRollList = new ArrayList<String>();
for (String playerId : playerIds) {
for (int i = 0; i < GameResources.TOTAL_INITIAL_DICE_ROLL; i++) {
diceRollList.add(GameResources.DICE_ROLL + "_" + playerId + "_" + i);
}
}
return diceRollList;
}
@SuppressWarnings("unchecked")
public static List<Integer> getTradedCards(List<Operation> operations) {
for (Operation operation : operations) {
if (operation instanceof org.risk.logic.GameApi.Set) {
if (((org.risk.logic.GameApi.Set) operation).getKey()
.equals(GameResources.CARDS_BEING_TRADED)) {
return (List<Integer>) ((org.risk.logic.GameApi.Set) operation).getValue();
}
}
}
return null;
}
public static String getStartPlayerId(List<String> playerIds) {
String startPlayerId = playerIds.get(GameResources.START_PLAYER_ID_INDEX);
if (startPlayerId.equals(GameApi.AI_PLAYER_ID)) {
startPlayerId = playerIds.get((GameResources.START_PLAYER_ID_INDEX + 1) % playerIds.size());
}
return startPlayerId;
}
public static void removeViewer(List<String> playerIds, List<Map<String, Object>> playersInfo) {
playerIds.remove(GameApi.VIEWER_ID);
Iterator<Map<String, Object>> iterator = playersInfo.iterator();
while (iterator.hasNext()) {
if (((String) iterator.next().get(GameApi.PLAYER_ID)).equals(GameApi.VIEWER_ID)) {
iterator.remove();
break;
}
}
}
}
|
|
/**
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.lens.server.query.save;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import javax.ws.rs.core.MultivaluedMap;
import org.apache.lens.api.query.save.ListResponse;
import org.apache.lens.api.query.save.Parameter;
import org.apache.lens.api.query.save.SavedQuery;
import org.apache.lens.server.api.error.LensException;
import org.apache.lens.server.api.query.save.exception.SavedQueryNotFound;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.lang3.StringEscapeUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import lombok.AllArgsConstructor;
import lombok.Data;
public class SavedQueryDao {
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final String VALUE_ALIAS = "value_alias";
private static final String SAVED_QUERY_TABLE_NAME = "saved_query";
private static final String ID_COL_NAME = "id";
private static final String NAME_COL_NAME = "name";
private static final String DESCRIPTION_COL_NAME = "description";
private static final String QUERY_COL_NAME = "query";
private static final String PARAMS_COL_NAME = "params_json";
private static final String CREATED_AT_COL_NAME = "created_at";
private static final String UPDATED_AT_COL_NAME = "updated_at";
private final QueryRunner runner;
private final Dialect dialect;
SavedQueryDao(String dialectClass, QueryRunner runner)
throws LensException {
try {
this.runner = runner;
this.dialect = (Dialect) Class.forName(dialectClass).newInstance();
createSavedQueryTableIfNotExists();
} catch (Exception e) {
throw new LensException("Error initializing saved query dao", e);
}
}
/**
* Creates the saved query table
*
* @throws LensException
*/
public void createSavedQueryTableIfNotExists() throws LensException {
try {
runner.update(dialect.getCreateTableSyntax());
} catch (SQLException e) {
throw new LensException("Cannot create saved query table!", e);
}
}
/**
* Saves the query passed
*
* @param savedQuery
* @return
* @throws LensException
*/
public long saveQuery(SavedQuery savedQuery) throws LensException {
try {
final ECMAEscapedSavedQuery ecmaEscaped = ECMAEscapedSavedQuery.getFor(savedQuery);
runner.update(
"insert into " + SAVED_QUERY_TABLE_NAME + " values (" + dialect.getAutoIncrementId(runner) + ", "
+ "'" + ecmaEscaped.getName() + "'"
+ ", "
+ "'" + ecmaEscaped.getDescription() + "'"
+ ","
+ "'" + ecmaEscaped.getQuery() + "'"
+ ","
+ "'" + ecmaEscaped.getParameters() + "'"
+ ","
+ "now()"
+ ","
+ "now()"
+ ")"
);
return dialect.getLastInsertedID(runner);
} catch (SQLException e) {
throw new LensException("Save query failed !", e);
}
}
/**
* Updates the saved query id with new payload
*
* @param id
* @param savedQuery
* @throws LensException
*/
public void updateQuery(long id, SavedQuery savedQuery) throws LensException {
try {
final ECMAEscapedSavedQuery ecmaEscaped = ECMAEscapedSavedQuery.getFor(savedQuery);
final int rowsUpdated = runner.update(
"update " + SAVED_QUERY_TABLE_NAME +" set "
+ NAME_COL_NAME + " = '" + ecmaEscaped.getName() + "',"
+ DESCRIPTION_COL_NAME + " = '" + ecmaEscaped.getDescription() + "',"
+ QUERY_COL_NAME + " = '" + ecmaEscaped.getQuery() + "',"
+ PARAMS_COL_NAME + " = '" + ecmaEscaped.getParameters() + "',"
+ UPDATED_AT_COL_NAME + " = now() "
+ "where " + ID_COL_NAME + " = " + id
);
if (rowsUpdated == 0) {
throw new SavedQueryNotFound(id);
}
} catch (SQLException e) {
throw new LensException("Update failed for " + id, e);
}
}
/**
* Gets saved query with the given id
*
* @param id
* @return
* @throws LensException
*/
public SavedQuery getSavedQueryByID(long id) throws LensException {
final List<SavedQuery> savedQueries;
try {
savedQueries = runner.query(
"select * from " + SAVED_QUERY_TABLE_NAME + " where " + ID_COL_NAME + " = " + id,
new SavedQueryResultSetHandler()
);
} catch (SQLException e) {
throw new LensException("Get failed for " + id, e);
}
int size = savedQueries.size();
switch (size) {
case 0:
throw new SavedQueryNotFound(id);
case 1:
return savedQueries.get(0);
default:
throw new RuntimeException("More than one obtained for id, Please check the integrity of the data!");
}
}
/**
* Returns a list of saved queries
*
* @param criteria a multivalued map that has the filter criteria
* @param start Displacement from the start of the search result
* @param count Count of number of records required
* @return list of saved queries
* @throws LensException
*/
public ListResponse getList(
MultivaluedMap<String, String> criteria, long start, long count) throws LensException {
final StringBuilder selectQueryBuilder = new StringBuilder("select * from " + SAVED_QUERY_TABLE_NAME);
final Set<String> availableFilterKeys = FILTER_KEYS.keySet();
final Sets.SetView<String> intersection = Sets.intersection(availableFilterKeys, criteria.keySet());
if (intersection.size() > 0) {
final StringBuilder whereClauseBuilder = new StringBuilder(" where ");
final List<String> predicates = Lists.newArrayList();
for (String colName : intersection) {
predicates.add(
FILTER_KEYS.get(colName)
.resolveFilterExpression(
colName,
criteria.getFirst(colName)
)
);
}
Joiner.on(" and ").skipNulls().appendTo(whereClauseBuilder, predicates);
selectQueryBuilder.append(whereClauseBuilder.toString());
}
final String listCountQuery = "select count(*) as " + VALUE_ALIAS
+ " from (" + selectQueryBuilder.toString() + ") tmp_table";
selectQueryBuilder
.append(" limit ")
.append(start)
.append(", ")
.append(count);
final String listQuery = selectQueryBuilder.toString();
try {
return new ListResponse(
start,
runner.query(listCountQuery, new SingleValuedResultHandler()),
runner.query(listQuery, new SavedQueryResultSetHandler())
);
} catch (SQLException e) {
throw new LensException("List query failed!", e);
}
}
/**
* Deletes the saved query with the given id
*
* @param id
* @throws LensException
*/
public void deleteSavedQueryByID(long id) throws LensException {
try {
int rowsDeleted = runner.update(
"delete from " + SAVED_QUERY_TABLE_NAME +" where " + ID_COL_NAME + " = " + id
);
if (rowsDeleted == 0) {
throw new SavedQueryNotFound(id);
} else if (rowsDeleted > 1) {
throw new LensException("Warning! More than one record was deleted", new Throwable());
}
} catch (SQLException e) {
throw new LensException("Delete query failed", e);
}
}
/**
* The interface Dialect.
*/
public interface Dialect {
/**
* The create table syntax for 'this' dialect
* @return
*/
String getCreateTableSyntax();
/**
* Method to get the auto increment id/keyword(null) for the ID column
* @param runner
* @return
* @throws SQLException
*/
Long getAutoIncrementId(QueryRunner runner) throws SQLException;
/**
* Get the last increment id after doing an auto increment
* @param runner
* @return
* @throws SQLException
*/
Long getLastInsertedID(QueryRunner runner) throws SQLException;
}
/**
* MySQL dialect for saved query.
*/
public static class MySQLDialect implements Dialect {
@Override
public String getCreateTableSyntax() {
return "CREATE TABLE IF NOT EXISTS " + SAVED_QUERY_TABLE_NAME + " ("
+ ID_COL_NAME + " int(11) NOT NULL AUTO_INCREMENT,"
+ NAME_COL_NAME + " varchar(255) NOT NULL,"
+ DESCRIPTION_COL_NAME + " varchar(255) DEFAULT NULL,"
+ QUERY_COL_NAME + " longtext,"
+ PARAMS_COL_NAME + " longtext,"
+ CREATED_AT_COL_NAME + " timestamp,"
+ UPDATED_AT_COL_NAME + " timestamp,"
+ " PRIMARY KEY ("+ ID_COL_NAME +")"
+ ")";
}
@Override
public Long getAutoIncrementId(QueryRunner runner) throws SQLException {
return null;
}
@Override
public Long getLastInsertedID(QueryRunner runner) throws SQLException {
return runner.query(
"select last_insert_id() as " + VALUE_ALIAS,
new SingleValuedResultHandler()
);
}
}
/**
* HSQL dialect for saved query (Used with testing).
*/
public static class HSQLDialect implements Dialect {
@Override
public String getCreateTableSyntax() {
return "CREATE TABLE if not exists " + SAVED_QUERY_TABLE_NAME + " ("
+ ID_COL_NAME + " int GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, "
+ NAME_COL_NAME + " varchar(255), "
+ DESCRIPTION_COL_NAME + " varchar(255), "
+ QUERY_COL_NAME + " varchar(255), "
+ PARAMS_COL_NAME + " varchar(255), "
+ CREATED_AT_COL_NAME + " timestamp, "
+ UPDATED_AT_COL_NAME + " timestamp)";
}
@Override
public Long getAutoIncrementId(QueryRunner runner) throws SQLException {
return runner.query("select max(" + ID_COL_NAME + ") as " + VALUE_ALIAS +" from " + SAVED_QUERY_TABLE_NAME
, new SingleValuedResultHandler()) + 1;
}
@Override
public Long getLastInsertedID(QueryRunner runner) throws SQLException {
Long id = runner.query("select max(" + ID_COL_NAME + ") as " + VALUE_ALIAS + " from " + SAVED_QUERY_TABLE_NAME
, new SingleValuedResultHandler());
if (id == 0) {
id++;
}
return id;
}
}
/**
* Result set handler class to get a saved query from result set
*/
public static class SavedQueryResultSetHandler implements ResultSetHandler<List<SavedQuery>> {
@Override
public List<SavedQuery> handle(ResultSet resultSet) throws SQLException {
List<SavedQuery> queries = Lists.newArrayList();
while (resultSet.next()) {
long id = resultSet.getLong(ID_COL_NAME);
final String name = StringEscapeUtils.unescapeEcmaScript(resultSet.getString(NAME_COL_NAME));
final String description = StringEscapeUtils.unescapeEcmaScript(resultSet.getString(DESCRIPTION_COL_NAME));
final String query = StringEscapeUtils.unescapeEcmaScript(resultSet.getString(QUERY_COL_NAME));
final List<Parameter> parameterList;
try {
parameterList = deserializeFrom(
StringEscapeUtils.unescapeEcmaScript(resultSet.getString(PARAMS_COL_NAME))
);
} catch (LensException e) {
throw new SQLException("Cannot deserialize parameters ", e);
}
queries.add(new SavedQuery(
id,
name,
description,
query,
parameterList
));
}
return queries;
}
}
/**
* Result set handler class to get a the last inserted ID from the resultset
*/
public static class SingleValuedResultHandler implements ResultSetHandler<Long> {
@Override
public Long handle(ResultSet resultSet) throws SQLException {
while (resultSet.next()) {
return resultSet.getLong(VALUE_ALIAS);
}
throw new SQLException("For cursor : " + resultSet.getCursorName());
}
}
@AllArgsConstructor
@Data
/**
* This class represents a ECMA escaped version of saved query,
* that can be safely inserted into DB
*/
private static class ECMAEscapedSavedQuery {
private final long id;
private final String name;
private final String description;
private final String query;
private final String parameters;
static ECMAEscapedSavedQuery getFor(SavedQuery savedQuery) throws LensException {
return new ECMAEscapedSavedQuery(
savedQuery.getId(),
StringEscapeUtils.escapeEcmaScript(savedQuery.getName()),
StringEscapeUtils.escapeEcmaScript(savedQuery.getDescription()),
StringEscapeUtils.escapeEcmaScript(savedQuery.getQuery()),
StringEscapeUtils.escapeEcmaScript(serializeParameters(savedQuery))
);
}
}
/**
* The filter data type used in the list api
*/
enum FilterDataType {
STRING {
String resolveFilterExpression(String col, String val) {
return " " + col + " like '%" + val + "%'";
}
},
NUMBER {
String resolveFilterExpression(String col, String val) {
return col + "=" + Long.parseLong(val);
}
},
BOOLEAN {
String resolveFilterExpression(String col, String val) {
return col + "=" + Boolean.parseBoolean(val);
}
};
abstract String resolveFilterExpression(String col, String val);
}
/**
* Map of available filter keys and their data types
* The list api can have filter criteria based on these keys.
*/
private static final ImmutableMap<String, FilterDataType> FILTER_KEYS;
static {
final ImmutableMap.Builder<String, FilterDataType> filterValuesBuilder = ImmutableMap.builder();
filterValuesBuilder.put(NAME_COL_NAME, FilterDataType.STRING);
filterValuesBuilder.put(DESCRIPTION_COL_NAME, FilterDataType.STRING);
filterValuesBuilder.put(QUERY_COL_NAME, FilterDataType.STRING);
filterValuesBuilder.put(ID_COL_NAME, FilterDataType.NUMBER);
FILTER_KEYS = filterValuesBuilder.build();
}
/**
* Serializes the parameters of saved query using jackson
*
* @param savedQuery
* @return
* @throws LensException
*/
private static String serializeParameters(SavedQuery savedQuery) throws LensException {
final String paramsJson;
try {
paramsJson = MAPPER.writeValueAsString(savedQuery.getParameters());
} catch (JsonProcessingException e) {
throw new LensException("Serialization failed for " + savedQuery.getParameters(), e);
}
return paramsJson;
}
/**
* Deserializes the parameters from string using jackson
*
* @param paramsJson
* @return
* @throws LensException
*/
private static List<Parameter> deserializeFrom(String paramsJson) throws LensException {
final Parameter[] parameterArray;
try {
parameterArray = MAPPER.readValue(paramsJson, Parameter[].class);
} catch (IOException e) {
throw new LensException("Failed to deserialize from " + paramsJson, e);
}
return Arrays.asList(parameterArray);
}
}
|
|
/*
* 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.ide.ui;
import com.intellij.ide.IdeBundle;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.components.ExportableApplicationComponent;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.util.xmlb.Accessor;
import com.intellij.util.xmlb.SerializationFilter;
import com.intellij.util.xmlb.XmlSerializerUtil;
import com.intellij.util.xmlb.annotations.Property;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import javax.swing.event.EventListenerList;
import java.awt.*;
import java.io.File;
import java.util.Map;
@State(
name = "UISettings",
storages = {
@Storage(
id ="uilnf",
file = "$APP_CONFIG$/ui.lnf.xml"
)}
)
public class UISettings implements PersistentStateComponent<UISettings>, ExportableApplicationComponent {
private final EventListenerList myListenerList;
@Property(filter = FontFilter.class)
@NonNls
public String FONT_FACE;
@Property(filter = FontFilter.class)
public int FONT_SIZE;
public int RECENT_FILES_LIMIT = 15;
public int EDITOR_TAB_LIMIT = 10;
public boolean ANIMATE_WINDOWS = true;
public int ANIMATION_SPEED = 2000; // Pixels per second
public boolean SHOW_TOOL_WINDOW_NUMBERS = true;
public boolean HIDE_TOOL_STRIPES = false;
public boolean SHOW_MEMORY_INDICATOR = true;
public boolean SHOW_MAIN_TOOLBAR = true;
public boolean SHOW_STATUS_BAR = true;
public boolean SHOW_NAVIGATION_BAR = true;
public boolean ALWAYS_SHOW_WINDOW_BUTTONS = false;
public boolean CYCLE_SCROLLING = true;
public boolean SCROLL_TAB_LAYOUT_IN_EDITOR = false;
public boolean SHOW_CLOSE_BUTTON = true;
public int EDITOR_TAB_PLACEMENT = 1;
public boolean HIDE_KNOWN_EXTENSION_IN_TABS = false;
public boolean SHOW_ICONS_IN_QUICK_NAVIGATION = true;
public boolean CLOSE_NON_MODIFIED_FILES_FIRST = false;
public boolean ACTIVATE_MRU_EDITOR_ON_CLOSE = false;
public boolean ANTIALIASING_IN_EDITOR = true;
public boolean MOVE_MOUSE_ON_DEFAULT_BUTTON = false;
public boolean ENABLE_ALPHA_MODE = false;
public int ALPHA_MODE_DELAY = 1500;
public float ALPHA_MODE_RATIO = 0.5f;
public int MAX_CLIPBOARD_CONTENTS = 5;
public boolean OVERRIDE_NONIDEA_LAF_FONTS = false;
public boolean SHOW_ICONS_IN_MENUS = true; // Only makes sense on MacOS
public boolean DISABLE_MNEMONICS = SystemInfo.isMac; // IDEADEV-33409, should be disabled by default on MacOS
/**
* Defines whether asterisk is shown on modified editor tab or not
*/
public boolean MARK_MODIFIED_TABS_WITH_ASTERISK = false;
/**
* Not tabbed pane
*/
public static final int TABS_NONE = 0;
/** Invoked by reflection */
public UISettings(){
myListenerList=new EventListenerList();
setSystemFontFaceAndSize();
}
public void addUISettingsListener(UISettingsListener listener){
myListenerList.add(UISettingsListener.class,listener);
}
/**
* Notifies all registered listeners that UI settings has been changed.
*/
public void fireUISettingsChanged(){
UISettingsListener[] listeners= myListenerList.getListeners(UISettingsListener.class);
for (UISettingsListener listener : listeners) {
listener.uiSettingsChanged(this);
}
}
public static UISettings getInstance() {
return ApplicationManager.getApplication().getComponent(UISettings.class);
}
public void removeUISettingsListener(UISettingsListener listener){
myListenerList.remove(UISettingsListener.class,listener);
}
private void setDefaultFontSettings(){
FONT_FACE = "Dialog";
FONT_SIZE = 12;
}
private static boolean isValidFont(final Font font){
try {
return
font.canDisplay('a') &&
font.canDisplay('z') &&
font.canDisplay('A') &&
font.canDisplay('Z') &&
font.canDisplay('0') &&
font.canDisplay('1');
}
catch (Exception e) {
// JRE has problems working with the font. Just skip.
return false;
}
}
/**
* Under Win32 it's possible to determine face and size of default fount.
*/
private void setSystemFontFaceAndSize(){
if(FONT_FACE == null || FONT_SIZE <= 0){
if(SystemInfo.isWindows){
//noinspection HardCodedStringLiteral
Font font=(Font)Toolkit.getDefaultToolkit().getDesktopProperty("win.messagebox.font");
if(font != null){
FONT_FACE = font.getName();
FONT_SIZE = font.getSize();
}else{
setDefaultFontSettings();
}
}else{ // UNIXes go here
setDefaultFontSettings();
}
}
}
private static boolean hasDefaultFontSetting(final UISettings settings) {
Font font=(Font)Toolkit.getDefaultToolkit().getDesktopProperty("win.messagebox.font");
return SystemInfo.isWindows && font != null && settings.FONT_FACE.equals(font.getName()) && settings.FONT_SIZE == font.getSize();
}
public UISettings getState() {
return this;
}
public void loadState(UISettings object) {
XmlSerializerUtil.copyBean(object, this);
// Check tab placement in editor
if(
EDITOR_TAB_PLACEMENT != TABS_NONE &&
EDITOR_TAB_PLACEMENT != SwingConstants.TOP&&
EDITOR_TAB_PLACEMENT != SwingConstants.LEFT&&
EDITOR_TAB_PLACEMENT != SwingConstants.BOTTOM&&
EDITOR_TAB_PLACEMENT != SwingConstants.RIGHT
){
EDITOR_TAB_PLACEMENT=SwingConstants.TOP;
}
// Check that alpha ration in in valid range
if(ALPHA_MODE_DELAY<0){
ALPHA_MODE_DELAY=1500;
}
if(ALPHA_MODE_RATIO< 0.0f ||ALPHA_MODE_RATIO>1.0f){
ALPHA_MODE_RATIO=0.5f;
}
setSystemFontFaceAndSize();
// 1. Sometimes system font cannot display standard ASCI symbols. If so we have
// find any other suitable font withing "preferred" fonts first.
boolean fontIsValid = isValidFont(new Font(FONT_FACE, Font.PLAIN, FONT_SIZE));
if(!fontIsValid){
@NonNls final String[] preferredFonts = new String[]{"dialog", "Arial", "Tahoma"};
for (String preferredFont : preferredFonts) {
if (isValidFont(new Font(preferredFont, Font.PLAIN, FONT_SIZE))) {
FONT_FACE = preferredFont;
fontIsValid = true;
break;
}
}
// 2. If all preferred fonts are not valid in current environment
// we have to find first valid font (if any)
if(!fontIsValid){
Font[] fonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts();
for (Font font : fonts) {
if (isValidFont(font)) {
FONT_FACE = font.getName();
break;
}
}
}
}
if (MAX_CLIPBOARD_CONTENTS <= 0) {
MAX_CLIPBOARD_CONTENTS = 5;
}
fireUISettingsChanged();
}
public static class FontFilter implements SerializationFilter {
public boolean accepts(Accessor accessor, Object bean) {
UISettings settings = (UISettings)bean;
return !hasDefaultFontSetting(settings);
}
}
private static final boolean DONT_TOUCH_ALIASING = "true".equalsIgnoreCase(System.getProperty("idea.use.default.antialiasing.in.editor"));
public static void setupAntialiasing(final Graphics g) {
if (DONT_TOUCH_ALIASING) return;
Graphics2D g2d=(Graphics2D)g;
UISettings uiSettings=getInstance();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_OFF);
if(uiSettings.ANTIALIASING_IN_EDITOR) {
Toolkit tk = Toolkit.getDefaultToolkit();
//noinspection HardCodedStringLiteral
Map map = (Map)tk.getDesktopProperty("awt.font.desktophints");
if (map != null) {
if (isRemoteDesktopConnected()) {
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_DEFAULT);
}
else {
g2d.addRenderingHints(map);
}
}
else {
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
}
}
else {
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
}
}
/**
* @return true when Remote Desktop (i.e. Windows RDP) is connected
*/
// TODO[neuro]: move to UIUtil
public static boolean isRemoteDesktopConnected() {
if(System.getProperty("os.name").contains("Windows")) {
final Map map = (Map)Toolkit.getDefaultToolkit().getDesktopProperty("awt.font.desktophints");
return map!= null ? RenderingHints.VALUE_TEXT_ANTIALIAS_DEFAULT.equals(map.get(RenderingHints.KEY_TEXT_ANTIALIASING)) : false;
}
return false;
}
@NotNull
public File[] getExportFiles() {
return new File[]{PathManager.getOptionsFile("ui.lnf")};
}
@NotNull
public String getPresentableName() {
return IdeBundle.message("ui.settings");
}
@NonNls
@NotNull
public String getComponentName() {
return "UISettings";
}
public void initComponent() {
}
public void disposeComponent() {
}
}
|
|
/*
* Copyright 2016 Red Hat, Inc. and/or its affiliates
* and other 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.credential;
import org.keycloak.common.util.reflections.Types;
import org.keycloak.models.CredentialValidationOutput;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.models.UserCredentialManager;
import org.keycloak.models.UserModel;
import org.keycloak.models.cache.CachedUserModel;
import org.keycloak.models.cache.OnUserCache;
import org.keycloak.provider.ProviderFactory;
import org.keycloak.storage.StorageId;
import org.keycloak.storage.UserStorageManager;
import org.keycloak.storage.UserStorageProvider;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
/**
* @author <a href="mailto:[email protected]">Bill Burke</a>
* @version $Revision: 1 $
*/
public class UserCredentialStoreManager implements UserCredentialManager, OnUserCache {
protected KeycloakSession session;
public UserCredentialStoreManager(KeycloakSession session) {
this.session = session;
}
protected UserCredentialStore getStoreForUser(UserModel user) {
if (StorageId.isLocalStorage(user)) {
return (UserCredentialStore)session.userLocalStorage();
} else {
return (UserCredentialStore)session.userFederatedStorage();
}
}
@Override
public void updateCredential(RealmModel realm, UserModel user, CredentialModel cred) {
getStoreForUser(user).updateCredential(realm, user, cred);
}
@Override
public CredentialModel createCredential(RealmModel realm, UserModel user, CredentialModel cred) {
return getStoreForUser(user).createCredential(realm, user, cred);
}
@Override
public boolean removeStoredCredential(RealmModel realm, UserModel user, String id) {
return getStoreForUser(user).removeStoredCredential(realm, user, id);
}
@Override
public CredentialModel getStoredCredentialById(RealmModel realm, UserModel user, String id) {
return getStoreForUser(user).getStoredCredentialById(realm, user, id);
}
@Override
public List<CredentialModel> getStoredCredentials(RealmModel realm, UserModel user) {
return getStoreForUser(user).getStoredCredentials(realm, user);
}
@Override
public List<CredentialModel> getStoredCredentialsByType(RealmModel realm, UserModel user, String type) {
return getStoreForUser(user).getStoredCredentialsByType(realm, user, type);
}
@Override
public CredentialModel getStoredCredentialByNameAndType(RealmModel realm, UserModel user, String name, String type) {
return getStoreForUser(user).getStoredCredentialByNameAndType(realm, user, name, type);
}
@Override
public boolean isValid(RealmModel realm, UserModel user, CredentialInput... inputs) {
return isValid(realm, user, Arrays.asList(inputs));
}
@Override
public boolean isValid(RealmModel realm, UserModel user, List<CredentialInput> inputs) {
List<CredentialInput> toValidate = new LinkedList<>();
toValidate.addAll(inputs);
if (!StorageId.isLocalStorage(user)) {
String providerId = StorageId.resolveProviderId(user);
UserStorageProvider provider = UserStorageManager.getStorageProvider(session, realm, providerId);
if (provider instanceof CredentialInputValidator) {
Iterator<CredentialInput> it = toValidate.iterator();
while (it.hasNext()) {
CredentialInput input = it.next();
CredentialInputValidator validator = (CredentialInputValidator)provider;
if (validator.supportsCredentialType(input.getType()) && validator.isValid(realm, user, input)) {
it.remove();
}
}
}
} else {
if (user.getFederationLink() != null) {
UserStorageProvider provider = UserStorageManager.getStorageProvider(session, realm, user.getFederationLink());
if (provider != null && provider instanceof CredentialInputValidator) {
validate(realm, user, toValidate, ((CredentialInputValidator)provider));
}
}
}
if (toValidate.isEmpty()) return true;
List<CredentialInputValidator> credentialProviders = getCredentialProviders(session, realm, CredentialInputValidator.class);
for (CredentialInputValidator validator : credentialProviders) {
validate(realm, user, toValidate, validator);
}
return toValidate.isEmpty();
}
private void validate(RealmModel realm, UserModel user, List<CredentialInput> toValidate, CredentialInputValidator validator) {
Iterator<CredentialInput> it = toValidate.iterator();
while (it.hasNext()) {
CredentialInput input = it.next();
if (validator.supportsCredentialType(input.getType()) && validator.isValid(realm, user, input)) {
it.remove();
}
}
}
public static <T> List<T> getCredentialProviders(KeycloakSession session, RealmModel realm, Class<T> type) {
List<T> list = new LinkedList<T>();
for (ProviderFactory f : session.getKeycloakSessionFactory().getProviderFactories(CredentialProvider.class)) {
if (!Types.supports(type, f, CredentialProviderFactory.class)) continue;
list.add((T)session.getProvider(CredentialProvider.class, f.getId()));
}
return list;
}
@Override
public void updateCredential(RealmModel realm, UserModel user, CredentialInput input) {
if (!StorageId.isLocalStorage(user)) {
String providerId = StorageId.resolveProviderId(user);
UserStorageProvider provider = UserStorageManager.getStorageProvider(session, realm, providerId);
if (provider instanceof CredentialInputUpdater) {
CredentialInputUpdater updater = (CredentialInputUpdater)provider;
if (updater.supportsCredentialType(input.getType())) {
if (updater.updateCredential(realm, user, input)) return;
}
}
} else {
if (user.getFederationLink() != null) {
UserStorageProvider provider = UserStorageManager.getStorageProvider(session, realm, user.getFederationLink());
if (provider != null && provider instanceof CredentialInputUpdater) {
if (((CredentialInputUpdater)provider).updateCredential(realm, user, input)) return;
}
}
}
List<CredentialInputUpdater> credentialProviders = getCredentialProviders(session, realm, CredentialInputUpdater.class);
for (CredentialInputUpdater updater : credentialProviders) {
if (!updater.supportsCredentialType(input.getType())) continue;
if (updater.updateCredential(realm, user, input)) return;
}
}
@Override
public void disableCredentialType(RealmModel realm, UserModel user, String credentialType) {
if (!StorageId.isLocalStorage(user)) {
String providerId = StorageId.resolveProviderId(user);
UserStorageProvider provider = UserStorageManager.getStorageProvider(session, realm, providerId);
if (provider instanceof CredentialInputUpdater) {
CredentialInputUpdater updater = (CredentialInputUpdater)provider;
if (updater.supportsCredentialType(credentialType)) {
updater.disableCredentialType(realm, user, credentialType);
}
}
} else {
if (user.getFederationLink() != null) {
UserStorageProvider provider = UserStorageManager.getStorageProvider(session, realm, user.getFederationLink());
if (provider != null && provider instanceof CredentialInputUpdater) {
((CredentialInputUpdater)provider).disableCredentialType(realm, user, credentialType);
}
}
}
List<CredentialInputUpdater> credentialProviders = getCredentialProviders(session, realm, CredentialInputUpdater.class);
for (CredentialInputUpdater updater : credentialProviders) {
if (!updater.supportsCredentialType(credentialType)) continue;
updater.disableCredentialType(realm, user, credentialType);
}
}
@Override
public Set<String> getDisableableCredentialTypes(RealmModel realm, UserModel user) {
Set<String> types = new HashSet<>();
if (!StorageId.isLocalStorage(user)) {
String providerId = StorageId.resolveProviderId(user);
UserStorageProvider provider = UserStorageManager.getStorageProvider(session, realm, providerId);
if (provider instanceof CredentialInputUpdater) {
CredentialInputUpdater updater = (CredentialInputUpdater)provider;
types.addAll(updater.getDisableableCredentialTypes(realm, user));
}
} else {
if (user.getFederationLink() != null) {
UserStorageProvider provider = UserStorageManager.getStorageProvider(session, realm, user.getFederationLink());
if (provider != null && provider instanceof CredentialInputUpdater) {
types.addAll(((CredentialInputUpdater)provider).getDisableableCredentialTypes(realm, user));
}
}
}
List<CredentialInputUpdater> credentialProviders = getCredentialProviders(session, realm, CredentialInputUpdater.class);
for (CredentialInputUpdater updater : credentialProviders) {
types.addAll(updater.getDisableableCredentialTypes(realm, user));
}
return types;
}
@Override
public boolean isConfiguredFor(RealmModel realm, UserModel user, String type) {
if (!StorageId.isLocalStorage(user)) {
String providerId = StorageId.resolveProviderId(user);
UserStorageProvider provider = UserStorageManager.getStorageProvider(session, realm, providerId);
if (provider instanceof CredentialInputValidator) {
CredentialInputValidator validator = (CredentialInputValidator)provider;
if (validator.supportsCredentialType(type) && validator.isConfiguredFor(realm, user, type)) {
return true;
}
}
} else {
if (user.getFederationLink() != null) {
UserStorageProvider provider = UserStorageManager.getStorageProvider(session, realm, user.getFederationLink());
if (provider != null && provider instanceof CredentialInputValidator) {
if (((CredentialInputValidator)provider).isConfiguredFor(realm, user, type)) return true;
}
}
}
return isConfiguredLocally(realm, user, type);
}
@Override
public boolean isConfiguredLocally(RealmModel realm, UserModel user, String type) {
List<CredentialInputValidator> credentialProviders = getCredentialProviders(session, realm, CredentialInputValidator.class);
for (CredentialInputValidator validator : credentialProviders) {
if (validator.supportsCredentialType(type) && validator.isConfiguredFor(realm, user, type)) {
return true;
}
}
return false;
}
@Override
public CredentialValidationOutput authenticate(KeycloakSession session, RealmModel realm, CredentialInput input) {
List<CredentialAuthentication> list = UserStorageManager.getStorageProviders(session, realm, CredentialAuthentication.class);
for (CredentialAuthentication auth : list) {
if (auth.supportsCredentialAuthenticationFor(input.getType())) {
CredentialValidationOutput output = auth.authenticate(realm, input);
if (output != null) return output;
}
}
list = getCredentialProviders(session, realm, CredentialAuthentication.class);
for (CredentialAuthentication auth : list) {
if (auth.supportsCredentialAuthenticationFor(input.getType())) {
CredentialValidationOutput output = auth.authenticate(realm, input);
if (output != null) return output;
}
}
return null;
}
@Override
public void onCache(RealmModel realm, CachedUserModel user, UserModel delegate) {
List<OnUserCache> credentialProviders = getCredentialProviders(session, realm, OnUserCache.class);
for (OnUserCache validator : credentialProviders) {
validator.onCache(realm, user, delegate);
}
}
@Override
public void close() {
}
}
|
|
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/*
* This code was generated by https://code.google.com/p/google-apis-client-generator/
* (build: 2015-11-16 19:10:01 UTC)
* on 2015-11-19 at 17:34:48 UTC
* Modify at your own risk.
*/
package com.google.api.services.discovery;
/**
* Service definition for Discovery (v1).
*
* <p>
* Lets you discover information about other Google APIs, such as what APIs are available, the resource and method details for each API.
* </p>
*
* <p>
* For more information about this service, see the
* <a href="https://developers.google.com/discovery/" target="_blank">API Documentation</a>
* </p>
*
* <p>
* This service uses {@link DiscoveryRequestInitializer} to initialize global parameters via its
* {@link Builder}.
* </p>
*
* @since 1.3
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public class Discovery extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient {
// Note: Leave this static initializer at the top of the file.
static {
com.google.api.client.util.Preconditions.checkState(
com.google.api.client.googleapis.GoogleUtils.MAJOR_VERSION == 1 &&
com.google.api.client.googleapis.GoogleUtils.MINOR_VERSION >= 15,
"You are currently running with version %s of google-api-client. " +
"You need at least version 1.15 of google-api-client to run version " +
"1.20.0 of the APIs Discovery Service library.", com.google.api.client.googleapis.GoogleUtils.VERSION);
}
/**
* The default encoded root URL of the service. This is determined when the library is generated
* and normally should not be changed.
*
* @since 1.7
*/
public static final String DEFAULT_ROOT_URL = "https://webapis-discovery.appspot.com/_ah/api/";
/**
* The default encoded service path of the service. This is determined when the library is
* generated and normally should not be changed.
*
* @since 1.7
*/
public static final String DEFAULT_SERVICE_PATH = "discovery/v1/";
/**
* The default encoded base URL of the service. This is determined when the library is generated
* and normally should not be changed.
*/
public static final String DEFAULT_BASE_URL = DEFAULT_ROOT_URL + DEFAULT_SERVICE_PATH;
/**
* Constructor.
*
* <p>
* Use {@link Builder} if you need to specify any of the optional parameters.
* </p>
*
* @param transport HTTP transport, which should normally be:
* <ul>
* <li>Google App Engine:
* {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}</li>
* <li>Android: {@code newCompatibleTransport} from
* {@code com.google.api.client.extensions.android.http.AndroidHttp}</li>
* <li>Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()}
* </li>
* </ul>
* @param jsonFactory JSON factory, which may be:
* <ul>
* <li>Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}</li>
* <li>Google GSON: {@code com.google.api.client.json.gson.GsonFactory}</li>
* <li>Android Honeycomb or higher:
* {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}</li>
* </ul>
* @param httpRequestInitializer HTTP request initializer or {@code null} for none
* @since 1.7
*/
public Discovery(com.google.api.client.http.HttpTransport transport, com.google.api.client.json.JsonFactory jsonFactory,
com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) {
this(new Builder(transport, jsonFactory, httpRequestInitializer));
}
/**
* @param builder builder
*/
Discovery(Builder builder) {
super(builder);
}
@Override
protected void initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest<?> httpClientRequest) throws java.io.IOException {
super.initialize(httpClientRequest);
}
/**
* An accessor for creating requests from the Apis collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code Discovery discovery = new Discovery(...);}
* {@code Discovery.Apis.List request = discovery.apis().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public Apis apis() {
return new Apis();
}
/**
* The "apis" collection of methods.
*/
public class Apis {
/**
* Generates the API directory from a list of API configurations.
*
* Create a request for the method "apis.generateDirectory".
*
* This request holds the parameters needed by the discovery server. After setting any optional
* parameters, call the {@link GenerateDirectory#execute()} method to invoke the remote operation.
*
* @param content the {@link com.google.api.services.discovery.model.ApiConfigs}
* @return the request
*/
public GenerateDirectory generateDirectory(com.google.api.services.discovery.model.ApiConfigs content) throws java.io.IOException {
GenerateDirectory result = new GenerateDirectory(content);
initialize(result);
return result;
}
public class GenerateDirectory extends DiscoveryRequest<com.google.api.services.discovery.model.DirectoryList> {
private static final String REST_PATH = "apis/generate/directory";
/**
* Generates the API directory from a list of API configurations.
*
* Create a request for the method "apis.generateDirectory".
*
* This request holds the parameters needed by the the discovery server. After setting any
* optional parameters, call the {@link GenerateDirectory#execute()} method to invoke the remote
* operation. <p> {@link GenerateDirectory#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)}
* must be called to initialize this instance immediately after invoking the constructor.</p>
*
* @param content the {@link com.google.api.services.discovery.model.ApiConfigs}
* @since 1.13
*/
protected GenerateDirectory(com.google.api.services.discovery.model.ApiConfigs content) {
super(Discovery.this, "POST", REST_PATH, content, com.google.api.services.discovery.model.DirectoryList.class);
}
@Override
public GenerateDirectory setAlt(java.lang.String alt) {
return (GenerateDirectory) super.setAlt(alt);
}
@Override
public GenerateDirectory setFields(java.lang.String fields) {
return (GenerateDirectory) super.setFields(fields);
}
@Override
public GenerateDirectory setKey(java.lang.String key) {
return (GenerateDirectory) super.setKey(key);
}
@Override
public GenerateDirectory setOauthToken(java.lang.String oauthToken) {
return (GenerateDirectory) super.setOauthToken(oauthToken);
}
@Override
public GenerateDirectory setPrettyPrint(java.lang.Boolean prettyPrint) {
return (GenerateDirectory) super.setPrettyPrint(prettyPrint);
}
@Override
public GenerateDirectory setQuotaUser(java.lang.String quotaUser) {
return (GenerateDirectory) super.setQuotaUser(quotaUser);
}
@Override
public GenerateDirectory setUserIp(java.lang.String userIp) {
return (GenerateDirectory) super.setUserIp(userIp);
}
@Override
public GenerateDirectory set(String parameterName, Object value) {
return (GenerateDirectory) super.set(parameterName, value);
}
}
/**
* Generates the Discovery Document of an API given its configuration.
*
* Create a request for the method "apis.generateRest".
*
* This request holds the parameters needed by the discovery server. After setting any optional
* parameters, call the {@link GenerateRest#execute()} method to invoke the remote operation.
*
* @param content the {@link com.google.api.services.discovery.model.ApiConfig}
* @return the request
*/
public GenerateRest generateRest(com.google.api.services.discovery.model.ApiConfig content) throws java.io.IOException {
GenerateRest result = new GenerateRest(content);
initialize(result);
return result;
}
public class GenerateRest extends DiscoveryRequest<com.google.api.services.discovery.model.RestDescription> {
private static final String REST_PATH = "apis/generate/rest";
/**
* Generates the Discovery Document of an API given its configuration.
*
* Create a request for the method "apis.generateRest".
*
* This request holds the parameters needed by the the discovery server. After setting any
* optional parameters, call the {@link GenerateRest#execute()} method to invoke the remote
* operation. <p> {@link
* GenerateRest#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)}
* must be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param content the {@link com.google.api.services.discovery.model.ApiConfig}
* @since 1.13
*/
protected GenerateRest(com.google.api.services.discovery.model.ApiConfig content) {
super(Discovery.this, "POST", REST_PATH, content, com.google.api.services.discovery.model.RestDescription.class);
}
@Override
public GenerateRest setAlt(java.lang.String alt) {
return (GenerateRest) super.setAlt(alt);
}
@Override
public GenerateRest setFields(java.lang.String fields) {
return (GenerateRest) super.setFields(fields);
}
@Override
public GenerateRest setKey(java.lang.String key) {
return (GenerateRest) super.setKey(key);
}
@Override
public GenerateRest setOauthToken(java.lang.String oauthToken) {
return (GenerateRest) super.setOauthToken(oauthToken);
}
@Override
public GenerateRest setPrettyPrint(java.lang.Boolean prettyPrint) {
return (GenerateRest) super.setPrettyPrint(prettyPrint);
}
@Override
public GenerateRest setQuotaUser(java.lang.String quotaUser) {
return (GenerateRest) super.setQuotaUser(quotaUser);
}
@Override
public GenerateRest setUserIp(java.lang.String userIp) {
return (GenerateRest) super.setUserIp(userIp);
}
@Override
public GenerateRest set(String parameterName, Object value) {
return (GenerateRest) super.set(parameterName, value);
}
}
/**
* Retrieve the description of a particular version of an api.
*
* Create a request for the method "apis.getRest".
*
* This request holds the parameters needed by the discovery server. After setting any optional
* parameters, call the {@link GetRest#execute()} method to invoke the remote operation.
*
* @param api The name of the API.
* @param version The version of the API.
* @return the request
*/
public GetRest getRest(java.lang.String api, java.lang.String version) throws java.io.IOException {
GetRest result = new GetRest(api, version);
initialize(result);
return result;
}
public class GetRest extends DiscoveryRequest<com.google.api.services.discovery.model.RestDescription> {
private static final String REST_PATH = "apis/{api}/{version}/rest";
/**
* Retrieve the description of a particular version of an api.
*
* Create a request for the method "apis.getRest".
*
* This request holds the parameters needed by the the discovery server. After setting any
* optional parameters, call the {@link GetRest#execute()} method to invoke the remote operation.
* <p> {@link
* GetRest#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must
* be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param api The name of the API.
* @param version The version of the API.
* @since 1.13
*/
protected GetRest(java.lang.String api, java.lang.String version) {
super(Discovery.this, "GET", REST_PATH, null, com.google.api.services.discovery.model.RestDescription.class);
this.api = com.google.api.client.util.Preconditions.checkNotNull(api, "Required parameter api must be specified.");
this.version = com.google.api.client.util.Preconditions.checkNotNull(version, "Required parameter version must be specified.");
}
@Override
public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException {
return super.executeUsingHead();
}
@Override
public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException {
return super.buildHttpRequestUsingHead();
}
@Override
public GetRest setAlt(java.lang.String alt) {
return (GetRest) super.setAlt(alt);
}
@Override
public GetRest setFields(java.lang.String fields) {
return (GetRest) super.setFields(fields);
}
@Override
public GetRest setKey(java.lang.String key) {
return (GetRest) super.setKey(key);
}
@Override
public GetRest setOauthToken(java.lang.String oauthToken) {
return (GetRest) super.setOauthToken(oauthToken);
}
@Override
public GetRest setPrettyPrint(java.lang.Boolean prettyPrint) {
return (GetRest) super.setPrettyPrint(prettyPrint);
}
@Override
public GetRest setQuotaUser(java.lang.String quotaUser) {
return (GetRest) super.setQuotaUser(quotaUser);
}
@Override
public GetRest setUserIp(java.lang.String userIp) {
return (GetRest) super.setUserIp(userIp);
}
/** The name of the API. */
@com.google.api.client.util.Key
private java.lang.String api;
/** The name of the API.
*/
public java.lang.String getApi() {
return api;
}
/** The name of the API. */
public GetRest setApi(java.lang.String api) {
this.api = api;
return this;
}
/** The version of the API. */
@com.google.api.client.util.Key
private java.lang.String version;
/** The version of the API.
*/
public java.lang.String getVersion() {
return version;
}
/** The version of the API. */
public GetRest setVersion(java.lang.String version) {
this.version = version;
return this;
}
@Override
public GetRest set(String parameterName, Object value) {
return (GetRest) super.set(parameterName, value);
}
}
/**
* Retrieve the list of APIs supported at this endpoint.
*
* Create a request for the method "apis.list".
*
* This request holds the parameters needed by the discovery server. After setting any optional
* parameters, call the {@link List#execute()} method to invoke the remote operation.
*
* @return the request
*/
public List list() throws java.io.IOException {
List result = new List();
initialize(result);
return result;
}
public class List extends DiscoveryRequest<com.google.api.services.discovery.model.DirectoryList> {
private static final String REST_PATH = "apis";
/**
* Retrieve the list of APIs supported at this endpoint.
*
* Create a request for the method "apis.list".
*
* This request holds the parameters needed by the the discovery server. After setting any
* optional parameters, call the {@link List#execute()} method to invoke the remote operation. <p>
* {@link List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)}
* must be called to initialize this instance immediately after invoking the constructor. </p>
*
* @since 1.13
*/
protected List() {
super(Discovery.this, "GET", REST_PATH, null, com.google.api.services.discovery.model.DirectoryList.class);
}
@Override
public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException {
return super.executeUsingHead();
}
@Override
public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException {
return super.buildHttpRequestUsingHead();
}
@Override
public List setAlt(java.lang.String alt) {
return (List) super.setAlt(alt);
}
@Override
public List setFields(java.lang.String fields) {
return (List) super.setFields(fields);
}
@Override
public List setKey(java.lang.String key) {
return (List) super.setKey(key);
}
@Override
public List setOauthToken(java.lang.String oauthToken) {
return (List) super.setOauthToken(oauthToken);
}
@Override
public List setPrettyPrint(java.lang.Boolean prettyPrint) {
return (List) super.setPrettyPrint(prettyPrint);
}
@Override
public List setQuotaUser(java.lang.String quotaUser) {
return (List) super.setQuotaUser(quotaUser);
}
@Override
public List setUserIp(java.lang.String userIp) {
return (List) super.setUserIp(userIp);
}
/** Only include APIs with the given name. */
@com.google.api.client.util.Key
private java.lang.String name;
/** Only include APIs with the given name.
*/
public java.lang.String getName() {
return name;
}
/** Only include APIs with the given name. */
public List setName(java.lang.String name) {
this.name = name;
return this;
}
/** Return only the preferred version of an API. */
@com.google.api.client.util.Key
private java.lang.Boolean preferred;
/** Return only the preferred version of an API. [default: false]
*/
public java.lang.Boolean getPreferred() {
return preferred;
}
/** Return only the preferred version of an API. */
public List setPreferred(java.lang.Boolean preferred) {
this.preferred = preferred;
return this;
}
/**
* Convenience method that returns only {@link Boolean#TRUE} or {@link Boolean#FALSE}.
*
* <p>
* Boolean properties can have four possible values:
* {@code null}, {@link com.google.api.client.util.Data#NULL_BOOLEAN}, {@link Boolean#TRUE}
* or {@link Boolean#FALSE}.
* </p>
*
* <p>
* This method returns {@link Boolean#TRUE} if the default of the property is {@link Boolean#TRUE}
* and it is {@code null} or {@link com.google.api.client.util.Data#NULL_BOOLEAN}.
* {@link Boolean#FALSE} is returned if the default of the property is {@link Boolean#FALSE} and
* it is {@code null} or {@link com.google.api.client.util.Data#NULL_BOOLEAN}.
* </p>
*
* <p>
* Return only the preferred version of an API.
* </p>
*/
public boolean isPreferred() {
if (preferred == null || preferred == com.google.api.client.util.Data.NULL_BOOLEAN) {
return false;
}
return preferred;
}
@Override
public List set(String parameterName, Object value) {
return (List) super.set(parameterName, value);
}
}
}
/**
* Builder for {@link Discovery}.
*
* <p>
* Implementation is not thread-safe.
* </p>
*
* @since 1.3.0
*/
public static final class Builder extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient.Builder {
/**
* Returns an instance of a new builder.
*
* @param transport HTTP transport, which should normally be:
* <ul>
* <li>Google App Engine:
* {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}</li>
* <li>Android: {@code newCompatibleTransport} from
* {@code com.google.api.client.extensions.android.http.AndroidHttp}</li>
* <li>Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()}
* </li>
* </ul>
* @param jsonFactory JSON factory, which may be:
* <ul>
* <li>Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}</li>
* <li>Google GSON: {@code com.google.api.client.json.gson.GsonFactory}</li>
* <li>Android Honeycomb or higher:
* {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}</li>
* </ul>
* @param httpRequestInitializer HTTP request initializer or {@code null} for none
* @since 1.7
*/
public Builder(com.google.api.client.http.HttpTransport transport, com.google.api.client.json.JsonFactory jsonFactory,
com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) {
super(
transport,
jsonFactory,
DEFAULT_ROOT_URL,
DEFAULT_SERVICE_PATH,
httpRequestInitializer,
false);
}
/** Builds a new instance of {@link Discovery}. */
@Override
public Discovery build() {
return new Discovery(this);
}
@Override
public Builder setRootUrl(String rootUrl) {
return (Builder) super.setRootUrl(rootUrl);
}
@Override
public Builder setServicePath(String servicePath) {
return (Builder) super.setServicePath(servicePath);
}
@Override
public Builder setHttpRequestInitializer(com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) {
return (Builder) super.setHttpRequestInitializer(httpRequestInitializer);
}
@Override
public Builder setApplicationName(String applicationName) {
return (Builder) super.setApplicationName(applicationName);
}
@Override
public Builder setSuppressPatternChecks(boolean suppressPatternChecks) {
return (Builder) super.setSuppressPatternChecks(suppressPatternChecks);
}
@Override
public Builder setSuppressRequiredParameterChecks(boolean suppressRequiredParameterChecks) {
return (Builder) super.setSuppressRequiredParameterChecks(suppressRequiredParameterChecks);
}
@Override
public Builder setSuppressAllChecks(boolean suppressAllChecks) {
return (Builder) super.setSuppressAllChecks(suppressAllChecks);
}
/**
* Set the {@link DiscoveryRequestInitializer}.
*
* @since 1.12
*/
public Builder setDiscoveryRequestInitializer(
DiscoveryRequestInitializer discoveryRequestInitializer) {
return (Builder) super.setGoogleClientRequestInitializer(discoveryRequestInitializer);
}
@Override
public Builder setGoogleClientRequestInitializer(
com.google.api.client.googleapis.services.GoogleClientRequestInitializer googleClientRequestInitializer) {
return (Builder) super.setGoogleClientRequestInitializer(googleClientRequestInitializer);
}
}
}
|
|
/*
* MIT License
*
* Copyright (c) 2016 Kartik Sharma
*
* 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.crazyhitty.chdev.ks.predator.ui.activities;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.Window;
import com.crazyhitty.chdev.ks.predator.BuildConfig;
import com.crazyhitty.chdev.ks.predator.R;
import com.crazyhitty.chdev.ks.predator.data.PredatorSharedPreferences;
import com.crazyhitty.chdev.ks.predator.receivers.NetworkBroadcastReceiver;
import com.crazyhitty.chdev.ks.predator.ui.base.BaseAppCompatActivity;
import com.crazyhitty.chdev.ks.predator.ui.fragments.CollectionFragment;
import com.crazyhitty.chdev.ks.predator.ui.fragments.PostsFragment;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Author: Kartik Sharma
* Email Id: [email protected]
* Created: 12/24/2016 7:32 PM
* Description: This activity holds a navigation menu as well as acts as a main container for mostly
* the entire app.
*/
public class DashboardActivity extends BaseAppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private static final String TAG = "DashboardActivity";
@BindView(R.id.toolbar)
Toolbar toolbar;
@BindView(R.id.drawer_layout_dashboard)
DrawerLayout drawerLayoutDashboard;
@BindView(R.id.navigation_view_dashboard)
NavigationView navigationView;
private NetworkBroadcastReceiver mNetworkBroadcastReceiver;
public static void startActivity(@NonNull Context context) {
Intent intent = new Intent(context, DashboardActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
/**
* Start this activity with any extra intent flags
*
* @param context Current context of the application
* @param flags Intent flags
*/
public static void startActivity(@NonNull Context context, int flags) {
Intent intent = new Intent(context, DashboardActivity.class);
intent.setFlags(flags);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
applyTheme();
setContentView(R.layout.activity_dashboard);
ButterKnife.bind(this);
initNetworkBroadcastReceiver();
initToolbar();
initDrawer();
showChangelog();
// Only set fragment when saved instance is null.
// This is done inorder to stop reloading fragment on orientation changes.
if (savedInstanceState == null) {
initFragment();
}
}
private void applyTheme() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.setStatusBarColor(ContextCompat.getColor(getApplicationContext(), android.R.color.transparent));
}
}
/**
* Initialize network braodcast receiver.
*/
private void initNetworkBroadcastReceiver() {
mNetworkBroadcastReceiver = new NetworkBroadcastReceiver();
registerReceiver(mNetworkBroadcastReceiver,
new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
/**
* Initialize toolbar.
*/
private void initToolbar() {
setSupportActionBar(toolbar);
toolbar.setTitle(R.string.app_name);
}
/**
* Initialize navigation drawer.
*/
private void initDrawer() {
// Set up the hamburger icon which will open/close nav drawer
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this,
drawerLayoutDashboard,
toolbar,
R.string.dashboard_open_nav_drawer,
R.string.dashboard_close_nav_drawer);
drawerLayoutDashboard.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
// Set up navigation drawer item clicks
navigationView.setNavigationItemSelectedListener(this);
}
/**
* Initialize fragment.
*/
private void initFragment() {
setFragment(R.id.frame_layout_dashboard_container,
PostsFragment.newInstance(),
false);
}
private void showChangelog() {
if (BuildConfig.VERSION_CODE >
PredatorSharedPreferences.getCurrentAppVersionCode(getApplicationContext()) &&
PredatorSharedPreferences.getCurrentAppVersionCode(getApplicationContext()) != 0) {
// The available version code is higher than the stored version code. This would only
// show when an app is updated.
openChangelog();
}
// Save the current version so that we can check it again in future.
PredatorSharedPreferences.setCurrentAppVersionCode(getApplicationContext(),
BuildConfig.VERSION_CODE);
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
drawerLayoutDashboard.closeDrawer(GravityCompat.START);
switch (item.getItemId()) {
case R.id.nav_posts:
setFragmentOnDashboard(PostsFragment.newInstance());
return true;
case R.id.nav_collections:
setFragmentOnDashboard(CollectionFragment.newInstance());
return true;
// TODO: Implement after bookmarks functionality is completed.
/*case R.id.nav_bookmarks:
return true;*/
// TODO: Implement after my profile functionality is completed.
/*case R.id.nav_my_profile:
return false;*/
case R.id.nav_settings:
// Start activity after a delay
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
SettingsActivity.startActivity(DashboardActivity.this, false);
}
}, 300);
return false;
case R.id.nav_about:
// Start activity after a delay
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
AboutActivity.startActivity(getApplicationContext());
}
}, 300);
return false;
// TODO: Implement after donate(in app purchases) functionality is completed.
/*case R.id.nav_donate:
return false;*/
case R.id.nav_rating:
// Start after a delay
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
rateApp();
}
}, 300);
return false;
case R.id.nav_spread_love:
// Start after a delay
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
shareApp();
}
}, 300);
return false;
default:
return false;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mNetworkBroadcastReceiver);
}
@Override
public void onBackPressed() {
if (drawerLayoutDashboard.isDrawerOpen(GravityCompat.START)) {
drawerLayoutDashboard.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
private void setFragmentOnDashboard(final Fragment fragment) {
if (!isFragmentVisible(fragment)) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
setFragment(R.id.frame_layout_dashboard_container,
fragment,
false);
}
}, 300);
}
}
}
|
|
/*
* #%L
* utils-assertor
* %%
* Copyright (C) 2016 - 2018 Gilles Landel
* %%
* 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.
* #L%
*/
package fr.landel.utils.assertor;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.util.regex.Pattern;
import org.junit.Test;
import fr.landel.utils.assertor.utils.AssertorCharSequence;
/**
* Check {@link AssertorCharSequence}
*
* @since Dec 10, 2015
* @author Gilles Landel
*
*/
public class AssertorCharSequenceTest extends AbstractTest {
/**
* Test method for {@link AssertorCharSequence#AssertorCharSequence()} .
*/
@Test
public void testConstructor() {
assertNotNull(new AssertorCharSequence());
}
/**
* Test method for {@link AssertorCharSequence#hasLength(int)} .
*/
@Test
public void testHasLength() {
assertTrue(Assertor.that("text").hasLength(4).isOK());
assertFalse(Assertor.that("text").hasLength(3).isOK());
assertFalse(Assertor.that("text").hasLength(-1).isOK());
assertFalse(Assertor.that((String) null).hasLength(1).isOK());
assertTrue(Assertor.that("text").hasLengthLT(5).isOK());
assertFalse(Assertor.that("text").hasLengthLT(4).isOK());
assertFalse(Assertor.that("text").hasLengthLT(3).isOK());
assertFalse(Assertor.that("text").hasLengthLT(-1).isOK());
assertFalse(Assertor.that((String) null).hasLengthLT(1).isOK());
assertTrue(Assertor.that("text").hasLengthLTE(5).isOK());
assertTrue(Assertor.that("text").hasLengthLTE(4).isOK());
assertFalse(Assertor.that("text").hasLengthLTE(3).isOK());
assertFalse(Assertor.that("text").hasLengthLTE(-1).isOK());
assertFalse(Assertor.that((String) null).hasLengthLTE(1).isOK());
assertFalse(Assertor.that("text").hasLengthGT(5).isOK());
assertFalse(Assertor.that("text").hasLengthGT(4).isOK());
assertTrue(Assertor.that("text").hasLengthGT(3).isOK());
assertFalse(Assertor.that("text").hasLengthGT(-1).isOK());
assertFalse(Assertor.that((String) null).hasLengthGT(1).isOK());
assertFalse(Assertor.that("text").hasLengthGTE(5).isOK());
assertTrue(Assertor.that("text").hasLengthGTE(4).isOK());
assertTrue(Assertor.that("text").hasLengthGTE(3).isOK());
assertFalse(Assertor.that("text").hasLengthGTE(-1).isOK());
assertFalse(Assertor.that((String) null).hasLengthGTE(1).isOK());
}
/**
* Test method for {@link AssertorCharSequence#hasLength(int)} .
*/
@Test
public void testHasNotLength() {
assertFalse(Assertor.that("text").not().hasLength(4).isOK());
assertTrue(Assertor.that("text").not().hasLength(3).isOK());
assertFalse(Assertor.that("text").not().hasLength(-1).isOK());
assertFalse(Assertor.that((String) null).not().hasLength(1).isOK());
}
/**
* Test method for
* {@link AssertorCharSequence#isNotEmpty(String, String, Object...)} .
*/
@Test
public void testIsNotEmptyOKStringString() {
try {
Assertor.that("a").isNotEmpty().orElseThrow("empty string");
} catch (IllegalArgumentException e) {
fail("The test isn't correct");
}
}
/**
* Test method for
* {@link AssertorCharSequence#isNotEmpty(String, String, Object...)} .
*/
@Test(expected = IllegalArgumentException.class)
public void testIsNotEmptyKOStringString() {
Assertor.that("").isNotEmpty().orElseThrow("empty string");
}
/**
* Test method for
* {@link AssertorCharSequence#isNotEmpty(String, String, Object...)} .
*/
@Test(expected = IllegalArgumentException.class)
public void testIsNotEmptyKONot() {
Assertor.that("z").not().isNotEmpty().orElseThrow("empty string");
}
/**
* Test method for
* {@link AssertorCharSequence#isNotEmpty(String, String, Object...)} .
*/
@Test(expected = IllegalArgumentException.class)
public void testIsNotEmptyKO2StringString() {
Assertor.that((String) null).isNotEmpty().orElseThrow("empty string");
}
/**
* Test method for {@link AssertorCharSequence#isNotEmpty(java.lang.String)}
* .
*/
@Test
public void testIsNotEmptyOKString() {
try {
Assertor.that("z").isNotEmpty().orElseThrow();
} catch (IllegalArgumentException e) {
fail("The test isn't correct");
}
}
/**
* Test method for {@link AssertorCharSequence#isNotEmpty(java.lang.String)}
* .
*/
@Test(expected = IllegalArgumentException.class)
public void testIsNotEmptyKOString() {
Assertor.that("").isNotEmpty().orElseThrow();
}
/**
* Test method for {@link AssertorCharSequence#isNotEmpty(java.lang.String)}
* .
*/
@Test(expected = IllegalArgumentException.class)
public void testIsNotEmptyKO2String() {
Assertor.that((String) null).isNotEmpty().orElseThrow();
}
/**
* Test method for
* {@link AssertorCharSequence#isEmpty(String, String, Object...)} .
*/
@Test
public void testIsEmptyOKStringString() {
try {
Assertor.that((String) null).isEmpty().orElseThrow("not empty or null");
Assertor.that("").isEmpty().orElseThrow("not empty");
} catch (IllegalArgumentException e) {
fail("The test isn't correct");
}
}
/**
* Test method for
* {@link AssertorCharSequence#isEmpty(String, String, Object...)} .
*/
@Test(expected = IllegalArgumentException.class)
public void testIsEmptyKOStringString() {
Assertor.that("r").isEmpty().orElseThrow("not empty");
}
/**
* Test method for {@link AssertorCharSequence#isEmpty(java.lang.String)} .
*/
@Test
public void testIsEmptyOKString() {
try {
Assertor.that((String) null).isEmpty().orElseThrow();
Assertor.that("").isEmpty().orElseThrow();
} catch (IllegalArgumentException e) {
fail("The test isn't correct");
}
}
/**
* Test method for {@link AssertorCharSequence#isEmpty(java.lang.String)} .
*/
@Test(expected = IllegalArgumentException.class)
public void testIsEmptyKOString() {
Assertor.that("e").isEmpty().orElseThrow();
}
/**
* Test method for
* {@link AssertorCharSequence#isNotBlank(String, String, Object...)} .
*/
@Test
public void testIsNotBlankOKStringString() {
try {
Assertor.that(" \t sds ").isNotBlank().orElseThrow("blank");
} catch (IllegalArgumentException e) {
fail("The test isn't correct");
}
}
/**
* Test method for
* {@link AssertorCharSequence#isNotBlank(String, String, Object...)} .
*/
@Test(expected = IllegalArgumentException.class)
public void testIsNotBlankKOStringString() {
Assertor.that(" \t ").isNotBlank().orElseThrow("blank");
}
/**
* Test method for {@link AssertorCharSequence#isNotBlank(java.lang.String)}
* .
*/
@Test
public void testIsNotBlankOKString() {
try {
Assertor.that(" \t e ").isNotBlank().orElseThrow();
} catch (IllegalArgumentException e) {
fail("The test isn't correct");
}
}
/**
* Test method for {@link AssertorCharSequence#isNotBlank(java.lang.String)}
* .
*/
@Test(expected = IllegalArgumentException.class)
public void testIsNotBlankKOString() {
Assertor.that(" \t ").isNotBlank().orElseThrow();
}
/**
* Test method for {@link AssertorCharSequence#isNotBlank(java.lang.String)}
* .
*/
@Test(expected = IllegalArgumentException.class)
public void testIsNotBlankKOnot() {
Assertor.that(" \t a").not().isNotBlank().orElseThrow();
}
/**
* Test method for
* {@link AssertorCharSequence#isBlank(String, String, Object...)} .
*/
@Test
public void testIsBlankOKStringString() {
try {
Assertor.that(" \t ").isBlank().orElseThrow("not blank");
} catch (IllegalArgumentException e) {
fail("The test isn't correct");
}
}
/**
* Test method for
* {@link AssertorCharSequence#isBlank(String, String, Object...)} .
*/
@Test(expected = IllegalArgumentException.class)
public void testIsBlankKOStringString() {
Assertor.that(" \t d ").isBlank().orElseThrow("not blank");
}
/**
* Test method for {@link AssertorCharSequence#isBlank(java.lang.String)} .
*/
@Test
public void testIsBlankOKString() {
try {
Assertor.that(" \t ").isBlank().orElseThrow();
} catch (IllegalArgumentException e) {
fail("The test isn't correct");
}
}
/**
* Test method for {@link AssertorCharSequence#isBlank(java.lang.String)} .
*/
@Test(expected = IllegalArgumentException.class)
public void testIsBlankKOString() {
Assertor.that(" j ").isBlank().orElseThrow();
}
/**
* Test method for
* {@link AssertorCharSequence#isEqual(StepAssertor, CharSequence, boolean, boolean, Message)}
* .
*/
@Test
public void testIsEqual() {
assertTrue(Assertor.that("test").isEqual("test").isOK());
assertFalse(Assertor.that("test").isEqual("Test").isOK());
assertFalse(Assertor.that("te\r\nst").isEqual("tes\nt").isOK());
assertFalse(Assertor.that("te\r\nst").isEqual("Tes\nt").isOK());
assertTrue(Assertor.that("test").isEqual(new StringBuilder("test")).isOK());
assertTrue(Assertor.that((String) null).isEqual(null).isOK());
assertFalse(Assertor.that((String) null).isEqual("test").isOK());
assertFalse(Assertor.that("test").isEqual(null).isOK());
}
/**
* Test method for
* {@link AssertorCharSequence#isNotEqual(StepAssertor, CharSequence, boolean, boolean, Message)}
* .
*/
@Test
public void testIsNotEqual() {
assertFalse(Assertor.that("test").isNotEqual("test").isOK());
assertTrue(Assertor.that("test").isNotEqual("Test").isOK());
assertTrue(Assertor.that("te\r\nst").isNotEqual("tes\nt").isOK());
assertTrue(Assertor.that("te\r\nst").isNotEqual("Tes\nt").isOK());
assertFalse(Assertor.that("test").isNotEqual(new StringBuilder("test")).isOK());
assertFalse(Assertor.that((String) null).isNotEqual(null).isOK());
assertTrue(Assertor.that((String) null).isNotEqual("test").isOK());
assertTrue(Assertor.that("test").isNotEqual(null).isOK());
}
/**
* Test method for
* {@link AssertorCharSequence#isEqualIgnoreCase(StepAssertor, CharSequence, boolean, boolean, Message)}
* .
*/
@Test
public void testIsEqualIgnoreCase() {
assertTrue(Assertor.that("test").isEqualIgnoreCase("test").isOK());
assertTrue(Assertor.that("test").isEqualIgnoreCase("Test").isOK());
assertFalse(Assertor.that("te\r\nst").isEqualIgnoreCase("tes\nt").isOK());
assertFalse(Assertor.that("te\r\nst").isEqualIgnoreCase("Tes\nt").isOK());
assertTrue(Assertor.that("test").isEqualIgnoreCase(new StringBuilder("test")).isOK());
assertTrue(Assertor.that((String) null).isEqualIgnoreCase(null).isOK());
assertFalse(Assertor.that((String) null).isEqualIgnoreCase("test").isOK());
assertFalse(Assertor.that("test").isEqualIgnoreCase(null).isOK());
}
/**
* Test method for
* {@link AssertorCharSequence#isNotEqualIgnoreCase(StepAssertor, CharSequence, boolean, boolean, Message)}
* .
*/
@Test
public void testIsNotEqualIgnoreCase() {
assertFalse(Assertor.that("test").isNotEqualIgnoreCase("test").isOK());
assertFalse(Assertor.that("test").isNotEqualIgnoreCase("Test").isOK());
assertTrue(Assertor.that("te\r\nst").isNotEqualIgnoreCase("tes\nt").isOK());
assertTrue(Assertor.that("te\r\nst").isNotEqualIgnoreCase("Tes\nt").isOK());
assertFalse(Assertor.that("test").isNotEqualIgnoreCase(new StringBuilder("test")).isOK());
assertFalse(Assertor.that((String) null).isNotEqualIgnoreCase(null).isOK());
assertTrue(Assertor.that((String) null).isNotEqualIgnoreCase("test").isOK());
assertTrue(Assertor.that("test").isNotEqualIgnoreCase(null).isOK());
}
/**
* Test method for
* {@link AssertorCharSequence#isEqualIgnoreLineReturns(StepAssertor, CharSequence, boolean, boolean, Message)}
* .
*/
@Test
public void testIsEqualIgnoreLineReturns() {
assertTrue(Assertor.that("test").isEqualIgnoreLineReturns("test").isOK());
assertFalse(Assertor.that("test").isEqualIgnoreLineReturns("Test").isOK());
assertTrue(Assertor.that("te\r\nst").isEqualIgnoreLineReturns("tes\nt").isOK());
assertFalse(Assertor.that("te\r\nst").isEqualIgnoreLineReturns("Tes\nt").isOK());
assertTrue(Assertor.that("test").isEqualIgnoreLineReturns(new StringBuilder("test")).isOK());
assertTrue(Assertor.that((String) null).isEqualIgnoreLineReturns(null).isOK());
assertFalse(Assertor.that((String) null).isEqualIgnoreLineReturns("test").isOK());
assertFalse(Assertor.that("test").isEqualIgnoreLineReturns(null).isOK());
}
/**
* Test method for
* {@link AssertorCharSequence#isNotEqualIgnoreLineReturns(StepAssertor, CharSequence, boolean, boolean, Message)}
* .
*/
@Test
public void testIsNotEqualIgnoreLineReturns() {
assertFalse(Assertor.that("test").isNotEqualIgnoreLineReturns("test").isOK());
assertTrue(Assertor.that("test").isNotEqualIgnoreLineReturns("Test").isOK());
assertFalse(Assertor.that("te\r\nst").isNotEqualIgnoreLineReturns("tes\nt").isOK());
assertTrue(Assertor.that("te\r\nst").isNotEqualIgnoreLineReturns("Tes\nt").isOK());
assertFalse(Assertor.that("test").isNotEqualIgnoreLineReturns(new StringBuilder("test")).isOK());
assertFalse(Assertor.that((String) null).isNotEqualIgnoreLineReturns(null).isOK());
assertTrue(Assertor.that((String) null).isNotEqualIgnoreLineReturns("test").isOK());
assertTrue(Assertor.that("test").isNotEqualIgnoreLineReturns(null).isOK());
}
/**
* Test method for
* {@link AssertorCharSequence#isEqualIgnoreCaseAndLineReturns(StepAssertor, CharSequence, boolean, boolean, Message)}
* .
*/
@Test
public void testIsEqualIgnoreCaseAndLineReturns() {
assertTrue(Assertor.that("test").isEqualIgnoreCaseAndLineReturns("test").isOK());
assertTrue(Assertor.that("test").isEqualIgnoreCaseAndLineReturns("Test").isOK());
assertTrue(Assertor.that("te\r\nst").isEqualIgnoreCaseAndLineReturns("tes\nt").isOK());
assertTrue(Assertor.that("te\r\nst").isEqualIgnoreCaseAndLineReturns("Tes\nt").isOK());
assertTrue(Assertor.that("test").isEqualIgnoreCaseAndLineReturns(new StringBuilder("test")).isOK());
assertTrue(Assertor.that((String) null).isEqualIgnoreCaseAndLineReturns(null).isOK());
assertFalse(Assertor.that((String) null).isEqualIgnoreCaseAndLineReturns("test").isOK());
assertFalse(Assertor.that("test").isEqualIgnoreCaseAndLineReturns(null).isOK());
}
/**
* Test method for
* {@link AssertorCharSequence#isNotEqual(StepAssertor, CharSequence, boolean, boolean, Message)}
* .
*/
@Test
public void testIsNotEqualIgnoreCaseAndLineReturns() {
assertFalse(Assertor.that("test").isNotEqualIgnoreCaseAndLineReturns("test").isOK());
assertFalse(Assertor.that("test").isNotEqualIgnoreCaseAndLineReturns("Test").isOK());
assertFalse(Assertor.that("te\r\nst").isNotEqualIgnoreCaseAndLineReturns("tes\nt").isOK());
assertFalse(Assertor.that("te\r\nst").isNotEqualIgnoreCaseAndLineReturns("Tes\nt").isOK());
assertFalse(Assertor.that("test").isNotEqualIgnoreCaseAndLineReturns(new StringBuilder("test")).isOK());
assertFalse(Assertor.that((String) null).isNotEqualIgnoreCaseAndLineReturns(null).isOK());
assertTrue(Assertor.that((String) null).isNotEqualIgnoreCaseAndLineReturns("test").isOK());
assertTrue(Assertor.that("test").isNotEqualIgnoreCaseAndLineReturns(null).isOK());
}
/**
* Test method for
* {@link AssertorCharSequence#contains(String, String, String, Object...)}
* .
*/
@Test
public void testDoesNotContainOKStringStringString() {
try {
Assertor.that("titi part en vacances").not().contains("toto").orElseThrow("not found");
} catch (IllegalArgumentException e) {
fail("The test isn't correct");
}
}
/**
* Test method for
* {@link AssertorCharSequence#contains(String, String, String, Object...)}
* .
*/
@Test(expected = IllegalArgumentException.class)
public void testDoesNotContainKOStringStringString() {
Assertor.that("titi part en vacances").not().contains("titi").orElseThrow("not found");
}
/**
* Test method for
* {@link AssertorCharSequence#not().contains(java.lang.String,
* java.lang.String)} .
*/
@Test
public void testDoesNotContain() {
assertTrue(Assertor.that("totos").not().contains("toto part en vacances").isOK());
assertTrue(Assertor.that("toto").not().contains("totu").isOK());
assertTrue(Assertor.that("toto").not().contains('x').isOK());
assertFalse(Assertor.that("toto part en vacances").not().contains("toto").isOK());
assertFalse(Assertor.that((String) null).not().contains("toto part en vacances").isOK());
assertFalse(Assertor.that("toto").not().contains((CharSequence) null).isOK());
assertFalse(Assertor.that("toto").not().contains((Character) null).isOK());
}
/**
* Test method for
* {@link AssertorCharSequence#contains(java.lang.String, java.lang.String)}
* .
*/
@Test(expected = IllegalArgumentException.class)
public void testDoesNotContainKOStringString() {
Assertor.that("tata part en vacances").not().contains("tata").orElseThrow();
}
/**
* Test method for
* {@link AssertorCharSequence#contains(java.lang.String, java.lang.String)}
* .
*/
@Test
public void testContains() {
assertTrue(Assertor.that("toto part en vacances").contains("toto").isOK());
assertTrue(Assertor.that("toto").contains('t').isOK());
assertTrue(Assertor.that("toto").contains("toto").isOK());
assertTrue(Assertor.that("toti et toto part en vacances").contains("toto").isOK());
assertFalse(Assertor.that("toti part en vacances en moto").contains("toto").isOK());
assertFalse(Assertor.that("toto").contains("toto part en vacances").isOK());
assertFalse(Assertor.that((String) null).contains("toto part en vacances").isOK());
assertFalse(Assertor.that("toto").contains((CharSequence) null).isOK());
assertFalse(Assertor.that("toto").contains((Character) null).isOK());
assertFalse(Assertor.that((String) null).contains((Character) null).isOK());
assertException(() -> {
Assertor.that("toto part en vacances").contains("toto").and().contains("voyage").orElseThrow();
}, IllegalArgumentException.class, "the char sequence 'toto part en vacances' should contain 'voyage'");
assertException(() -> {
Assertor.that("toto part en vacances").contains("toto").and().contains("voyage")
.and(Assertor.that("text").isBlank().or().contains("text")).orElseThrow();
}, IllegalArgumentException.class, "the char sequence 'toto part en vacances' should contain 'voyage'");
assertException(() -> {
Assertor.that("toto part en vacances").contains("toto").and().contains("voyage")
.or(Assertor.that("text").isBlank().or().not().contains("text")).orElseThrow();
}, IllegalArgumentException.class, "the char sequence 'toto part en vacances' should contain 'voyage'");
assertException(() -> {
Assertor.that("toto part en vacances").contains('t').and().contains('y').orElseThrow();
}, IllegalArgumentException.class, "the char sequence 'toto part en vacances' should contain 'y'");
assertException(() -> {
Assertor.that("toto part en vacances").contains('t').and().contains('y')
.and(Assertor.that("text").isBlank().or().contains("text")).orElseThrow();
}, IllegalArgumentException.class, "the char sequence 'toto part en vacances' should contain 'y'");
assertException(() -> {
Assertor.that("toto part en vacances").contains('t').and().contains('y')
.or(Assertor.that("text").isBlank().or().not().contains('t')).orElseThrow();
}, IllegalArgumentException.class, "the char sequence 'toto part en vacances' should contain 'y'");
assertException(() -> {
Assertor.that((CharSequence) null).contains('t').and().contains((Character) null).orElseThrow();
}, IllegalArgumentException.class, "the char sequence cannot be null and the searched substring cannot be null or empty");
}
/**
* Test method for
* {@link AssertorCharSequence#contains(java.lang.String, java.lang.String)}
* .
*/
@Test(expected = IllegalArgumentException.class)
public void testContainsKOStringString() {
Assertor.that("tata part en vacances").contains("tutu").orElseThrow();
}
/**
* Test method for
* {@link AssertorCharSequence#contains(String, String, String, Object...)}
* .
*/
@Test
public void testContainsOKStringStringString() {
try {
Assertor.that("toto part en vacances").contains("toto").orElseThrow("text not found");
} catch (IllegalArgumentException e) {
fail("The test isn't correct");
}
}
/**
* Test method for
* {@link AssertorCharSequence#contains(String, String, String, Object...)}
* .
*/
@Test(expected = IllegalArgumentException.class)
public void testContainsKOStringStringString() {
Assertor.that("tata part en vacances").contains("tutu").orElseThrow("text not found");
}
/**
* Test method for {@link AssertorCharSequence#startsWith} and
* {@link AssertorCharSequence#startsWithIgnoreCase}.
*/
@Test
public void testStartsWith() {
assertTrue(Assertor.that("TexT").startsWith("Tex").isOK());
assertFalse(Assertor.that("TexT").startsWith("tex").isOK());
assertFalse(Assertor.that("TexT").startsWith("ext").isOK());
assertFalse(Assertor.that("TexT").startsWith("").isOK());
assertFalse(Assertor.that("").startsWith("").isOK());
assertFalse(Assertor.that("TexT").startsWith("Texte").isOK());
assertFalse(Assertor.that((String) null).startsWith("Tex").isOK());
assertFalse(Assertor.that("TexT").startsWith(null).isOK());
assertTrue(Assertor.that("TexT").startsWithIgnoreCase("tex").isOK());
assertTrue(Assertor.that("TexT").startsWithIgnoreCase("tex").isOK());
assertFalse(Assertor.that("TexT").startsWithIgnoreCase("ext").isOK());
assertFalse(Assertor.that("TexT").startsWithIgnoreCase("").isOK());
assertFalse(Assertor.that("").startsWithIgnoreCase("").isOK());
assertFalse(Assertor.that("TexT").startsWithIgnoreCase("texte").isOK());
assertFalse(Assertor.that((String) null).startsWithIgnoreCase("tex").isOK());
assertFalse(Assertor.that("TexT").startsWithIgnoreCase(null).isOK());
}
/**
* Test method for {@link AssertorCharSequence#endsWith} and
* {@link AssertorCharSequence#endsWithIgnoreCase}.
*/
@Test
public void testEndsWith() {
assertTrue(Assertor.that("TexT").endsWith("exT").isOK());
assertFalse(Assertor.that("TexT").endsWith("ext").isOK());
assertFalse(Assertor.that("TexT").endsWith("tex").isOK());
assertFalse(Assertor.that("TexT").endsWith("").isOK());
assertFalse(Assertor.that("").endsWith("").isOK());
assertFalse(Assertor.that("TexT").endsWith("eTexT").isOK());
assertFalse(Assertor.that((String) null).endsWith("exT").isOK());
assertFalse(Assertor.that("TexT").endsWith(null).isOK());
assertTrue(Assertor.that("TexT").endsWithIgnoreCase("exT").isOK());
assertTrue(Assertor.that("TexT").endsWithIgnoreCase("ext").isOK());
assertFalse(Assertor.that("TexT").endsWithIgnoreCase("tex").isOK());
assertFalse(Assertor.that("TexT").endsWithIgnoreCase("").isOK());
assertFalse(Assertor.that("").endsWithIgnoreCase("").isOK());
assertFalse(Assertor.that("TexT").endsWithIgnoreCase("eTexT").isOK());
assertFalse(Assertor.that((String) null).endsWithIgnoreCase("exT").isOK());
assertFalse(Assertor.that("TexT").endsWithIgnoreCase(null).isOK());
}
/**
* Test method for {@link AssertorCharSequence#matches}.
*/
@Test
public void testMatches() {
final String regex = "[xeT]{4}";
final Pattern pattern = Pattern.compile(regex);
assertTrue(Assertor.that("TexT").matches(pattern).isOK());
assertFalse(Assertor.that("Text").matches(pattern).isOK());
assertFalse(Assertor.that((String) null).matches(pattern).isOK());
assertFalse(Assertor.that("Text").matches((Pattern) null).isOK());
assertTrue(Assertor.that("TexT").matches(regex).isOK());
assertFalse(Assertor.that("Text").matches(regex).isOK());
assertFalse(Assertor.that((String) null).matches(regex).isOK());
assertFalse(Assertor.that("Text").matches((String) null).isOK());
}
/**
* Test method for {@link AssertorCharSequence#find}.
*/
@Test
public void testFind() {
final String regex = "[xeT]{3}";
final Pattern pattern = Pattern.compile(regex);
assertTrue(Assertor.that("TexT").find(pattern).isOK());
assertTrue(Assertor.that("Text").find(pattern).isOK());
assertFalse(Assertor.that("Tetxt").find(pattern).isOK());
assertFalse(Assertor.that((String) null).find(pattern).isOK());
assertFalse(Assertor.that("Text").find((Pattern) null).isOK());
assertTrue(Assertor.that("TexT").find(regex).isOK());
assertTrue(Assertor.that("Text").find(regex).isOK());
assertFalse(Assertor.that("Tetxt").find(regex).isOK());
assertFalse(Assertor.that((String) null).find(regex).isOK());
assertFalse(Assertor.that("Text").find((String) null).isOK());
assertFalse(Assertor.that((String) null).find((String) null).isOK());
}
@Test
public void testSubAssertor() {
Assertor.that(new IOException("error")).isNotNull().andCharSequence(e -> e.getMessage()).startsWith("er").orElseThrow();
// @formatter:off
Assertor.that(new IOException("error"))
.isNotNull()
.andAssertor(e -> Assertor.that(e.getMessage()).startsWith("er"))
.andAssertor(e -> Assertor.that(e.getCause()).isNull())
.orElseThrow();
// @formatter:on
}
}
|
|
/*
* Copyright (c) 2018 Livio, Inc.
* 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 Livio Inc. nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package com.smartdevicelink.transport;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.Parcelable;
import android.util.Log;
import com.smartdevicelink.protocol.SdlPacket;
import com.smartdevicelink.protocol.enums.ControlFrameTags;
import com.smartdevicelink.transport.enums.TransportType;
import com.smartdevicelink.transport.utl.TransportRecord;
import com.smartdevicelink.util.DebugTool;
import java.lang.ref.WeakReference;
import java.util.List;
@SuppressWarnings("unused")
public class TransportManager extends TransportManagerBase{
private static final String TAG = "TransportManager";
TransportBrokerImpl transport;
//Legacy Transport
MultiplexBluetoothTransport legacyBluetoothTransport;
LegacyBluetoothHandler legacyBluetoothHandler;
final WeakReference<Context> contextWeakReference;
/**
* Managing transports
* List for status of all transports
* If transport is not connected. Request Router service connect to it. Get connected message
*/
public TransportManager(MultiplexTransportConfig config, TransportEventListener listener){
super(config,listener);
if(config.service == null) {
config.service = SdlBroadcastReceiver.consumeQueuedRouterService();
}
contextWeakReference = new WeakReference<>(config.context);
RouterServiceValidator validator = new RouterServiceValidator(config);
if(validator.validate()){
transport = new TransportBrokerImpl(config.context, config.appId,config.service);
}else{
enterLegacyMode("Router service is not trusted. Entering legacy mode");
}
}
@Override
public void start(){
if(transport != null){
if (!transport.start()){
//Unable to connect to a router service
if(transportListener != null){
transportListener.onError("Unable to connect with the router service");
}
}
}else if(legacyBluetoothTransport != null){
legacyBluetoothTransport.start();
}
}
@Override
public void close(long sessionId){
if(transport != null) {
transport.removeSession(sessionId);
transport.stop();
}else if(legacyBluetoothTransport != null){
legacyBluetoothTransport.stop();
legacyBluetoothTransport = null;
}
}
@Override
@Deprecated
public void resetSession(){
transport.resetSession();
}
/**
* Check to see if a transport is connected.
* @param transportType the transport to have its connection status returned. If `null` is
* passed in, all transports will be checked and if any are connected a
* true value will be returned.
* @param address the address associated with the transport type. If null, the first transport
* of supplied type will be used to return if connected.
* @return if a transport is connected based on included variables
*/
@Override
public boolean isConnected(TransportType transportType, String address){
synchronized (TRANSPORT_STATUS_LOCK) {
if (transportType == null) {
return !transportStatus.isEmpty();
}
for (TransportRecord record : transportStatus) {
if (record.getType().equals(transportType)) {
if (address != null) {
if (address.equals(record.getAddress())) {
return true;
} // Address doesn't match, move forward
} else {
//If no address is included, assume any transport of correct type is acceptable
return true;
}
}
}
return false;
}
}
/**
* Retrieve a transport record with the supplied params
* @param transportType the transport to have its connection status returned.
* @param address the address associated with the transport type. If null, the first transport
* of supplied type will be returned.
* @return the transport record for the transport type and address if supplied
*/
@Override
public TransportRecord getTransportRecord(TransportType transportType, String address){
synchronized (TRANSPORT_STATUS_LOCK) {
if (transportType == null) {
return null;
}
for (TransportRecord record : transportStatus) {
if (record.getType().equals(transportType)) {
if (address != null) {
if (address.equals(record.getAddress())) {
return record;
} // Address doesn't match, move forward
} else {
//If no address is included, assume any transport of correct type is acceptable
return record;
}
}
}
return null;
}
}
/**
* Retrieves the currently connected transports
* @return the currently connected transports
*/
@Override
public List<TransportRecord> getConnectedTransports(){
return this.transportStatus;
}
@Override
public boolean isHighBandwidthAvailable(){
synchronized (TRANSPORT_STATUS_LOCK) {
for (TransportRecord record : transportStatus) {
if (record.getType().equals(TransportType.USB)
|| record.getType().equals(TransportType.TCP)) {
return true;
}
}
return false;
}
}
@Override
public BaseTransportConfig updateTransportConfig(BaseTransportConfig config){
if(transport != null && TransportType.MULTIPLEX.equals(config.getTransportType())){
((MultiplexTransportConfig)config).setService(transport.getRouterService());
}
return config;
}
@Deprecated
public ComponentName getRouterService(){
if(transport != null) {
return transport.getRouterService();
}
return null;
}
@Override
public void sendPacket(SdlPacket packet){
if(transport !=null){
transport.sendPacketToRouterService(packet);
}else if(legacyBluetoothTransport != null){
byte[] data = packet.constructPacket();
legacyBluetoothTransport.write(data, 0, data.length);
}
}
@Override
public void requestNewSession(TransportRecord transportRecord){
if(transport != null){
transport.requestNewSession(transportRecord);
}else if(legacyBluetoothTransport != null){
Log.w(TAG, "Session requested for non-bluetooth transport while in legacy mode");
}
}
@Deprecated
public void requestSecondaryTransportConnection(byte sessionId, Bundle params){
transport.requestSecondaryTransportConnection(sessionId, (Bundle)params);
}
@Override
public void requestSecondaryTransportConnection(byte sessionId, TransportRecord transportRecord){
if(transportRecord != null){
Bundle bundle = new Bundle();
bundle.putString(TransportConstants.TRANSPORT_TYPE, transportRecord.getType().name());
if(transportRecord.getType().equals(TransportType.TCP)) {
String address = transportRecord.getAddress();
if(address.contains(":")){
String[] split = address.split(":");
if(split.length == 2) {
bundle.putString(ControlFrameTags.RPC.TransportEventUpdate.TCP_IP_ADDRESS, split[0]);
bundle.putInt(ControlFrameTags.RPC.TransportEventUpdate.TCP_PORT, Integer.valueOf(split[1]));
} //else {something went wrong;}
}else{
bundle.putString(ControlFrameTags.RPC.TransportEventUpdate.TCP_IP_ADDRESS, address);
}
}
transport.requestSecondaryTransportConnection(sessionId, bundle);
}
}
protected class TransportBrokerImpl extends TransportBroker{
boolean shuttingDown = false;
public TransportBrokerImpl(Context context, String appId, ComponentName routerService){
super(context,appId,routerService);
}
@SuppressWarnings("deprecation")
@Override
@Deprecated
public boolean onHardwareConnected(TransportType transportType){
return false;
}
@Override
public synchronized boolean onHardwareConnected(List<TransportRecord> transports) {
super.onHardwareConnected(transports);
DebugTool.logInfo("OnHardwareConnected");
if(shuttingDown){
return false;
}
synchronized (TRANSPORT_STATUS_LOCK){
transportStatus.clear();
transportStatus.addAll(transports);
}
transportListener.onTransportConnected(transports);
return true;
}
@Override
public synchronized void onHardwareDisconnected(TransportRecord record, List<TransportRecord> connectedTransports) {
if(record != null){
Log.d(TAG, "Transport disconnected - " + record);
}else{
Log.d(TAG, "Transport disconnected");
}
if(shuttingDown){
return;
}
synchronized (TRANSPORT_STATUS_LOCK){
boolean wasRemoved = TransportManager.this.transportStatus.remove(record);
//Might check connectedTransports vs transportStatus to ensure they are equal
//If the transport wasn't removed, check RS version for corner case
if(!wasRemoved && getRouterServiceVersion() == 8){
boolean foundMatch = false;
//There is an issue in the first gen of multi transport router services that
//will remove certain extras from messages to the TransportBroker if older apps
//are connected that do not support the multi transport messages. Because of
//that, we check the records we have and if the transport matches we assume it
//was the original transport that was received regardless of the address.
TransportType disconnectedTransportType = record.getType();
if(disconnectedTransportType != null) {
for (TransportRecord transportRecord : TransportManager.this.transportStatus) {
if (disconnectedTransportType.equals(transportRecord.getType())) {
//The record stored in the TM will contain the actual record the
//protocol layer used during the transport connection event
record = transportRecord;
foundMatch = true;
break;
}
}
if (foundMatch) { //Remove item after the loop to avoid concurrent modifications
TransportManager.this.transportStatus.remove(record);
Log.d(TAG, "Handling corner case of transport disconnect mismatch");
}
}
}
}
if(isLegacyModeEnabled()
&& record != null
&& TransportType.BLUETOOTH.equals(record.getType())){ //Make sure it's bluetooth that has be d/c
//&& legacyBluetoothTransport == null){ //Make sure we aren't already in legacy mode
if(legacyBluetoothTransport == null) {
//Legacy mode has been enabled so we need to cycle
enterLegacyModeAndStart("Router service has enabled legacy mode");
}
}else{
//Inform the transport listener that a transport has disconnected
transportListener.onTransportDisconnected("", record, connectedTransports);
}
}
@Override
public synchronized void onLegacyModeEnabled() {
if(shuttingDown){
return;
}
if( legacyBluetoothTransport == null){
//First remove the connected bluetooth transport if one exists
TransportRecord toBeRemoved = null;
for (TransportRecord transportRecord : TransportManager.this.transportStatus) {
if (TransportType.BLUETOOTH.equals(transportRecord.getType())) {
//There was a previously connected bluetooth transport through the router service
toBeRemoved = transportRecord;
break;
}
}
if(toBeRemoved != null){ //Remove item after the loop to avoid concurrent modifications
TransportManager.this.transportStatus.remove(toBeRemoved);
}
enterLegacyModeAndStart("Router service has enabled legacy mode");
}
}
@Override
public void onPacketReceived(Parcelable packet) {
if(packet!=null){
transportListener.onPacketReceived((SdlPacket)packet);
}
}
@Override
public synchronized void stop() {
shuttingDown = true;
super.stop();
}
}
void enterLegacyModeAndStart(final String info){
enterLegacyMode(info);
if(legacyBluetoothTransport != null
&& legacyBluetoothTransport.getState() == MultiplexBaseTransport.STATE_NONE){
legacyBluetoothTransport.start();
}
}
@Override
synchronized void enterLegacyMode(final String info){
if(legacyBluetoothTransport != null && legacyBluetoothHandler != null){
return; //Already in legacy mode
}
if(transportListener.onLegacyModeEnabled(info)) {
if(Looper.myLooper() == null){
Looper.prepare();
}
legacyBluetoothHandler = new LegacyBluetoothHandler(this);
legacyBluetoothTransport = new MultiplexBluetoothTransport(legacyBluetoothHandler);
if(contextWeakReference.get() != null){
contextWeakReference.get().registerReceiver(legacyDisconnectReceiver,new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED) );
}
}else{
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
transportListener.onError(info + " - Legacy mode unacceptable; shutting down.");
}
},500);
}
}
@Override
synchronized void exitLegacyMode(String info ){
TransportRecord legacyTransportRecord = null;
if(legacyBluetoothTransport != null){
legacyTransportRecord = legacyBluetoothTransport.getTransportRecord();
legacyBluetoothTransport.stop();
legacyBluetoothTransport = null;
}
legacyBluetoothHandler = null;
synchronized (TRANSPORT_STATUS_LOCK){
TransportManager.this.transportStatus.clear();
}
if(contextWeakReference !=null){
try{
contextWeakReference.get().unregisterReceiver(legacyDisconnectReceiver);
}catch (Exception e){}
}
transportListener.onTransportDisconnected(info, legacyTransportRecord,null);
}
private BroadcastReceiver legacyDisconnectReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if(intent != null){
if(BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(intent.getAction())){
exitLegacyMode("Bluetooth disconnected");
}
}
}
};
protected static class LegacyBluetoothHandler extends Handler{
final WeakReference<TransportManager> provider;
public LegacyBluetoothHandler(TransportManager provider){
this.provider = new WeakReference<>(provider);
}
@Override
public void handleMessage(Message msg) {
if(this.provider.get() == null){
return;
}
TransportManager service = this.provider.get();
if(service.transportListener == null){
return;
}
switch (msg.what) {
case SdlRouterService.MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case MultiplexBaseTransport.STATE_CONNECTED:
synchronized (service.TRANSPORT_STATUS_LOCK){
service.transportStatus.clear();
service.transportStatus.add(service.legacyBluetoothTransport.getTransportRecord());
}
service.transportListener.onTransportConnected(service.transportStatus);
break;
case MultiplexBaseTransport.STATE_CONNECTING:
// Currently attempting to connect - update UI?
break;
case MultiplexBaseTransport.STATE_LISTEN:
if(service.transport != null){
service.transport.stop();
service.transport = null;
}
break;
case MultiplexBaseTransport.STATE_NONE:
// We've just lost the connection
service.exitLegacyMode("Lost connection");
break;
case MultiplexBaseTransport.STATE_ERROR:
Log.d(TAG, "Bluetooth serial server error received, setting state to none, and clearing local copy");
service.exitLegacyMode("Transport error");
break;
}
break;
case SdlRouterService.MESSAGE_READ:
service.transportListener.onPacketReceived((SdlPacket) msg.obj);
break;
}
}
}
}
|
|
/*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.sunshine.app;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.TypedArray;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.design.widget.AppBarLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.AbsListView;
import android.widget.TextView;
import com.example.android.sunshine.app.data.WeatherContract;
import com.example.android.sunshine.app.sync.SunshineSyncAdapter;
/**
* Encapsulates fetching the forecast and displaying it as a {@link android.support.v7.widget.RecyclerView} layout.
*/
public class ForecastFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor>, SharedPreferences.OnSharedPreferenceChangeListener {
public static final String LOG_TAG = ForecastFragment.class.getSimpleName();
// These indices are tied to FORECAST_COLUMNS. If FORECAST_COLUMNS changes, these
// must change.
static final int COL_WEATHER_ID = 0;
static final int COL_WEATHER_DATE = 1;
static final int COL_WEATHER_DESC = 2;
static final int COL_WEATHER_MAX_TEMP = 3;
static final int COL_WEATHER_MIN_TEMP = 4;
static final int COL_LOCATION_SETTING = 5;
static final int COL_WEATHER_CONDITION_ID = 6;
static final int COL_COORD_LAT = 7;
static final int COL_COORD_LONG = 8;
private static final String SELECTED_KEY = "selected_position";
private static final int FORECAST_LOADER = 0;
// For the forecast view we're showing only a small subset of the stored data.
// Specify the columns we need.
private static final String[] FORECAST_COLUMNS = {
// In this case the id needs to be fully qualified with a table name, since
// the content provider joins the location & weather tables in the background
// (both have an _id column)
// On the one hand, that's annoying. On the other, you can search the weather table
// using the location set by the user, which is only in the Location table.
// So the convenience is worth it.
WeatherContract.WeatherEntry.TABLE_NAME + "." + WeatherContract.WeatherEntry._ID,
WeatherContract.WeatherEntry.COLUMN_DATE,
WeatherContract.WeatherEntry.COLUMN_SHORT_DESC,
WeatherContract.WeatherEntry.COLUMN_MAX_TEMP,
WeatherContract.WeatherEntry.COLUMN_MIN_TEMP,
WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING,
WeatherContract.WeatherEntry.COLUMN_WEATHER_ID,
WeatherContract.LocationEntry.COLUMN_COORD_LAT,
WeatherContract.LocationEntry.COLUMN_COORD_LONG
};
private ForecastAdapter mForecastAdapter;
private RecyclerView mRecyclerView;
private boolean mUseTodayLayout, mAutoSelectView;
private int mChoiceMode;
private boolean mHoldForTransition;
private long mInitialSelectedDate = -1;
public ForecastFragment() {
}
@Override
public void onStart() {
super.onStart();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Add this line in order for this fragment to handle menu events.
setHasOptionsMenu(true);
}
@Override
public void onResume() {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
sp.registerOnSharedPreferenceChangeListener(this);
super.onResume();
}
@Override
public void onPause() {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
sp.unregisterOnSharedPreferenceChangeListener(this);
super.onPause();
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.forecastfragment, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
// if (id == R.id.action_refresh) {
// updateWeather();
// return true;
// }
if (id == R.id.action_map) {
openPreferredLocationInMap();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onInflate(Activity activity, AttributeSet attrs, Bundle savedInstanceState) {
super.onInflate(activity, attrs, savedInstanceState);
TypedArray a = activity.obtainStyledAttributes(attrs, R.styleable.ForecastFragment,
0, 0);
mChoiceMode = a.getInt(R.styleable.ForecastFragment_android_choiceMode, AbsListView.CHOICE_MODE_NONE);
mAutoSelectView = a.getBoolean(R.styleable.ForecastFragment_autoSelectView, false);
mHoldForTransition = a.getBoolean(R.styleable.ForecastFragment_sharedElementTransitions, false);
a.recycle();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
// Get a reference to the RecyclerView, and attach this adapter to it.
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerview_forecast);
// Set the layout manager
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
View emptyView = rootView.findViewById(R.id.recyclerview_forecast_empty);
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
mRecyclerView.setHasFixedSize(true);
// The ForecastAdapter will take data from a source and
// use it to populate the RecyclerView it's attached to.
mForecastAdapter = new ForecastAdapter(getActivity(), new ForecastAdapter.ForecastAdapterOnClickHandler() {
@Override
public void onClick(Long date, ForecastAdapter.ForecastAdapterViewHolder vh) {
String locationSetting = Utility.getPreferredLocation(getActivity());
((Callback) getActivity())
.onItemSelected(WeatherContract.WeatherEntry.buildWeatherLocationWithDate(
locationSetting, date),
vh
);
}
}, emptyView, mChoiceMode);
// specify an adapter (see also next example)
mRecyclerView.setAdapter(mForecastAdapter);
final View parallaxView = rootView.findViewById(R.id.parallax_bar);
if (null != parallaxView) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int max = parallaxView.getHeight();
if (dy > 0) {
parallaxView.setTranslationY(Math.max(-max, parallaxView.getTranslationY() - dy / 2));
} else {
parallaxView.setTranslationY(Math.min(0, parallaxView.getTranslationY() - dy / 2));
}
}
});
}
}
final AppBarLayout appbarView = (AppBarLayout)rootView.findViewById(R.id.appbar);
if (null != appbarView) {
ViewCompat.setElevation(appbarView, 0);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
if (0 == mRecyclerView.computeVerticalScrollOffset()) {
appbarView.setElevation(0);
} else {
appbarView.setElevation(appbarView.getTargetElevation());
}
}
});
}
}
// If there's instance state, mine it for useful information.
// The end-goal here is that the user never knows that turning their device sideways
// does crazy lifecycle related things. It should feel like some stuff stretched out,
// or magically appeared to take advantage of room, but data or place in the app was never
// actually *lost*.
if (savedInstanceState != null) {
mForecastAdapter.onRestoreInstanceState(savedInstanceState);
}
mForecastAdapter.setUseTodayLayout(mUseTodayLayout);
return rootView;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
// We hold for transition here just in-case the activity
// needs to be re-created. In a standard return transition,
// this doesn't actually make a difference.
if ( mHoldForTransition ) {
getActivity().supportPostponeEnterTransition();
}
getLoaderManager().initLoader(FORECAST_LOADER, null, this);
super.onActivityCreated(savedInstanceState);
}
// since we read the location when we create the loader, all we need to do is restart things
void onLocationChanged() {
getLoaderManager().restartLoader(FORECAST_LOADER, null, this);
}
private void openPreferredLocationInMap() {
// Using the URI scheme for showing a location found on a map. This super-handy
// intent can is detailed in the "Common Intents" page of Android's developer site:
// http://developer.android.com/guide/components/intents-common.html#Maps
if (null != mForecastAdapter) {
Cursor c = mForecastAdapter.getCursor();
if (null != c) {
c.moveToPosition(0);
String posLat = c.getString(COL_COORD_LAT);
String posLong = c.getString(COL_COORD_LONG);
Uri geoLocation = Uri.parse("geo:" + posLat + "," + posLong);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(geoLocation);
if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
startActivity(intent);
} else {
Log.d(LOG_TAG, "Couldn't call " + geoLocation.toString() + ", no receiving apps installed!");
}
}
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
// When tablets rotate, the currently selected list item needs to be saved.
mForecastAdapter.onSaveInstanceState(outState);
super.onSaveInstanceState(outState);
}
@Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
// This is called when a new Loader needs to be created. This
// fragment only uses one loader, so we don't care about checking the id.
// To only show current and future dates, filter the query to return weather only for
// dates after or including today.
// Sort order: Ascending, by date.
String sortOrder = WeatherContract.WeatherEntry.COLUMN_DATE + " ASC";
String locationSetting = Utility.getPreferredLocation(getActivity());
Uri weatherForLocationUri = WeatherContract.WeatherEntry.buildWeatherLocationWithStartDate(
locationSetting, System.currentTimeMillis());
return new CursorLoader(getActivity(),
weatherForLocationUri,
FORECAST_COLUMNS,
null,
null,
sortOrder);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
mForecastAdapter.swapCursor(data);
updateEmptyView();
if ( data.getCount() == 0 ) {
getActivity().supportStartPostponedEnterTransition();
} else {
mRecyclerView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
@Override
public boolean onPreDraw() {
// Since we know we're going to get items, we keep the listener around until
// we see Children.
if (mRecyclerView.getChildCount() > 0) {
mRecyclerView.getViewTreeObserver().removeOnPreDrawListener(this);
int position = mForecastAdapter.getSelectedItemPosition();
if (position == RecyclerView.NO_POSITION &&
-1 != mInitialSelectedDate) {
Cursor data = mForecastAdapter.getCursor();
int count = data.getCount();
int dateColumn = data.getColumnIndex(WeatherContract.WeatherEntry.COLUMN_DATE);
for ( int i = 0; i < count; i++ ) {
data.moveToPosition(i);
if ( data.getLong(dateColumn) == mInitialSelectedDate ) {
position = i;
break;
}
}
}
if (position == RecyclerView.NO_POSITION) position = 0;
// If we don't need to restart the loader, and there's a desired position to restore
// to, do so now.
mRecyclerView.smoothScrollToPosition(position);
RecyclerView.ViewHolder vh = mRecyclerView.findViewHolderForAdapterPosition(position);
if (null != vh && mAutoSelectView) {
mForecastAdapter.selectView(vh);
}
if ( mHoldForTransition ) {
getActivity().supportStartPostponedEnterTransition();
}
return true;
}
return false;
}
});
}
}
@Override
public void onDestroy() {
super.onDestroy();
if (null != mRecyclerView) {
mRecyclerView.clearOnScrollListeners();
}
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
mForecastAdapter.swapCursor(null);
}
public void setUseTodayLayout(boolean useTodayLayout) {
mUseTodayLayout = useTodayLayout;
if (mForecastAdapter != null) {
mForecastAdapter.setUseTodayLayout(mUseTodayLayout);
}
}
public void setInitialSelectedDate(long initialSelectedDate) {
mInitialSelectedDate = initialSelectedDate;
}
/*
Updates the empty list view with contextually relevant information that the user can
use to determine why they aren't seeing weather.
*/
private void updateEmptyView() {
if ( mForecastAdapter.getItemCount() == 0 ) {
TextView tv = (TextView) getView().findViewById(R.id.recyclerview_forecast_empty);
if ( null != tv ) {
// if cursor is empty, why? do we have an invalid location
int message = R.string.empty_forecast_list;
@SunshineSyncAdapter.LocationStatus int location = Utility.getLocationStatus(getActivity());
switch (location) {
case SunshineSyncAdapter.LOCATION_STATUS_SERVER_DOWN:
message = R.string.empty_forecast_list_server_down;
break;
case SunshineSyncAdapter.LOCATION_STATUS_SERVER_INVALID:
message = R.string.empty_forecast_list_server_error;
break;
case SunshineSyncAdapter.LOCATION_STATUS_INVALID:
message = R.string.empty_forecast_list_invalid_location;
break;
default:
if (!Utility.isNetworkAvailable(getActivity())) {
message = R.string.empty_forecast_list_no_network;
}
}
tv.setText(message);
}
}
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals(getString(R.string.pref_location_status_key))) {
updateEmptyView();
}
}
/**
* A callback interface that all activities containing this fragment must
* implement. This mechanism allows activities to be notified of item
* selections.
*/
public interface Callback {
/**
* DetailFragmentCallback for when an item has been selected.
*/
void onItemSelected(Uri dateUri, ForecastAdapter.ForecastAdapterViewHolder vh);
}
}
|
|
/*
* Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.siddhi.core.query.processor.join;
import org.apache.log4j.Logger;
import org.wso2.siddhi.core.event.AtomicEvent;
import org.wso2.siddhi.core.event.BundleEvent;
import org.wso2.siddhi.core.event.ComplexEvent;
import org.wso2.siddhi.core.event.Event;
import org.wso2.siddhi.core.event.ListAtomicEvent;
import org.wso2.siddhi.core.event.ListEvent;
import org.wso2.siddhi.core.event.StateEvent;
import org.wso2.siddhi.core.event.StreamEvent;
import org.wso2.siddhi.core.event.in.InStream;
import org.wso2.siddhi.core.executor.conditon.ConditionExecutor;
import org.wso2.siddhi.core.query.QueryPostProcessingElement;
import org.wso2.siddhi.core.query.processor.PreSelectProcessingElement;
import org.wso2.siddhi.core.query.processor.window.WindowProcessor;
import org.wso2.siddhi.core.query.selector.QuerySelector;
import org.wso2.siddhi.core.util.LogHelper;
import java.util.Iterator;
import java.util.concurrent.locks.Lock;
//written in thinking of LEFT
// RIGHT is handled in the #createNewEvent()
public abstract class JoinProcessor implements QueryPostProcessingElement, PreSelectProcessingElement {
static final Logger log = Logger.getLogger(JoinProcessor.class);
private WindowProcessor windowProcessor;
protected ConditionExecutor onConditionExecutor;
private boolean triggerEvent;
private WindowProcessor oppositeWindowProcessor;
protected long within = -1;
private boolean distributedProcessing;
private QuerySelector querySelector;
private Lock lock;
private boolean fromDB = false;
public WindowProcessor getWindowProcessor() {
return windowProcessor;
}
public JoinProcessor(ConditionExecutor onConditionExecutor, boolean triggerEvent,
boolean distributedProcessing, Lock lock, boolean fromDB) {
this.onConditionExecutor = onConditionExecutor;
this.triggerEvent = triggerEvent;
this.distributedProcessing = distributedProcessing;
this.lock = lock;
this.fromDB = fromDB;
}
private boolean isEventsWithin(ComplexEvent complexEvent, ComplexEvent windowComplexEvent) {
if (within > -1) {
long diff = Math.abs(complexEvent.getTimeStamp() - windowComplexEvent.getTimeStamp());
if (diff > within || diff == Long.MIN_VALUE) {
return false;
}
return true;
} else {
return true;
}
}
protected void sendEventList(ListAtomicEvent list) {
if (log.isDebugEnabled()) {
log.debug(list);
}
int size = list.getActiveEvents();
if (size > 1) {
querySelector.process(list);
} else if (size == 1) {
querySelector.process(list.getEvent0());
}
}
public void setOppositeWindowProcessor(WindowProcessor windowProcessor) {
this.oppositeWindowProcessor = windowProcessor;
}
public void setWindowProcessor(WindowProcessor windowProcessor) {
this.windowProcessor = windowProcessor;
}
public void setWithin(long within) {
this.within = within;
}
public void setNext(QuerySelector querySelector) {
this.querySelector = querySelector;
}
public void process(AtomicEvent atomicEvent) {
LogHelper.logMethod(log, atomicEvent);
if (atomicEvent instanceof Event && triggerEventTypeCheck((Event) atomicEvent)) {
if (triggerEvent) {
acquireLock();
ListAtomicEvent listAtomicEvent = createNewListAtomicEvent();
Iterator<StreamEvent> iterator = getStreamEventIterator((Event) atomicEvent);
while (iterator.hasNext()) {
StreamEvent windowStreamEvent = iterator.next();
if (windowStreamEvent instanceof Event) {
// Event newEvent = (new InComplexEvent(new Event[]{((Event) complexEvent), ((Event) windowStreamEvent)}));
if (isEventsWithin((Event) atomicEvent, windowStreamEvent)) {
StateEvent newEvent = createNewEvent((Event) atomicEvent, (Event) windowStreamEvent);
if (onConditionExecutor.execute(newEvent)) {
listAtomicEvent.addEvent(newEvent);
}
} else {
break;
}
} else if (windowStreamEvent instanceof ListEvent) {
Event[] events = ((ListEvent) windowStreamEvent).getEvents();
for (Event event : events) {
// Event newEvent = (new InComplexEvent(new Event[]{((Event) complexEvent), ((Event) events[i])}));
if (isEventsWithin((Event) atomicEvent, windowStreamEvent)) {
StateEvent newEvent = createNewEvent((Event) atomicEvent, event);
if (onConditionExecutor.execute(newEvent)) {
listAtomicEvent.addEvent(newEvent);
}
} else {
break;
}
}
} else {
//todo error Complex atomicEvent not supported
}
}
if (listAtomicEvent.getActiveEvents() > 0) {
sendEventList(listAtomicEvent);
}
if (atomicEvent instanceof InStream) {
windowProcessor.process(atomicEvent);
}
releaseLock();
} else {
if (atomicEvent instanceof InStream) {
windowProcessor.process(atomicEvent);
}
}
}
}
protected abstract boolean triggerEventTypeCheck(ComplexEvent complexEvent);
public void process(BundleEvent bundleEvent) {
// System.out.println("Arrived");
ListEvent listEvent = (ListEvent) bundleEvent;
if (triggerEventTypeCheck(listEvent)) {
if (triggerEvent) {
ListAtomicEvent listAtomicEvent = createNewListAtomicEvent();
if (log.isDebugEnabled()) {
log.debug("Joining input events " + listEvent.getActiveEvents());
}
acquireLock();
try {
Iterator<StreamEvent> iterator = oppositeWindowProcessor.iterator();
while (iterator.hasNext()) {
StreamEvent windowStreamEvent = iterator.next();
//Assuming all events in complexEvent have time == to the timeStamp of the complexEvent.
if (isEventsWithin(listEvent, windowStreamEvent)) {
for (int i = 0; i < listEvent.getActiveEvents(); i++) {
Event event = listEvent.getEvent(i);
if (windowStreamEvent instanceof Event) {
StateEvent newEvent = createNewEvent(event, windowStreamEvent);
if (onConditionExecutor.execute(newEvent)) {
listAtomicEvent.addEvent(newEvent);
}
} else if (windowStreamEvent instanceof ListEvent) {
for (int i1 = 0; i1 < ((ListEvent) windowStreamEvent).getActiveEvents(); i1++) {
Event windowEvent = ((ListEvent) windowStreamEvent).getEvent(i1);
StateEvent newEvent = createNewEvent(event, windowEvent);
if (onConditionExecutor.execute(newEvent)) {
listAtomicEvent.addEvent(newEvent);
}
}
} else {
//todo error Complex event not supported
}
}
} else {
break;
}
}
if (log.isDebugEnabled()) {
log.debug("Sending join output events " + listAtomicEvent.getActiveEvents());
}
sendEventList(listAtomicEvent);
if (listEvent instanceof InStream) {
windowProcessor.process(listEvent);
}
} finally {
releaseLock();
}
} else {
if (listEvent instanceof InStream) {
windowProcessor.process(listEvent);
}
}
}
}
protected abstract ListAtomicEvent createNewListAtomicEvent();
private Iterator<StreamEvent> getStreamEventIterator(Event event) {
Iterator<StreamEvent> iterator;
if (distributedProcessing) {
StateEvent newEvent = createNewEvent(event, null);
if (fromDB) {
//Todo fix this based on the SQL impel
iterator = oppositeWindowProcessor.iterator();
} else {
String sqlPredicate = onConditionExecutor.constructFilterQuery(newEvent, 1);
if (within > -1) {
sqlPredicate = sqlPredicate + " and ( timeStamp < " + (event.getTimeStamp() + within) + ")";
}
log.debug("Join sql predicate: " + sqlPredicate);
iterator = oppositeWindowProcessor.iterator(sqlPredicate);
}
} else {
if (fromDB) {
//todo fix
iterator = oppositeWindowProcessor.iterator();
} else {
iterator = oppositeWindowProcessor.iterator();
}
}
return iterator;
}
public void acquireLock() {
if (lock != null) {
if (log.isDebugEnabled()) {
log.debug(lock + " trying to acquire join locked");
}
lock.lock();
if (log.isDebugEnabled()) {
log.debug(lock + " join locked");
}
}
}
public void releaseLock() {
if (lock != null) {
lock.unlock();
if (log.isDebugEnabled()) {
log.debug(lock + " join unlocked");
}
}
}
protected abstract StateEvent createNewEvent(ComplexEvent complexEvent, ComplexEvent complexEvent1);
}
|
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.stream.camel;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.camel.CamelContext;
import org.apache.camel.Endpoint;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.ServiceStatus;
import org.apache.camel.component.properties.PropertiesComponent;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.support.LifecycleStrategySupport;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.IgniteDataStreamer;
import org.apache.ignite.IgniteException;
import org.apache.ignite.cache.CachePeekMode;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.events.CacheEvent;
import org.apache.ignite.events.EventType;
import org.apache.ignite.internal.util.lang.GridMapEntry;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.lang.IgniteBiPredicate;
import org.apache.ignite.lang.IgniteInClosure;
import org.apache.ignite.stream.StreamMultipleTupleExtractor;
import org.apache.ignite.stream.StreamSingleTupleExtractor;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
import org.junit.Test;
import static org.apache.ignite.events.EventType.EVT_CACHE_OBJECT_PUT;
/**
* Test class for {@link CamelStreamer}.
*/
public class IgniteCamelStreamerTest extends GridCommonAbstractTest {
/** text/plain media type. */
private static final MediaType TEXT_PLAIN = MediaType.parse("text/plain;charset=utf-8");
/** The test data. */
private static final Map<Integer, String> TEST_DATA = new HashMap<>();
/** The Camel streamer currently under test. */
private CamelStreamer<Integer, String> streamer;
/** The Ignite data streamer. */
private IgniteDataStreamer<Integer, String> dataStreamer;
/** URL where the REST service will be exposed. */
private String url;
/** The UUID of the currently active remote listener. */
private UUID remoteLsnr;
/** The OkHttpClient. */
private OkHttpClient httpClient = new OkHttpClient();
// Initialize the test data.
static {
for (int i = 0; i < 100; i++)
TEST_DATA.put(i, "v" + i);
}
/** Constructor. */
public IgniteCamelStreamerTest() {
super(true);
}
/** {@inheritDoc} */
@Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
return super.getConfiguration(igniteInstanceName).setIncludeEventTypes(EventType.EVTS_ALL);
}
@SuppressWarnings("unchecked")
@Override public void beforeTest() throws Exception {
grid().<Integer, String>getOrCreateCache(defaultCacheConfiguration());
// find an available local port
try (ServerSocket ss = new ServerSocket(0)) {
int port = ss.getLocalPort();
url = "http://localhost:" + port + "/ignite";
}
// create Camel streamer
dataStreamer = grid().dataStreamer(DEFAULT_CACHE_NAME);
streamer = createCamelStreamer(dataStreamer);
}
@Override public void afterTest() throws Exception {
try {
streamer.stop();
}
catch (Exception ignored) {
// ignore if already stopped
}
dataStreamer.close();
grid().cache(DEFAULT_CACHE_NAME).clear();
}
/**
* @throws Exception
*/
@Test
public void testSendOneEntryPerMessage() throws Exception {
streamer.setSingleTupleExtractor(singleTupleExtractor());
// Subscribe to cache PUT events.
CountDownLatch latch = subscribeToPutEvents(50);
// Action time.
streamer.start();
// Send messages.
sendMessages(0, 50, false);
// Assertions.
assertTrue(latch.await(10, TimeUnit.SECONDS));
assertCacheEntriesLoaded(50);
}
/**
* @throws Exception
*/
@Test
public void testMultipleEntriesInOneMessage() throws Exception {
streamer.setMultipleTupleExtractor(multipleTupleExtractor());
// Subscribe to cache PUT events.
CountDownLatch latch = subscribeToPutEvents(50);
// Action time.
streamer.start();
// Send messages.
sendMessages(0, 50, true);
// Assertions.
assertTrue(latch.await(10, TimeUnit.SECONDS));
assertCacheEntriesLoaded(50);
}
/**
* @throws Exception
*/
@Test
public void testResponseProcessorIsCalled() throws Exception {
streamer.setSingleTupleExtractor(singleTupleExtractor());
streamer.setResponseProcessor(new Processor() {
@Override public void process(Exchange exchange) throws Exception {
exchange.getOut().setBody("Foo bar");
}
});
// Subscribe to cache PUT events.
CountDownLatch latch = subscribeToPutEvents(50);
// Action time.
streamer.start();
// Send messages.
List<String> responses = sendMessages(0, 50, false);
for (String r : responses)
assertEquals("Foo bar", r);
// Assertions.
assertTrue(latch.await(10, TimeUnit.SECONDS));
assertCacheEntriesLoaded(50);
}
/**
* @throws Exception
*/
@Test
public void testUserSpecifiedCamelContext() throws Exception {
final AtomicInteger cnt = new AtomicInteger();
// Create a CamelContext with a probe that'll help us know if it has been used.
CamelContext context = new DefaultCamelContext();
context.setTracing(true);
context.addLifecycleStrategy(new LifecycleStrategySupport() {
@Override public void onEndpointAdd(Endpoint endpoint) {
cnt.incrementAndGet();
}
});
streamer.setSingleTupleExtractor(singleTupleExtractor());
streamer.setCamelContext(context);
// Subscribe to cache PUT events.
CountDownLatch latch = subscribeToPutEvents(50);
// Action time.
streamer.start();
// Send messages.
sendMessages(0, 50, false);
// Assertions.
assertTrue(latch.await(10, TimeUnit.SECONDS));
assertCacheEntriesLoaded(50);
assertTrue(cnt.get() > 0);
}
/**
* @throws Exception
*/
@Test
public void testUserSpecifiedCamelContextWithPropertyPlaceholders() throws Exception {
// Create a CamelContext with a custom property placeholder.
CamelContext context = new DefaultCamelContext();
PropertiesComponent pc = new PropertiesComponent("camel.test.properties");
context.addComponent("properties", pc);
// Replace the context path in the test URL with the property placeholder.
url = url.replaceAll("/ignite", "{{test.contextPath}}");
// Recreate the Camel streamer with the new URL.
streamer = createCamelStreamer(dataStreamer);
streamer.setSingleTupleExtractor(singleTupleExtractor());
streamer.setCamelContext(context);
// Subscribe to cache PUT events.
CountDownLatch latch = subscribeToPutEvents(50);
// Action time.
streamer.start();
// Before sending the messages, get the actual URL after the property placeholder was resolved,
// stripping the jetty: prefix from it.
url = streamer.getCamelContext().getEndpoints().iterator().next().getEndpointUri().replaceAll("jetty:", "");
// Send messages.
sendMessages(0, 50, false);
// Assertions.
assertTrue(latch.await(10, TimeUnit.SECONDS));
assertCacheEntriesLoaded(50);
}
/**
* @throws Exception
*/
@Test
public void testInvalidEndpointUri() throws Exception {
streamer.setSingleTupleExtractor(singleTupleExtractor());
streamer.setEndpointUri("abc");
// Action time.
try {
streamer.start();
fail("Streamer started; should have failed.");
}
catch (IgniteException ignored) {
assertTrue(streamer.getCamelContext().getStatus() == ServiceStatus.Stopped);
assertTrue(streamer.getCamelContext().getEndpointRegistry().size() == 0);
}
}
/**
* Creates a Camel streamer.
*/
private CamelStreamer<Integer, String> createCamelStreamer(IgniteDataStreamer<Integer, String> dataStreamer) {
CamelStreamer<Integer, String> streamer = new CamelStreamer<>();
streamer.setIgnite(grid());
streamer.setStreamer(dataStreamer);
streamer.setEndpointUri("jetty:" + url);
dataStreamer.allowOverwrite(true);
dataStreamer.autoFlushFrequency(1);
return streamer;
}
/**
* @throws IOException
* @return HTTP response payloads.
*/
private List<String> sendMessages(int fromIdx, int cnt, boolean singleMessage) throws IOException {
List<String> responses = Lists.newArrayList();
if (singleMessage) {
StringBuilder sb = new StringBuilder();
for (int i = fromIdx; i < fromIdx + cnt; i++)
sb.append(i).append(",").append(TEST_DATA.get(i)).append("\n");
Request request = new Request.Builder()
.url(url)
.post(RequestBody.create(TEXT_PLAIN, sb.toString()))
.build();
Response response = httpClient.newCall(request).execute();
responses.add(response.body().string());
}
else {
for (int i = fromIdx; i < fromIdx + cnt; i++) {
String payload = i + "," + TEST_DATA.get(i);
Request request = new Request.Builder()
.url(url)
.post(RequestBody.create(TEXT_PLAIN, payload))
.build();
Response response = httpClient.newCall(request).execute();
responses.add(response.body().string());
}
}
return responses;
}
/**
* Returns a {@link StreamSingleTupleExtractor} for testing.
*/
private static StreamSingleTupleExtractor<Exchange, Integer, String> singleTupleExtractor() {
return new StreamSingleTupleExtractor<Exchange, Integer, String>() {
@Override public Map.Entry<Integer, String> extract(Exchange exchange) {
List<String> s = Splitter.on(",").splitToList(exchange.getIn().getBody(String.class));
return new GridMapEntry<>(Integer.parseInt(s.get(0)), s.get(1));
}
};
}
/**
* Returns a {@link StreamMultipleTupleExtractor} for testing.
*/
private static StreamMultipleTupleExtractor<Exchange, Integer, String> multipleTupleExtractor() {
return new StreamMultipleTupleExtractor<Exchange, Integer, String>() {
@Override public Map<Integer, String> extract(Exchange exchange) {
final Map<String, String> map = Splitter.on("\n")
.omitEmptyStrings()
.withKeyValueSeparator(",")
.split(exchange.getIn().getBody(String.class));
final Map<Integer, String> answer = new HashMap<>();
F.forEach(map.keySet(), new IgniteInClosure<String>() {
@Override public void apply(String s) {
answer.put(Integer.parseInt(s), map.get(s));
}
});
return answer;
}
};
}
/**
* Subscribe to cache put events.
*/
private CountDownLatch subscribeToPutEvents(int expect) {
Ignite ignite = grid();
// Listen to cache PUT events and expect as many as messages as test data items
final CountDownLatch latch = new CountDownLatch(expect);
@SuppressWarnings("serial") IgniteBiPredicate<UUID, CacheEvent> callback =
new IgniteBiPredicate<UUID, CacheEvent>() {
@Override public boolean apply(UUID uuid, CacheEvent evt) {
latch.countDown();
return true;
}
};
remoteLsnr = ignite.events(ignite.cluster().forCacheNodes(DEFAULT_CACHE_NAME))
.remoteListen(callback, null, EVT_CACHE_OBJECT_PUT);
return latch;
}
/**
* Assert a given number of cache entries have been loaded.
*/
private void assertCacheEntriesLoaded(int cnt) {
// get the cache and check that the entries are present
IgniteCache<Integer, String> cache = grid().cache(DEFAULT_CACHE_NAME);
// for each key from 0 to count from the TEST_DATA (ordered by key), check that the entry is present in cache
for (Integer key : new ArrayList<>(new TreeSet<>(TEST_DATA.keySet())).subList(0, cnt))
assertEquals(TEST_DATA.get(key), cache.get(key));
// assert that the cache exactly the specified amount of elements
assertEquals(cnt, cache.size(CachePeekMode.ALL));
// remove the event listener
grid().events(grid().cluster().forCacheNodes(DEFAULT_CACHE_NAME)).stopRemoteListen(remoteLsnr);
}
}
|
|
/**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2005, 2006, 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.shared.impl.assessment;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sakaiproject.tool.assessment.data.ifc.assessment.ItemDataIfc;
import org.sakaiproject.tool.assessment.facade.ItemFacade;
import org.sakaiproject.tool.assessment.services.ItemService;
import org.sakaiproject.tool.assessment.services.assessment.AssessmentServiceException;
import org.sakaiproject.tool.assessment.shared.api.assessment.ItemServiceAPI;
/**
* AssessmentServiceImpl implements a shared interface to get/set item
* information.
* @author Ed Smiley <[email protected]>
*/
// Our API just uses our internal service. If we want, we can always replace
// this internal service and use its implementation as our own.
// Note that ItemFacade implements ItemDataIfc.
public class ItemServiceImpl implements ItemServiceAPI
{
private Logger log = LoggerFactory.getLogger(ItemServiceImpl.class);
/**
* Get a particular item.
*
* @param itemId the item id
* @param agentId the agent id
* @return the item data interface
*/
public ItemDataIfc getItem(Long itemId, String agentId)
{
ItemFacade item = null;
try
{
ItemService service = new ItemService();
item = service.getItem(itemId, agentId);
}
catch(Exception e)
{
throw new AssessmentServiceException(e);
}
return item;
}
/**
* Delete a item.
*
* @param itemId the item id
* @param agentId the agent id
*/
public void deleteItem(Long itemId, String agentId)
{
try
{
ItemService service = new ItemService();
service.deleteItem(itemId, agentId);
}
catch(Exception e)
{
throw new AssessmentServiceException(e);
}
}
/**
* Delete itemtextset for an item, used for modify
*
* @param itemId the item id
* @param agentId the agent id
*/
public void deleteItemContent(Long itemId, String agentId)
{
try
{
ItemService service = new ItemService();
service.deleteItemContent(itemId, agentId);
}
catch(Exception e)
{
throw new AssessmentServiceException(e);
}
}
/**
* Delete metadata for an item, used for modify.
* param: itemid, label, agentId
*
* @param itemId the item id
* @param label the metadata label
* @param agentId the agent id
*/
public void deleteItemMetaData(Long itemId, String label, String agentId)
{
try
{
ItemService service = new ItemService();
service.deleteItemMetaData(itemId, label, agentId);
}
catch(Exception e)
{
throw new AssessmentServiceException(e);
}
}
/**
* Add metadata for an item, used for modify
* param: itemid, label, value, agentId
*
* @param itemId the item id
* @param label the metadata label
* @param value the value for the label
* @param agentId the agent id
*/
public void addItemMetaData(Long itemId, String label, String value,
String agentId)
{
try
{
ItemService service = new ItemService();
service.addItemMetaData(itemId, label, value, agentId);
}
catch(Exception e)
{
throw new AssessmentServiceException(e);
}
}
/**
* Save item.
* @param item interface
* @return item interface
*/
public ItemDataIfc saveItem(ItemDataIfc item)
{
try
{
String itemId = item.getItemIdString();
ItemService service = new ItemService();
item = service.saveItem(service.getItem(itemId));
}
catch(Exception e)
{
throw new AssessmentServiceException(e);
}
return item;
}
/**
* Get item.
* @param itemId the item id
* @return item interface
*/
public ItemDataIfc getItem(String itemId)
{
ItemFacade item = null;
try
{
ItemService service = new ItemService();
item = service.getItem(itemId);
}
catch(Exception e)
{
throw new AssessmentServiceException(e);
}
return item;
}
/**
* Search for items.
* @param keyword the keyword to search by.
* @return Map of ItemDataIfcs with item id strings as keys.
*/
public Map getItemsByKeyword(String keyword)
{
Map itemKeywordMap = new HashMap();
try
{
ItemService service = new ItemService();
itemKeywordMap = service.getItemsByKeyword(keyword);
}
catch(Exception e)
{
throw new AssessmentServiceException(e);
}
return itemKeywordMap;
}
}
|
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.internal.processors.cache.distributed;
import org.apache.ignite.*;
import org.apache.ignite.events.*;
import org.apache.ignite.internal.*;
import org.apache.ignite.internal.processors.cache.*;
import org.apache.ignite.internal.util.*;
import org.apache.ignite.internal.util.future.*;
import org.apache.ignite.internal.util.typedef.*;
import org.apache.ignite.internal.util.typedef.internal.*;
import org.apache.ignite.lang.*;
import org.apache.ignite.transactions.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import static org.apache.ignite.events.EventType.*;
import static org.apache.ignite.transactions.TransactionConcurrency.*;
import static org.apache.ignite.transactions.TransactionIsolation.*;
/**
* Tests events.
*/
public abstract class GridCacheEventAbstractTest extends GridCacheAbstractSelfTest {
/** */
private static final boolean TEST_INFO = true;
/** Wait timeout. */
private static final long WAIT_TIMEOUT = 5000;
/** Key. */
private static final String KEY = "key";
/** */
private static volatile int gridCnt;
/**
* @return {@code True} if partitioned.
*/
protected boolean partitioned() {
return false;
}
/** {@inheritDoc} */
@Override protected void beforeTestsStarted() throws Exception {
super.beforeTestsStarted();
gridCnt = gridCount();
for (int i = 0; i < gridCnt; i++)
grid(i).events().localListen(new TestEventListener(partitioned()), EVTS_CACHE);
}
/** {@inheritDoc} */
@Override protected void beforeTest() throws Exception {
super.beforeTest();
if (TEST_INFO)
info("Called beforeTest() callback.");
TestEventListener.reset();
}
/** {@inheritDoc} */
@Override protected void afterTest() throws Exception {
if (TEST_INFO)
info("Called afterTest() callback.");
TestEventListener.stopListen();
try {
super.afterTest();
}
finally {
TestEventListener.listen();
}
}
/**
* Waits for event count on all nodes.
*
* @param gridIdx Grid index.
* @param evtCnts Array of tuples with values: V1 - event type, V2 - expected event count on one node.
* @throws InterruptedException If thread has been interrupted while waiting.
*/
private void waitForEvents(int gridIdx, IgniteBiTuple<Integer, Integer>... evtCnts) throws Exception {
if (!F.isEmpty(evtCnts))
try {
TestEventListener.waitForEventCount(evtCnts);
}
catch (IgniteCheckedException e) {
printEventCounters(gridIdx, evtCnts);
throw e;
}
}
/**
* @param gridIdx Grid index.
* @param expCnts Expected counters
*/
private void printEventCounters(int gridIdx, IgniteBiTuple<Integer, Integer>[] expCnts) {
info("Printing counters [gridIdx=" + gridIdx + ']');
for (IgniteBiTuple<Integer, Integer> t : expCnts) {
Integer evtType = t.get1();
int actCnt = TestEventListener.eventCount(evtType);
info("Event [evtType=" + evtType + ", expCnt=" + t.get2() + ", actCnt=" + actCnt + ']');
}
}
/**
* Clear caches without generating events.
*/
private void clearCaches() {
for (int i = 0; i < gridCnt; i++) {
IgniteCache<String, Integer> cache = jcache(i);
cache.removeAll();
assert cache.localSize() == 0;
}
}
/**
* Runs provided {@link TestCacheRunnable} instance on all caches.
*
* @param run {@link TestCacheRunnable} instance.
* @param evtCnts Expected event counts for each iteration.
* @throws Exception In failed.
*/
@SuppressWarnings({"CaughtExceptionImmediatelyRethrown"})
private void runTest(TestCacheRunnable run, IgniteBiTuple<Integer, Integer>... evtCnts) throws Exception {
for (int i = 0; i < gridCount(); i++) {
info(">>> Running test for grid [idx=" + i + ", grid=" + grid(i).name() +
", id=" + grid(i).localNode().id() + ']');
try {
run.run(jcache(i));
waitForEvents(i, evtCnts);
}
catch (Exception e) { // Leave this catch to be able to set breakpoint.
throw e;
}
finally {
// This call is mainly required to correctly clear event futures.
TestEventListener.reset();
clearCaches();
// This call is required for the second time to reset counters for
// the previous call.
TestEventListener.reset();
}
}
}
/**
* Get key-value pairs.
*
* @param size Pairs count.
* @return Key-value pairs.
*/
private Map<String, Integer> pairs(int size) {
Map<String, Integer> pairs = new HashMap<>(size);
for (int i = 1; i <= size; i++)
pairs.put(KEY + i, i);
return pairs;
}
/**
* @throws Exception If test failed.
*
* Note: test was disabled for REPPLICATED cache case because IGNITE-607.
* This comment should be removed if test passed stably.
*/
public void testGetPutRemove() throws Exception {
runTest(
new TestCacheRunnable() {
@Override public void run(IgniteCache<String, Integer> cache) throws IgniteCheckedException {
String key = "key";
Integer val = 1;
assert cache.getAndPut(key, val) == null;
assert cache.containsKey(key);
assertEquals(val, cache.get(key));
assertEquals(val, cache.getAndRemove(key));
assert !cache.containsKey(key);
}
},
F.t(EVT_CACHE_OBJECT_PUT, gridCnt),
F.t(EVT_CACHE_OBJECT_READ, 3),
F.t(EVT_CACHE_OBJECT_REMOVED, gridCnt)
);
}
/**
* @throws Exception If test failed.
*/
public void testGetPutRemoveTx1() throws Exception {
runTest(new TestCacheRunnable() {
@Override public void run(IgniteCache<String, Integer> cache) throws IgniteCheckedException {
Map.Entry<String, Integer> e = F.first(pairs(1).entrySet());
assert e != null;
String key = e.getKey();
Integer val = e.getValue();
Transaction tx = cache.unwrap(Ignite.class).transactions().txStart();
assert cache.getAndPut(key, val) == null;
assert cache.containsKey(key);
assert val.equals(cache.get(key));
assert val.equals(cache.getAndRemove(key));
assert !cache.containsKey(key);
tx.commit();
assert !cache.containsKey(key);
}
}, F.t(EVT_CACHE_OBJECT_REMOVED, gridCnt));
}
/**
* @throws Exception If test failed.
*/
public void testGetPutRemoveTx2() throws Exception {
runTest(new TestCacheRunnable() {
@Override public void run(IgniteCache<String, Integer> cache) throws IgniteCheckedException {
Map.Entry<String, Integer> e = F.first(pairs(1).entrySet());
assert e != null;
String key = e.getKey();
Integer val = e.getValue();
Transaction tx = cache.unwrap(Ignite.class).transactions().txStart();
assert cache.getAndPut(key, val) == null;
assert cache.containsKey(key);
assert val.equals(cache.get(key));
assert val.equals(cache.getAndRemove(key));
assert !cache.containsKey(key);
cache.put(key, val);
assert cache.containsKey(key);
tx.commit();
assert cache.containsKey(key);
}
}, F.t(EVT_CACHE_OBJECT_PUT, gridCnt));
}
/**
* @throws Exception If test failed.
*
* Note: test was disabled for REPPLICATED cache case because IGNITE-607.
* This comment should be removed if test passed stably.
*/
public void testGetPutRemoveAsync() throws Exception {
runTest(new TestCacheRunnable() {
@Override public void run(IgniteCache<String, Integer> cache) throws IgniteCheckedException {
IgniteCache<String, Integer> asyncCache = cache.withAsync();
Map.Entry<String, Integer> e = F.first(pairs(1).entrySet());
assert e != null;
String key = e.getKey();
Integer val = e.getValue();
asyncCache.getAndPut(key, val);
assert asyncCache.future().get() == null;
assert cache.containsKey(key);
asyncCache.get(key);
assert val.equals(asyncCache.future().get());
asyncCache.getAndRemove(key);
assert val.equals(asyncCache.future().get());
assert !cache.containsKey(key);
}
}, F.t(EVT_CACHE_OBJECT_PUT, gridCnt), F.t(EVT_CACHE_OBJECT_READ, 3), F.t(EVT_CACHE_OBJECT_REMOVED, gridCnt));
}
/**
* @throws Exception If test failed.
*/
public void testGetPutRemoveAsyncTx1() throws Exception {
runTest(new TestCacheRunnable() {
@Override public void run(IgniteCache<String, Integer> cache) throws IgniteCheckedException {
IgniteCache<String, Integer> asyncCache = cache.withAsync();
Map.Entry<String, Integer> e = F.first(pairs(1).entrySet());
assert e != null;
String key = e.getKey();
Integer val = e.getValue();
Transaction tx = cache.unwrap(Ignite.class).transactions().txStart();
asyncCache.getAndPut(key, val);
assert asyncCache.future().get() == null;
assert cache.containsKey(key);
asyncCache.get(key);
assert val.equals(asyncCache.future().get());
asyncCache.getAndRemove(key);
assert val.equals(asyncCache.future().get());
assert !cache.containsKey(key);
tx.commit();
assert !cache.containsKey(key);
}
}, F.t(EVT_CACHE_OBJECT_REMOVED, gridCnt));
}
/**
* @throws Exception If test failed.
*/
public void testGetPutRemoveAsyncTx2() throws Exception {
runTest(new TestCacheRunnable() {
@Override public void run(IgniteCache<String, Integer> cache) throws IgniteCheckedException {
IgniteCache<String, Integer> asyncCache = cache.withAsync();
Map.Entry<String, Integer> e = F.first(pairs(1).entrySet());
assert e != null;
String key = e.getKey();
Integer val = e.getValue();
Transaction tx = cache.unwrap(Ignite.class).transactions().txStart();
asyncCache.getAndPut(key, val);
assert asyncCache.future().get() == null;
assert cache.containsKey(key);
asyncCache.get(key);
assert val.equals(asyncCache.future().get());
asyncCache.getAndRemove(key);
assert val.equals(asyncCache.future().get());
assert !cache.containsKey(key);
asyncCache.getAndPut(key, val);
assert asyncCache.future().get() == null;
assert cache.containsKey(key);
tx.commit();
assert cache.containsKey(key);
}
}, F.t(EVT_CACHE_OBJECT_PUT, gridCnt));
}
/**
* @throws Exception If test failed.
*/
public void testPutRemovex() throws Exception {
runTest(new TestCacheRunnable() {
@Override public void run(IgniteCache<String, Integer> cache) throws IgniteCheckedException {
Map.Entry<String, Integer> e = F.first(pairs(1).entrySet());
assert e != null;
String key = e.getKey();
Integer val = e.getValue();
cache.put(key, val);
assert cache.containsKey(key);
assert cache.remove(key);
assert !cache.containsKey(key);
}
}, F.t(EVT_CACHE_OBJECT_PUT, gridCnt), F.t(EVT_CACHE_OBJECT_REMOVED, gridCnt));
}
/**
* @throws Exception If test failed.
*/
public void testPutRemovexTx1() throws Exception {
runTest(new TestCacheRunnable() {
@Override public void run(IgniteCache<String, Integer> cache) throws IgniteCheckedException {
Map.Entry<String, Integer> e = F.first(pairs(1).entrySet());
assert e != null;
String key = e.getKey();
Integer val = e.getValue();
Transaction tx = cache.unwrap(Ignite.class).transactions().txStart();
cache.put(key, val);
assert cache.containsKey(key);
assert cache.remove(key);
assert !cache.containsKey(key);
tx.commit();
assert !cache.containsKey(key);
}
}, F.t(EVT_CACHE_OBJECT_REMOVED, gridCnt));
}
/**
* @throws Exception If test failed.
*/
public void testPutRemovexTx2() throws Exception {
runTest(new TestCacheRunnable() {
@Override public void run(IgniteCache<String, Integer> cache) throws IgniteCheckedException {
Map.Entry<String, Integer> e = F.first(pairs(1).entrySet());
assert e != null;
String key = e.getKey();
Integer val = e.getValue();
Transaction tx = cache.unwrap(Ignite.class).transactions().txStart();
cache.put(key, val);
assert cache.containsKey(key);
assert cache.remove(key);
assert !cache.containsKey(key);
cache.put(key, val);
assert cache.containsKey(key);
tx.commit();
assert cache.containsKey(key);
}
}, F.t(EVT_CACHE_OBJECT_PUT, gridCnt));
}
/**
* @throws Exception If test failed.
*/
public void testPutIfAbsent() throws Exception {
runTest(new TestCacheRunnable() {
@Override public void run(IgniteCache<String, Integer> cache) throws IgniteCheckedException {
Iterator<Map.Entry<String, Integer>> iter = pairs(2).entrySet().iterator();
Map.Entry<String, Integer> e = iter.next();
String key = e.getKey();
Integer val = e.getValue();
assert cache.getAndPutIfAbsent(key, val) == null;
assert val.equals(cache.getAndPutIfAbsent(key, val));
assert cache.containsKey(key);
e = iter.next();
key = e.getKey();
val = e.getValue();
assert cache.putIfAbsent(key, val);
assert !cache.putIfAbsent(key, val);
assert cache.containsKey(key);
}
}, F.t(EVT_CACHE_OBJECT_PUT, 2 * gridCnt));
}
/**
* @throws Exception If test failed.
*/
public void testPutIfAbsentTx() throws Exception {
runTest(new TestCacheRunnable() {
@Override public void run(IgniteCache<String, Integer> cache) throws IgniteCheckedException {
Iterator<Map.Entry<String, Integer>> iter = pairs(2).entrySet().iterator();
Map.Entry<String, Integer> e = iter.next();
String key = e.getKey();
Integer val = e.getValue();
try (Transaction tx = grid(0).transactions().txStart();) {
assert cache.getAndPutIfAbsent(key, val) == null;
assertEquals(val, cache.getAndPutIfAbsent(key, val));
assert cache.containsKey(key);
e = iter.next();
key = e.getKey();
val = e.getValue();
assert cache.putIfAbsent(key, val);
assert !cache.putIfAbsent(key, val);
assert cache.containsKey(key);
tx.commit();
}
assert cache.containsKey(key);
}
}, F.t(EVT_CACHE_OBJECT_PUT, 2 * gridCnt));
}
/**
* @throws Exception If test failed.
*/
public void testPutIfAbsentAsync() throws Exception {
runTest(new TestCacheRunnable() {
@Override public void run(IgniteCache<String, Integer> cache) throws IgniteCheckedException {
IgniteCache<String, Integer> asyncCache = cache.withAsync();
Iterator<Map.Entry<String, Integer>> iter = pairs(2).entrySet().iterator();
Map.Entry<String, Integer> e = iter.next();
String key = e.getKey();
Integer val = e.getValue();
asyncCache.getAndPutIfAbsent(key, val);
assert asyncCache.future().get() == null;
asyncCache.getAndPutIfAbsent(key, val);
assert val.equals(asyncCache.future().get());
assert cache.containsKey(key);
e = iter.next();
key = e.getKey();
val = e.getValue();
asyncCache.putIfAbsent(key, val);
assert ((Boolean)asyncCache.future().get()).booleanValue();
asyncCache.putIfAbsent(key, val);
assert !((Boolean)asyncCache.future().get()).booleanValue();
assert cache.containsKey(key);
}
}, F.t(EVT_CACHE_OBJECT_PUT, 2 * gridCnt));
}
/**
* @throws Exception If test failed.
*/
@SuppressWarnings("unchecked")
public void testPutIfAbsentAsyncTx() throws Exception {
IgniteBiTuple[] evts = new IgniteBiTuple[] {F.t(EVT_CACHE_OBJECT_PUT, 2 * gridCnt)};
runTest(new TestCacheRunnable() {
@Override public void run(IgniteCache<String, Integer> cache) throws IgniteCheckedException {
IgniteCache<String, Integer> asyncCache = cache.withAsync();
Iterator<Map.Entry<String, Integer>> iter = pairs(2).entrySet().iterator();
// Optimistic transaction.
try (Transaction tx = cache.unwrap(Ignite.class).transactions().txStart(OPTIMISTIC, REPEATABLE_READ)) {
Map.Entry<String, Integer> e = iter.next();
String key = e.getKey();
Integer val = e.getValue();
asyncCache.getAndPutIfAbsent(key, val);
assert asyncCache.future().get() == null;
asyncCache.getAndPutIfAbsent(key, val);
assert val.equals(asyncCache.future().get());
assert cache.containsKey(key);
e = iter.next();
key = e.getKey();
val = e.getValue();
asyncCache.putIfAbsent(key, val);
assert ((Boolean)asyncCache.future().get()).booleanValue();
asyncCache.putIfAbsent(key, val);
assert !((Boolean)asyncCache.future().get()).booleanValue();
assert cache.containsKey(key);
tx.commit();
assert cache.containsKey(key);
}
}
}, evts);
}
/**
*
*/
private static interface TestCacheRunnable {
/**
* @param cache Cache.
* @throws IgniteCheckedException If any exception occurs.
*/
void run(IgniteCache<String, Integer> cache) throws IgniteCheckedException;
}
/**
* Local event listener.
*/
private static class TestEventListener implements IgnitePredicate<Event> {
/** Events count map. */
private static ConcurrentMap<Integer, AtomicInteger> cntrs = new ConcurrentHashMap<>();
/** Event futures. */
private static Collection<EventTypeFuture> futs = new GridConcurrentHashSet<>();
/** */
private static volatile boolean listen = true;
/** */
private static boolean partitioned;
/**
* @param p Partitioned flag.
*/
private TestEventListener(boolean p) {
partitioned = p;
}
/**
*
*/
private static void listen() {
listen = true;
}
/**
*
*/
private static void stopListen() {
listen = false;
}
/**
* @param type Event type.
* @return Count.
*/
static int eventCount(int type) {
assert type > 0;
AtomicInteger cntr = cntrs.get(type);
return cntr != null ? cntr.get() : 0;
}
/**
* Reset listener.
*/
static void reset() {
cntrs.clear();
futs.clear();
}
/** {@inheritDoc} */
@Override public boolean apply(Event evt) {
assert evt instanceof CacheEvent;
if (!listen)
return true;
if (TEST_INFO)
X.println("Cache event: " + evt.shortDisplay());
AtomicInteger cntr = F.addIfAbsent(cntrs, evt.type(), F.newAtomicInt());
assert cntr != null;
int cnt = cntr.incrementAndGet();
for (EventTypeFuture f : futs)
f.onEvent(evt.type(), cnt);
return true;
}
/**
* Waits for event count.
*
* @param evtCnts Array of tuples with values: V1 - event type, V2 - expected event count.
* @throws IgniteCheckedException If failed to wait.
*/
private static void waitForEventCount(IgniteBiTuple<Integer, Integer>... evtCnts)
throws IgniteCheckedException {
if (F.isEmpty(evtCnts))
return;
// Create future that aggregates all required event types.
GridCompoundIdentityFuture<Object> cf = new GridCompoundIdentityFuture<>();
for (IgniteBiTuple<Integer, Integer> t : evtCnts) {
Integer evtType = t.get1();
Integer expCnt = t.get2();
assert expCnt != null && expCnt > 0;
EventTypeFuture fut = new EventTypeFuture(evtType, expCnt, partitioned);
futs.add(fut);
// We need to account the window.
AtomicInteger cntr = cntrs.get(evtType);
if (!fut.isDone())
fut.onEvent(evtType, cntr != null ? cntr.get() : 0);
cf.add(fut);
}
cf.markInitialized();
try {
cf.get(WAIT_TIMEOUT);
}
catch (IgniteFutureTimeoutCheckedException e) {
throw new RuntimeException("Timed out waiting for events: " + cf, e);
}
}
}
/**
*
*/
private static class EventTypeFuture extends GridFutureAdapter<Object> {
/** */
private int evtType;
/** */
private int expCnt;
/** */
private int cnt;
/** Partitioned flag. */
private boolean partitioned;
/**
* @param evtType Event type.
* @param expCnt Expected count.
* @param partitioned Partitioned flag.
*/
EventTypeFuture(int evtType, int expCnt, boolean partitioned) {
assert expCnt > 0;
this.evtType = evtType;
this.expCnt = expCnt;
this.partitioned = partitioned;
}
/**
* @return Count.
*/
int count() {
return cnt;
}
/**
* @param evtType Event type.
* @param cnt Count.
*/
void onEvent(int evtType, int cnt) {
if (isDone() || this.evtType != evtType)
return;
if (TEST_INFO)
X.println("EventTypeFuture.onEvent() [evtName=" + U.gridEventName(evtType) + ", evtType=" + evtType +
", cnt=" + cnt + ", expCnt=" + expCnt + ']');
this.cnt = cnt;
// For partitioned caches we allow extra event for reads.
if (expCnt < cnt && (!partitioned || evtType != EVT_CACHE_OBJECT_READ || expCnt + 1 < cnt))
onDone(new IgniteCheckedException("Wrong event count [evtName=" + U.gridEventName(evtType) + ", evtType=" +
evtType + ", expCnt=" + expCnt + ", actCnt=" + cnt + ", partitioned=" + partitioned + "]"));
if (expCnt == cnt || (partitioned && expCnt + 1 == cnt))
onDone();
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(EventTypeFuture.class, this, "evtName", U.gridEventName(evtType));
}
}
}
|
|
/**
* FlexCore - Licensed under the MIT License (MIT)
*
* Copyright (c) Stealth2800 <http://stealthyone.com/>
* Copyright (c) contributors <https://github.com/FlexSeries>
*
* 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 me.st28.flexseries.flexcore.plugin;
import me.st28.flexseries.flexcore.events.PluginReloadedEvent;
import me.st28.flexseries.flexcore.logging.LogHelper;
import me.st28.flexseries.flexcore.message.MessageManager;
import me.st28.flexseries.flexcore.plugin.exceptions.ModuleDisabledException;
import me.st28.flexseries.flexcore.plugin.module.FlexModule;
import me.st28.flexseries.flexcore.plugin.module.ModuleStatus;
import me.st28.flexseries.flexcore.util.TimeUtils;
import org.apache.commons.lang.Validate;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.event.Listener;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.*;
/**
* Represents a Bukkit plugin that uses FlexCore's plugin framework.
*/
public abstract class FlexPlugin extends JavaPlugin {
/**
* References to each FlexPlugin's autosaving runnable (where applicable).
*/
private static final Map<Class<? extends FlexPlugin>, BukkitRunnable> AUTOSAVE_RUNNABLES = new HashMap<>();
/**
* An index of each FlexPlugin's registered modules, for easy reference via {@link FlexPlugin#getRegisteredModule(Class)}.
*/
private static final Map<Class<? extends FlexModule>, FlexPlugin> REGISTERED_MODULES = new HashMap<>();
/**
* Retrieves a registered {@link FlexModule} from any loaded {@link FlexPlugin}.
*
* @param clazz The class of the module.
* @return The module matching the class.
* @throws java.lang.IllegalArgumentException Thrown if there is no registered module matching the given class.
*/
public static <T extends FlexModule> T getRegisteredModule(Class<T> clazz) {
Validate.notNull(clazz, "Module class cannot be null.");
if (!REGISTERED_MODULES.containsKey(clazz)) {
throw new IllegalArgumentException("No module with class '" + clazz.getCanonicalName() + "' is registered.");
}
FlexPlugin plugin = REGISTERED_MODULES.get(clazz);
if (plugin.getModuleStatus(clazz) != ModuleStatus.ENABLED) {
throw new ModuleDisabledException(plugin.getModule(clazz));
}
return plugin.getModule(clazz);
}
/**
* Retrieves a registered {@link FlexModule} from any loaded {@link FlexPlugin} but returns null if an error occurred.
* @see #getRegisteredModule(Class)
*/
public static <T extends FlexModule> T getRegisteredModuleSilent(Class<T> clazz) {
Validate.notNull(clazz, "Module class cannot be null.");
if (!REGISTERED_MODULES.containsKey(clazz)) {
return null;
}
FlexPlugin plugin = REGISTERED_MODULES.get(clazz);
if (plugin.getModuleStatus(clazz) != ModuleStatus.ENABLED) {
return null;
}
return plugin.getModule(clazz);
}
/**
* The current status of the plugin.
*/
private PluginStatus status;
/**
* Whether or not the plugin has a configuration file.
*/
private boolean hasConfig;
/**
* The {@link FlexModule}s registered under this plugin.
*/
private final Map<Class<? extends FlexModule>, FlexModule> modules = new HashMap<>();
/**
* An index of the module identifiers.
*/
private final Map<String, FlexModule> moduleIdentifiers = new HashMap<>();
/**
* The current load statuses of each registered {@link FlexModule}.
*/
private final Map<Class<? extends FlexModule>, ModuleStatus> moduleStatuses = new HashMap<>();
@Override
public final void onLoad() {
// Mark plugin as loading and start loading data.
status = PluginStatus.LOADING;
try {
handlePluginLoad();
} catch (Exception ex) {
LogHelper.severe(this, "An error occurred while loading: " + ex.getMessage());
LogHelper.severe(this, "The plugin will be disabled to help prevent any damage from occurring.");
ex.printStackTrace();
Bukkit.getPluginManager().disablePlugin(this);
}
}
@Override
public final void onEnable() {
// Mark plugin as enabling and start enabling registered modules.
status = PluginStatus.ENABLING;
long loadStartTime = System.currentTimeMillis();
// Register self as a listener if implemented.
if (this instanceof Listener) {
Bukkit.getPluginManager().registerEvents((Listener) this, this);
}
// Determine if the plugin has a configuration file or not, and save it if there is one.
if (getResource("config.yml") != null) {
saveDefaultConfig();
getConfig().options().copyDefaults(true);
saveConfig();
hasConfig = true;
reloadConfig();
}
// Load modules
//TODO: Detect circular dependencies
List<String> disabledDependencies = hasConfig ? getConfig().getStringList("disabled modules") : null;
List<Class<? extends FlexModule>> loadOrder = new ArrayList<>();
for (FlexModule module : modules.values()) {
addToLoadOrder(loadOrder, module);
}
// !!DEBUG!! //
StringBuilder loadOrderDebug = new StringBuilder("\n--MODULE LOAD ORDER--\n");
for (Class<? extends FlexModule> clazz : loadOrder) {
if (loadOrderDebug.length() > 0) {
loadOrderDebug.append("\n");
}
loadOrderDebug.append(clazz.getCanonicalName());
}
loadOrderDebug.append("\n\n--MODULE LOAD ORDER--\n");
LogHelper.debug(this, loadOrderDebug.toString());
// !!DEBUG!! //
// This monstrosity of a loop determines the order in which modules should be loaded and loads them in the appropriate order.
_moduleLoop: // EWWWWWWWWWW. Yeah, I know.
for (Class<? extends FlexModule> clazz : loadOrder) {
FlexModule<?> module = modules.get(clazz);
LogHelper.info(this, "Loading module: " + module.getIdentifier());
// Check if the module is disabled via the configuration file.
if (disabledDependencies != null && disabledDependencies.contains(module.getIdentifier())) {
moduleStatuses.put(clazz, ModuleStatus.DISABLED_CONFIG);
LogHelper.info(this, "Module '" + module.getIdentifier() + "' disabled via the config.");
continue;
}
// Locate dependencies to make sure all are present.
for (Class<? extends FlexModule> dep : module.getDependencies()) {
// Checks if the dependency is present on the server.
if (!REGISTERED_MODULES.containsKey(dep)) {
moduleStatuses.put(clazz, ModuleStatus.DISABLED_DEPENDENCY);
LogHelper.severe(this, "Unable to load module '" + module.getIdentifier() + "': dependency '" + dep.getCanonicalName() + "' is not a valid module on the server.");
continue _moduleLoop;
}
// Checks if the dependency is enabled.
if (REGISTERED_MODULES.get(dep).getModuleStatus(dep) != ModuleStatus.ENABLED) {
moduleStatuses.put(clazz, ModuleStatus.DISABLED_DEPENDENCY);
LogHelper.severe(this, "Unable to load module '" + module.getIdentifier() + "': dependency '" + dep.getCanonicalName() + "' is disabled.");
continue _moduleLoop;
}
}
// Attempts to load the module.
try {
module.loadAll();
moduleStatuses.put(clazz, ModuleStatus.ENABLED);
LogHelper.info(this, "Successfully loaded module: " + module.getIdentifier());
} catch (Exception ex) {
moduleStatuses.put(clazz, ModuleStatus.DISABLED_ERROR);
LogHelper.severe(this, "An error occurred while loading module '" + module.getIdentifier() + "': " + ex.getMessage());
ex.printStackTrace();
}
if (moduleStatuses.get(clazz) != ModuleStatus.ENABLED) {
modules.remove(clazz);
}
}
// If the plugin has a messages.yml file, a MessageProvider will be created for it.
if (getResource("messages.yml") != null) {
MessageManager.registerMessageProvider(this);
}
// Attempts to enable the plugin.
try {
handlePluginEnable();
handlePluginReload();
} catch (Exception ex) {
LogHelper.severe(this, "An error occurred while enabling: " + ex.getMessage());
status = PluginStatus.LOADED_ERROR;
ex.printStackTrace();
return;
}
status = PluginStatus.ENABLED;
LogHelper.info(this, String.format("%s v%s by %s ENABLED (%dms)", getName(), getDescription().getVersion(), getDescription().getAuthors(), System.currentTimeMillis() - loadStartTime));
}
private void addToLoadOrder(List<Class<? extends FlexModule>> loadOrder, FlexModule<?> module) {
Class<? extends FlexModule> clazz = module.getClass();
if (loadOrder.contains(clazz)) return;
for (Class<? extends FlexModule> depClass : module.getDependencies()) {
if (modules.containsKey(depClass)) {
// From this plugin
addToLoadOrder(loadOrder, modules.get(depClass));
}
}
loadOrder.add(clazz);
}
@Override
public final void onDisable() {
status = PluginStatus.DISABLING;
try {
saveAll(false);
} catch (Exception ex) {
LogHelper.warning(this, "An error occurred while saving: " + ex.getMessage());
ex.printStackTrace();
}
try {
handlePluginDisable();
} catch (Exception ex) {
LogHelper.warning(this, "An error occurred while disabling: " + ex.getMessage());
ex.printStackTrace();
}
}
/**
* Reloads:
* <ul>
* <li>Plugin configuration file</li>
* <li>Registered {@link FlexModule}s</li>
* <li>Custom reload tasks ({@link #handlePluginReload()}</li>
* </ul>
*/
public final void reloadAll() {
reloadConfig();
for (FlexModule module : modules.values()) {
if (getModuleStatus(module.getClass()) == ModuleStatus.ENABLED) {
module.reloadAll();
}
}
handlePluginReload();
Bukkit.getPluginManager().callEvent(new PluginReloadedEvent(this.getClass()));
}
@Override
public final void reloadConfig() {
super.reloadConfig();
if (hasConfig) {
int autosaveInterval = getConfig().getInt("autosave interval", 0);
if (autosaveInterval == 0) {
LogHelper.warning(this, "Autosaving disabled. It is recommended to enable it to help prevent data loss!");
} else {
if (AUTOSAVE_RUNNABLES.containsKey(getClass())) {
AUTOSAVE_RUNNABLES.remove(getClass()).cancel();
}
BukkitRunnable runnable = new BukkitRunnable() {
@Override
public void run() {
saveAll(true);
}
};
runnable.runTaskTimer(this, autosaveInterval * 1200L, autosaveInterval * 1200L);
AUTOSAVE_RUNNABLES.put(getClass(), runnable);
LogHelper.info(this, "Autosaving enabled. Saving every " + TimeUtils.translateSeconds(autosaveInterval * 60) + ".");
}
handleConfigReload(getConfig());
}
}
/**
* Saves the entirety of the plugin.
*
* @param async If true, should save asynchronously (where applicable).
*/
public final void saveAll(boolean async) {
if (hasConfig) {
saveConfig();
}
for (FlexModule<?> module : modules.values()) {
if (getModuleStatus(module.getClass()) == ModuleStatus.ENABLED) {
module.saveAll(async);
}
}
handlePluginSave(async);
}
/**
* @return true if the plugin has a configuration file.
*/
public final boolean hasConfig() {
return hasConfig;
}
/**
* @return the current status of the plugin.
*/
public final PluginStatus getStatus() {
return status;
}
/**
* @return the current status for a module registered for this plugin.
* @throws java.lang.IllegalArgumentException Thrown if the module is not registered under this plugin.
*/
public final ModuleStatus getModuleStatus(Class<? extends FlexModule> module) {
if (!moduleStatuses.containsKey(module)) {
throw new IllegalArgumentException("Module with class '" + module.getCanonicalName() + "' is not registered underneath this plugin.");
}
return moduleStatuses.get(module);
}
/**
* @return a read-only collection of all of the registered modules for this plugin.
*/
public final Collection<FlexModule> getModules() {
return Collections.unmodifiableCollection(modules.values());
}
/**
* @return a module registered for this plugin.
* @throws java.lang.IllegalArgumentException Thrown if the module is not registered under this plugin.
*/
public final <T extends FlexModule> T getModule(Class<T> clazz) {
if (!modules.containsKey(clazz)) {
throw new IllegalArgumentException("Module with class '" + clazz.getCanonicalName() + "' is not registered underneath this plugin.");
}
return (T) modules.get(clazz);
}
/**
* Registers a FlexModule for this plugin.
*
* @param module The module to register.
* @return True if successfully registered.<br />
* False if the module's class has already been registered.
* @throws java.lang.IllegalStateException Thrown if this method after the plugin has gone through the loading phase.
*/
public final boolean registerModule(FlexModule module) {
Validate.notNull(module, "Module cannot be null.");
Class<? extends FlexModule> clazz = module.getClass();
if (REGISTERED_MODULES.containsKey(clazz)) {
return false;
}
if (status != PluginStatus.LOADING) {
throw new IllegalStateException("Currently not accepting new module registrations.");
}
REGISTERED_MODULES.put(clazz, this);
modules.put(clazz, module);
moduleStatuses.put(clazz, null);
return true;
}
/**
* Handles custom load tasks, such as, but not limited to:
* <ul>
* <li>Registering modules</li>
* </ul>
*/
public void handlePluginLoad() {}
/**
* Handles custom enable tasks.
*/
public void handlePluginEnable() {}
/**
* Handles custom disable tasks.
*/
public void handlePluginDisable() {}
/**
* Handles custom reload tasks.
*/
public void handlePluginReload() {}
/**
* Handles custom config reload tasks.
*/
public void handleConfigReload(FileConfiguration config) {}
/**
* Handles custom save tasks.
*
* @param async If true, should save asynchronously (where applicable).
*/
public void handlePluginSave(boolean async) {}
}
|
|
/*
* 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.gobblin.service.modules.orchestration;
import java.io.IOException;
import java.net.URI;
import java.util.Collections;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.mockito.Mockito;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import com.google.common.base.Predicate;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigValueFactory;
import javax.annotation.Nullable;
import org.apache.gobblin.configuration.ConfigurationKeys;
import org.apache.gobblin.runtime.api.FlowSpec;
import org.apache.gobblin.runtime.api.TopologySpec;
import org.apache.gobblin.service.ExecutionStatus;
import org.apache.gobblin.service.FlowId;
import org.apache.gobblin.service.modules.flowgraph.Dag;
import org.apache.gobblin.service.modules.spec.JobExecutionPlan;
import org.apache.gobblin.service.monitoring.JobStatusRetriever;
import org.apache.gobblin.testing.AssertWithBackoff;
import org.apache.gobblin.util.ConfigUtils;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class DagManagerFlowTest {
MockedDagManager dagManager;
int dagNumThreads;
static final String ERROR_MESSAGE = "Waiting for the map to update";
@BeforeClass
public void setUp() {
Properties props = new Properties();
props.put(DagManager.JOB_STATUS_POLLING_INTERVAL_KEY, 1);
dagManager = new MockedDagManager(ConfigUtils.propertiesToConfig(props), false);
dagManager.setActive(true);
this.dagNumThreads = dagManager.getNumThreads();
}
@Test
void testAddDeleteSpec() throws Exception {
long flowExecutionId1 = System.currentTimeMillis();
long flowExecutionId2 = flowExecutionId1 + 1;
long flowExecutionId3 = flowExecutionId1 + 2;
Dag<JobExecutionPlan> dag1 = DagManagerTest.buildDag("0", flowExecutionId1, "FINISH_RUNNING", 1);
Dag<JobExecutionPlan> dag2 = DagManagerTest.buildDag("1", flowExecutionId2, "FINISH_RUNNING", 1);
Dag<JobExecutionPlan> dag3 = DagManagerTest.buildDag("2", flowExecutionId3, "FINISH_RUNNING", 1);
String dagId1 = DagManagerUtils.generateDagId(dag1);
String dagId2 = DagManagerUtils.generateDagId(dag2);
String dagId3 = DagManagerUtils.generateDagId(dag3);
int queue1 = DagManagerUtils.getDagQueueId(dag1, dagNumThreads);
int queue2 = DagManagerUtils.getDagQueueId(dag2, dagNumThreads);
int queue3 = DagManagerUtils.getDagQueueId(dag3, dagNumThreads);
when(this.dagManager.getJobStatusRetriever().getLatestExecutionIdsForFlow(eq("flow0"), eq("group0"), anyInt()))
.thenReturn(Collections.singletonList(flowExecutionId1));
when(this.dagManager.getJobStatusRetriever().getLatestExecutionIdsForFlow(eq("flow1"), eq("group1"), anyInt()))
.thenReturn(Collections.singletonList(flowExecutionId2));
when(this.dagManager.getJobStatusRetriever().getLatestExecutionIdsForFlow(eq("flow2"), eq("group2"), anyInt()))
.thenReturn(Collections.singletonList(flowExecutionId3));
// mock add spec
dagManager.addDag(dag1, true, true);
dagManager.addDag(dag2, true, true);
dagManager.addDag(dag3, true, true);
// check existence of dag in dagToJobs map
AssertWithBackoff.create().maxSleepMs(5000).backoffFactor(1).
assertTrue(input -> dagManager.dagManagerThreads[queue1].dagToJobs.containsKey(dagId1), ERROR_MESSAGE);
AssertWithBackoff.create().maxSleepMs(1000).backoffFactor(1).
assertTrue(input -> dagManager.dagManagerThreads[queue2].dagToJobs.containsKey(dagId2), ERROR_MESSAGE);
AssertWithBackoff.create().maxSleepMs(1000).backoffFactor(1).
assertTrue(input -> dagManager.dagManagerThreads[queue3].dagToJobs.containsKey(dagId3), ERROR_MESSAGE);
// mock cancel job
dagManager.stopDag(FlowSpec.Utils.createFlowSpecUri(new FlowId().setFlowGroup("group0").setFlowName("flow0")));
dagManager.stopDag(FlowSpec.Utils.createFlowSpecUri(new FlowId().setFlowGroup("group1").setFlowName("flow1")));
dagManager.stopDag(FlowSpec.Utils.createFlowSpecUri(new FlowId().setFlowGroup("group2").setFlowName("flow2")));
// verify cancelJob() of specProducer is called once
AssertWithBackoff.create().maxSleepMs(5000).backoffFactor(1).assertTrue(new CancelPredicate(dag1), ERROR_MESSAGE);
AssertWithBackoff.create().maxSleepMs(1000).backoffFactor(1).assertTrue(new CancelPredicate(dag2), ERROR_MESSAGE);
AssertWithBackoff.create().maxSleepMs(1000).backoffFactor(1).assertTrue(new CancelPredicate(dag3), ERROR_MESSAGE);
// mock flow cancellation tracking event
Mockito.doReturn(DagManagerTest.getMockJobStatus("flow0", "group0", flowExecutionId1,
"group0", "job0", String.valueOf(ExecutionStatus.CANCELLED)))
.when(dagManager.getJobStatusRetriever()).getJobStatusesForFlowExecution("flow0", "group0",
flowExecutionId1, "job0", "group0");
Mockito.doReturn(DagManagerTest.getMockJobStatus("flow1", "group1", flowExecutionId2,
"group1", "job0", String.valueOf(ExecutionStatus.CANCELLED)))
.when(dagManager.getJobStatusRetriever()).getJobStatusesForFlowExecution("flow1", "group1",
flowExecutionId2, "job0", "group1");
Mockito.doReturn(DagManagerTest.getMockJobStatus("flow2", "group2", flowExecutionId3,
"group2", "job0", String.valueOf(ExecutionStatus.CANCELLED)))
.when(dagManager.getJobStatusRetriever()).getJobStatusesForFlowExecution("flow2", "group2",
flowExecutionId3, "job0", "group2");
// check removal of dag in dagToJobs map
AssertWithBackoff.create().maxSleepMs(5000).backoffFactor(1).
assertTrue(input -> !dagManager.dagManagerThreads[queue1].dagToJobs.containsKey(dagId1), ERROR_MESSAGE);
AssertWithBackoff.create().maxSleepMs(1000).backoffFactor(1).
assertTrue(input -> !dagManager.dagManagerThreads[queue2].dagToJobs.containsKey(dagId2), ERROR_MESSAGE);
AssertWithBackoff.create().maxSleepMs(1000).backoffFactor(1).
assertTrue(input -> !dagManager.dagManagerThreads[queue3].dagToJobs.containsKey(dagId3), ERROR_MESSAGE);
}
@Test
void testFlowSlaWithoutConfig() throws Exception {
long flowExecutionId = System.currentTimeMillis();
Dag<JobExecutionPlan> dag = DagManagerTest.buildDag("3", flowExecutionId, "FINISH_RUNNING", 1);
String dagId = DagManagerUtils.generateDagId(dag);
int queue = DagManagerUtils.getDagQueueId(dag, dagNumThreads);
when(this.dagManager.getJobStatusRetriever().getLatestExecutionIdsForFlow(eq("flow3"), eq("group3"), anyInt()))
.thenReturn(Collections.singletonList(flowExecutionId));
// mock add spec
dagManager.addDag(dag, true, true);
// check existence of dag in dagToJobs map
AssertWithBackoff.create().maxSleepMs(5000).backoffFactor(1).
assertTrue(input -> dagManager.dagManagerThreads[queue].dagToJobs.containsKey(dagId), ERROR_MESSAGE);
// check existence of dag in dagToSLA map
AssertWithBackoff.create().maxSleepMs(5000).backoffFactor(1).
assertTrue(input -> dagManager.dagManagerThreads[queue].dagToSLA.containsKey(dagId), ERROR_MESSAGE);
// check the SLA value
Assert.assertEquals(dagManager.dagManagerThreads[queue].dagToSLA.get(dagId).longValue(), DagManagerUtils.DEFAULT_FLOW_SLA_MILLIS);
// verify cancelJob() of the specProducer is not called once
// which means job cancellation was triggered
try {
AssertWithBackoff.create().maxSleepMs(5000).backoffFactor(1).assertTrue(new CancelPredicate(dag), ERROR_MESSAGE);
} catch (TimeoutException e) {
AssertWithBackoff.create().maxSleepMs(5000).backoffFactor(1).
assertTrue(input -> dagManager.dagManagerThreads[queue].dagToJobs.containsKey(dagId), ERROR_MESSAGE);
return;
}
Assert.fail("Job cancellation was not triggered.");
}
@Test()
void testFlowSlaWithConfig() throws Exception {
long flowExecutionId = System.currentTimeMillis();
Dag<JobExecutionPlan> dag = DagManagerTest.buildDag("4", flowExecutionId, "FINISH_RUNNING", 1);
String dagId = DagManagerUtils.generateDagId(dag);
int queue = DagManagerUtils.getDagQueueId(dag, dagNumThreads);
when(this.dagManager.getJobStatusRetriever().getLatestExecutionIdsForFlow(eq("flow4"), eq("group4"), anyInt()))
.thenReturn(Collections.singletonList(flowExecutionId));
// change config to set a small sla
Config jobConfig = dag.getStartNodes().get(0).getValue().getJobSpec().getConfig();
jobConfig = jobConfig
.withValue(ConfigurationKeys.GOBBLIN_FLOW_SLA_TIME, ConfigValueFactory.fromAnyRef("7"))
.withValue(ConfigurationKeys.GOBBLIN_FLOW_SLA_TIME_UNIT, ConfigValueFactory.fromAnyRef(TimeUnit.SECONDS.name()));
dag.getStartNodes().get(0).getValue().getJobSpec().setConfig(jobConfig);
// mock add spec
dagManager.addDag(dag, true, true);
// check existence of dag in dagToSLA map
AssertWithBackoff.create().maxSleepMs(5000).backoffFactor(1).
assertTrue(input -> dagManager.dagManagerThreads[queue].dagToSLA.containsKey(dagId), ERROR_MESSAGE);
// check the SLA value
Assert.assertEquals(dagManager.dagManagerThreads[queue].dagToSLA.get(dagId).longValue(), TimeUnit.SECONDS.toMillis(7L));
// check existence of dag in dagToJobs map
AssertWithBackoff.create().maxSleepMs(5000).backoffFactor(1).
assertTrue(input -> dagManager.dagManagerThreads[queue].dagToJobs.containsKey(dagId), ERROR_MESSAGE);
// verify cancelJob() of specProducer is called once
// which means job cancellation was triggered
AssertWithBackoff.create().maxSleepMs(5000).backoffFactor(1).assertTrue(new CancelPredicate(dag), ERROR_MESSAGE);
// check removal of dag from dagToSLA map
AssertWithBackoff.create().maxSleepMs(5000).backoffFactor(1).
assertTrue(input -> !dagManager.dagManagerThreads[queue].dagToSLA.containsKey(dagId), ERROR_MESSAGE);
}
@Test()
void testOrphanFlowKill() throws Exception {
Long flowExecutionId = System.currentTimeMillis() - TimeUnit.SECONDS.toMillis(10);
Dag<JobExecutionPlan> dag = DagManagerTest.buildDag("6", flowExecutionId, "FINISH_RUNNING", 1);
String dagId = DagManagerUtils.generateDagId(dag);
int queue = DagManagerUtils.getDagQueueId(dag, dagNumThreads);
// change config to set a small sla
Config jobConfig = dag.getStartNodes().get(0).getValue().getJobSpec().getConfig();
jobConfig = jobConfig
.withValue(ConfigurationKeys.GOBBLIN_JOB_START_SLA_TIME, ConfigValueFactory.fromAnyRef("7"))
.withValue(ConfigurationKeys.GOBBLIN_JOB_START_SLA_TIME_UNIT, ConfigValueFactory.fromAnyRef(TimeUnit.SECONDS.name()));
dag.getStartNodes().get(0).getValue().getJobSpec().setConfig(jobConfig);
// mock add spec
dagManager.addDag(dag, true, true);
// check existence of dag in dagToSLA map
AssertWithBackoff.create().maxSleepMs(5000).backoffFactor(1).
assertTrue(input -> dagManager.dagManagerThreads[queue].dagToSLA.containsKey(dagId), ERROR_MESSAGE);
Mockito.doReturn(DagManagerTest.getMockJobStatus("flow6", "group6", flowExecutionId,
"group6", "job0", String.valueOf(ExecutionStatus.ORCHESTRATED)))
.when(dagManager.getJobStatusRetriever()).getJobStatusesForFlowExecution("flow6", "group6",
flowExecutionId, "job0", "group6");
// check existence of dag in dagToJobs map
AssertWithBackoff.create().maxSleepMs(5000).backoffFactor(1).
assertTrue(input -> dagManager.dagManagerThreads[queue].dagToJobs.containsKey(dagId), ERROR_MESSAGE);
// verify cancelJob() of specProducer is called once
// which means job cancellation was triggered
AssertWithBackoff.create().maxSleepMs(5000).backoffFactor(1).assertTrue(new CancelPredicate(dag), ERROR_MESSAGE);
// check removal of dag from dagToSLA map
AssertWithBackoff.create().maxSleepMs(5000).backoffFactor(1).
assertTrue(input -> !dagManager.dagManagerThreads[queue].dagToSLA.containsKey(dagId), ERROR_MESSAGE);
}
@Test
void slaConfigCheck() throws Exception {
Dag<JobExecutionPlan> dag = DagManagerTest.buildDag("5", 123456783L, "FINISH_RUNNING", 1);
Assert.assertEquals(DagManagerUtils.getFlowSLA(dag.getStartNodes().get(0)), DagManagerUtils.DEFAULT_FLOW_SLA_MILLIS);
Config jobConfig = dag.getStartNodes().get(0).getValue().getJobSpec().getConfig();
jobConfig = jobConfig
.withValue(ConfigurationKeys.GOBBLIN_FLOW_SLA_TIME, ConfigValueFactory.fromAnyRef("7"))
.withValue(ConfigurationKeys.GOBBLIN_FLOW_SLA_TIME_UNIT, ConfigValueFactory.fromAnyRef(TimeUnit.SECONDS.name()));
dag.getStartNodes().get(0).getValue().getJobSpec().setConfig(jobConfig);
Assert.assertEquals(DagManagerUtils.getFlowSLA(dag.getStartNodes().get(0)), TimeUnit.SECONDS.toMillis(7L));
jobConfig = jobConfig
.withValue(ConfigurationKeys.GOBBLIN_FLOW_SLA_TIME, ConfigValueFactory.fromAnyRef("8"))
.withValue(ConfigurationKeys.GOBBLIN_FLOW_SLA_TIME_UNIT, ConfigValueFactory.fromAnyRef(TimeUnit.MINUTES.name()));
dag.getStartNodes().get(0).getValue().getJobSpec().setConfig(jobConfig);
Assert.assertEquals(DagManagerUtils.getFlowSLA(dag.getStartNodes().get(0)), TimeUnit.MINUTES.toMillis(8L));
}
}
class CancelPredicate implements Predicate<Void> {
private final Dag<JobExecutionPlan> dag;
public CancelPredicate(Dag<JobExecutionPlan> dag) {
this.dag = dag;
}
@Override
public boolean apply(@Nullable Void input) {
try {
verify(dag.getNodes().get(0).getValue().getSpecExecutor().getProducer().get()).cancelJob(any(), any());
} catch (Throwable e) {
return false;
}
return true;
}
}
class MockedDagManager extends DagManager {
public MockedDagManager(Config config, boolean instrumentationEnabled) {
super(config, createJobStatusRetriever(), instrumentationEnabled);
}
private static JobStatusRetriever createJobStatusRetriever() {
JobStatusRetriever mockedJbStatusRetriever = Mockito.mock(JobStatusRetriever.class);
Mockito.doReturn(Collections.emptyIterator()).when(mockedJbStatusRetriever).
getJobStatusesForFlowExecution(anyString(), anyString(), anyLong(), anyString(), anyString());
return mockedJbStatusRetriever;
}
@Override
DagStateStore createDagStateStore(Config config, Map<URI, TopologySpec> topologySpecMap) {
DagStateStore mockedDagStateStore = Mockito.mock(DagStateStore.class);
try {
doNothing().when(mockedDagStateStore).writeCheckpoint(any());
} catch (IOException e) {
throw new RuntimeException(e);
}
return mockedDagStateStore;
}
}
|
|
/*
* Copyright 2012-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.autoconfigure.velocity;
import java.io.File;
import java.io.StringWriter;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.boot.test.EnvironmentTestUtils;
import org.springframework.boot.web.servlet.view.velocity.EmbeddedVelocityViewResolver;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockServletContext;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.resource.ResourceUrlEncodingFilter;
import org.springframework.web.servlet.support.RequestContext;
import org.springframework.web.servlet.view.AbstractTemplateViewResolver;
import org.springframework.web.servlet.view.velocity.VelocityConfigurer;
import org.springframework.web.servlet.view.velocity.VelocityViewResolver;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
/**
* Tests for {@link VelocityAutoConfiguration}.
*
* @author Andy Wilkinson
*/
public class VelocityAutoConfigurationTests {
private AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
@Before
public void setupContext() {
this.context.setServletContext(new MockServletContext());
}
@After
public void close() {
if (this.context != null) {
this.context.close();
}
}
@Test
public void defaultConfiguration() {
registerAndRefreshContext();
assertThat(this.context.getBean(VelocityViewResolver.class), notNullValue());
assertThat(this.context.getBean(VelocityConfigurer.class), notNullValue());
}
@Test(expected = BeanCreationException.class)
public void nonExistentTemplateLocation() {
registerAndRefreshContext("spring.velocity.resourceLoaderPath:"
+ "classpath:/does-not-exist/");
}
@Test
public void emptyTemplateLocation() {
new File("target/test-classes/templates/empty-directory").mkdir();
registerAndRefreshContext("spring.velocity.resourceLoaderPath:"
+ "classpath:/templates/empty-directory/");
}
@Test
public void defaultViewResolution() throws Exception {
registerAndRefreshContext();
MockHttpServletResponse response = render("home");
String result = response.getContentAsString();
assertThat(result, containsString("home"));
assertThat(response.getContentType(), equalTo("text/html;charset=UTF-8"));
}
@Test
public void customContentType() throws Exception {
registerAndRefreshContext("spring.velocity.contentType:application/json");
MockHttpServletResponse response = render("home");
String result = response.getContentAsString();
assertThat(result, containsString("home"));
assertThat(response.getContentType(), equalTo("application/json;charset=UTF-8"));
}
@Test
public void customPrefix() throws Exception {
registerAndRefreshContext("spring.velocity.prefix:prefix/");
MockHttpServletResponse response = render("prefixed");
String result = response.getContentAsString();
assertThat(result, containsString("prefixed"));
}
@Test
public void customSuffix() throws Exception {
registerAndRefreshContext("spring.velocity.suffix:.freemarker");
MockHttpServletResponse response = render("suffixed");
String result = response.getContentAsString();
assertThat(result, containsString("suffixed"));
}
@Test
public void customTemplateLoaderPath() throws Exception {
registerAndRefreshContext("spring.velocity.resourceLoaderPath:classpath:/custom-templates/");
MockHttpServletResponse response = render("custom");
String result = response.getContentAsString();
assertThat(result, containsString("custom"));
}
@Test
public void disableCache() {
registerAndRefreshContext("spring.velocity.cache:false");
assertThat(this.context.getBean(VelocityViewResolver.class).getCacheLimit(),
equalTo(0));
}
@Test
public void customVelocitySettings() {
registerAndRefreshContext("spring.velocity.properties.directive.parse.max.depth:10");
assertThat(this.context.getBean(VelocityConfigurer.class).getVelocityEngine()
.getProperty("directive.parse.max.depth"), equalTo((Object) "10"));
}
@Test
public void renderTemplate() throws Exception {
registerAndRefreshContext();
VelocityConfigurer velocity = this.context.getBean(VelocityConfigurer.class);
StringWriter writer = new StringWriter();
Template template = velocity.getVelocityEngine().getTemplate("message.vm");
template.process();
VelocityContext velocityContext = new VelocityContext();
velocityContext.put("greeting", "Hello World");
template.merge(velocityContext, writer);
assertThat(writer.toString(), containsString("Hello World"));
}
@Test
public void renderNonWebAppTemplate() throws Exception {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
VelocityAutoConfiguration.class);
try {
VelocityEngine velocity = context.getBean(VelocityEngine.class);
StringWriter writer = new StringWriter();
Template template = velocity.getTemplate("message.vm");
template.process();
VelocityContext velocityContext = new VelocityContext();
velocityContext.put("greeting", "Hello World");
template.merge(velocityContext, writer);
assertThat(writer.toString(), containsString("Hello World"));
}
finally {
context.close();
}
}
@Test
public void usesEmbeddedVelocityViewResolver() {
registerAndRefreshContext("spring.velocity.toolbox:/toolbox.xml");
VelocityViewResolver resolver = this.context.getBean(VelocityViewResolver.class);
assertThat(resolver, instanceOf(EmbeddedVelocityViewResolver.class));
}
@Test
public void registerResourceHandlingFilter() throws Exception {
registerAndRefreshContext();
assertNotNull(this.context.getBean(ResourceUrlEncodingFilter.class));
}
@Test
public void allowSessionOverride() {
registerAndRefreshContext("spring.velocity.allow-session-override:true");
AbstractTemplateViewResolver viewResolver = this.context
.getBean(VelocityViewResolver.class);
assertThat((Boolean) ReflectionTestUtils.getField(viewResolver,
"allowSessionOverride"), is(true));
}
private void registerAndRefreshContext(String... env) {
EnvironmentTestUtils.addEnvironment(this.context, env);
this.context.register(VelocityAutoConfiguration.class);
this.context.refresh();
}
public String getGreeting() {
return "Hello World";
}
private MockHttpServletResponse render(String viewName) throws Exception {
VelocityViewResolver resolver = this.context.getBean(VelocityViewResolver.class);
View view = resolver.resolveViewName(viewName, Locale.UK);
assertThat(view, notNullValue());
HttpServletRequest request = new MockHttpServletRequest();
request.setAttribute(RequestContext.WEB_APPLICATION_CONTEXT_ATTRIBUTE,
this.context);
MockHttpServletResponse response = new MockHttpServletResponse();
view.render(null, request, response);
return response;
}
}
|
|
/* The contents of this file are subject to the license and copyright terms
* detailed in the license directory at the root of the source tree (also
* available online at http://fedora-commons.org/license/).
*/
package org.fcrepo.server.storage;
import java.io.File;
import java.net.URI;
import java.net.URL;
import java.util.Hashtable;
import java.util.Map;
import javax.activation.MimetypesFileTypeMap;
import org.apache.commons.httpclient.Header;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.fcrepo.common.http.HttpInputStream;
import org.fcrepo.common.http.WebClient;
import org.fcrepo.common.http.WebClientConfiguration;
import org.fcrepo.server.Module;
import org.fcrepo.server.Server;
import org.fcrepo.server.errors.GeneralException;
import org.fcrepo.server.errors.HttpServiceNotFoundException;
import org.fcrepo.server.errors.ModuleInitializationException;
import org.fcrepo.server.errors.authorization.AuthzException;
import org.fcrepo.server.security.Authorization;
import org.fcrepo.server.security.BackendPolicies;
import org.fcrepo.server.security.BackendSecurity;
import org.fcrepo.server.security.BackendSecuritySpec;
import org.fcrepo.server.storage.types.MIMETypedStream;
import org.fcrepo.server.storage.types.Property;
import org.fcrepo.server.utilities.ServerUtility;
/**
* Provides a mechanism to obtain external HTTP-accessible content.
*
* @author Ross Wayland
* @version $Id$
*
*/
public class DefaultExternalContentManager
extends Module
implements ExternalContentManager {
private static final Logger logger =
LoggerFactory.getLogger(DefaultExternalContentManager.class);
private static final String DEFAULT_MIMETYPE="text/plain";
private String m_userAgent;
private String fedoraServerHost;
private String fedoraServerPort;
private String fedoraServerRedirectPort;
private WebClientConfiguration m_httpconfig;
private WebClient m_http;
/**
* Creates a new DefaultExternalContentManager.
*
* @param moduleParameters
* The name/value pair map of module parameters.
* @param server
* The server instance.
* @param role
* The module role name.
* @throws ModuleInitializationException
* If initialization values are invalid or initialization fails for
* some other reason.
*/
public DefaultExternalContentManager(Map<String, String> moduleParameters,
Server server,
String role)
throws ModuleInitializationException {
super(moduleParameters, server, role);
}
/**
* Initializes the Module based on configuration parameters. The
* implementation of this method is dependent on the schema used to define
* the parameter names for the role of
* <code>org.fcrepo.server.storage.DefaultExternalContentManager</code>.
*
* @throws ModuleInitializationException
* If initialization values are invalid or initialization fails for
* some other reason.
*/
@Override
public void initModule() throws ModuleInitializationException {
try {
Server s_server = getServer();
m_userAgent = getParameter("userAgent");
if (m_userAgent == null) {
m_userAgent = "Fedora";
}
fedoraServerPort = s_server.getParameter("fedoraServerPort");
fedoraServerHost = s_server.getParameter("fedoraServerHost");
fedoraServerRedirectPort =
s_server.getParameter("fedoraRedirectPort");
m_httpconfig = s_server.getWebClientConfig();
if (m_httpconfig.getUserAgent() == null ) {
m_httpconfig.setUserAgent(m_userAgent);
}
m_http = new WebClient(m_httpconfig);
} catch (Throwable th) {
throw new ModuleInitializationException("[DefaultExternalContentManager] "
+ "An external content manager "
+ "could not be instantiated. The underlying error was a "
+ th.getClass()
.getName()
+ "The message was \""
+ th.getMessage()
+ "\".",
getRole());
}
}
/*
* Retrieves the external content.
* Currently the protocols <code>file</code> and
* <code>http[s]</code> are supported.
*
* @see
* org.fcrepo.server.storage.ExternalContentManager#getExternalContent(fedora
* .server.storage.ContentManagerParams)
*/
public MIMETypedStream getExternalContent(ContentManagerParams params)
throws GeneralException, HttpServiceNotFoundException{
logger.debug("in getExternalContent(), url=" + params.getUrl());
try {
if(params.getProtocol().equals("file")){
return getFromFilesystem(params);
}
if (params.getProtocol().equals("http") || params.getProtocol().equals("https")){
return getFromWeb(params);
}
throw new GeneralException("protocol for retrieval of external content not supported. URL: " + params.getUrl());
} catch (Exception ex) {
// catch anything but generalexception
ex.printStackTrace();
throw new HttpServiceNotFoundException("[" + this.getClass().getSimpleName() + "] "
+ "returned an error. The underlying error was a "
+ ex.getClass().getName()
+ " The message "
+ "was \""
+ ex.getMessage() + "\" . ",ex);
}
}
/**
* Get a MIMETypedStream for the given URL. If user or password are
* <code>null</code>, basic authentication will not be attempted.
*/
private MIMETypedStream get(String url, String user, String pass, String knownMimeType)
throws GeneralException {
logger.debug("DefaultExternalContentManager.get(" + url + ")");
try {
HttpInputStream response = m_http.get(url, true, user, pass);
String mimeType =
response.getResponseHeaderValue("Content-Type",
knownMimeType);
Property[] headerArray =
toPropertyArray(response.getResponseHeaders());
if (mimeType == null || mimeType.equals("")) {
mimeType = DEFAULT_MIMETYPE;
}
return new MIMETypedStream(mimeType, response, headerArray);
} catch (Exception e) {
throw new GeneralException("Error getting " + url, e);
}
}
/**
* Convert the given HTTP <code>Headers</code> to an array of
* <code>Property</code> objects.
*/
private static Property[] toPropertyArray(Header[] headers) {
Property[] props = new Property[headers.length];
for (int i = 0; i < headers.length; i++) {
props[i] = new Property();
props[i].name = headers[i].getName();
props[i].value = headers[i].getValue();
}
return props;
}
/**
* Creates a property array out of the MIME type and the length of the
* provided file.
*
* @param file
* the file containing the content.
* @return an array of properties containing content-length and
* content-type.
*/
private static Property[] getPropertyArray(File file, String mimeType) {
Property[] props = new Property[2];
Property clen = new Property("Content-Length",Long.toString(file.length()));
Property ctype = new Property("Content-Type", mimeType);
props[0] = clen;
props[1] = ctype;
return props;
}
/**
* Get a MIMETypedStream for the given URL. If user or password are
* <code>null</code>, basic authentication will not be attempted.
*
* @param params
* @return
* @throws HttpServiceNotFoundException
* @throws GeneralException
*/
private MIMETypedStream getFromFilesystem(ContentManagerParams params)
throws HttpServiceNotFoundException,GeneralException {
logger.debug("in getFile(), url=" + params.getUrl());
try {
URL fileUrl = new URL(params.getUrl());
File cFile = new File(fileUrl.toURI()).getCanonicalFile();
// security check
URI cURI = cFile.toURI();
logger.info("Checking resolution security on " + cURI);
Authorization authModule = (Authorization) getServer().getModule(
"org.fcrepo.server.security.Authorization");
if (authModule == null) {
throw new GeneralException(
"Missing required Authorization module");
}
authModule.enforceRetrieveFile(params.getContext(), cURI.toString());
// end security check
String mimeType = params.getMimeType();
// if mimeType was not given, try to determine it automatically
if (mimeType == null || mimeType.equalsIgnoreCase("")){
mimeType = determineMimeType(cFile);
}
return new MIMETypedStream(mimeType,fileUrl.openStream(),getPropertyArray(cFile,mimeType));
}
catch(AuthzException ae){
logger.error(ae.getMessage(),ae);
throw new HttpServiceNotFoundException("Policy blocked datastream resolution",ae);
}
catch (GeneralException me) {
logger.error(me.getMessage(),me);
throw me;
} catch (Throwable th) {
th.printStackTrace(System.err);
// catch anything but generalexception
logger.error(th.getMessage(),th);
throw new HttpServiceNotFoundException("[FileExternalContentManager] "
+ "returned an error. The underlying error was a "
+ th.getClass().getName()
+ " The message "
+ "was \""
+ th.getMessage() + "\" . ",th);
}
}
/**
* Retrieves external content via http or https.
*
* @param url
* The url pointing to the content.
* @param context
* The Map containing parameters.
* @param mimeType
* The default MIME type to be used in case no MIME type can be
* detected.
* @return A MIMETypedStream
* @throws ModuleInitializationException
* @throws GeneralException
*/
private MIMETypedStream getFromWeb(ContentManagerParams params)
throws ModuleInitializationException, GeneralException {
String username = params.getUsername();
String password = params.getPassword();
boolean backendSSL = false;
String url = params.getUrl();
if (ServerUtility.isURLFedoraServer(url) && !params.isBypassBackend()) {
BackendSecuritySpec m_beSS;
BackendSecurity m_beSecurity =
(BackendSecurity) getServer()
.getModule("org.fcrepo.server.security.BackendSecurity");
try {
m_beSS = m_beSecurity.getBackendSecuritySpec();
} catch (Exception e) {
throw new ModuleInitializationException(
"Can't intitialize BackendSecurity module (in default access) from Server.getModule",
getRole());
}
Hashtable<String, String> beHash =
m_beSS.getSecuritySpec(BackendPolicies.FEDORA_INTERNAL_CALL);
username = beHash.get("callUsername");
password = beHash.get("callPassword");
backendSSL =
new Boolean(beHash.get("callSSL"))
.booleanValue();
if (backendSSL) {
if (params.getProtocol().equals("http:")) {
url = url.replaceFirst("http:", "https:");
}
url =
url.replaceFirst(":" + fedoraServerPort + "/",
":" + fedoraServerRedirectPort
+ "/");
}
if (logger.isDebugEnabled()) {
logger.debug("************************* backendUsername: "
+ username + " backendPassword: "
+ password + " backendSSL: " + backendSSL);
logger.debug("************************* doAuthnGetURL: " + url);
}
}
return get(url, username, password, params.getMimeType());
}
/**
* Determines the mime type of a given file
*
* @param file for which the mime type needs to be detected
* @return the detected mime type
*/
private String determineMimeType(File file){
String mimeType = new MimetypesFileTypeMap().getContentType(file);
// if mimeType detection failed, fall back to the default
if (mimeType == null || mimeType.equalsIgnoreCase("")){
mimeType = DEFAULT_MIMETYPE;
}
return mimeType;
}
}
|
|
package se.sitic.megatron.entity.base;
import java.io.Serializable;
/**
* This is an object that contains data related to the organization table.
* Do not modify this class because it will be overwritten if the configuration file
* related to this class is modified.
*
* @hibernate.class
* table="organization"
*/
public abstract class BaseOrganization implements Serializable {
private static final long serialVersionUID = 1L;
public static String REF = "Organization";
public static String PROP_ENABLED = "Enabled";
public static String PROP_DESCRIPTION = "Description";
public static String PROP_EMAIL_ADDRESSES = "EmailAddresses";
public static String PROP_MODIFIED_BY = "ModifiedBy";
public static String PROP_COMMENT = "Comment";
public static String PROP_REGISTRATION_NO = "RegistrationNo";
public static String PROP_PRIORITY = "Priority";
public static String PROP_NAME = "Name";
public static String PROP_CREATED = "Created";
public static String PROP_LANGUAGE_CODE = "LanguageCode";
public static String PROP_ID = "Id";
public static String PROP_COUNTRY_CODE = "CountryCode";
public static String PROP_LAST_MODIFIED = "LastModified";
public static String PROP_AUTO_UPDATE_MATCH_FIELDS = "AutoUpdateMatchFields";
public static String PROP_AUTO_UPDATE_EMAIL = "AutoUpdateEmail";
// constructors
public BaseOrganization () {
initialize();
}
/**
* Constructor for primary key
*/
public BaseOrganization (java.lang.Integer id) {
this.setId(id);
initialize();
}
/**
* Constructor for required fields
*/
public BaseOrganization (
java.lang.Integer id,
java.lang.String name,
boolean enabled,
java.lang.Long created,
java.lang.Long lastModified,
java.lang.String modifiedBy,
boolean autoUpdateEmail,
boolean autoUpdateMatchFields) {
this.setId(id);
this.setName(name);
this.setEnabled(enabled);
this.setCreated(created);
this.setLastModified(lastModified);
this.setModifiedBy(modifiedBy);
this.setAutoUpdateEmail(autoUpdateEmail);
this.setAutoUpdateMatchFields(autoUpdateMatchFields);
initialize();
}
protected void initialize () {}
private int hashCode = Integer.MIN_VALUE;
// primary key
private java.lang.Integer id;
// fields
private java.lang.String name;
private boolean enabled;
private java.lang.String countryCode;
private java.lang.String languageCode;
private java.lang.String emailAddresses;
private java.lang.String description;
private java.lang.String comment;
private java.lang.Long created;
private java.lang.Long lastModified;
private java.lang.String modifiedBy;
private java.lang.String registrationNo;
private boolean autoUpdateEmail;
private boolean autoUpdateMatchFields;
// many to one
private se.sitic.megatron.entity.Priority priority;
// collections
private java.util.Set<se.sitic.megatron.entity.IpRange> ipRanges;
private java.util.Set<se.sitic.megatron.entity.DomainName> domainNames;
private java.util.Set<se.sitic.megatron.entity.ASNumber> aSNumbers;
/**
* Return the unique identifier of this class
* @hibernate.id
* generator-class="native"
* column="id"
*/
public java.lang.Integer getId () {
return id;
}
/**
* Set the unique identifier of this class
* @param id the new ID
*/
public void setId (java.lang.Integer id) {
this.id = id;
this.hashCode = Integer.MIN_VALUE;
}
/**
* Return the value associated with the column: name
*/
public java.lang.String getName () {
return name;
}
/**
* Set the value related to the column: name
* @param name the name value
*/
public void setName (java.lang.String name) {
this.name = name;
}
/**
* Return the value associated with the column: enabled
*/
public boolean isEnabled () {
return enabled;
}
/**
* Set the value related to the column: enabled
* @param enabled the enabled value
*/
public void setEnabled (boolean enabled) {
this.enabled = enabled;
}
/**
* Return the value associated with the column: country_code
*/
public java.lang.String getCountryCode () {
return countryCode;
}
/**
* Set the value related to the column: country_code
* @param countryCode the country_code value
*/
public void setCountryCode (java.lang.String countryCode) {
this.countryCode = countryCode;
}
/**
* Return the value associated with the column: language_code
*/
public java.lang.String getLanguageCode () {
return languageCode;
}
/**
* Set the value related to the column: language_code
* @param languageCode the language_code value
*/
public void setLanguageCode (java.lang.String languageCode) {
this.languageCode = languageCode;
}
/**
* Return the value associated with the column: email_addresses
*/
public java.lang.String getEmailAddresses () {
return emailAddresses;
}
/**
* Set the value related to the column: email_addresses
* @param emailAddresses the email_addresses value
*/
public void setEmailAddresses (java.lang.String emailAddresses) {
this.emailAddresses = emailAddresses;
}
/**
* Return the value associated with the column: description
*/
public java.lang.String getDescription () {
return description;
}
/**
* Set the value related to the column: description
* @param description the description value
*/
public void setDescription (java.lang.String description) {
this.description = description;
}
/**
* Return the value associated with the column: comment
*/
public java.lang.String getComment () {
return comment;
}
/**
* Set the value related to the column: comment
* @param comment the comment value
*/
public void setComment (java.lang.String comment) {
this.comment = comment;
}
/**
* Return the value associated with the column: created
*/
public java.lang.Long getCreated () {
return created;
}
/**
* Set the value related to the column: created
* @param created the created value
*/
public void setCreated (java.lang.Long created) {
this.created = created;
}
/**
* Return the value associated with the column: last_modified
*/
public java.lang.Long getLastModified () {
return lastModified;
}
/**
* Set the value related to the column: last_modified
* @param lastModified the last_modified value
*/
public void setLastModified (java.lang.Long lastModified) {
this.lastModified = lastModified;
}
/**
* Return the value associated with the column: modified_by
*/
public java.lang.String getModifiedBy () {
return modifiedBy;
}
/**
* Set the value related to the column: modified_by
* @param modifiedBy the modified_by value
*/
public void setModifiedBy (java.lang.String modifiedBy) {
this.modifiedBy = modifiedBy;
}
/**
* Return the value associated with the column: registration_no
*/
public java.lang.String getRegistrationNo () {
return registrationNo;
}
/**
* Set the value related to the column: registration_no
* @param registrationNo the registration_no value
*/
public void setRegistrationNo (java.lang.String registrationNo) {
this.registrationNo = registrationNo;
}
/**
* Return the value associated with the column: auto_update_email
*/
public boolean isAutoUpdateEmail () {
return autoUpdateEmail;
}
/**
* Set the value related to the column: auto_update_email
* @param autoUpdateEmail the auto_update_email value
*/
public void setAutoUpdateEmail (boolean autoUpdateEmail) {
this.autoUpdateEmail = autoUpdateEmail;
}
/**
* Return the value associated with the column: auto_update_match_fields
*/
public boolean isAutoUpdateMatchFields () {
return autoUpdateMatchFields;
}
/**
* Set the value related to the column: auto_update_match_fields
* @param autoUpdateMatchFields the auto_update_match_fields value
*/
public void setAutoUpdateMatchFields (boolean autoUpdateMatchFields) {
this.autoUpdateMatchFields = autoUpdateMatchFields;
}
/**
* Return the value associated with the column: prio_id
*/
public se.sitic.megatron.entity.Priority getPriority () {
return priority;
}
/**
* Set the value related to the column: prio_id
* @param priority the prio_id value
*/
public void setPriority (se.sitic.megatron.entity.Priority priority) {
this.priority = priority;
}
/**
* Return the value associated with the column: IpRanges
*/
public java.util.Set<se.sitic.megatron.entity.IpRange> getIpRanges () {
return ipRanges;
}
/**
* Set the value related to the column: IpRanges
* @param ipRanges the IpRanges value
*/
public void setIpRanges (java.util.Set<se.sitic.megatron.entity.IpRange> ipRanges) {
this.ipRanges = ipRanges;
}
public void addToIpRanges (se.sitic.megatron.entity.IpRange ipRange) {
if (null == getIpRanges()) setIpRanges(new java.util.TreeSet<se.sitic.megatron.entity.IpRange>());
getIpRanges().add(ipRange);
}
/**
* Return the value associated with the column: DomainNames
*/
public java.util.Set<se.sitic.megatron.entity.DomainName> getDomainNames () {
return domainNames;
}
/**
* Set the value related to the column: DomainNames
* @param domainNames the DomainNames value
*/
public void setDomainNames (java.util.Set<se.sitic.megatron.entity.DomainName> domainNames) {
this.domainNames = domainNames;
}
public void addToDomainNames (se.sitic.megatron.entity.DomainName domainName) {
if (null == getDomainNames()) setDomainNames(new java.util.TreeSet<se.sitic.megatron.entity.DomainName>());
getDomainNames().add(domainName);
}
/**
* Return the value associated with the column: ASNumbers
*/
public java.util.Set<se.sitic.megatron.entity.ASNumber> getASNumbers () {
return aSNumbers;
}
/**
* Set the value related to the column: ASNumbers
* @param aSNumbers the ASNumbers value
*/
public void setASNumbers (java.util.Set<se.sitic.megatron.entity.ASNumber> aSNumbers) {
this.aSNumbers = aSNumbers;
}
public void addToASNumbers (se.sitic.megatron.entity.ASNumber aSNumber) {
if (null == getASNumbers()) setASNumbers(new java.util.TreeSet<se.sitic.megatron.entity.ASNumber>());
getASNumbers().add(aSNumber);
}
public boolean equals (Object obj) {
if (null == obj) return false;
if (!(obj instanceof se.sitic.megatron.entity.Organization)) return false;
else {
se.sitic.megatron.entity.Organization organization = (se.sitic.megatron.entity.Organization) obj;
if (null == this.getId() || null == organization.getId()) return false;
else return (this.getId().equals(organization.getId()));
}
}
public int hashCode () {
if (Integer.MIN_VALUE == this.hashCode) {
if (null == this.getId()) return super.hashCode();
else {
String hashStr = this.getClass().getName() + ":" + this.getId().hashCode();
this.hashCode = hashStr.hashCode();
}
}
return this.hashCode;
}
public String toString () {
return super.toString();
}
}
|
|
/*
* Copyright Terracotta, 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.ehcache.impl.internal.store.offheap;
import org.ehcache.config.EvictionAdvisor;
import org.ehcache.core.spi.function.BiFunction;
import org.ehcache.core.spi.function.Function;
import org.ehcache.impl.internal.store.offheap.factories.EhcacheSegmentFactory;
import org.junit.Test;
import java.io.IOException;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
/**
* AbstractEhcacheOffHeapBackingMapTest
*/
public abstract class AbstractEhcacheOffHeapBackingMapTest {
protected abstract EhcacheOffHeapBackingMap<String, String> createTestSegment() throws IOException;
protected abstract EhcacheOffHeapBackingMap<String, String> createTestSegment(EvictionAdvisor<? super String, ? super String> evictionPredicate) throws IOException;
protected abstract void destroySegment(EhcacheOffHeapBackingMap<String, String> segment);
protected abstract void putPinned(String key, String value, EhcacheOffHeapBackingMap<String, String> segment);
protected abstract boolean isPinned(String key, EhcacheOffHeapBackingMap<String, String> segment);
protected abstract int getMetadata(String key, int mask, EhcacheOffHeapBackingMap<String, String> segment);
@Test
public void testComputeFunctionCalledWhenNoMapping() throws Exception {
EhcacheOffHeapBackingMap<String, String> segment = createTestSegment();
try {
String value = segment.compute("key", new BiFunction<String, String, String>() {
@Override
public String apply(String s, String s2) {
return "value";
}
}, false);
assertThat(value, is("value"));
assertThat(segment.get("key"), is(value));
} finally {
destroySegment(segment);
}
}
@Test
public void testComputeFunctionReturnsSameNoPin() throws Exception {
EhcacheOffHeapBackingMap<String, String> segment = createTestSegment();
try {
segment.put("key", "value");
String value = segment.compute("key", new BiFunction<String, String, String>() {
@Override
public String apply(String s, String s2) {
return s2;
}
}, false);
assertThat(value, is("value"));
assertThat(isPinned("key", segment), is(false));
} finally {
destroySegment(segment);
}
}
@Test
public void testComputeFunctionReturnsSamePins() throws Exception {
EhcacheOffHeapBackingMap<String, String> segment = createTestSegment();
try {
segment.put("key", "value");
String value = segment.compute("key", new BiFunction<String, String, String>() {
@Override
public String apply(String s, String s2) {
return s2;
}
}, true);
assertThat(value, is("value"));
assertThat(isPinned("key", segment), is(true));
} finally {
destroySegment(segment);
}
}
@Test
public void testComputeFunctionReturnsSamePreservesPinWhenNoPin() throws Exception {
EhcacheOffHeapBackingMap<String, String> segment = createTestSegment();
try {
putPinned("key", "value", segment);
String value = segment.compute("key", new BiFunction<String, String, String>() {
@Override
public String apply(String s, String s2) {
return s2;
}
}, false);
assertThat(value, is("value"));
assertThat(isPinned("key", segment), is(true));
} finally {
destroySegment(segment);
}
}
@Test
public void testComputeFunctionReturnsDifferentNoPin() throws Exception {
EhcacheOffHeapBackingMap<String, String> segment = createTestSegment();
try {
segment.put("key", "value");
String value = segment.compute("key", new BiFunction<String, String, String>() {
@Override
public String apply(String s, String s2) {
return "otherValue";
}
}, false);
assertThat(value, is("otherValue"));
assertThat(isPinned("key", segment), is(false));
} finally {
destroySegment(segment);
}
}
@Test
public void testComputeFunctionReturnsDifferentPins() throws Exception {
EhcacheOffHeapBackingMap<String, String> segment = createTestSegment();
try {
segment.put("key", "value");
String value = segment.compute("key", new BiFunction<String, String, String>() {
@Override
public String apply(String s, String s2) {
return "otherValue";
}
}, true);
assertThat(value, is("otherValue"));
assertThat(isPinned("key", segment), is(true));
} finally {
destroySegment(segment);
}
}
@Test
public void testComputeFunctionReturnsDifferentClearsPin() throws Exception {
EhcacheOffHeapBackingMap<String, String> segment = createTestSegment();
try {
putPinned("key", "value", segment);
String value = segment.compute("key", new BiFunction<String, String, String>() {
@Override
public String apply(String s, String s2) {
return "otherValue";
}
}, false);
assertThat(value, is("otherValue"));
assertThat(isPinned("key", segment), is(false));
} finally {
destroySegment(segment);
}
}
@Test
public void testComputeFunctionReturnsNullRemoves() throws Exception {
EhcacheOffHeapBackingMap<String, String> segment = createTestSegment();
try {
putPinned("key", "value", segment);
String value = segment.compute("key", new BiFunction<String, String, String>() {
@Override
public String apply(String s, String s2) {
return null;
}
}, false);
assertThat(value, nullValue());
assertThat(segment.containsKey("key"), is(false));
} finally {
destroySegment(segment);
}
}
@Test
public void testComputeIfPresentNotCalledOnNotContainedKey() throws Exception {
EhcacheOffHeapBackingMap<String, String> segment = createTestSegment();
try {
try {
segment.computeIfPresent("key", new BiFunction<String, String, String>() {
@Override
public String apply(String s, String s2) {
throw new UnsupportedOperationException("Should not have been called!");
}
});
} catch (UnsupportedOperationException e) {
fail("Mapping function should not have been called.");
}
} finally {
destroySegment(segment);
}
}
@Test
public void testComputeIfPresentReturnsSameValue() throws Exception {
EhcacheOffHeapBackingMap<String, String> segment = createTestSegment();
try {
segment.put("key", "value");
String value = segment.computeIfPresent("key", new BiFunction<String, String, String>() {
@Override
public String apply(String s, String s2) {
return s2;
}
});
assertThat(segment.get("key"), is(value));
} finally {
destroySegment(segment);
}
}
@Test
public void testComputeIfPresentReturnsDifferentValue() throws Exception {
EhcacheOffHeapBackingMap<String, String> segment = createTestSegment();
try {
segment.put("key", "value");
String value = segment.computeIfPresent("key", new BiFunction<String, String, String>() {
@Override
public String apply(String s, String s2) {
return "newValue";
}
});
assertThat(segment.get("key"), is(value));
} finally {
destroySegment(segment);
}
}
@Test
public void testComputeIfPresentReturnsNullRemovesMapping() throws Exception {
EhcacheOffHeapBackingMap<String, String> segment = createTestSegment();
try {
segment.put("key", "value");
String value = segment.computeIfPresent("key", new BiFunction<String, String, String>() {
@Override
public String apply(String s, String s2) {
return null;
}
});
assertThat(segment.containsKey("key"), is(false));
} finally {
destroySegment(segment);
}
}
@Test
public void testComputeIfPinnedNoOpUnpinned() throws Exception {
EhcacheOffHeapBackingMap<String, String> segment = createTestSegment();
try {
segment.put("key", "value");
boolean result = segment.computeIfPinned("key", new BiFunction<String, String, String>() {
@Override
public String apply(String s, String s2) {
fail("Method should not be invoked");
return null;
}
}, new Function<String, Boolean>() {
@Override
public Boolean apply(String s) {
fail("Method should not be invoked");
return false;
}
});
assertThat(isPinned("key", segment), is(false));
assertThat(result, is(false));
} finally {
destroySegment(segment);
}
}
@Test
public void testComputeIfPinnedClearsMappingOnNullReturnWithPinningFalse() throws Exception {
EhcacheOffHeapBackingMap<String, String> segment = createTestSegment();
final String value = "value";
try {
putPinned("key", value, segment);
boolean result = segment.computeIfPinned("key", new BiFunction<String, String, String>() {
@Override
public String apply(String s, String s2) {
assertThat(s2, is(value));
return null;
}
}, new Function<String, Boolean>() {
@Override
public Boolean apply(String s) {
assertThat(s, is(value));
return false;
}
});
assertThat(segment.containsKey("key"), is(false));
assertThat(result, is(true));
} finally {
destroySegment(segment);
}
}
@Test
public void testComputeIfPinnedClearsMappingOnNullReturnWithPinningTrue() throws Exception {
EhcacheOffHeapBackingMap<String, String> segment = createTestSegment();
final String value = "value";
try {
putPinned("key", value, segment);
boolean result = segment.computeIfPinned("key", new BiFunction<String, String, String>() {
@Override
public String apply(String s, String s2) {
assertThat(s2, is(value));
return null;
}
}, new Function<String, Boolean>() {
@Override
public Boolean apply(String s) {
assertThat(s, is(value));
return true;
}
});
assertThat(segment.containsKey("key"), is(false));
assertThat(result, is(true));
} finally {
destroySegment(segment);
}
}
@Test
public void testComputeIfPinnedClearsPinWithoutChangingValue() throws Exception {
EhcacheOffHeapBackingMap<String, String> segment = createTestSegment();
final String value = "value";
try {
putPinned("key", value, segment);
boolean result = segment.computeIfPinned("key", new BiFunction<String, String, String>() {
@Override
public String apply(String s, String s2) {
assertThat(s2, is(value));
return s2;
}
}, new Function<String, Boolean>() {
@Override
public Boolean apply(String s) {
assertThat(s, is(value));
return true;
}
});
assertThat(isPinned("key", segment), is(false));
assertThat(result, is(true));
} finally {
destroySegment(segment);
}
}
@Test
public void testComputeIfPinnedPreservesPinWithoutChangingValue() throws Exception {
EhcacheOffHeapBackingMap<String, String> segment = createTestSegment();
final String value = "value";
try {
putPinned("key", value, segment);
boolean result = segment.computeIfPinned("key", new BiFunction<String, String, String>() {
@Override
public String apply(String s, String s2) {
assertThat(s2, is(value));
return s2;
}
}, new Function<String, Boolean>() {
@Override
public Boolean apply(String s) {
assertThat(s, is(value));
return false;
}
});
assertThat(isPinned("key", segment), is(true));
assertThat(result, is(false));
} finally {
destroySegment(segment);
}
}
@Test
public void testComputeIfPinnedReplacesValueUnpinnedWhenUnpinFunctionFalse() throws Exception {
EhcacheOffHeapBackingMap<String, String> segment = createTestSegment();
final String value = "value";
final String newValue = "newValue";
try {
putPinned("key", value, segment);
boolean result = segment.computeIfPinned("key", new BiFunction<String, String, String>() {
@Override
public String apply(String s, String s2) {
assertThat(s2, is(value));
return newValue;
}
}, new Function<String, Boolean>() {
@Override
public Boolean apply(String s) {
assertThat(s, is(value));
return false;
}
});
assertThat(segment.get("key"), is(newValue));
assertThat(isPinned("key", segment), is(false));
assertThat(result, is(false));
} finally {
destroySegment(segment);
}
}
@Test
public void testComputeIfPinnedReplacesValueUnpinnedWhenUnpinFunctionTrue() throws Exception {
EhcacheOffHeapBackingMap<String, String> segment = createTestSegment();
final String value = "value";
final String newValue = "newValue";
try {
putPinned("key", value, segment);
boolean result = segment.computeIfPinned("key", new BiFunction<String, String, String>() {
@Override
public String apply(String s, String s2) {
assertThat(s2, is(value));
return newValue;
}
}, new Function<String, Boolean>() {
@Override
public Boolean apply(String s) {
assertThat(s, is(value));
return true;
}
});
assertThat(segment.get("key"), is(newValue));
assertThat(isPinned("key", segment), is(false));
assertThat(result, is(false));
} finally {
destroySegment(segment);
}
}
@Test
public void testComputeIfPresentAndPinNoOpNoMapping() throws Exception {
EhcacheOffHeapBackingMap<String, String> segment = createTestSegment();
segment.computeIfPresentAndPin("key", new BiFunction<String, String, String>() {
@Override
public String apply(String s, String s2) {
fail("Function should not be invoked");
return null;
}
});
}
@Test
public void testComputeIfPresentAndPinDoesPin() throws Exception {
EhcacheOffHeapBackingMap<String, String> segment = createTestSegment();
final String value = "value";
segment.put("key", value);
segment.computeIfPresentAndPin("key", new BiFunction<String, String, String>() {
@Override
public String apply(String s, String s2) {
assertThat(s2, is(value));
return value;
}
});
assertThat(isPinned("key", segment), is(true));
}
@Test
public void testComputeIfPresentAndPinPreservesPin() throws Exception {
EhcacheOffHeapBackingMap<String, String> segment = createTestSegment();
final String value = "value";
putPinned("key", value, segment);
segment.computeIfPresentAndPin("key", new BiFunction<String, String, String>() {
@Override
public String apply(String s, String s2) {
assertThat(s2, is(value));
return value;
}
});
assertThat(isPinned("key", segment), is(true));
}
@Test
public void testComputeIfPresentAndPinReplacesAndPins() throws Exception {
EhcacheOffHeapBackingMap<String, String> segment = createTestSegment();
final String value = "value";
final String newValue = "newValue";
segment.put("key", value);
segment.computeIfPresentAndPin("key", new BiFunction<String, String, String>() {
@Override
public String apply(String s, String s2) {
assertThat(s2, is(value));
return newValue;
}
});
assertThat(isPinned("key", segment), is(true));
assertThat(segment.get("key"), is(newValue));
}
@Test
public void testPutAdvicedAgainstEvictionComputesMetadata() throws Exception {
EhcacheOffHeapBackingMap<String, String> segment = createTestSegment(new EvictionAdvisor<String, String>() {
@Override
public boolean adviseAgainstEviction(String key, String value) {
return "please-do-not-evict-me".equals(key);
}
});
try {
segment.put("please-do-not-evict-me", "value");
assertThat(getMetadata("please-do-not-evict-me", EhcacheSegmentFactory.EhcacheSegment.ADVISED_AGAINST_EVICTION, segment), is(EhcacheSegmentFactory.EhcacheSegment.ADVISED_AGAINST_EVICTION));
} finally {
destroySegment(segment);
}
}
@Test
public void testPutPinnedAdvicedAgainstEvictionComputesMetadata() throws Exception {
EhcacheOffHeapBackingMap<String, String> segment = createTestSegment(new EvictionAdvisor<String, String>() {
@Override
public boolean adviseAgainstEviction(String key, String value) {
return "please-do-not-evict-me".equals(key);
}
});
try {
putPinned("please-do-not-evict-me", "value", segment);
assertThat(getMetadata("please-do-not-evict-me", EhcacheSegmentFactory.EhcacheSegment.ADVISED_AGAINST_EVICTION, segment), is(EhcacheSegmentFactory.EhcacheSegment.ADVISED_AGAINST_EVICTION));
} finally {
destroySegment(segment);
}
}
}
|
|
/*
* Copyright 2009 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 org.jboss.netty.handler.codec.http;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* Splits an HTTP query string into a path string and key-value parameter pairs.
* This decoder is for one time use only. Create a new instance for each URI:
* <pre>
* {@link QueryStringDecoder} decoder = new {@link QueryStringDecoder}("/hello?recipient=world");
* assert decoder.getPath().equals("/hello");
* assert decoder.getParameters().get("recipient").equals("world");
* </pre>
*
* @author <a href="http://www.jboss.org/netty/">The Netty Project</a>
* @author Andy Taylor ([email protected])
* @author <a href="http://gleamynode.net/">Trustin Lee</a>
* @author <a href="http://tsunanet.net/">Benoit Sigoure</a>
* @version $Rev: 2302 $, $Date: 2010-06-14 20:07:44 +0900 (Mon, 14 Jun 2010) $
*
* @see QueryStringEncoder
*
* @apiviz.stereotype utility
* @apiviz.has org.jboss.netty.handler.codec.http.HttpRequest oneway - - decodes
*/
public class QueryStringDecoder {
private final Charset charset;
private final String uri;
private String path;
private Map<String, List<String>> params;
/**
* Creates a new decoder that decodes the specified URI. The decoder will
* assume that the query string is encoded in UTF-8.
*/
public QueryStringDecoder(String uri) {
this(uri, HttpCodecUtil.DEFAULT_CHARSET);
}
/**
* Creates a new decoder that decodes the specified URI encoded in the
* specified charset.
*/
public QueryStringDecoder(String uri, Charset charset) {
if (uri == null) {
throw new NullPointerException("uri");
}
if (charset == null) {
throw new NullPointerException("charset");
}
this.uri = uri;
this.charset = charset;
}
/**
* @deprecated Use {@link #QueryStringDecoder(String, Charset)} instead.
*/
@Deprecated
public QueryStringDecoder(String uri, String charset) {
this(uri, Charset.forName(charset));
}
/**
* Creates a new decoder that decodes the specified URI. The decoder will
* assume that the query string is encoded in UTF-8.
*/
public QueryStringDecoder(URI uri) {
this(uri, HttpCodecUtil.DEFAULT_CHARSET);
}
/**
* Creates a new decoder that decodes the specified URI encoded in the
* specified charset.
*/
public QueryStringDecoder(URI uri, Charset charset){
if (uri == null) {
throw new NullPointerException("uri");
}
if (charset == null) {
throw new NullPointerException("charset");
}
this.uri = uri.toASCIIString();
this.charset = charset;
}
/**
* @deprecated Use {@link #QueryStringDecoder(URI, Charset)} instead.
*/
@Deprecated
public QueryStringDecoder(URI uri, String charset){
this(uri, Charset.forName(charset));
}
/**
* Returns the decoded path string of the URI.
*/
public String getPath() {
if (path == null) {
int pathEndPos = uri.indexOf('?');
if (pathEndPos < 0) {
path = uri;
}
else {
return path = uri.substring(0, pathEndPos);
}
}
return path;
}
/**
* Returns the decoded key-value parameter pairs of the URI.
*/
public Map<String, List<String>> getParameters() {
if (params == null) {
int pathLength = getPath().length();
if (uri.length() == pathLength) {
return Collections.emptyMap();
}
params = decodeParams(uri.substring(pathLength + 1));
}
return params;
}
private Map<String, List<String>> decodeParams(String s) {
Map<String, List<String>> params = new LinkedHashMap<String, List<String>>();
String name = null;
int pos = 0; // Beginning of the unprocessed region
int i; // End of the unprocessed region
char c = 0; // Current character
for (i = 0; i < s.length(); i++) {
c = s.charAt(i);
if (c == '=' && name == null) {
if (pos != i) {
name = decodeComponent(s.substring(pos, i), charset);
}
pos = i + 1;
} else if (c == '&') {
if (name == null && pos != i) {
// We haven't seen an `=' so far but moved forward.
// Must be a param of the form '&a&' so add it with
// an empty value.
addParam(params, decodeComponent(s.substring(pos, i), charset), "");
} else if (name != null) {
addParam(params, name, decodeComponent(s.substring(pos, i), charset));
name = null;
}
pos = i + 1;
}
}
if (pos != i) { // Are there characters we haven't dealt with?
if (name == null) { // Yes and we haven't seen any `='.
addParam(params, decodeComponent(s.substring(pos, i), charset), "");
} else { // Yes and this must be the last value.
addParam(params, name, decodeComponent(s.substring(pos, i), charset));
}
} else if (name != null) { // Have we seen a name without value?
addParam(params, name, "");
}
return params;
}
private static String decodeComponent(String s, Charset charset) {
if (s == null) {
return "";
}
try {
return URLDecoder.decode(s, charset.name());
} catch (UnsupportedEncodingException e) {
throw new UnsupportedCharsetException(charset.name());
}
}
private static void addParam(Map<String, List<String>> params, String name, String value) {
List<String> values = params.get(name);
if (values == null) {
values = new ArrayList<String>(1); // Often there's only 1 value.
params.put(name, values);
}
values.add(value);
}
}
|
|
/*
Copyright 2020 Makani Technologies 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 Domain;
import java.util.ArrayList;
import java.util.Collection;
import star.common.*;
import star.base.neo.*;
import GeometricObject.*;
public class OversetDomain extends Domain{
//Extension of string names
String oversetStr;
//Extension of Overset Boundaries
ArrayList<Boundary> oversetBoundaries;
//Tracking Domains that the Oveset is interfaced with
ArrayList<Domain> interfacedWithDomains=new ArrayList();
//Track what Objects are inside this domain
ArrayList<AerodynamicSurface> airfoilObjects=new ArrayList();
//Coordinate system
CartesianCoordinateSystem localCsys;
//Overset Domain info
double domainAngle=0.0;
Tag primaryOSDomainTag;
public OversetDomain(Simulation tmpSim, GeometryPart geomPart){
super(tmpSim,geomPart);
//Identification
this.oversetStr = globalNames.getOversetStr();
}
//GEOMETRY & OBJECTS
public void trackAirfoilObject(AerodynamicSurface tmpObj){
airfoilObjects.add(tmpObj);
}
public ArrayList<AerodynamicSurface> getAirfoilObjects(){
return airfoilObjects;
}
//
public void setOversetCoordinateSystem(CartesianCoordinateSystem tmpCsys){
localCsys = tmpCsys;
}
public void setBodyCoordinateSystem(CartesianCoordinateSystem newBodyCsys){
bodyCsys = newBodyCsys;
}
public void setInletCoordinateSystem(CartesianCoordinateSystem newBodyCsys){
inletCsys = newBodyCsys;
}
// INTERFACE TRACKING
//REGIONS
public IndirectRegionInterface interfaceToDomain(Domain intToDomain){
IndirectRegionInterface oversetInterface = null;
boolean doIcreate=true;
String myRegName = domainRegion.getPresentationName();
String toRegName = intToDomain.getRegion().getPresentationName();
String newInterfaceName;
if(intToDomain instanceof OversetDomain){
newInterfaceName = myRegName+"_to_"+toRegName;
}else{
newInterfaceName = myRegName+"_to_Background";
}
domainRegion.getSimulation().println(
"OS MSG: Interfacing with Domain "+intToDomain.getName());
//make sure that the interface doesn't already exist
Collection<Interface> allInterfaces =
domainRegion.getSimulation().getInterfaceManager().getObjects();
for(Interface tmpInterface:allInterfaces){
//check it is overset type
if(tmpInterface instanceof IndirectRegionInterface){
Region tmpReg0=tmpInterface.getRegion0();
Region tmpReg1=tmpInterface.getRegion1();
//check if the interface already exists
if((tmpReg0 == domainRegion && tmpReg1 == intToDomain.getRegion())||
(tmpReg1 == domainRegion && tmpReg0 == intToDomain.getRegion())){
interfacedWithDomains.add(intToDomain);
//check naming convention
if(intToDomain instanceof OversetDomain){
//the Region0 controls the naming convention
if(tmpReg0==domainRegion){
tmpInterface.setPresentationName(newInterfaceName);
}
}else{
tmpInterface.setPresentationName(newInterfaceName);
}
doIcreate=false;
oversetInterface = (IndirectRegionInterface) tmpInterface;
break;
}
}
}
//create the interface
if(doIcreate){
oversetInterface =
domainRegion.getSimulation().getInterfaceManager().createIndirectRegionInterface(
domainRegion, intToDomain.getRegion(),
"Overset Mesh", false);
oversetInterface.getConditions().
get(OversetMeshInterpolationOption.class).
setSelected(OversetMeshInterpolationOption.Type.LINEAR);
oversetInterface.setUseAlternateHoleCutting(true);
if(intToDomain instanceof OversetDomain){
oversetInterface.setPresentationName(newInterfaceName);
}else{
oversetInterface.setPresentationName(newInterfaceName);
}
interfacedWithDomains.add(intToDomain);
}
//either way, need to track the interface
return oversetInterface;
}
public double getDomainAngle(){
return domainAngle;
}
public void zeroOutDomainCsys(){
double oldxValue=localCsys.getBasis0().toDoubleArray()[0];
double newXMultiplier=1.0;
if(oldxValue<0.0) newXMultiplier=-1.0;
double oldyValue=localCsys.getBasis1().toDoubleArray()[1];
double newYMultiplier=1.0;
if(oldyValue<0.0) newYMultiplier=-1.0;
localCsys.setBasis0(new DoubleVector(new double[] {newXMultiplier,0.0,0.0}));
localCsys.setBasis1(new DoubleVector(new double[] {0.0,newYMultiplier,0.0}));
}
public double setDomainAngleFromZero(double newAngleInDeg, double[] rotationVector){
Units units_0 =
domainRegion.getSimulation().getUnitsManager().getPreferredUnits(new IntVector(
new int[] {0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}));
Units units_1 =
domainRegion.getSimulation().getUnitsManager().getPreferredUnits(new IntVector(
new int[] {0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}));
// Need to counter rotate the Region's mesh.
double oldAngleInDeg = domainAngle;
double oldAngleInRad = oldAngleInDeg * Math.PI / 180.0;
domainRegion.getSimulation().println("OS: Domain " + domainName
+ " was at " + oldAngleInDeg + " deg.");
// First, counter rotate rotate the mesh if |angle| > 0 degrees
// so that the mesh ends up back in its original CAD Zero meshed
// orientation.
if(Math.abs(oldAngleInDeg) > 1.e-6){
domainRegion.getSimulation().getRepresentationManager().rotateMesh(
new NeoObjectVector(
new Object[] {domainRegion}), new DoubleVector(rotationVector),
new NeoObjectVector(new Object[] {units_1, units_1, units_1}),
oldAngleInRad, localCsys);
}
// Store the new domain angle from the specified argument.
// Note, based on the formal right hand rule this rotation for positive
// angles requires a negative rotation about its expected axis.
domainAngle = newAngleInDeg;
domainRegion.getSimulation().println("OS: Domain "
+ domainName + " new angle at " + domainAngle+" deg.");
double angleInRads = newAngleInDeg*Math.PI/180.;
// Reset the overset Coordinate system back to zero to allow rotation again.
// This is allowed because the mesh is counter-rotated by the old angle
// above so we don't need the basis to track angles at this stage.
double oldxValue = localCsys.getBasis0().toDoubleArray()[0];
double newXMultiplier = 1.0;
if(oldxValue<0.0) newXMultiplier = -1.0;
double oldyValue = localCsys.getBasis1().toDoubleArray()[1];
double newYMultiplier = 1.0;
if(oldyValue<0.0) newYMultiplier = -1.0;
localCsys.setBasis0(
new DoubleVector(new double[] {newXMultiplier, 0.0, 0.0}));
localCsys.setBasis1(
new DoubleVector(new double[] {0.0, newYMultiplier, 0.0}));
// Only rotate the mesh if |angle| > 0 degrees as the CFD tool cannot handle
// a zero rotation angle. If the angle is zero just accept the reset from
// above.
if(Math.abs(newAngleInDeg)>1.e-6){
domainRegion.getSimulation().getRepresentationManager()
.rotateMesh(new NeoObjectVector(
new Object[] {domainRegion}), new DoubleVector(rotationVector),
new NeoObjectVector(new Object[] {units_1, units_1, units_1}),
-angleInRads, localCsys);
localCsys.getLocalCoordinateSystemManager()
.rotateLocalCoordinateSystems(
new NeoObjectVector(new Object[] {localCsys}),
new DoubleVector(rotationVector),
new NeoObjectVector(new Object[] {units_1, units_1, units_1}),
-angleInRads, localCsys);
}
// Let the solver know which angle you came from.
return(oldAngleInDeg);
}
public double determineDomainAngle(){
//get X orientation
double xOrientation = localCsys.getBasis0().toDoubleArray()[0];
double xBasisYComp = localCsys.getBasis0().toDoubleArray()[1];
double mX=1.0;
//get X orientation
double yOrientation=localCsys.getBasis1().toDoubleArray()[1];
double mY=1.0;
if(xOrientation<0&&yOrientation>0){
if(xBasisYComp>0){
mX=-1.0;
}else{
mX=1.0;
}
}else if(xOrientation<0&&yOrientation<0){
if(xBasisYComp>0){
mX=1.0;
}else{
mX=-1.0;
}
}else if(xOrientation>0&&yOrientation>0){
if(xBasisYComp>0){
mX=-1.0;
}else{
mX=1.0;
}
}else if(xOrientation>0&&yOrientation<0){
if(xBasisYComp>0){
mX=1.0;
}else{
mX=-1.0;
}
}else{
mX=0.0;
}
domainAngle = mX * Math.abs( Math.asin(xBasisYComp) ) * 180.0 / Math.PI;
domainRegion.getSimulation().println(
"OS MSG: "+domainName+" angle detected is "+domainAngle+" degrees");
return domainAngle;
}
public void setPrimaryDomainTag(Tag newTag){
primaryOSDomainTag = newTag;
}
public Tag getPrimaryDomainTag(){
return primaryOSDomainTag;
}
}
|
|
/*
* Copyright 2017, Hridesh Rajan, Robert Dyer
* Iowa State University of Science and Technology
* and Bowling Green State University
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package boa.compiler.visitors;
import boa.compiler.ast.*;
import boa.compiler.ast.expressions.*;
import boa.compiler.ast.literals.*;
import boa.compiler.ast.statements.*;
import boa.compiler.ast.types.*;
/*
* A debugging visitor class that pretty prints the Boa AST.
*
* @author rdyer
*/
public class PrettyPrintVisitor extends AbstractVisitorNoArg {
private int indent = 0;
private void indent() {
for (int i = 0; i < indent; i++)
System.out.print(" ");
}
// dont actually indent blocks
// but many places a block can appear, statements could also appear
// and we want to indent statements
public void indentBlock(final Node n) {
if (!(n instanceof Block))
indent++;
}
public void outdentBlock(final Node n) {
if (!(n instanceof Block))
indent--;
}
/** {@inheritDoc} */
@Override
public void initialize() {
indent = 0;
}
/** {@inheritDoc} */
@Override
public void visit(final Call n) {
System.out.print("(");
boolean seen = false;
for (final Expression e : n.getArgs()) {
if (seen) System.out.print(", ");
else seen = true;
e.accept(this);
}
System.out.print(")");
}
/** {@inheritDoc} */
@Override
public void visit(final Comparison n) {
n.getLhs().accept(this);
if (n.hasOp()) {
System.out.print(" " + n.getOp() + " ");
n.getRhs().accept(this);
}
}
/** {@inheritDoc} */
@Override
public void visit(final Component n) {
if (n.hasIdentifier()) {
n.getIdentifier().accept(this);
System.out.print(": ");
}
n.getType().accept(this);
}
/** {@inheritDoc} */
@Override
public void visit(final Composite n) {
System.out.print("{ ");
if (n.isEmpty())
System.out.print(": ");
boolean seen = false;
for (final Pair p : n.getPairs()) {
if (seen) System.out.print(", ");
else seen = true;
p.accept(this);
}
seen = false;
for (final Expression e : n.getExprs()) {
if (seen) System.out.print(", ");
else seen = true;
e.accept(this);
}
System.out.print("}");
}
/** {@inheritDoc} */
@Override
public void visit(final Conjunction n) {
n.getLhs().accept(this);
for (int i = 0; i < n.getOpsSize(); i++) {
System.out.print(" " + n.getOp(i) + " ");
n.getRhs(i).accept(this);
}
}
/** {@inheritDoc} */
@Override
public void visit(final Factor n) {
n.getOperand().accept(this);
for (final Node op : n.getOps())
op.accept(this);
}
/** {@inheritDoc} */
@Override
public void visit(final Identifier n) {
System.out.print(n.getToken());
}
/** {@inheritDoc} */
@Override
public void visit(final Index n) {
System.out.print("[");
n.getStart().accept(this);
if (n.hasEnd()) {
System.out.print(" : ");
n.getEnd().accept(this);
}
System.out.print("]");
}
/** {@inheritDoc} */
@Override
public void visit(final Pair n) {
n.getExpr1().accept(this);
System.out.print(" : ");
n.getExpr2().accept(this);
}
/** {@inheritDoc} */
@Override
public void visit(final Selector n) {
System.out.print(".");
n.getId().accept(this);
}
/** {@inheritDoc} */
@Override
public void visit(final Term n) {
n.getLhs().accept(this);
for (int i = 0; i < n.getOpsSize(); i++) {
System.out.print(" " + n.getOp(i) + " ");
n.getRhs(i).accept(this);
}
}
/** {@inheritDoc} */
@Override
public void visit(final UnaryFactor n) {
System.out.print(n.getOp());
n.getFactor().accept(this);
}
//
// statements
//
/** {@inheritDoc} */
@Override
public void visit(final AssignmentStatement n) {
indent();
n.getLhs().accept(this);
System.out.print(" = ");
n.getRhs().accept(this);
System.out.println(";");
}
/** {@inheritDoc} */
@Override
public void visit(final Block n) {
System.out.println("{");
indent++;
super.visit(n);
indent--;
indent();
System.out.println("}");
}
/** {@inheritDoc} */
@Override
public void visit(final BreakStatement n) {
indent();
System.out.println("break;");
}
/** {@inheritDoc} */
@Override
public void visit(final ContinueStatement n) {
indent();
System.out.println("continue;");
}
/** {@inheritDoc} */
@Override
public void visit(final DoStatement n) {
indent();
System.out.println("do");
n.getBody().accept(this);
indent();
System.out.print("while (");
n.getCondition().accept(this);
System.out.println(");");
}
/** {@inheritDoc} */
@Override
public void visit(final EmitStatement n) {
indent();
n.getId().accept(this);
if (n.getIndicesSize() > 0)
for (final Expression e : n.getIndices()) {
System.out.print("[");
e.accept(this);
System.out.print("]");
}
System.out.print(" << ");
n.getValue().accept(this);
if (n.hasWeight()) {
System.out.print(" weight ");
n.getWeight().accept(this);
}
System.out.println(";");
}
/** {@inheritDoc} */
@Override
public void visit(final ExistsStatement n) {
indent();
System.out.print("exists (");
n.getVar().accept(this);
System.out.print("; ");
n.getCondition().accept(this);
System.out.print(") ");
indentBlock(n.getBody());
n.getBody().accept(this);
outdentBlock(n.getBody());
}
/** {@inheritDoc} */
@Override
public void visit(final ExprStatement n) {
indent();
n.getExpr().accept(this);
System.out.println(";");
}
/** {@inheritDoc} */
@Override
public void visit(final ForeachStatement n) {
indent();
System.out.print("foreach (");
n.getVar().accept(this);
System.out.print("; ");
n.getCondition().accept(this);
System.out.print(") ");
indentBlock(n.getBody());
n.getBody().accept(this);
outdentBlock(n.getBody());
}
/** {@inheritDoc} */
@Override
public void visit(final ForStatement n) {
indent();
System.out.print("for (");
if (n.hasInit()) n.getInit().accept(this);
else System.out.print(";");
System.out.print(" ");
if (n.hasCondition()) n.getCondition().accept(this);
else System.out.print(";");
System.out.print(" ");
if (n.hasUpdate()) n.getUpdate().accept(this);
System.out.print(") ");
indentBlock(n.getBody());
n.getBody().accept(this);
outdentBlock(n.getBody());
}
/** {@inheritDoc} */
@Override
public void visit(final IfAllStatement n) {
indent();
System.out.print("ifall (");
n.getVar().accept(this);
System.out.print("; ");
n.getCondition().accept(this);
System.out.print(") ");
indentBlock(n.getBody());
n.getBody().accept(this);
outdentBlock(n.getBody());
}
/** {@inheritDoc} */
@Override
public void visit(final IfStatement n) {
indent();
System.out.print("if (");
n.getCondition().accept(this);
System.out.print(") ");
indentBlock(n.getBody());
n.getBody().accept(this);
if (n.hasElse()) {
outdentBlock(n.getBody());
indent();
System.out.println("else ");
indentBlock(n.getElse());
n.getElse().accept(this);
outdentBlock(n.getElse());
} else {
outdentBlock(n.getBody());
}
}
/** {@inheritDoc} */
@Override
public void visit(final PostfixStatement n) {
indent();
n.getExpr().accept(this);
System.out.print(n.getOp());
System.out.println(";");
}
/** {@inheritDoc} */
@Override
public void visit(final ReturnStatement n) {
indent();
System.out.print("return");
if (n.hasExpr()) {
System.out.print(" ");
n.getExpr().accept(this);
}
System.out.println(";");
}
/** {@inheritDoc} */
@Override
public void visit(final StopStatement n) {
indent();
System.out.println("stop;");
}
/** {@inheritDoc} */
@Override
public void visit(final SwitchCase n) {
indent();
if (n.isDefault())
System.out.print("default: ");
else {
boolean seen = false;
for (final Expression e : n.getCases()) {
if (seen) System.out.print(", ");
else seen = true;
e.accept(this);
}
System.out.print(": ");
}
indentBlock(n.getBody());
n.getBody().accept(this);
outdentBlock(n.getBody());
}
/** {@inheritDoc} */
@Override
public void visit(final SwitchStatement n) {
indent();
System.out.print("switch (");
n.getCondition().accept(this);
System.out.println(") {");
indent++;
for (final SwitchCase sc : n.getCases())
sc.accept(this);
n.getDefault().accept(this);
indent--;
indent();
System.out.println("}");
}
/** {@inheritDoc} */
@Override
public void visit(final TypeDecl n) {
indent();
System.out.print("type ");
n.getId().accept(this);
System.out.print(" =");
n.getType().accept(this);
System.out.println(";");
}
/** {@inheritDoc} */
@Override
public void visit(final VarDeclStatement n) {
indent();
if (n.isStatic()) System.out.print("static ");
n.getId().accept(this);
if (n.hasType()) {
System.out.print(": ");
n.getType().accept(this);
if (n.hasInitializer())
System.out.print(" = ");
} else {
System.out.print(" := ");
}
if (n.hasInitializer())
n.getInitializer().accept(this);
System.out.println(";");
}
/** {@inheritDoc} */
@Override
public void visit(final VisitStatement n) {
indent();
if (n.isBefore()) System.out.print("before ");
else System.out.print("after ");
if (n.hasWildcard()) System.out.print("_");
else if (n.hasComponent()) n.getComponent().accept(this);
else {
boolean seen = false;
for (final Identifier id : n.getIdList()) {
if (seen) System.out.print(", ");
else seen = true;
id.accept(this);
}
}
System.out.print(" -> ");
n.getBody().accept(this);
}
/** {@inheritDoc} */
@Override
public void visit(final WhileStatement n) {
indent();
System.out.print("while (");
n.getCondition().accept(this);
System.out.println(")");
n.getBody().accept(this);
}
//
// expressions
//
/** {@inheritDoc} */
@Override
public void visit(final Expression n) {
n.getLhs().accept(this);
for (int i = 0; i < n.getRhsSize(); i++) {
System.out.print(" || ");
n.getRhs(i).accept(this);
}
}
/** {@inheritDoc} */
@Override
public void visit(final ParenExpression n) {
System.out.print("(");
n.getExpression().accept(this);
System.out.print(")");
}
/** {@inheritDoc} */
@Override
public void visit(final SimpleExpr n) {
n.getLhs().accept(this);
for (int i = 0; i < n.getOpsSize(); i++) {
System.out.print(" " + n.getOp(i) + " ");
n.getRhs(i).accept(this);
}
}
//
// types
//
/** {@inheritDoc} */
@Override
public void visit(final ArrayType n) {
System.out.print("array of ");
n.getValue().accept(this);
}
/** {@inheritDoc} */
@Override
public void visit(final FunctionType n) {
System.out.print("function (");
boolean seen = false;
for (final Component c : n.getArgs()) {
if (seen) System.out.print(", ");
else seen = true;
c.accept(this);
}
System.out.print(")");
if (n.hasType()) {
System.out.print(" : ");
n.getType().accept(this);
}
System.out.println();
}
/** {@inheritDoc} */
@Override
public void visit(final MapType n) {
System.out.print("map[");
n.getIndex().accept(this);
System.out.print("] of ");
n.getValue().accept(this);
}
/** {@inheritDoc} */
@Override
public void visit(final OutputType n) {
System.out.print("output ");
n.getId().accept(this);
if (n.getArgsSize() > 0) {
System.out.print("(");
boolean seen = false;
for (final Expression e : n.getArgs()) {
if (seen) System.out.print(", ");
else seen = true;
e.accept(this);
}
System.out.print(")");
}
if (n.getIndicesSize() > 0) {
for (final Component c : n.getIndices()) {
System.out.print("[");
c.accept(this);
System.out.print("]");
}
}
System.out.print(" of ");
n.getType().accept(this);
if (n.hasWeight()) {
System.out.print("weight ");
n.getWeight().accept(this);
}
}
/** {@inheritDoc} */
@Override
public void visit(final StackType n) {
System.out.print("stack of ");
n.getValue().accept(this);
}
/** {@inheritDoc} */
@Override
public void visit(final SetType n) {
System.out.print("set of ");
n.getValue().accept(this);
}
/** {@inheritDoc} */
@Override
public void visit(final TupleType n) {
System.out.print("{ ");
boolean seen = false;
for (final Component c : n.getMembers()) {
if (seen) System.out.print(", ");
else seen = true;
c.accept(this);
}
System.out.print(" }");
}
/** {@inheritDoc} */
@Override
public void visit(final VisitorType n) {
System.out.print("visitor ");
}
//
// literals
//
/** {@inheritDoc} */
@Override
public void visit(final CharLiteral n) {
System.out.print(n.getLiteral());
}
/** {@inheritDoc} */
@Override
public void visit(final FloatLiteral n) {
System.out.print(n.getLiteral());
}
/** {@inheritDoc} */
@Override
public void visit(final IntegerLiteral n) {
System.out.print(n.getLiteral());
}
/** {@inheritDoc} */
@Override
public void visit(final StringLiteral n) {
System.out.print(n.getLiteral());
}
/** {@inheritDoc} */
@Override
public void visit(final TimeLiteral n) {
System.out.print(n.getLiteral());
}
}
|
|
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.smpp;
import org.apache.camel.Component;
import org.apache.camel.Consumer;
import org.apache.camel.Exchange;
import org.apache.camel.ExchangePattern;
import org.apache.camel.Processor;
import org.apache.camel.Producer;
import org.jsmpp.bean.AlertNotification;
import org.jsmpp.bean.DataSm;
import org.jsmpp.bean.DeliverSm;
import org.junit.Before;
import org.junit.Test;
import static org.easymock.EasyMock.eq;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.isA;
import static org.easymock.classextension.EasyMock.createMock;
import static org.easymock.classextension.EasyMock.replay;
import static org.easymock.classextension.EasyMock.verify;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
/**
* JUnit test class for <code>org.apache.camel.component.smpp.SmppEndpoint</code>
*
* @version
* @author muellerc
*/
public class SmppEndpointTest {
private SmppEndpoint endpoint;
private SmppConfiguration configuration;
private Component component;
private SmppBinding binding;
@Before
public void setUp() throws Exception {
configuration = createMock(SmppConfiguration.class);
component = createMock(Component.class);
binding = createMock(SmppBinding.class);
endpoint = new SmppEndpoint("smpp://smppclient@localhost:2775", component, configuration);
endpoint.setBinding(binding);
}
@Test
public void isLenientPropertiesShouldReturnTrue() {
assertTrue(endpoint.isLenientProperties());
}
@Test
public void isSingletonShouldReturnTrue() {
assertTrue(endpoint.isSingleton());
}
@Test
public void createEndpointUriShouldReturnTheEndpointUri() {
expect(configuration.getUsingSSL()).andReturn(false);
expect(configuration.getSystemId()).andReturn("smppclient");
expect(configuration.getHost()).andReturn("localhost");
expect(configuration.getPort()).andReturn(new Integer(2775));
replay(configuration);
assertEquals("smpp://smppclient@localhost:2775", endpoint.createEndpointUri());
verify(configuration);
}
@Test
public void createConsumerShouldReturnASmppConsumer() throws Exception {
Processor processor = createMock(Processor.class);
replay(processor);
Consumer consumer = endpoint.createConsumer(processor);
verify(processor);
assertTrue(consumer instanceof SmppConsumer);
}
@Test
public void createProducerShouldReturnASmppProducer() throws Exception {
Producer producer = endpoint.createProducer();
assertTrue(producer instanceof SmppProducer);
}
@Test
public void createOnAcceptAlertNotificationExchange() {
AlertNotification alertNotification = createMock(AlertNotification.class);
SmppMessage message = createMock(SmppMessage.class);
expect(binding.createSmppMessage(alertNotification)).andReturn(message);
message.setExchange(isA(Exchange.class));
replay(alertNotification, binding, message);
Exchange exchange = endpoint.createOnAcceptAlertNotificationExchange(alertNotification);
verify(alertNotification, binding, message);
assertSame(binding, exchange.getProperty(Exchange.BINDING));
assertSame(message, exchange.getIn());
assertSame(ExchangePattern.InOnly, exchange.getPattern());
}
@Test
public void createOnAcceptAlertNotificationExchangeWithExchangePattern() {
AlertNotification alertNotification = createMock(AlertNotification.class);
SmppMessage message = createMock(SmppMessage.class);
expect(binding.createSmppMessage(alertNotification)).andReturn(message);
message.setExchange(isA(Exchange.class));
replay(alertNotification, binding, message);
Exchange exchange = endpoint.createOnAcceptAlertNotificationExchange(ExchangePattern.InOut, alertNotification);
verify(alertNotification, binding, message);
assertSame(binding, exchange.getProperty(Exchange.BINDING));
assertSame(message, exchange.getIn());
assertSame(ExchangePattern.InOut, exchange.getPattern());
}
@Test
public void createOnAcceptDeliverSmExchange() throws Exception {
DeliverSm deliverSm = createMock(DeliverSm.class);
SmppMessage message = createMock(SmppMessage.class);
expect(binding.createSmppMessage(deliverSm)).andReturn(message);
message.setExchange(isA(Exchange.class));
replay(deliverSm, binding, message);
Exchange exchange = endpoint.createOnAcceptDeliverSmExchange(deliverSm);
verify(deliverSm, binding, message);
assertSame(binding, exchange.getProperty(Exchange.BINDING));
assertSame(message, exchange.getIn());
assertSame(ExchangePattern.InOnly, exchange.getPattern());
}
@Test
public void createOnAcceptDeliverSmWithExchangePattern() throws Exception {
DeliverSm deliverSm = createMock(DeliverSm.class);
SmppMessage message = createMock(SmppMessage.class);
expect(binding.createSmppMessage(deliverSm)).andReturn(message);
message.setExchange(isA(Exchange.class));
replay(deliverSm, binding, message);
Exchange exchange = endpoint.createOnAcceptDeliverSmExchange(ExchangePattern.InOut, deliverSm);
verify(deliverSm, binding, message);
assertSame(binding, exchange.getProperty(Exchange.BINDING));
assertSame(message, exchange.getIn());
assertSame(ExchangePattern.InOut, exchange.getPattern());
}
@Test
public void createOnAcceptDataSm() throws Exception {
DataSm dataSm = createMock(DataSm.class);
SmppMessage message = createMock(SmppMessage.class);
expect(binding.createSmppMessage(eq(dataSm), isA(String.class))).andReturn(message);
message.setExchange(isA(Exchange.class));
replay(dataSm, binding, message);
Exchange exchange = endpoint.createOnAcceptDataSm(dataSm, "1");
verify(dataSm, binding, message);
assertSame(binding, exchange.getProperty(Exchange.BINDING));
assertSame(message, exchange.getIn());
assertSame(ExchangePattern.InOnly, exchange.getPattern());
}
@Test
public void createOnAcceptDataSmWithExchangePattern() throws Exception {
DataSm dataSm = createMock(DataSm.class);
SmppMessage message = createMock(SmppMessage.class);
expect(binding.createSmppMessage(eq(dataSm), isA(String.class))).andReturn(message);
message.setExchange(isA(Exchange.class));
replay(dataSm, binding, message);
Exchange exchange = endpoint.createOnAcceptDataSm(ExchangePattern.InOut, dataSm, "1");
verify(dataSm, binding, message);
assertSame(binding, exchange.getProperty(Exchange.BINDING));
assertSame(message, exchange.getIn());
assertSame(ExchangePattern.InOut, exchange.getPattern());
}
@Test
public void getConnectionStringShouldReturnTheConnectionString() {
expect(configuration.getUsingSSL()).andReturn(false);
expect(configuration.getSystemId()).andReturn("smppclient");
expect(configuration.getHost()).andReturn("localhost");
expect(configuration.getPort()).andReturn(new Integer(2775));
replay(configuration);
assertEquals("smpp://smppclient@localhost:2775", endpoint.getConnectionString());
verify(configuration);
}
@Test
public void getConfigurationShouldReturnTheSetValue() {
assertSame(configuration, endpoint.getConfiguration());
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.