repo_name
stringlengths
7
104
file_path
stringlengths
13
198
context
stringlengths
67
7.15k
import_statement
stringlengths
16
4.43k
code
stringlengths
40
6.98k
prompt
stringlengths
227
8.27k
next_line
stringlengths
8
795
aurbroszniowski/Rainfall-core
src/main/java/io/rainfall/statistics/StatisticsPeekHolder.java
// Path: src/main/java/io/rainfall/statistics/exporter/Exporter.java // public interface Exporter { // }
import io.rainfall.statistics.collector.StatisticsCollector; import io.rainfall.statistics.exporter.Exporter; import org.HdrHistogram.Histogram; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap;
/* * Copyright (c) 2014-2022 Aurélien Broszniowski * * 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.rainfall.statistics; /** * @author Aurelien Broszniowski */ public class StatisticsPeekHolder<E extends Enum<E>> { public final static String ALL = "ALL"; private final Enum<E>[] resultsReported; private final ConcurrentHashMap<String, LongAdder> assertionsErrors; private final RainfallHistogramSink<E> histograms; private final long startTime; private Map<String, StatisticsPeek<E>> statisticsPeeks = new ConcurrentHashMap<String, StatisticsPeek<E>>();
// Path: src/main/java/io/rainfall/statistics/exporter/Exporter.java // public interface Exporter { // } // Path: src/main/java/io/rainfall/statistics/StatisticsPeekHolder.java import io.rainfall.statistics.collector.StatisticsCollector; import io.rainfall.statistics.exporter.Exporter; import org.HdrHistogram.Histogram; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; /* * Copyright (c) 2014-2022 Aurélien Broszniowski * * 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.rainfall.statistics; /** * @author Aurelien Broszniowski */ public class StatisticsPeekHolder<E extends Enum<E>> { public final static String ALL = "ALL"; private final Enum<E>[] resultsReported; private final ConcurrentHashMap<String, LongAdder> assertionsErrors; private final RainfallHistogramSink<E> histograms; private final long startTime; private Map<String, StatisticsPeek<E>> statisticsPeeks = new ConcurrentHashMap<String, StatisticsPeek<E>>();
private Map<String, Exporter> extraCollectedStatistics = new ConcurrentHashMap<String, Exporter>();
aurbroszniowski/Rainfall-core
src/main/java/io/rainfall/execution/WarmUp.java
// Path: src/main/java/io/rainfall/Configuration.java // public abstract class Configuration { // // public abstract List<String> getDescription(); // // } // // Path: src/main/java/io/rainfall/Execution.java // public abstract class Execution { // // public enum ExecutionState { // UNKNOWN, // BEGINNING, // ENDING // } // // /** // * Provide an easy way to mark all operations as underway. // * // * @param scenario the test scenario // * @param state phase of execution of the scenario // */ // public void markExecutionState(Scenario scenario, ExecutionState state) { // final Map<String, RangeMap<WeightedOperation>> scenarioOperations = scenario.getOperations(); // for (RangeMap<WeightedOperation> operationRangeMap : scenarioOperations.values()) { // for (WeightedOperation op : operationRangeMap.getAll()) { // op.markExecutionState(state); // } // } // } // // protected ConcurrentPseudoRandom weightRnd = new ConcurrentPseudoRandom(); // // public abstract <E extends Enum<E>> void execute(final StatisticsHolder<E> statisticsHolder, final Scenario scenario, // final Map<Class<? extends Configuration>, Configuration> configurations, // final List<AssertionEvaluator> assertions) throws TestException; // // public abstract String toString(); // // } // // Path: src/main/java/io/rainfall/statistics/StatisticsHolder.java // public abstract class StatisticsHolder<E extends Enum<E>> { // // public abstract Enum<E>[] getResultsReported(); // // public abstract Set<String> getStatisticsKeys(); // // public abstract Statistics<E> getStatistics(String name); // // public abstract Set<StatisticsCollector> getStatisticsCollectors(); // // public abstract Histogram fetchHistogram(final Enum<E> result); // // public abstract void reset(); // // public abstract long getCurrentTps(Enum result); // // public abstract void record(String name, long responseTimeInNs, Enum result); // // public abstract void increaseAssertionsErrorsCount(String name); // // public abstract void pause(); // // public abstract void resume(); // // public long getTimeInNs() { // return System.nanoTime(); // } // // public abstract long getStartTime(); // }
import io.rainfall.AssertionEvaluator; import io.rainfall.Configuration; import io.rainfall.Execution; import io.rainfall.Scenario; import io.rainfall.TestException; import io.rainfall.statistics.StatisticsHolder; import io.rainfall.statistics.WarmUpStatisticsHolder; import java.util.List; import java.util.Map;
/* * Copyright (c) 2014-2022 Aurélien Broszniowski * * 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.rainfall.execution; /** * Execute the {@link Scenario} for a period of time * * @author Aurelien Broszniowski */ public class WarmUp extends Execution { private final RunsDuring during;
// Path: src/main/java/io/rainfall/Configuration.java // public abstract class Configuration { // // public abstract List<String> getDescription(); // // } // // Path: src/main/java/io/rainfall/Execution.java // public abstract class Execution { // // public enum ExecutionState { // UNKNOWN, // BEGINNING, // ENDING // } // // /** // * Provide an easy way to mark all operations as underway. // * // * @param scenario the test scenario // * @param state phase of execution of the scenario // */ // public void markExecutionState(Scenario scenario, ExecutionState state) { // final Map<String, RangeMap<WeightedOperation>> scenarioOperations = scenario.getOperations(); // for (RangeMap<WeightedOperation> operationRangeMap : scenarioOperations.values()) { // for (WeightedOperation op : operationRangeMap.getAll()) { // op.markExecutionState(state); // } // } // } // // protected ConcurrentPseudoRandom weightRnd = new ConcurrentPseudoRandom(); // // public abstract <E extends Enum<E>> void execute(final StatisticsHolder<E> statisticsHolder, final Scenario scenario, // final Map<Class<? extends Configuration>, Configuration> configurations, // final List<AssertionEvaluator> assertions) throws TestException; // // public abstract String toString(); // // } // // Path: src/main/java/io/rainfall/statistics/StatisticsHolder.java // public abstract class StatisticsHolder<E extends Enum<E>> { // // public abstract Enum<E>[] getResultsReported(); // // public abstract Set<String> getStatisticsKeys(); // // public abstract Statistics<E> getStatistics(String name); // // public abstract Set<StatisticsCollector> getStatisticsCollectors(); // // public abstract Histogram fetchHistogram(final Enum<E> result); // // public abstract void reset(); // // public abstract long getCurrentTps(Enum result); // // public abstract void record(String name, long responseTimeInNs, Enum result); // // public abstract void increaseAssertionsErrorsCount(String name); // // public abstract void pause(); // // public abstract void resume(); // // public long getTimeInNs() { // return System.nanoTime(); // } // // public abstract long getStartTime(); // } // Path: src/main/java/io/rainfall/execution/WarmUp.java import io.rainfall.AssertionEvaluator; import io.rainfall.Configuration; import io.rainfall.Execution; import io.rainfall.Scenario; import io.rainfall.TestException; import io.rainfall.statistics.StatisticsHolder; import io.rainfall.statistics.WarmUpStatisticsHolder; import java.util.List; import java.util.Map; /* * Copyright (c) 2014-2022 Aurélien Broszniowski * * 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.rainfall.execution; /** * Execute the {@link Scenario} for a period of time * * @author Aurelien Broszniowski */ public class WarmUp extends Execution { private final RunsDuring during;
private final StatisticsHolder blankStatsHolder;
aurbroszniowski/Rainfall-core
src/main/java/io/rainfall/execution/WarmUp.java
// Path: src/main/java/io/rainfall/Configuration.java // public abstract class Configuration { // // public abstract List<String> getDescription(); // // } // // Path: src/main/java/io/rainfall/Execution.java // public abstract class Execution { // // public enum ExecutionState { // UNKNOWN, // BEGINNING, // ENDING // } // // /** // * Provide an easy way to mark all operations as underway. // * // * @param scenario the test scenario // * @param state phase of execution of the scenario // */ // public void markExecutionState(Scenario scenario, ExecutionState state) { // final Map<String, RangeMap<WeightedOperation>> scenarioOperations = scenario.getOperations(); // for (RangeMap<WeightedOperation> operationRangeMap : scenarioOperations.values()) { // for (WeightedOperation op : operationRangeMap.getAll()) { // op.markExecutionState(state); // } // } // } // // protected ConcurrentPseudoRandom weightRnd = new ConcurrentPseudoRandom(); // // public abstract <E extends Enum<E>> void execute(final StatisticsHolder<E> statisticsHolder, final Scenario scenario, // final Map<Class<? extends Configuration>, Configuration> configurations, // final List<AssertionEvaluator> assertions) throws TestException; // // public abstract String toString(); // // } // // Path: src/main/java/io/rainfall/statistics/StatisticsHolder.java // public abstract class StatisticsHolder<E extends Enum<E>> { // // public abstract Enum<E>[] getResultsReported(); // // public abstract Set<String> getStatisticsKeys(); // // public abstract Statistics<E> getStatistics(String name); // // public abstract Set<StatisticsCollector> getStatisticsCollectors(); // // public abstract Histogram fetchHistogram(final Enum<E> result); // // public abstract void reset(); // // public abstract long getCurrentTps(Enum result); // // public abstract void record(String name, long responseTimeInNs, Enum result); // // public abstract void increaseAssertionsErrorsCount(String name); // // public abstract void pause(); // // public abstract void resume(); // // public long getTimeInNs() { // return System.nanoTime(); // } // // public abstract long getStartTime(); // }
import io.rainfall.AssertionEvaluator; import io.rainfall.Configuration; import io.rainfall.Execution; import io.rainfall.Scenario; import io.rainfall.TestException; import io.rainfall.statistics.StatisticsHolder; import io.rainfall.statistics.WarmUpStatisticsHolder; import java.util.List; import java.util.Map;
/* * Copyright (c) 2014-2022 Aurélien Broszniowski * * 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.rainfall.execution; /** * Execute the {@link Scenario} for a period of time * * @author Aurelien Broszniowski */ public class WarmUp extends Execution { private final RunsDuring during; private final StatisticsHolder blankStatsHolder; public WarmUp(RunsDuring during) { this.during = during; blankStatsHolder = new WarmUpStatisticsHolder(); } @Override public <E extends Enum<E>> void execute(final StatisticsHolder<E> statisticsHolder, final Scenario scenario,
// Path: src/main/java/io/rainfall/Configuration.java // public abstract class Configuration { // // public abstract List<String> getDescription(); // // } // // Path: src/main/java/io/rainfall/Execution.java // public abstract class Execution { // // public enum ExecutionState { // UNKNOWN, // BEGINNING, // ENDING // } // // /** // * Provide an easy way to mark all operations as underway. // * // * @param scenario the test scenario // * @param state phase of execution of the scenario // */ // public void markExecutionState(Scenario scenario, ExecutionState state) { // final Map<String, RangeMap<WeightedOperation>> scenarioOperations = scenario.getOperations(); // for (RangeMap<WeightedOperation> operationRangeMap : scenarioOperations.values()) { // for (WeightedOperation op : operationRangeMap.getAll()) { // op.markExecutionState(state); // } // } // } // // protected ConcurrentPseudoRandom weightRnd = new ConcurrentPseudoRandom(); // // public abstract <E extends Enum<E>> void execute(final StatisticsHolder<E> statisticsHolder, final Scenario scenario, // final Map<Class<? extends Configuration>, Configuration> configurations, // final List<AssertionEvaluator> assertions) throws TestException; // // public abstract String toString(); // // } // // Path: src/main/java/io/rainfall/statistics/StatisticsHolder.java // public abstract class StatisticsHolder<E extends Enum<E>> { // // public abstract Enum<E>[] getResultsReported(); // // public abstract Set<String> getStatisticsKeys(); // // public abstract Statistics<E> getStatistics(String name); // // public abstract Set<StatisticsCollector> getStatisticsCollectors(); // // public abstract Histogram fetchHistogram(final Enum<E> result); // // public abstract void reset(); // // public abstract long getCurrentTps(Enum result); // // public abstract void record(String name, long responseTimeInNs, Enum result); // // public abstract void increaseAssertionsErrorsCount(String name); // // public abstract void pause(); // // public abstract void resume(); // // public long getTimeInNs() { // return System.nanoTime(); // } // // public abstract long getStartTime(); // } // Path: src/main/java/io/rainfall/execution/WarmUp.java import io.rainfall.AssertionEvaluator; import io.rainfall.Configuration; import io.rainfall.Execution; import io.rainfall.Scenario; import io.rainfall.TestException; import io.rainfall.statistics.StatisticsHolder; import io.rainfall.statistics.WarmUpStatisticsHolder; import java.util.List; import java.util.Map; /* * Copyright (c) 2014-2022 Aurélien Broszniowski * * 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.rainfall.execution; /** * Execute the {@link Scenario} for a period of time * * @author Aurelien Broszniowski */ public class WarmUp extends Execution { private final RunsDuring during; private final StatisticsHolder blankStatsHolder; public WarmUp(RunsDuring during) { this.during = during; blankStatsHolder = new WarmUpStatisticsHolder(); } @Override public <E extends Enum<E>> void execute(final StatisticsHolder<E> statisticsHolder, final Scenario scenario,
final Map<Class<? extends Configuration>, Configuration> configurations,
aurbroszniowski/Rainfall-core
src/main/java/io/rainfall/execution/Repeat.java
// Path: src/main/java/io/rainfall/Configuration.java // public abstract class Configuration { // // public abstract List<String> getDescription(); // // } // // Path: src/main/java/io/rainfall/Execution.java // public abstract class Execution { // // public enum ExecutionState { // UNKNOWN, // BEGINNING, // ENDING // } // // /** // * Provide an easy way to mark all operations as underway. // * // * @param scenario the test scenario // * @param state phase of execution of the scenario // */ // public void markExecutionState(Scenario scenario, ExecutionState state) { // final Map<String, RangeMap<WeightedOperation>> scenarioOperations = scenario.getOperations(); // for (RangeMap<WeightedOperation> operationRangeMap : scenarioOperations.values()) { // for (WeightedOperation op : operationRangeMap.getAll()) { // op.markExecutionState(state); // } // } // } // // protected ConcurrentPseudoRandom weightRnd = new ConcurrentPseudoRandom(); // // public abstract <E extends Enum<E>> void execute(final StatisticsHolder<E> statisticsHolder, final Scenario scenario, // final Map<Class<? extends Configuration>, Configuration> configurations, // final List<AssertionEvaluator> assertions) throws TestException; // // public abstract String toString(); // // } // // Path: src/main/java/io/rainfall/statistics/StatisticsHolder.java // public abstract class StatisticsHolder<E extends Enum<E>> { // // public abstract Enum<E>[] getResultsReported(); // // public abstract Set<String> getStatisticsKeys(); // // public abstract Statistics<E> getStatistics(String name); // // public abstract Set<StatisticsCollector> getStatisticsCollectors(); // // public abstract Histogram fetchHistogram(final Enum<E> result); // // public abstract void reset(); // // public abstract long getCurrentTps(Enum result); // // public abstract void record(String name, long responseTimeInNs, Enum result); // // public abstract void increaseAssertionsErrorsCount(String name); // // public abstract void pause(); // // public abstract void resume(); // // public long getTimeInNs() { // return System.nanoTime(); // } // // public abstract long getStartTime(); // }
import io.rainfall.AssertionEvaluator; import io.rainfall.Configuration; import io.rainfall.Execution; import io.rainfall.Scenario; import io.rainfall.TestException; import io.rainfall.statistics.StatisticsHolder; import java.util.List; import java.util.Map;
/* * Copyright (c) 2014-2022 Aurélien Broszniowski * * 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.rainfall.execution; /** * @author Aurelien Broszniowski */ public class Repeat extends Execution { private final int executionCount; private final Execution[] executions; public Repeat(int executionCount, Execution[] executions) { this.executionCount = executionCount; this.executions = executions; } @Override
// Path: src/main/java/io/rainfall/Configuration.java // public abstract class Configuration { // // public abstract List<String> getDescription(); // // } // // Path: src/main/java/io/rainfall/Execution.java // public abstract class Execution { // // public enum ExecutionState { // UNKNOWN, // BEGINNING, // ENDING // } // // /** // * Provide an easy way to mark all operations as underway. // * // * @param scenario the test scenario // * @param state phase of execution of the scenario // */ // public void markExecutionState(Scenario scenario, ExecutionState state) { // final Map<String, RangeMap<WeightedOperation>> scenarioOperations = scenario.getOperations(); // for (RangeMap<WeightedOperation> operationRangeMap : scenarioOperations.values()) { // for (WeightedOperation op : operationRangeMap.getAll()) { // op.markExecutionState(state); // } // } // } // // protected ConcurrentPseudoRandom weightRnd = new ConcurrentPseudoRandom(); // // public abstract <E extends Enum<E>> void execute(final StatisticsHolder<E> statisticsHolder, final Scenario scenario, // final Map<Class<? extends Configuration>, Configuration> configurations, // final List<AssertionEvaluator> assertions) throws TestException; // // public abstract String toString(); // // } // // Path: src/main/java/io/rainfall/statistics/StatisticsHolder.java // public abstract class StatisticsHolder<E extends Enum<E>> { // // public abstract Enum<E>[] getResultsReported(); // // public abstract Set<String> getStatisticsKeys(); // // public abstract Statistics<E> getStatistics(String name); // // public abstract Set<StatisticsCollector> getStatisticsCollectors(); // // public abstract Histogram fetchHistogram(final Enum<E> result); // // public abstract void reset(); // // public abstract long getCurrentTps(Enum result); // // public abstract void record(String name, long responseTimeInNs, Enum result); // // public abstract void increaseAssertionsErrorsCount(String name); // // public abstract void pause(); // // public abstract void resume(); // // public long getTimeInNs() { // return System.nanoTime(); // } // // public abstract long getStartTime(); // } // Path: src/main/java/io/rainfall/execution/Repeat.java import io.rainfall.AssertionEvaluator; import io.rainfall.Configuration; import io.rainfall.Execution; import io.rainfall.Scenario; import io.rainfall.TestException; import io.rainfall.statistics.StatisticsHolder; import java.util.List; import java.util.Map; /* * Copyright (c) 2014-2022 Aurélien Broszniowski * * 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.rainfall.execution; /** * @author Aurelien Broszniowski */ public class Repeat extends Execution { private final int executionCount; private final Execution[] executions; public Repeat(int executionCount, Execution[] executions) { this.executionCount = executionCount; this.executions = executions; } @Override
public <E extends Enum<E>> void execute(StatisticsHolder<E> statisticsHolder, Scenario scenario,
aurbroszniowski/Rainfall-core
src/main/java/io/rainfall/execution/Repeat.java
// Path: src/main/java/io/rainfall/Configuration.java // public abstract class Configuration { // // public abstract List<String> getDescription(); // // } // // Path: src/main/java/io/rainfall/Execution.java // public abstract class Execution { // // public enum ExecutionState { // UNKNOWN, // BEGINNING, // ENDING // } // // /** // * Provide an easy way to mark all operations as underway. // * // * @param scenario the test scenario // * @param state phase of execution of the scenario // */ // public void markExecutionState(Scenario scenario, ExecutionState state) { // final Map<String, RangeMap<WeightedOperation>> scenarioOperations = scenario.getOperations(); // for (RangeMap<WeightedOperation> operationRangeMap : scenarioOperations.values()) { // for (WeightedOperation op : operationRangeMap.getAll()) { // op.markExecutionState(state); // } // } // } // // protected ConcurrentPseudoRandom weightRnd = new ConcurrentPseudoRandom(); // // public abstract <E extends Enum<E>> void execute(final StatisticsHolder<E> statisticsHolder, final Scenario scenario, // final Map<Class<? extends Configuration>, Configuration> configurations, // final List<AssertionEvaluator> assertions) throws TestException; // // public abstract String toString(); // // } // // Path: src/main/java/io/rainfall/statistics/StatisticsHolder.java // public abstract class StatisticsHolder<E extends Enum<E>> { // // public abstract Enum<E>[] getResultsReported(); // // public abstract Set<String> getStatisticsKeys(); // // public abstract Statistics<E> getStatistics(String name); // // public abstract Set<StatisticsCollector> getStatisticsCollectors(); // // public abstract Histogram fetchHistogram(final Enum<E> result); // // public abstract void reset(); // // public abstract long getCurrentTps(Enum result); // // public abstract void record(String name, long responseTimeInNs, Enum result); // // public abstract void increaseAssertionsErrorsCount(String name); // // public abstract void pause(); // // public abstract void resume(); // // public long getTimeInNs() { // return System.nanoTime(); // } // // public abstract long getStartTime(); // }
import io.rainfall.AssertionEvaluator; import io.rainfall.Configuration; import io.rainfall.Execution; import io.rainfall.Scenario; import io.rainfall.TestException; import io.rainfall.statistics.StatisticsHolder; import java.util.List; import java.util.Map;
/* * Copyright (c) 2014-2022 Aurélien Broszniowski * * 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.rainfall.execution; /** * @author Aurelien Broszniowski */ public class Repeat extends Execution { private final int executionCount; private final Execution[] executions; public Repeat(int executionCount, Execution[] executions) { this.executionCount = executionCount; this.executions = executions; } @Override public <E extends Enum<E>> void execute(StatisticsHolder<E> statisticsHolder, Scenario scenario,
// Path: src/main/java/io/rainfall/Configuration.java // public abstract class Configuration { // // public abstract List<String> getDescription(); // // } // // Path: src/main/java/io/rainfall/Execution.java // public abstract class Execution { // // public enum ExecutionState { // UNKNOWN, // BEGINNING, // ENDING // } // // /** // * Provide an easy way to mark all operations as underway. // * // * @param scenario the test scenario // * @param state phase of execution of the scenario // */ // public void markExecutionState(Scenario scenario, ExecutionState state) { // final Map<String, RangeMap<WeightedOperation>> scenarioOperations = scenario.getOperations(); // for (RangeMap<WeightedOperation> operationRangeMap : scenarioOperations.values()) { // for (WeightedOperation op : operationRangeMap.getAll()) { // op.markExecutionState(state); // } // } // } // // protected ConcurrentPseudoRandom weightRnd = new ConcurrentPseudoRandom(); // // public abstract <E extends Enum<E>> void execute(final StatisticsHolder<E> statisticsHolder, final Scenario scenario, // final Map<Class<? extends Configuration>, Configuration> configurations, // final List<AssertionEvaluator> assertions) throws TestException; // // public abstract String toString(); // // } // // Path: src/main/java/io/rainfall/statistics/StatisticsHolder.java // public abstract class StatisticsHolder<E extends Enum<E>> { // // public abstract Enum<E>[] getResultsReported(); // // public abstract Set<String> getStatisticsKeys(); // // public abstract Statistics<E> getStatistics(String name); // // public abstract Set<StatisticsCollector> getStatisticsCollectors(); // // public abstract Histogram fetchHistogram(final Enum<E> result); // // public abstract void reset(); // // public abstract long getCurrentTps(Enum result); // // public abstract void record(String name, long responseTimeInNs, Enum result); // // public abstract void increaseAssertionsErrorsCount(String name); // // public abstract void pause(); // // public abstract void resume(); // // public long getTimeInNs() { // return System.nanoTime(); // } // // public abstract long getStartTime(); // } // Path: src/main/java/io/rainfall/execution/Repeat.java import io.rainfall.AssertionEvaluator; import io.rainfall.Configuration; import io.rainfall.Execution; import io.rainfall.Scenario; import io.rainfall.TestException; import io.rainfall.statistics.StatisticsHolder; import java.util.List; import java.util.Map; /* * Copyright (c) 2014-2022 Aurélien Broszniowski * * 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.rainfall.execution; /** * @author Aurelien Broszniowski */ public class Repeat extends Execution { private final int executionCount; private final Execution[] executions; public Repeat(int executionCount, Execution[] executions) { this.executionCount = executionCount; this.executions = executions; } @Override public <E extends Enum<E>> void execute(StatisticsHolder<E> statisticsHolder, Scenario scenario,
Map<Class<? extends Configuration>, Configuration> configurations,
aurbroszniowski/Rainfall-core
src/main/java/io/rainfall/execution/NothingFor.java
// Path: src/main/java/io/rainfall/Configuration.java // public abstract class Configuration { // // public abstract List<String> getDescription(); // // } // // Path: src/main/java/io/rainfall/Execution.java // public abstract class Execution { // // public enum ExecutionState { // UNKNOWN, // BEGINNING, // ENDING // } // // /** // * Provide an easy way to mark all operations as underway. // * // * @param scenario the test scenario // * @param state phase of execution of the scenario // */ // public void markExecutionState(Scenario scenario, ExecutionState state) { // final Map<String, RangeMap<WeightedOperation>> scenarioOperations = scenario.getOperations(); // for (RangeMap<WeightedOperation> operationRangeMap : scenarioOperations.values()) { // for (WeightedOperation op : operationRangeMap.getAll()) { // op.markExecutionState(state); // } // } // } // // protected ConcurrentPseudoRandom weightRnd = new ConcurrentPseudoRandom(); // // public abstract <E extends Enum<E>> void execute(final StatisticsHolder<E> statisticsHolder, final Scenario scenario, // final Map<Class<? extends Configuration>, Configuration> configurations, // final List<AssertionEvaluator> assertions) throws TestException; // // public abstract String toString(); // // } // // Path: src/main/java/io/rainfall/statistics/StatisticsHolder.java // public abstract class StatisticsHolder<E extends Enum<E>> { // // public abstract Enum<E>[] getResultsReported(); // // public abstract Set<String> getStatisticsKeys(); // // public abstract Statistics<E> getStatistics(String name); // // public abstract Set<StatisticsCollector> getStatisticsCollectors(); // // public abstract Histogram fetchHistogram(final Enum<E> result); // // public abstract void reset(); // // public abstract long getCurrentTps(Enum result); // // public abstract void record(String name, long responseTimeInNs, Enum result); // // public abstract void increaseAssertionsErrorsCount(String name); // // public abstract void pause(); // // public abstract void resume(); // // public long getTimeInNs() { // return System.nanoTime(); // } // // public abstract long getStartTime(); // } // // Path: src/main/java/io/rainfall/unit/TimeDivision.java // public class TimeDivision implements Unit { // // private TimeUnit timeUnit; // // public static final TimeDivision seconds = new TimeDivision(TimeUnit.SECONDS); // // public static final TimeDivision minutes = new TimeDivision(TimeUnit.MINUTES); // // public TimeDivision(TimeUnit timeUnit) { // this.timeUnit = timeUnit; // } // // public TimeUnit getTimeUnit() { // return timeUnit; // } // // @Override // public String toString() { // return timeUnit.name().toLowerCase(); // } // }
import io.rainfall.AssertionEvaluator; import io.rainfall.Configuration; import io.rainfall.Execution; import io.rainfall.Scenario; import io.rainfall.TestException; import io.rainfall.statistics.StatisticsHolder; import io.rainfall.unit.TimeDivision; import java.util.List; import java.util.Map;
/* * Copyright (c) 2014-2022 Aurélien Broszniowski * * 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.rainfall.execution; /** * This will do nothing for a certain amount of time. * * @author Aurelien Broszniowski */ public class NothingFor extends Execution { private final int nb;
// Path: src/main/java/io/rainfall/Configuration.java // public abstract class Configuration { // // public abstract List<String> getDescription(); // // } // // Path: src/main/java/io/rainfall/Execution.java // public abstract class Execution { // // public enum ExecutionState { // UNKNOWN, // BEGINNING, // ENDING // } // // /** // * Provide an easy way to mark all operations as underway. // * // * @param scenario the test scenario // * @param state phase of execution of the scenario // */ // public void markExecutionState(Scenario scenario, ExecutionState state) { // final Map<String, RangeMap<WeightedOperation>> scenarioOperations = scenario.getOperations(); // for (RangeMap<WeightedOperation> operationRangeMap : scenarioOperations.values()) { // for (WeightedOperation op : operationRangeMap.getAll()) { // op.markExecutionState(state); // } // } // } // // protected ConcurrentPseudoRandom weightRnd = new ConcurrentPseudoRandom(); // // public abstract <E extends Enum<E>> void execute(final StatisticsHolder<E> statisticsHolder, final Scenario scenario, // final Map<Class<? extends Configuration>, Configuration> configurations, // final List<AssertionEvaluator> assertions) throws TestException; // // public abstract String toString(); // // } // // Path: src/main/java/io/rainfall/statistics/StatisticsHolder.java // public abstract class StatisticsHolder<E extends Enum<E>> { // // public abstract Enum<E>[] getResultsReported(); // // public abstract Set<String> getStatisticsKeys(); // // public abstract Statistics<E> getStatistics(String name); // // public abstract Set<StatisticsCollector> getStatisticsCollectors(); // // public abstract Histogram fetchHistogram(final Enum<E> result); // // public abstract void reset(); // // public abstract long getCurrentTps(Enum result); // // public abstract void record(String name, long responseTimeInNs, Enum result); // // public abstract void increaseAssertionsErrorsCount(String name); // // public abstract void pause(); // // public abstract void resume(); // // public long getTimeInNs() { // return System.nanoTime(); // } // // public abstract long getStartTime(); // } // // Path: src/main/java/io/rainfall/unit/TimeDivision.java // public class TimeDivision implements Unit { // // private TimeUnit timeUnit; // // public static final TimeDivision seconds = new TimeDivision(TimeUnit.SECONDS); // // public static final TimeDivision minutes = new TimeDivision(TimeUnit.MINUTES); // // public TimeDivision(TimeUnit timeUnit) { // this.timeUnit = timeUnit; // } // // public TimeUnit getTimeUnit() { // return timeUnit; // } // // @Override // public String toString() { // return timeUnit.name().toLowerCase(); // } // } // Path: src/main/java/io/rainfall/execution/NothingFor.java import io.rainfall.AssertionEvaluator; import io.rainfall.Configuration; import io.rainfall.Execution; import io.rainfall.Scenario; import io.rainfall.TestException; import io.rainfall.statistics.StatisticsHolder; import io.rainfall.unit.TimeDivision; import java.util.List; import java.util.Map; /* * Copyright (c) 2014-2022 Aurélien Broszniowski * * 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.rainfall.execution; /** * This will do nothing for a certain amount of time. * * @author Aurelien Broszniowski */ public class NothingFor extends Execution { private final int nb;
private final TimeDivision timeDivision;
aurbroszniowski/Rainfall-core
src/main/java/io/rainfall/execution/NothingFor.java
// Path: src/main/java/io/rainfall/Configuration.java // public abstract class Configuration { // // public abstract List<String> getDescription(); // // } // // Path: src/main/java/io/rainfall/Execution.java // public abstract class Execution { // // public enum ExecutionState { // UNKNOWN, // BEGINNING, // ENDING // } // // /** // * Provide an easy way to mark all operations as underway. // * // * @param scenario the test scenario // * @param state phase of execution of the scenario // */ // public void markExecutionState(Scenario scenario, ExecutionState state) { // final Map<String, RangeMap<WeightedOperation>> scenarioOperations = scenario.getOperations(); // for (RangeMap<WeightedOperation> operationRangeMap : scenarioOperations.values()) { // for (WeightedOperation op : operationRangeMap.getAll()) { // op.markExecutionState(state); // } // } // } // // protected ConcurrentPseudoRandom weightRnd = new ConcurrentPseudoRandom(); // // public abstract <E extends Enum<E>> void execute(final StatisticsHolder<E> statisticsHolder, final Scenario scenario, // final Map<Class<? extends Configuration>, Configuration> configurations, // final List<AssertionEvaluator> assertions) throws TestException; // // public abstract String toString(); // // } // // Path: src/main/java/io/rainfall/statistics/StatisticsHolder.java // public abstract class StatisticsHolder<E extends Enum<E>> { // // public abstract Enum<E>[] getResultsReported(); // // public abstract Set<String> getStatisticsKeys(); // // public abstract Statistics<E> getStatistics(String name); // // public abstract Set<StatisticsCollector> getStatisticsCollectors(); // // public abstract Histogram fetchHistogram(final Enum<E> result); // // public abstract void reset(); // // public abstract long getCurrentTps(Enum result); // // public abstract void record(String name, long responseTimeInNs, Enum result); // // public abstract void increaseAssertionsErrorsCount(String name); // // public abstract void pause(); // // public abstract void resume(); // // public long getTimeInNs() { // return System.nanoTime(); // } // // public abstract long getStartTime(); // } // // Path: src/main/java/io/rainfall/unit/TimeDivision.java // public class TimeDivision implements Unit { // // private TimeUnit timeUnit; // // public static final TimeDivision seconds = new TimeDivision(TimeUnit.SECONDS); // // public static final TimeDivision minutes = new TimeDivision(TimeUnit.MINUTES); // // public TimeDivision(TimeUnit timeUnit) { // this.timeUnit = timeUnit; // } // // public TimeUnit getTimeUnit() { // return timeUnit; // } // // @Override // public String toString() { // return timeUnit.name().toLowerCase(); // } // }
import io.rainfall.AssertionEvaluator; import io.rainfall.Configuration; import io.rainfall.Execution; import io.rainfall.Scenario; import io.rainfall.TestException; import io.rainfall.statistics.StatisticsHolder; import io.rainfall.unit.TimeDivision; import java.util.List; import java.util.Map;
/* * Copyright (c) 2014-2022 Aurélien Broszniowski * * 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.rainfall.execution; /** * This will do nothing for a certain amount of time. * * @author Aurelien Broszniowski */ public class NothingFor extends Execution { private final int nb; private final TimeDivision timeDivision; public NothingFor(final int nb, final TimeDivision timeDivision) { this.nb = nb; this.timeDivision = timeDivision; } @Override
// Path: src/main/java/io/rainfall/Configuration.java // public abstract class Configuration { // // public abstract List<String> getDescription(); // // } // // Path: src/main/java/io/rainfall/Execution.java // public abstract class Execution { // // public enum ExecutionState { // UNKNOWN, // BEGINNING, // ENDING // } // // /** // * Provide an easy way to mark all operations as underway. // * // * @param scenario the test scenario // * @param state phase of execution of the scenario // */ // public void markExecutionState(Scenario scenario, ExecutionState state) { // final Map<String, RangeMap<WeightedOperation>> scenarioOperations = scenario.getOperations(); // for (RangeMap<WeightedOperation> operationRangeMap : scenarioOperations.values()) { // for (WeightedOperation op : operationRangeMap.getAll()) { // op.markExecutionState(state); // } // } // } // // protected ConcurrentPseudoRandom weightRnd = new ConcurrentPseudoRandom(); // // public abstract <E extends Enum<E>> void execute(final StatisticsHolder<E> statisticsHolder, final Scenario scenario, // final Map<Class<? extends Configuration>, Configuration> configurations, // final List<AssertionEvaluator> assertions) throws TestException; // // public abstract String toString(); // // } // // Path: src/main/java/io/rainfall/statistics/StatisticsHolder.java // public abstract class StatisticsHolder<E extends Enum<E>> { // // public abstract Enum<E>[] getResultsReported(); // // public abstract Set<String> getStatisticsKeys(); // // public abstract Statistics<E> getStatistics(String name); // // public abstract Set<StatisticsCollector> getStatisticsCollectors(); // // public abstract Histogram fetchHistogram(final Enum<E> result); // // public abstract void reset(); // // public abstract long getCurrentTps(Enum result); // // public abstract void record(String name, long responseTimeInNs, Enum result); // // public abstract void increaseAssertionsErrorsCount(String name); // // public abstract void pause(); // // public abstract void resume(); // // public long getTimeInNs() { // return System.nanoTime(); // } // // public abstract long getStartTime(); // } // // Path: src/main/java/io/rainfall/unit/TimeDivision.java // public class TimeDivision implements Unit { // // private TimeUnit timeUnit; // // public static final TimeDivision seconds = new TimeDivision(TimeUnit.SECONDS); // // public static final TimeDivision minutes = new TimeDivision(TimeUnit.MINUTES); // // public TimeDivision(TimeUnit timeUnit) { // this.timeUnit = timeUnit; // } // // public TimeUnit getTimeUnit() { // return timeUnit; // } // // @Override // public String toString() { // return timeUnit.name().toLowerCase(); // } // } // Path: src/main/java/io/rainfall/execution/NothingFor.java import io.rainfall.AssertionEvaluator; import io.rainfall.Configuration; import io.rainfall.Execution; import io.rainfall.Scenario; import io.rainfall.TestException; import io.rainfall.statistics.StatisticsHolder; import io.rainfall.unit.TimeDivision; import java.util.List; import java.util.Map; /* * Copyright (c) 2014-2022 Aurélien Broszniowski * * 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.rainfall.execution; /** * This will do nothing for a certain amount of time. * * @author Aurelien Broszniowski */ public class NothingFor extends Execution { private final int nb; private final TimeDivision timeDivision; public NothingFor(final int nb, final TimeDivision timeDivision) { this.nb = nb; this.timeDivision = timeDivision; } @Override
public <E extends Enum<E>> void execute(final StatisticsHolder<E> statisticsHolder, final Scenario scenario,
aurbroszniowski/Rainfall-core
src/main/java/io/rainfall/execution/NothingFor.java
// Path: src/main/java/io/rainfall/Configuration.java // public abstract class Configuration { // // public abstract List<String> getDescription(); // // } // // Path: src/main/java/io/rainfall/Execution.java // public abstract class Execution { // // public enum ExecutionState { // UNKNOWN, // BEGINNING, // ENDING // } // // /** // * Provide an easy way to mark all operations as underway. // * // * @param scenario the test scenario // * @param state phase of execution of the scenario // */ // public void markExecutionState(Scenario scenario, ExecutionState state) { // final Map<String, RangeMap<WeightedOperation>> scenarioOperations = scenario.getOperations(); // for (RangeMap<WeightedOperation> operationRangeMap : scenarioOperations.values()) { // for (WeightedOperation op : operationRangeMap.getAll()) { // op.markExecutionState(state); // } // } // } // // protected ConcurrentPseudoRandom weightRnd = new ConcurrentPseudoRandom(); // // public abstract <E extends Enum<E>> void execute(final StatisticsHolder<E> statisticsHolder, final Scenario scenario, // final Map<Class<? extends Configuration>, Configuration> configurations, // final List<AssertionEvaluator> assertions) throws TestException; // // public abstract String toString(); // // } // // Path: src/main/java/io/rainfall/statistics/StatisticsHolder.java // public abstract class StatisticsHolder<E extends Enum<E>> { // // public abstract Enum<E>[] getResultsReported(); // // public abstract Set<String> getStatisticsKeys(); // // public abstract Statistics<E> getStatistics(String name); // // public abstract Set<StatisticsCollector> getStatisticsCollectors(); // // public abstract Histogram fetchHistogram(final Enum<E> result); // // public abstract void reset(); // // public abstract long getCurrentTps(Enum result); // // public abstract void record(String name, long responseTimeInNs, Enum result); // // public abstract void increaseAssertionsErrorsCount(String name); // // public abstract void pause(); // // public abstract void resume(); // // public long getTimeInNs() { // return System.nanoTime(); // } // // public abstract long getStartTime(); // } // // Path: src/main/java/io/rainfall/unit/TimeDivision.java // public class TimeDivision implements Unit { // // private TimeUnit timeUnit; // // public static final TimeDivision seconds = new TimeDivision(TimeUnit.SECONDS); // // public static final TimeDivision minutes = new TimeDivision(TimeUnit.MINUTES); // // public TimeDivision(TimeUnit timeUnit) { // this.timeUnit = timeUnit; // } // // public TimeUnit getTimeUnit() { // return timeUnit; // } // // @Override // public String toString() { // return timeUnit.name().toLowerCase(); // } // }
import io.rainfall.AssertionEvaluator; import io.rainfall.Configuration; import io.rainfall.Execution; import io.rainfall.Scenario; import io.rainfall.TestException; import io.rainfall.statistics.StatisticsHolder; import io.rainfall.unit.TimeDivision; import java.util.List; import java.util.Map;
/* * Copyright (c) 2014-2022 Aurélien Broszniowski * * 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.rainfall.execution; /** * This will do nothing for a certain amount of time. * * @author Aurelien Broszniowski */ public class NothingFor extends Execution { private final int nb; private final TimeDivision timeDivision; public NothingFor(final int nb, final TimeDivision timeDivision) { this.nb = nb; this.timeDivision = timeDivision; } @Override public <E extends Enum<E>> void execute(final StatisticsHolder<E> statisticsHolder, final Scenario scenario,
// Path: src/main/java/io/rainfall/Configuration.java // public abstract class Configuration { // // public abstract List<String> getDescription(); // // } // // Path: src/main/java/io/rainfall/Execution.java // public abstract class Execution { // // public enum ExecutionState { // UNKNOWN, // BEGINNING, // ENDING // } // // /** // * Provide an easy way to mark all operations as underway. // * // * @param scenario the test scenario // * @param state phase of execution of the scenario // */ // public void markExecutionState(Scenario scenario, ExecutionState state) { // final Map<String, RangeMap<WeightedOperation>> scenarioOperations = scenario.getOperations(); // for (RangeMap<WeightedOperation> operationRangeMap : scenarioOperations.values()) { // for (WeightedOperation op : operationRangeMap.getAll()) { // op.markExecutionState(state); // } // } // } // // protected ConcurrentPseudoRandom weightRnd = new ConcurrentPseudoRandom(); // // public abstract <E extends Enum<E>> void execute(final StatisticsHolder<E> statisticsHolder, final Scenario scenario, // final Map<Class<? extends Configuration>, Configuration> configurations, // final List<AssertionEvaluator> assertions) throws TestException; // // public abstract String toString(); // // } // // Path: src/main/java/io/rainfall/statistics/StatisticsHolder.java // public abstract class StatisticsHolder<E extends Enum<E>> { // // public abstract Enum<E>[] getResultsReported(); // // public abstract Set<String> getStatisticsKeys(); // // public abstract Statistics<E> getStatistics(String name); // // public abstract Set<StatisticsCollector> getStatisticsCollectors(); // // public abstract Histogram fetchHistogram(final Enum<E> result); // // public abstract void reset(); // // public abstract long getCurrentTps(Enum result); // // public abstract void record(String name, long responseTimeInNs, Enum result); // // public abstract void increaseAssertionsErrorsCount(String name); // // public abstract void pause(); // // public abstract void resume(); // // public long getTimeInNs() { // return System.nanoTime(); // } // // public abstract long getStartTime(); // } // // Path: src/main/java/io/rainfall/unit/TimeDivision.java // public class TimeDivision implements Unit { // // private TimeUnit timeUnit; // // public static final TimeDivision seconds = new TimeDivision(TimeUnit.SECONDS); // // public static final TimeDivision minutes = new TimeDivision(TimeUnit.MINUTES); // // public TimeDivision(TimeUnit timeUnit) { // this.timeUnit = timeUnit; // } // // public TimeUnit getTimeUnit() { // return timeUnit; // } // // @Override // public String toString() { // return timeUnit.name().toLowerCase(); // } // } // Path: src/main/java/io/rainfall/execution/NothingFor.java import io.rainfall.AssertionEvaluator; import io.rainfall.Configuration; import io.rainfall.Execution; import io.rainfall.Scenario; import io.rainfall.TestException; import io.rainfall.statistics.StatisticsHolder; import io.rainfall.unit.TimeDivision; import java.util.List; import java.util.Map; /* * Copyright (c) 2014-2022 Aurélien Broszniowski * * 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.rainfall.execution; /** * This will do nothing for a certain amount of time. * * @author Aurelien Broszniowski */ public class NothingFor extends Execution { private final int nb; private final TimeDivision timeDivision; public NothingFor(final int nb, final TimeDivision timeDivision) { this.nb = nb; this.timeDivision = timeDivision; } @Override public <E extends Enum<E>> void execute(final StatisticsHolder<E> statisticsHolder, final Scenario scenario,
final Map<Class<? extends Configuration>, Configuration> configurations,
aurbroszniowski/Rainfall-core
src/test/java/io/rainfall/execution/RepeatTest.java
// Path: src/main/java/io/rainfall/Configuration.java // public abstract class Configuration { // // public abstract List<String> getDescription(); // // } // // Path: src/main/java/io/rainfall/Execution.java // public abstract class Execution { // // public enum ExecutionState { // UNKNOWN, // BEGINNING, // ENDING // } // // /** // * Provide an easy way to mark all operations as underway. // * // * @param scenario the test scenario // * @param state phase of execution of the scenario // */ // public void markExecutionState(Scenario scenario, ExecutionState state) { // final Map<String, RangeMap<WeightedOperation>> scenarioOperations = scenario.getOperations(); // for (RangeMap<WeightedOperation> operationRangeMap : scenarioOperations.values()) { // for (WeightedOperation op : operationRangeMap.getAll()) { // op.markExecutionState(state); // } // } // } // // protected ConcurrentPseudoRandom weightRnd = new ConcurrentPseudoRandom(); // // public abstract <E extends Enum<E>> void execute(final StatisticsHolder<E> statisticsHolder, final Scenario scenario, // final Map<Class<? extends Configuration>, Configuration> configurations, // final List<AssertionEvaluator> assertions) throws TestException; // // public abstract String toString(); // // } // // Path: src/main/java/io/rainfall/statistics/StatisticsHolder.java // public abstract class StatisticsHolder<E extends Enum<E>> { // // public abstract Enum<E>[] getResultsReported(); // // public abstract Set<String> getStatisticsKeys(); // // public abstract Statistics<E> getStatistics(String name); // // public abstract Set<StatisticsCollector> getStatisticsCollectors(); // // public abstract Histogram fetchHistogram(final Enum<E> result); // // public abstract void reset(); // // public abstract long getCurrentTps(Enum result); // // public abstract void record(String name, long responseTimeInNs, Enum result); // // public abstract void increaseAssertionsErrorsCount(String name); // // public abstract void pause(); // // public abstract void resume(); // // public long getTimeInNs() { // return System.nanoTime(); // } // // public abstract long getStartTime(); // }
import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import io.rainfall.AssertionEvaluator; import io.rainfall.Configuration; import io.rainfall.Execution; import io.rainfall.Scenario; import io.rainfall.TestException; import io.rainfall.statistics.StatisticsHolder; import org.junit.Test; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.mockito.Mockito.mock;
/* * Copyright (c) 2014-2022 Aurélien Broszniowski * * 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.rainfall.execution; /** * @author Aurelien Broszniowski */ public class RepeatTest { @Test public void testRepeat() throws TestException {
// Path: src/main/java/io/rainfall/Configuration.java // public abstract class Configuration { // // public abstract List<String> getDescription(); // // } // // Path: src/main/java/io/rainfall/Execution.java // public abstract class Execution { // // public enum ExecutionState { // UNKNOWN, // BEGINNING, // ENDING // } // // /** // * Provide an easy way to mark all operations as underway. // * // * @param scenario the test scenario // * @param state phase of execution of the scenario // */ // public void markExecutionState(Scenario scenario, ExecutionState state) { // final Map<String, RangeMap<WeightedOperation>> scenarioOperations = scenario.getOperations(); // for (RangeMap<WeightedOperation> operationRangeMap : scenarioOperations.values()) { // for (WeightedOperation op : operationRangeMap.getAll()) { // op.markExecutionState(state); // } // } // } // // protected ConcurrentPseudoRandom weightRnd = new ConcurrentPseudoRandom(); // // public abstract <E extends Enum<E>> void execute(final StatisticsHolder<E> statisticsHolder, final Scenario scenario, // final Map<Class<? extends Configuration>, Configuration> configurations, // final List<AssertionEvaluator> assertions) throws TestException; // // public abstract String toString(); // // } // // Path: src/main/java/io/rainfall/statistics/StatisticsHolder.java // public abstract class StatisticsHolder<E extends Enum<E>> { // // public abstract Enum<E>[] getResultsReported(); // // public abstract Set<String> getStatisticsKeys(); // // public abstract Statistics<E> getStatistics(String name); // // public abstract Set<StatisticsCollector> getStatisticsCollectors(); // // public abstract Histogram fetchHistogram(final Enum<E> result); // // public abstract void reset(); // // public abstract long getCurrentTps(Enum result); // // public abstract void record(String name, long responseTimeInNs, Enum result); // // public abstract void increaseAssertionsErrorsCount(String name); // // public abstract void pause(); // // public abstract void resume(); // // public long getTimeInNs() { // return System.nanoTime(); // } // // public abstract long getStartTime(); // } // Path: src/test/java/io/rainfall/execution/RepeatTest.java import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import io.rainfall.AssertionEvaluator; import io.rainfall.Configuration; import io.rainfall.Execution; import io.rainfall.Scenario; import io.rainfall.TestException; import io.rainfall.statistics.StatisticsHolder; import org.junit.Test; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.mockito.Mockito.mock; /* * Copyright (c) 2014-2022 Aurélien Broszniowski * * 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.rainfall.execution; /** * @author Aurelien Broszniowski */ public class RepeatTest { @Test public void testRepeat() throws TestException {
StatisticsHolder statisticsHolder = mock(StatisticsHolder.class);
aurbroszniowski/Rainfall-core
src/test/java/io/rainfall/execution/RepeatTest.java
// Path: src/main/java/io/rainfall/Configuration.java // public abstract class Configuration { // // public abstract List<String> getDescription(); // // } // // Path: src/main/java/io/rainfall/Execution.java // public abstract class Execution { // // public enum ExecutionState { // UNKNOWN, // BEGINNING, // ENDING // } // // /** // * Provide an easy way to mark all operations as underway. // * // * @param scenario the test scenario // * @param state phase of execution of the scenario // */ // public void markExecutionState(Scenario scenario, ExecutionState state) { // final Map<String, RangeMap<WeightedOperation>> scenarioOperations = scenario.getOperations(); // for (RangeMap<WeightedOperation> operationRangeMap : scenarioOperations.values()) { // for (WeightedOperation op : operationRangeMap.getAll()) { // op.markExecutionState(state); // } // } // } // // protected ConcurrentPseudoRandom weightRnd = new ConcurrentPseudoRandom(); // // public abstract <E extends Enum<E>> void execute(final StatisticsHolder<E> statisticsHolder, final Scenario scenario, // final Map<Class<? extends Configuration>, Configuration> configurations, // final List<AssertionEvaluator> assertions) throws TestException; // // public abstract String toString(); // // } // // Path: src/main/java/io/rainfall/statistics/StatisticsHolder.java // public abstract class StatisticsHolder<E extends Enum<E>> { // // public abstract Enum<E>[] getResultsReported(); // // public abstract Set<String> getStatisticsKeys(); // // public abstract Statistics<E> getStatistics(String name); // // public abstract Set<StatisticsCollector> getStatisticsCollectors(); // // public abstract Histogram fetchHistogram(final Enum<E> result); // // public abstract void reset(); // // public abstract long getCurrentTps(Enum result); // // public abstract void record(String name, long responseTimeInNs, Enum result); // // public abstract void increaseAssertionsErrorsCount(String name); // // public abstract void pause(); // // public abstract void resume(); // // public long getTimeInNs() { // return System.nanoTime(); // } // // public abstract long getStartTime(); // }
import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import io.rainfall.AssertionEvaluator; import io.rainfall.Configuration; import io.rainfall.Execution; import io.rainfall.Scenario; import io.rainfall.TestException; import io.rainfall.statistics.StatisticsHolder; import org.junit.Test; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.mockito.Mockito.mock;
/* * Copyright (c) 2014-2022 Aurélien Broszniowski * * 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.rainfall.execution; /** * @author Aurelien Broszniowski */ public class RepeatTest { @Test public void testRepeat() throws TestException { StatisticsHolder statisticsHolder = mock(StatisticsHolder.class); Scenario scenario = mock(Scenario.class);
// Path: src/main/java/io/rainfall/Configuration.java // public abstract class Configuration { // // public abstract List<String> getDescription(); // // } // // Path: src/main/java/io/rainfall/Execution.java // public abstract class Execution { // // public enum ExecutionState { // UNKNOWN, // BEGINNING, // ENDING // } // // /** // * Provide an easy way to mark all operations as underway. // * // * @param scenario the test scenario // * @param state phase of execution of the scenario // */ // public void markExecutionState(Scenario scenario, ExecutionState state) { // final Map<String, RangeMap<WeightedOperation>> scenarioOperations = scenario.getOperations(); // for (RangeMap<WeightedOperation> operationRangeMap : scenarioOperations.values()) { // for (WeightedOperation op : operationRangeMap.getAll()) { // op.markExecutionState(state); // } // } // } // // protected ConcurrentPseudoRandom weightRnd = new ConcurrentPseudoRandom(); // // public abstract <E extends Enum<E>> void execute(final StatisticsHolder<E> statisticsHolder, final Scenario scenario, // final Map<Class<? extends Configuration>, Configuration> configurations, // final List<AssertionEvaluator> assertions) throws TestException; // // public abstract String toString(); // // } // // Path: src/main/java/io/rainfall/statistics/StatisticsHolder.java // public abstract class StatisticsHolder<E extends Enum<E>> { // // public abstract Enum<E>[] getResultsReported(); // // public abstract Set<String> getStatisticsKeys(); // // public abstract Statistics<E> getStatistics(String name); // // public abstract Set<StatisticsCollector> getStatisticsCollectors(); // // public abstract Histogram fetchHistogram(final Enum<E> result); // // public abstract void reset(); // // public abstract long getCurrentTps(Enum result); // // public abstract void record(String name, long responseTimeInNs, Enum result); // // public abstract void increaseAssertionsErrorsCount(String name); // // public abstract void pause(); // // public abstract void resume(); // // public long getTimeInNs() { // return System.nanoTime(); // } // // public abstract long getStartTime(); // } // Path: src/test/java/io/rainfall/execution/RepeatTest.java import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import io.rainfall.AssertionEvaluator; import io.rainfall.Configuration; import io.rainfall.Execution; import io.rainfall.Scenario; import io.rainfall.TestException; import io.rainfall.statistics.StatisticsHolder; import org.junit.Test; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.mockito.Mockito.mock; /* * Copyright (c) 2014-2022 Aurélien Broszniowski * * 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.rainfall.execution; /** * @author Aurelien Broszniowski */ public class RepeatTest { @Test public void testRepeat() throws TestException { StatisticsHolder statisticsHolder = mock(StatisticsHolder.class); Scenario scenario = mock(Scenario.class);
Map<Class<? extends Configuration>, Configuration> configurations = new HashMap<>();
aurbroszniowski/Rainfall-core
src/test/java/io/rainfall/execution/RepeatTest.java
// Path: src/main/java/io/rainfall/Configuration.java // public abstract class Configuration { // // public abstract List<String> getDescription(); // // } // // Path: src/main/java/io/rainfall/Execution.java // public abstract class Execution { // // public enum ExecutionState { // UNKNOWN, // BEGINNING, // ENDING // } // // /** // * Provide an easy way to mark all operations as underway. // * // * @param scenario the test scenario // * @param state phase of execution of the scenario // */ // public void markExecutionState(Scenario scenario, ExecutionState state) { // final Map<String, RangeMap<WeightedOperation>> scenarioOperations = scenario.getOperations(); // for (RangeMap<WeightedOperation> operationRangeMap : scenarioOperations.values()) { // for (WeightedOperation op : operationRangeMap.getAll()) { // op.markExecutionState(state); // } // } // } // // protected ConcurrentPseudoRandom weightRnd = new ConcurrentPseudoRandom(); // // public abstract <E extends Enum<E>> void execute(final StatisticsHolder<E> statisticsHolder, final Scenario scenario, // final Map<Class<? extends Configuration>, Configuration> configurations, // final List<AssertionEvaluator> assertions) throws TestException; // // public abstract String toString(); // // } // // Path: src/main/java/io/rainfall/statistics/StatisticsHolder.java // public abstract class StatisticsHolder<E extends Enum<E>> { // // public abstract Enum<E>[] getResultsReported(); // // public abstract Set<String> getStatisticsKeys(); // // public abstract Statistics<E> getStatistics(String name); // // public abstract Set<StatisticsCollector> getStatisticsCollectors(); // // public abstract Histogram fetchHistogram(final Enum<E> result); // // public abstract void reset(); // // public abstract long getCurrentTps(Enum result); // // public abstract void record(String name, long responseTimeInNs, Enum result); // // public abstract void increaseAssertionsErrorsCount(String name); // // public abstract void pause(); // // public abstract void resume(); // // public long getTimeInNs() { // return System.nanoTime(); // } // // public abstract long getStartTime(); // }
import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import io.rainfall.AssertionEvaluator; import io.rainfall.Configuration; import io.rainfall.Execution; import io.rainfall.Scenario; import io.rainfall.TestException; import io.rainfall.statistics.StatisticsHolder; import org.junit.Test; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.mockito.Mockito.mock;
/* * Copyright (c) 2014-2022 Aurélien Broszniowski * * 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.rainfall.execution; /** * @author Aurelien Broszniowski */ public class RepeatTest { @Test public void testRepeat() throws TestException { StatisticsHolder statisticsHolder = mock(StatisticsHolder.class); Scenario scenario = mock(Scenario.class); Map<Class<? extends Configuration>, Configuration> configurations = new HashMap<>(); List<AssertionEvaluator> assertions = new ArrayList<>();
// Path: src/main/java/io/rainfall/Configuration.java // public abstract class Configuration { // // public abstract List<String> getDescription(); // // } // // Path: src/main/java/io/rainfall/Execution.java // public abstract class Execution { // // public enum ExecutionState { // UNKNOWN, // BEGINNING, // ENDING // } // // /** // * Provide an easy way to mark all operations as underway. // * // * @param scenario the test scenario // * @param state phase of execution of the scenario // */ // public void markExecutionState(Scenario scenario, ExecutionState state) { // final Map<String, RangeMap<WeightedOperation>> scenarioOperations = scenario.getOperations(); // for (RangeMap<WeightedOperation> operationRangeMap : scenarioOperations.values()) { // for (WeightedOperation op : operationRangeMap.getAll()) { // op.markExecutionState(state); // } // } // } // // protected ConcurrentPseudoRandom weightRnd = new ConcurrentPseudoRandom(); // // public abstract <E extends Enum<E>> void execute(final StatisticsHolder<E> statisticsHolder, final Scenario scenario, // final Map<Class<? extends Configuration>, Configuration> configurations, // final List<AssertionEvaluator> assertions) throws TestException; // // public abstract String toString(); // // } // // Path: src/main/java/io/rainfall/statistics/StatisticsHolder.java // public abstract class StatisticsHolder<E extends Enum<E>> { // // public abstract Enum<E>[] getResultsReported(); // // public abstract Set<String> getStatisticsKeys(); // // public abstract Statistics<E> getStatistics(String name); // // public abstract Set<StatisticsCollector> getStatisticsCollectors(); // // public abstract Histogram fetchHistogram(final Enum<E> result); // // public abstract void reset(); // // public abstract long getCurrentTps(Enum result); // // public abstract void record(String name, long responseTimeInNs, Enum result); // // public abstract void increaseAssertionsErrorsCount(String name); // // public abstract void pause(); // // public abstract void resume(); // // public long getTimeInNs() { // return System.nanoTime(); // } // // public abstract long getStartTime(); // } // Path: src/test/java/io/rainfall/execution/RepeatTest.java import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import io.rainfall.AssertionEvaluator; import io.rainfall.Configuration; import io.rainfall.Execution; import io.rainfall.Scenario; import io.rainfall.TestException; import io.rainfall.statistics.StatisticsHolder; import org.junit.Test; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.mockito.Mockito.mock; /* * Copyright (c) 2014-2022 Aurélien Broszniowski * * 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.rainfall.execution; /** * @author Aurelien Broszniowski */ public class RepeatTest { @Test public void testRepeat() throws TestException { StatisticsHolder statisticsHolder = mock(StatisticsHolder.class); Scenario scenario = mock(Scenario.class); Map<Class<? extends Configuration>, Configuration> configurations = new HashMap<>(); List<AssertionEvaluator> assertions = new ArrayList<>();
Execution execution1 = mock(Execution.class);
aurbroszniowski/Rainfall-core
src/main/java/io/rainfall/reporting/HlogReporter.java
// Path: src/main/java/io/rainfall/statistics/StatisticsHolder.java // public abstract class StatisticsHolder<E extends Enum<E>> { // // public abstract Enum<E>[] getResultsReported(); // // public abstract Set<String> getStatisticsKeys(); // // public abstract Statistics<E> getStatistics(String name); // // public abstract Set<StatisticsCollector> getStatisticsCollectors(); // // public abstract Histogram fetchHistogram(final Enum<E> result); // // public abstract void reset(); // // public abstract long getCurrentTps(Enum result); // // public abstract void record(String name, long responseTimeInNs, Enum result); // // public abstract void increaseAssertionsErrorsCount(String name); // // public abstract void pause(); // // public abstract void resume(); // // public long getTimeInNs() { // return System.nanoTime(); // } // // public abstract long getStartTime(); // } // // Path: src/main/java/io/rainfall/statistics/StatisticsPeekHolder.java // public class StatisticsPeekHolder<E extends Enum<E>> { // public final static String ALL = "ALL"; // private final Enum<E>[] resultsReported; // private final ConcurrentHashMap<String, LongAdder> assertionsErrors; // private final RainfallHistogramSink<E> histograms; // private final long startTime; // // private Map<String, StatisticsPeek<E>> statisticsPeeks = new ConcurrentHashMap<String, StatisticsPeek<E>>(); // private Map<String, Exporter> extraCollectedStatistics = new ConcurrentHashMap<String, Exporter>(); // private StatisticsPeek<E> totalStatisticsPeeks = null; // private long timestamp; // // public StatisticsPeekHolder(final Enum<E>[] resultsReported, final Map<String, Statistics<E>> statisticsMap, // final Set<StatisticsCollector> statisticsCollectors, // final ConcurrentHashMap<String, LongAdder> assertionsErrors, RainfallHistogramSink<E> histograms, // long startTime) { // this.resultsReported = resultsReported; // this.assertionsErrors = assertionsErrors; // this.histograms = histograms; // this.startTime = startTime; // this.timestamp = System.currentTimeMillis(); // for (String name : statisticsMap.keySet()) { // statisticsPeeks.put(name, statisticsMap.get(name).peek(timestamp)); // } // this.totalStatisticsPeeks = new StatisticsPeek<E>(ALL, this.resultsReported, this.timestamp); // totalStatisticsPeeks.addAll(statisticsPeeks); // // for (StatisticsCollector statisticsCollector : statisticsCollectors) { // extraCollectedStatistics.put(statisticsCollector.getName(), statisticsCollector.peek()); // } // } // // public StatisticsPeek<E> getStatisticsPeeks(String name) { // return statisticsPeeks.get(name); // } // // public Long getAssertionsErrorsCount(String name) {return assertionsErrors.get(name).longValue();} // // public Set<String> getStatisticsPeeksNames() { // return statisticsPeeks.keySet(); // } // // public StatisticsPeek<E> getTotalStatisticsPeeks() { // return totalStatisticsPeeks; // } // // public long getTimestamp() { // return timestamp; // } // // public long getStartTime() { // return startTime; // } // // public Enum<E>[] getResultsReported() { // return resultsReported; // } // // public Map<String, Exporter> getExtraCollectedStatistics() { // return extraCollectedStatistics; // } // // public Long getTotalAssertionsErrorsCount() { // Long totalAssertionsErrorsCount = 0L; // for (LongAdder count : assertionsErrors.values()) { // totalAssertionsErrorsCount += count.longValue(); // } // return totalAssertionsErrorsCount; // } // // public Histogram fetchHistogram(final Enum<E> result) { // return histograms.fetchHistogram(result); // } // // } // // Path: src/main/java/io/rainfall/utils/CompressionUtils.java // public static String cleanFilename(String filename) { // Arrays.sort(illegalChars); // StringBuilder cleanName = new StringBuilder(); // for (int i = 0; i < filename.length(); i++) { // int c = (int)filename.charAt(i); // if (Arrays.binarySearch(illegalChars, c) < 0) { // cleanName.append((char)c); // } // } // return cleanName.toString(); // }
import io.rainfall.statistics.StatisticsHolder; import io.rainfall.statistics.StatisticsPeekHolder; import org.HdrHistogram.Histogram; import org.HdrHistogram.HistogramLogWriter; import java.io.File; import java.io.PrintStream; import java.util.List; import static io.rainfall.utils.CompressionUtils.cleanFilename;
/* * Copyright (c) 2014-2022 Aurélien Broszniowski * * 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.rainfall.reporting; /** * @author Ludovic Orban */ public class HlogReporter<E extends Enum<E>> extends FileReporter<E> { private final String basedir; public HlogReporter() { this("target/rainfall-histograms"); } public HlogReporter(String outputPath) { this.basedir = new File(outputPath).getAbsoluteFile().getAbsolutePath(); this.reportPath = new File(this.basedir); } @Override public void header(final List<String> description) { } @Override
// Path: src/main/java/io/rainfall/statistics/StatisticsHolder.java // public abstract class StatisticsHolder<E extends Enum<E>> { // // public abstract Enum<E>[] getResultsReported(); // // public abstract Set<String> getStatisticsKeys(); // // public abstract Statistics<E> getStatistics(String name); // // public abstract Set<StatisticsCollector> getStatisticsCollectors(); // // public abstract Histogram fetchHistogram(final Enum<E> result); // // public abstract void reset(); // // public abstract long getCurrentTps(Enum result); // // public abstract void record(String name, long responseTimeInNs, Enum result); // // public abstract void increaseAssertionsErrorsCount(String name); // // public abstract void pause(); // // public abstract void resume(); // // public long getTimeInNs() { // return System.nanoTime(); // } // // public abstract long getStartTime(); // } // // Path: src/main/java/io/rainfall/statistics/StatisticsPeekHolder.java // public class StatisticsPeekHolder<E extends Enum<E>> { // public final static String ALL = "ALL"; // private final Enum<E>[] resultsReported; // private final ConcurrentHashMap<String, LongAdder> assertionsErrors; // private final RainfallHistogramSink<E> histograms; // private final long startTime; // // private Map<String, StatisticsPeek<E>> statisticsPeeks = new ConcurrentHashMap<String, StatisticsPeek<E>>(); // private Map<String, Exporter> extraCollectedStatistics = new ConcurrentHashMap<String, Exporter>(); // private StatisticsPeek<E> totalStatisticsPeeks = null; // private long timestamp; // // public StatisticsPeekHolder(final Enum<E>[] resultsReported, final Map<String, Statistics<E>> statisticsMap, // final Set<StatisticsCollector> statisticsCollectors, // final ConcurrentHashMap<String, LongAdder> assertionsErrors, RainfallHistogramSink<E> histograms, // long startTime) { // this.resultsReported = resultsReported; // this.assertionsErrors = assertionsErrors; // this.histograms = histograms; // this.startTime = startTime; // this.timestamp = System.currentTimeMillis(); // for (String name : statisticsMap.keySet()) { // statisticsPeeks.put(name, statisticsMap.get(name).peek(timestamp)); // } // this.totalStatisticsPeeks = new StatisticsPeek<E>(ALL, this.resultsReported, this.timestamp); // totalStatisticsPeeks.addAll(statisticsPeeks); // // for (StatisticsCollector statisticsCollector : statisticsCollectors) { // extraCollectedStatistics.put(statisticsCollector.getName(), statisticsCollector.peek()); // } // } // // public StatisticsPeek<E> getStatisticsPeeks(String name) { // return statisticsPeeks.get(name); // } // // public Long getAssertionsErrorsCount(String name) {return assertionsErrors.get(name).longValue();} // // public Set<String> getStatisticsPeeksNames() { // return statisticsPeeks.keySet(); // } // // public StatisticsPeek<E> getTotalStatisticsPeeks() { // return totalStatisticsPeeks; // } // // public long getTimestamp() { // return timestamp; // } // // public long getStartTime() { // return startTime; // } // // public Enum<E>[] getResultsReported() { // return resultsReported; // } // // public Map<String, Exporter> getExtraCollectedStatistics() { // return extraCollectedStatistics; // } // // public Long getTotalAssertionsErrorsCount() { // Long totalAssertionsErrorsCount = 0L; // for (LongAdder count : assertionsErrors.values()) { // totalAssertionsErrorsCount += count.longValue(); // } // return totalAssertionsErrorsCount; // } // // public Histogram fetchHistogram(final Enum<E> result) { // return histograms.fetchHistogram(result); // } // // } // // Path: src/main/java/io/rainfall/utils/CompressionUtils.java // public static String cleanFilename(String filename) { // Arrays.sort(illegalChars); // StringBuilder cleanName = new StringBuilder(); // for (int i = 0; i < filename.length(); i++) { // int c = (int)filename.charAt(i); // if (Arrays.binarySearch(illegalChars, c) < 0) { // cleanName.append((char)c); // } // } // return cleanName.toString(); // } // Path: src/main/java/io/rainfall/reporting/HlogReporter.java import io.rainfall.statistics.StatisticsHolder; import io.rainfall.statistics.StatisticsPeekHolder; import org.HdrHistogram.Histogram; import org.HdrHistogram.HistogramLogWriter; import java.io.File; import java.io.PrintStream; import java.util.List; import static io.rainfall.utils.CompressionUtils.cleanFilename; /* * Copyright (c) 2014-2022 Aurélien Broszniowski * * 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.rainfall.reporting; /** * @author Ludovic Orban */ public class HlogReporter<E extends Enum<E>> extends FileReporter<E> { private final String basedir; public HlogReporter() { this("target/rainfall-histograms"); } public HlogReporter(String outputPath) { this.basedir = new File(outputPath).getAbsoluteFile().getAbsolutePath(); this.reportPath = new File(this.basedir); } @Override public void header(final List<String> description) { } @Override
public void report(final StatisticsPeekHolder<E> statisticsHolder) {
aurbroszniowski/Rainfall-core
src/main/java/io/rainfall/reporting/HlogReporter.java
// Path: src/main/java/io/rainfall/statistics/StatisticsHolder.java // public abstract class StatisticsHolder<E extends Enum<E>> { // // public abstract Enum<E>[] getResultsReported(); // // public abstract Set<String> getStatisticsKeys(); // // public abstract Statistics<E> getStatistics(String name); // // public abstract Set<StatisticsCollector> getStatisticsCollectors(); // // public abstract Histogram fetchHistogram(final Enum<E> result); // // public abstract void reset(); // // public abstract long getCurrentTps(Enum result); // // public abstract void record(String name, long responseTimeInNs, Enum result); // // public abstract void increaseAssertionsErrorsCount(String name); // // public abstract void pause(); // // public abstract void resume(); // // public long getTimeInNs() { // return System.nanoTime(); // } // // public abstract long getStartTime(); // } // // Path: src/main/java/io/rainfall/statistics/StatisticsPeekHolder.java // public class StatisticsPeekHolder<E extends Enum<E>> { // public final static String ALL = "ALL"; // private final Enum<E>[] resultsReported; // private final ConcurrentHashMap<String, LongAdder> assertionsErrors; // private final RainfallHistogramSink<E> histograms; // private final long startTime; // // private Map<String, StatisticsPeek<E>> statisticsPeeks = new ConcurrentHashMap<String, StatisticsPeek<E>>(); // private Map<String, Exporter> extraCollectedStatistics = new ConcurrentHashMap<String, Exporter>(); // private StatisticsPeek<E> totalStatisticsPeeks = null; // private long timestamp; // // public StatisticsPeekHolder(final Enum<E>[] resultsReported, final Map<String, Statistics<E>> statisticsMap, // final Set<StatisticsCollector> statisticsCollectors, // final ConcurrentHashMap<String, LongAdder> assertionsErrors, RainfallHistogramSink<E> histograms, // long startTime) { // this.resultsReported = resultsReported; // this.assertionsErrors = assertionsErrors; // this.histograms = histograms; // this.startTime = startTime; // this.timestamp = System.currentTimeMillis(); // for (String name : statisticsMap.keySet()) { // statisticsPeeks.put(name, statisticsMap.get(name).peek(timestamp)); // } // this.totalStatisticsPeeks = new StatisticsPeek<E>(ALL, this.resultsReported, this.timestamp); // totalStatisticsPeeks.addAll(statisticsPeeks); // // for (StatisticsCollector statisticsCollector : statisticsCollectors) { // extraCollectedStatistics.put(statisticsCollector.getName(), statisticsCollector.peek()); // } // } // // public StatisticsPeek<E> getStatisticsPeeks(String name) { // return statisticsPeeks.get(name); // } // // public Long getAssertionsErrorsCount(String name) {return assertionsErrors.get(name).longValue();} // // public Set<String> getStatisticsPeeksNames() { // return statisticsPeeks.keySet(); // } // // public StatisticsPeek<E> getTotalStatisticsPeeks() { // return totalStatisticsPeeks; // } // // public long getTimestamp() { // return timestamp; // } // // public long getStartTime() { // return startTime; // } // // public Enum<E>[] getResultsReported() { // return resultsReported; // } // // public Map<String, Exporter> getExtraCollectedStatistics() { // return extraCollectedStatistics; // } // // public Long getTotalAssertionsErrorsCount() { // Long totalAssertionsErrorsCount = 0L; // for (LongAdder count : assertionsErrors.values()) { // totalAssertionsErrorsCount += count.longValue(); // } // return totalAssertionsErrorsCount; // } // // public Histogram fetchHistogram(final Enum<E> result) { // return histograms.fetchHistogram(result); // } // // } // // Path: src/main/java/io/rainfall/utils/CompressionUtils.java // public static String cleanFilename(String filename) { // Arrays.sort(illegalChars); // StringBuilder cleanName = new StringBuilder(); // for (int i = 0; i < filename.length(); i++) { // int c = (int)filename.charAt(i); // if (Arrays.binarySearch(illegalChars, c) < 0) { // cleanName.append((char)c); // } // } // return cleanName.toString(); // }
import io.rainfall.statistics.StatisticsHolder; import io.rainfall.statistics.StatisticsPeekHolder; import org.HdrHistogram.Histogram; import org.HdrHistogram.HistogramLogWriter; import java.io.File; import java.io.PrintStream; import java.util.List; import static io.rainfall.utils.CompressionUtils.cleanFilename;
/* * Copyright (c) 2014-2022 Aurélien Broszniowski * * 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.rainfall.reporting; /** * @author Ludovic Orban */ public class HlogReporter<E extends Enum<E>> extends FileReporter<E> { private final String basedir; public HlogReporter() { this("target/rainfall-histograms"); } public HlogReporter(String outputPath) { this.basedir = new File(outputPath).getAbsoluteFile().getAbsolutePath(); this.reportPath = new File(this.basedir); } @Override public void header(final List<String> description) { } @Override public void report(final StatisticsPeekHolder<E> statisticsHolder) { } @Override
// Path: src/main/java/io/rainfall/statistics/StatisticsHolder.java // public abstract class StatisticsHolder<E extends Enum<E>> { // // public abstract Enum<E>[] getResultsReported(); // // public abstract Set<String> getStatisticsKeys(); // // public abstract Statistics<E> getStatistics(String name); // // public abstract Set<StatisticsCollector> getStatisticsCollectors(); // // public abstract Histogram fetchHistogram(final Enum<E> result); // // public abstract void reset(); // // public abstract long getCurrentTps(Enum result); // // public abstract void record(String name, long responseTimeInNs, Enum result); // // public abstract void increaseAssertionsErrorsCount(String name); // // public abstract void pause(); // // public abstract void resume(); // // public long getTimeInNs() { // return System.nanoTime(); // } // // public abstract long getStartTime(); // } // // Path: src/main/java/io/rainfall/statistics/StatisticsPeekHolder.java // public class StatisticsPeekHolder<E extends Enum<E>> { // public final static String ALL = "ALL"; // private final Enum<E>[] resultsReported; // private final ConcurrentHashMap<String, LongAdder> assertionsErrors; // private final RainfallHistogramSink<E> histograms; // private final long startTime; // // private Map<String, StatisticsPeek<E>> statisticsPeeks = new ConcurrentHashMap<String, StatisticsPeek<E>>(); // private Map<String, Exporter> extraCollectedStatistics = new ConcurrentHashMap<String, Exporter>(); // private StatisticsPeek<E> totalStatisticsPeeks = null; // private long timestamp; // // public StatisticsPeekHolder(final Enum<E>[] resultsReported, final Map<String, Statistics<E>> statisticsMap, // final Set<StatisticsCollector> statisticsCollectors, // final ConcurrentHashMap<String, LongAdder> assertionsErrors, RainfallHistogramSink<E> histograms, // long startTime) { // this.resultsReported = resultsReported; // this.assertionsErrors = assertionsErrors; // this.histograms = histograms; // this.startTime = startTime; // this.timestamp = System.currentTimeMillis(); // for (String name : statisticsMap.keySet()) { // statisticsPeeks.put(name, statisticsMap.get(name).peek(timestamp)); // } // this.totalStatisticsPeeks = new StatisticsPeek<E>(ALL, this.resultsReported, this.timestamp); // totalStatisticsPeeks.addAll(statisticsPeeks); // // for (StatisticsCollector statisticsCollector : statisticsCollectors) { // extraCollectedStatistics.put(statisticsCollector.getName(), statisticsCollector.peek()); // } // } // // public StatisticsPeek<E> getStatisticsPeeks(String name) { // return statisticsPeeks.get(name); // } // // public Long getAssertionsErrorsCount(String name) {return assertionsErrors.get(name).longValue();} // // public Set<String> getStatisticsPeeksNames() { // return statisticsPeeks.keySet(); // } // // public StatisticsPeek<E> getTotalStatisticsPeeks() { // return totalStatisticsPeeks; // } // // public long getTimestamp() { // return timestamp; // } // // public long getStartTime() { // return startTime; // } // // public Enum<E>[] getResultsReported() { // return resultsReported; // } // // public Map<String, Exporter> getExtraCollectedStatistics() { // return extraCollectedStatistics; // } // // public Long getTotalAssertionsErrorsCount() { // Long totalAssertionsErrorsCount = 0L; // for (LongAdder count : assertionsErrors.values()) { // totalAssertionsErrorsCount += count.longValue(); // } // return totalAssertionsErrorsCount; // } // // public Histogram fetchHistogram(final Enum<E> result) { // return histograms.fetchHistogram(result); // } // // } // // Path: src/main/java/io/rainfall/utils/CompressionUtils.java // public static String cleanFilename(String filename) { // Arrays.sort(illegalChars); // StringBuilder cleanName = new StringBuilder(); // for (int i = 0; i < filename.length(); i++) { // int c = (int)filename.charAt(i); // if (Arrays.binarySearch(illegalChars, c) < 0) { // cleanName.append((char)c); // } // } // return cleanName.toString(); // } // Path: src/main/java/io/rainfall/reporting/HlogReporter.java import io.rainfall.statistics.StatisticsHolder; import io.rainfall.statistics.StatisticsPeekHolder; import org.HdrHistogram.Histogram; import org.HdrHistogram.HistogramLogWriter; import java.io.File; import java.io.PrintStream; import java.util.List; import static io.rainfall.utils.CompressionUtils.cleanFilename; /* * Copyright (c) 2014-2022 Aurélien Broszniowski * * 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.rainfall.reporting; /** * @author Ludovic Orban */ public class HlogReporter<E extends Enum<E>> extends FileReporter<E> { private final String basedir; public HlogReporter() { this("target/rainfall-histograms"); } public HlogReporter(String outputPath) { this.basedir = new File(outputPath).getAbsoluteFile().getAbsolutePath(); this.reportPath = new File(this.basedir); } @Override public void header(final List<String> description) { } @Override public void report(final StatisticsPeekHolder<E> statisticsHolder) { } @Override
public void summarize(final StatisticsHolder<E> statisticsHolder) {
aurbroszniowski/Rainfall-core
src/main/java/io/rainfall/reporting/HlogReporter.java
// Path: src/main/java/io/rainfall/statistics/StatisticsHolder.java // public abstract class StatisticsHolder<E extends Enum<E>> { // // public abstract Enum<E>[] getResultsReported(); // // public abstract Set<String> getStatisticsKeys(); // // public abstract Statistics<E> getStatistics(String name); // // public abstract Set<StatisticsCollector> getStatisticsCollectors(); // // public abstract Histogram fetchHistogram(final Enum<E> result); // // public abstract void reset(); // // public abstract long getCurrentTps(Enum result); // // public abstract void record(String name, long responseTimeInNs, Enum result); // // public abstract void increaseAssertionsErrorsCount(String name); // // public abstract void pause(); // // public abstract void resume(); // // public long getTimeInNs() { // return System.nanoTime(); // } // // public abstract long getStartTime(); // } // // Path: src/main/java/io/rainfall/statistics/StatisticsPeekHolder.java // public class StatisticsPeekHolder<E extends Enum<E>> { // public final static String ALL = "ALL"; // private final Enum<E>[] resultsReported; // private final ConcurrentHashMap<String, LongAdder> assertionsErrors; // private final RainfallHistogramSink<E> histograms; // private final long startTime; // // private Map<String, StatisticsPeek<E>> statisticsPeeks = new ConcurrentHashMap<String, StatisticsPeek<E>>(); // private Map<String, Exporter> extraCollectedStatistics = new ConcurrentHashMap<String, Exporter>(); // private StatisticsPeek<E> totalStatisticsPeeks = null; // private long timestamp; // // public StatisticsPeekHolder(final Enum<E>[] resultsReported, final Map<String, Statistics<E>> statisticsMap, // final Set<StatisticsCollector> statisticsCollectors, // final ConcurrentHashMap<String, LongAdder> assertionsErrors, RainfallHistogramSink<E> histograms, // long startTime) { // this.resultsReported = resultsReported; // this.assertionsErrors = assertionsErrors; // this.histograms = histograms; // this.startTime = startTime; // this.timestamp = System.currentTimeMillis(); // for (String name : statisticsMap.keySet()) { // statisticsPeeks.put(name, statisticsMap.get(name).peek(timestamp)); // } // this.totalStatisticsPeeks = new StatisticsPeek<E>(ALL, this.resultsReported, this.timestamp); // totalStatisticsPeeks.addAll(statisticsPeeks); // // for (StatisticsCollector statisticsCollector : statisticsCollectors) { // extraCollectedStatistics.put(statisticsCollector.getName(), statisticsCollector.peek()); // } // } // // public StatisticsPeek<E> getStatisticsPeeks(String name) { // return statisticsPeeks.get(name); // } // // public Long getAssertionsErrorsCount(String name) {return assertionsErrors.get(name).longValue();} // // public Set<String> getStatisticsPeeksNames() { // return statisticsPeeks.keySet(); // } // // public StatisticsPeek<E> getTotalStatisticsPeeks() { // return totalStatisticsPeeks; // } // // public long getTimestamp() { // return timestamp; // } // // public long getStartTime() { // return startTime; // } // // public Enum<E>[] getResultsReported() { // return resultsReported; // } // // public Map<String, Exporter> getExtraCollectedStatistics() { // return extraCollectedStatistics; // } // // public Long getTotalAssertionsErrorsCount() { // Long totalAssertionsErrorsCount = 0L; // for (LongAdder count : assertionsErrors.values()) { // totalAssertionsErrorsCount += count.longValue(); // } // return totalAssertionsErrorsCount; // } // // public Histogram fetchHistogram(final Enum<E> result) { // return histograms.fetchHistogram(result); // } // // } // // Path: src/main/java/io/rainfall/utils/CompressionUtils.java // public static String cleanFilename(String filename) { // Arrays.sort(illegalChars); // StringBuilder cleanName = new StringBuilder(); // for (int i = 0; i < filename.length(); i++) { // int c = (int)filename.charAt(i); // if (Arrays.binarySearch(illegalChars, c) < 0) { // cleanName.append((char)c); // } // } // return cleanName.toString(); // }
import io.rainfall.statistics.StatisticsHolder; import io.rainfall.statistics.StatisticsPeekHolder; import org.HdrHistogram.Histogram; import org.HdrHistogram.HistogramLogWriter; import java.io.File; import java.io.PrintStream; import java.util.List; import static io.rainfall.utils.CompressionUtils.cleanFilename;
public void summarize(final StatisticsHolder<E> statisticsHolder) { // dump raw histograms as hlog files long startTime = statisticsHolder.getStartTime(); // ManagementFactory.getRuntimeMXBean().getStartTime(); long endTime = System.currentTimeMillis(); try { Enum<E>[] results = statisticsHolder.getResultsReported(); for (Enum<E> result : results) { Histogram rawHistogram = statisticsHolder.fetchHistogram(result); rawHistogram.setStartTimeStamp(startTime); rawHistogram.setEndTimeStamp(endTime); File hlogFile = new File(this.basedir + File.separatorChar + buildHlogFilename(result.name())); hlogFile.getParentFile().mkdirs(); HistogramLogWriter writer = new HistogramLogWriter(new PrintStream(hlogFile)); writer.setBaseTime(startTime); writer.outputLogFormatVersion(); writer.outputBaseTime(writer.getBaseTime()); writer.outputLegend(); writer.outputIntervalHistogram(rawHistogram); writer.close(); } } catch (Exception e) { throw new RuntimeException("Can not report to hlog", e); } } private String buildHlogFilename(String result) {
// Path: src/main/java/io/rainfall/statistics/StatisticsHolder.java // public abstract class StatisticsHolder<E extends Enum<E>> { // // public abstract Enum<E>[] getResultsReported(); // // public abstract Set<String> getStatisticsKeys(); // // public abstract Statistics<E> getStatistics(String name); // // public abstract Set<StatisticsCollector> getStatisticsCollectors(); // // public abstract Histogram fetchHistogram(final Enum<E> result); // // public abstract void reset(); // // public abstract long getCurrentTps(Enum result); // // public abstract void record(String name, long responseTimeInNs, Enum result); // // public abstract void increaseAssertionsErrorsCount(String name); // // public abstract void pause(); // // public abstract void resume(); // // public long getTimeInNs() { // return System.nanoTime(); // } // // public abstract long getStartTime(); // } // // Path: src/main/java/io/rainfall/statistics/StatisticsPeekHolder.java // public class StatisticsPeekHolder<E extends Enum<E>> { // public final static String ALL = "ALL"; // private final Enum<E>[] resultsReported; // private final ConcurrentHashMap<String, LongAdder> assertionsErrors; // private final RainfallHistogramSink<E> histograms; // private final long startTime; // // private Map<String, StatisticsPeek<E>> statisticsPeeks = new ConcurrentHashMap<String, StatisticsPeek<E>>(); // private Map<String, Exporter> extraCollectedStatistics = new ConcurrentHashMap<String, Exporter>(); // private StatisticsPeek<E> totalStatisticsPeeks = null; // private long timestamp; // // public StatisticsPeekHolder(final Enum<E>[] resultsReported, final Map<String, Statistics<E>> statisticsMap, // final Set<StatisticsCollector> statisticsCollectors, // final ConcurrentHashMap<String, LongAdder> assertionsErrors, RainfallHistogramSink<E> histograms, // long startTime) { // this.resultsReported = resultsReported; // this.assertionsErrors = assertionsErrors; // this.histograms = histograms; // this.startTime = startTime; // this.timestamp = System.currentTimeMillis(); // for (String name : statisticsMap.keySet()) { // statisticsPeeks.put(name, statisticsMap.get(name).peek(timestamp)); // } // this.totalStatisticsPeeks = new StatisticsPeek<E>(ALL, this.resultsReported, this.timestamp); // totalStatisticsPeeks.addAll(statisticsPeeks); // // for (StatisticsCollector statisticsCollector : statisticsCollectors) { // extraCollectedStatistics.put(statisticsCollector.getName(), statisticsCollector.peek()); // } // } // // public StatisticsPeek<E> getStatisticsPeeks(String name) { // return statisticsPeeks.get(name); // } // // public Long getAssertionsErrorsCount(String name) {return assertionsErrors.get(name).longValue();} // // public Set<String> getStatisticsPeeksNames() { // return statisticsPeeks.keySet(); // } // // public StatisticsPeek<E> getTotalStatisticsPeeks() { // return totalStatisticsPeeks; // } // // public long getTimestamp() { // return timestamp; // } // // public long getStartTime() { // return startTime; // } // // public Enum<E>[] getResultsReported() { // return resultsReported; // } // // public Map<String, Exporter> getExtraCollectedStatistics() { // return extraCollectedStatistics; // } // // public Long getTotalAssertionsErrorsCount() { // Long totalAssertionsErrorsCount = 0L; // for (LongAdder count : assertionsErrors.values()) { // totalAssertionsErrorsCount += count.longValue(); // } // return totalAssertionsErrorsCount; // } // // public Histogram fetchHistogram(final Enum<E> result) { // return histograms.fetchHistogram(result); // } // // } // // Path: src/main/java/io/rainfall/utils/CompressionUtils.java // public static String cleanFilename(String filename) { // Arrays.sort(illegalChars); // StringBuilder cleanName = new StringBuilder(); // for (int i = 0; i < filename.length(); i++) { // int c = (int)filename.charAt(i); // if (Arrays.binarySearch(illegalChars, c) < 0) { // cleanName.append((char)c); // } // } // return cleanName.toString(); // } // Path: src/main/java/io/rainfall/reporting/HlogReporter.java import io.rainfall.statistics.StatisticsHolder; import io.rainfall.statistics.StatisticsPeekHolder; import org.HdrHistogram.Histogram; import org.HdrHistogram.HistogramLogWriter; import java.io.File; import java.io.PrintStream; import java.util.List; import static io.rainfall.utils.CompressionUtils.cleanFilename; public void summarize(final StatisticsHolder<E> statisticsHolder) { // dump raw histograms as hlog files long startTime = statisticsHolder.getStartTime(); // ManagementFactory.getRuntimeMXBean().getStartTime(); long endTime = System.currentTimeMillis(); try { Enum<E>[] results = statisticsHolder.getResultsReported(); for (Enum<E> result : results) { Histogram rawHistogram = statisticsHolder.fetchHistogram(result); rawHistogram.setStartTimeStamp(startTime); rawHistogram.setEndTimeStamp(endTime); File hlogFile = new File(this.basedir + File.separatorChar + buildHlogFilename(result.name())); hlogFile.getParentFile().mkdirs(); HistogramLogWriter writer = new HistogramLogWriter(new PrintStream(hlogFile)); writer.setBaseTime(startTime); writer.outputLogFormatVersion(); writer.outputBaseTime(writer.getBaseTime()); writer.outputLegend(); writer.outputIntervalHistogram(rawHistogram); writer.close(); } } catch (Exception e) { throw new RuntimeException("Can not report to hlog", e); } } private String buildHlogFilename(String result) {
return cleanFilename(result) + ".hlog";
aurbroszniowski/Rainfall-core
src/main/java/io/rainfall/Execution.java
// Path: src/main/java/io/rainfall/statistics/StatisticsHolder.java // public abstract class StatisticsHolder<E extends Enum<E>> { // // public abstract Enum<E>[] getResultsReported(); // // public abstract Set<String> getStatisticsKeys(); // // public abstract Statistics<E> getStatistics(String name); // // public abstract Set<StatisticsCollector> getStatisticsCollectors(); // // public abstract Histogram fetchHistogram(final Enum<E> result); // // public abstract void reset(); // // public abstract long getCurrentTps(Enum result); // // public abstract void record(String name, long responseTimeInNs, Enum result); // // public abstract void increaseAssertionsErrorsCount(String name); // // public abstract void pause(); // // public abstract void resume(); // // public long getTimeInNs() { // return System.nanoTime(); // } // // public abstract long getStartTime(); // } // // Path: src/main/java/io/rainfall/utils/ConcurrentPseudoRandom.java // public class ConcurrentPseudoRandom { // // private final ThreadLocal<RandomFunction> randomFunction = new ThreadLocal<RandomFunction>() { // protected RandomFunction initialValue() { // return new RandomFunction(); // } // }; // // private RandomFunction getRandomFunction() { // return randomFunction.get(); // } // // public long nextLong() { // return getRandomFunction().nextLong(); // } // // public long nextLong(final long seed) { // return getRandomFunction().nextLong(seed); // } // // public float nextFloat() { // return getRandomFunction().nextFloat(); // } // // public float nextFloat(final long seed) { // return getRandomFunction().nextFloat(seed); // } // // public float nextFloat(float max) { // return max * getRandomFunction().nextFloat(); // } // // private class RandomFunction { // // long seed = 8682522807148012L ^ System.nanoTime(); // // public long nextLong() { // long nb = nextLong(this.seed); // this.seed = this.seed * 181783497276652981L; // return nb; // } // // public long nextLong(long seed) { // seed ^= (seed << 21); // seed ^= (seed >>> 35); // seed ^= (seed << 4); // return seed; // } // // public float nextFloat() { // float nb = nextFloat(this.seed); // this.seed = this.seed * 181783497276652981L; // return nb; // } // // // Float.intBitsToFloat(nextInt()) ??? // public float nextFloat(final long next) { // return Math.abs(((nextLong(next)) % 100000) / 100000f); // } // } // } // // Path: src/main/java/io/rainfall/utils/RangeMap.java // public class RangeMap<E> { // // private final Map<Float, E> values = new HashMap<Float, E>(); // private final List<Range> keys = new LinkedList<Range>(); // private Float higherBound = 0.0f; // private final ConcurrentPseudoRandom rnd = new ConcurrentPseudoRandom(); // // public synchronized void put(final Float weight, final E value) { // if (weight > 0) { // values.put(higherBound, value); // keys.add(new Range(higherBound, higherBound + weight, higherBound)); // higherBound += weight; // } // } // // public E get(final float key) { // for (Range range : keys) { // the Iterator is way better for the LinkedList that doesn't implement RandomAccess // if (range.contains(key)) // return values.get(range.getKey()); // } // return null; // } // // public Float getHigherBound() { // return higherBound; // } // // public Collection<E> getAll() { // return values.values(); // } // // public E getNextRandom(ConcurrentPseudoRandom concurrentPseudoRandom) { // return get(concurrentPseudoRandom.nextFloat(higherBound)); // } // // public class Range { // private float low; // private float high; // private Float key; // // public Range(final float low, final float high, final Float key) { // this.low = low; // this.high = high; // this.key = key; // } // // public boolean contains(final float key) { // return (this.low <= key && this.high > key); // } // // public Float getKey() { // return key; // } // } // }
import io.rainfall.statistics.StatisticsHolder; import io.rainfall.utils.ConcurrentPseudoRandom; import io.rainfall.utils.RangeMap; import java.util.List; import java.util.Map;
/* * Copyright (c) 2014-2022 Aurélien Broszniowski * * 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.rainfall; /** * This executes a {@link Scenario}, with the specific {@link Configuration}, and {@link Assertion} * * @author Aurelien Broszniowski */ public abstract class Execution { public enum ExecutionState { UNKNOWN, BEGINNING, ENDING } /** * Provide an easy way to mark all operations as underway. * * @param scenario the test scenario * @param state phase of execution of the scenario */ public void markExecutionState(Scenario scenario, ExecutionState state) {
// Path: src/main/java/io/rainfall/statistics/StatisticsHolder.java // public abstract class StatisticsHolder<E extends Enum<E>> { // // public abstract Enum<E>[] getResultsReported(); // // public abstract Set<String> getStatisticsKeys(); // // public abstract Statistics<E> getStatistics(String name); // // public abstract Set<StatisticsCollector> getStatisticsCollectors(); // // public abstract Histogram fetchHistogram(final Enum<E> result); // // public abstract void reset(); // // public abstract long getCurrentTps(Enum result); // // public abstract void record(String name, long responseTimeInNs, Enum result); // // public abstract void increaseAssertionsErrorsCount(String name); // // public abstract void pause(); // // public abstract void resume(); // // public long getTimeInNs() { // return System.nanoTime(); // } // // public abstract long getStartTime(); // } // // Path: src/main/java/io/rainfall/utils/ConcurrentPseudoRandom.java // public class ConcurrentPseudoRandom { // // private final ThreadLocal<RandomFunction> randomFunction = new ThreadLocal<RandomFunction>() { // protected RandomFunction initialValue() { // return new RandomFunction(); // } // }; // // private RandomFunction getRandomFunction() { // return randomFunction.get(); // } // // public long nextLong() { // return getRandomFunction().nextLong(); // } // // public long nextLong(final long seed) { // return getRandomFunction().nextLong(seed); // } // // public float nextFloat() { // return getRandomFunction().nextFloat(); // } // // public float nextFloat(final long seed) { // return getRandomFunction().nextFloat(seed); // } // // public float nextFloat(float max) { // return max * getRandomFunction().nextFloat(); // } // // private class RandomFunction { // // long seed = 8682522807148012L ^ System.nanoTime(); // // public long nextLong() { // long nb = nextLong(this.seed); // this.seed = this.seed * 181783497276652981L; // return nb; // } // // public long nextLong(long seed) { // seed ^= (seed << 21); // seed ^= (seed >>> 35); // seed ^= (seed << 4); // return seed; // } // // public float nextFloat() { // float nb = nextFloat(this.seed); // this.seed = this.seed * 181783497276652981L; // return nb; // } // // // Float.intBitsToFloat(nextInt()) ??? // public float nextFloat(final long next) { // return Math.abs(((nextLong(next)) % 100000) / 100000f); // } // } // } // // Path: src/main/java/io/rainfall/utils/RangeMap.java // public class RangeMap<E> { // // private final Map<Float, E> values = new HashMap<Float, E>(); // private final List<Range> keys = new LinkedList<Range>(); // private Float higherBound = 0.0f; // private final ConcurrentPseudoRandom rnd = new ConcurrentPseudoRandom(); // // public synchronized void put(final Float weight, final E value) { // if (weight > 0) { // values.put(higherBound, value); // keys.add(new Range(higherBound, higherBound + weight, higherBound)); // higherBound += weight; // } // } // // public E get(final float key) { // for (Range range : keys) { // the Iterator is way better for the LinkedList that doesn't implement RandomAccess // if (range.contains(key)) // return values.get(range.getKey()); // } // return null; // } // // public Float getHigherBound() { // return higherBound; // } // // public Collection<E> getAll() { // return values.values(); // } // // public E getNextRandom(ConcurrentPseudoRandom concurrentPseudoRandom) { // return get(concurrentPseudoRandom.nextFloat(higherBound)); // } // // public class Range { // private float low; // private float high; // private Float key; // // public Range(final float low, final float high, final Float key) { // this.low = low; // this.high = high; // this.key = key; // } // // public boolean contains(final float key) { // return (this.low <= key && this.high > key); // } // // public Float getKey() { // return key; // } // } // } // Path: src/main/java/io/rainfall/Execution.java import io.rainfall.statistics.StatisticsHolder; import io.rainfall.utils.ConcurrentPseudoRandom; import io.rainfall.utils.RangeMap; import java.util.List; import java.util.Map; /* * Copyright (c) 2014-2022 Aurélien Broszniowski * * 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.rainfall; /** * This executes a {@link Scenario}, with the specific {@link Configuration}, and {@link Assertion} * * @author Aurelien Broszniowski */ public abstract class Execution { public enum ExecutionState { UNKNOWN, BEGINNING, ENDING } /** * Provide an easy way to mark all operations as underway. * * @param scenario the test scenario * @param state phase of execution of the scenario */ public void markExecutionState(Scenario scenario, ExecutionState state) {
final Map<String, RangeMap<WeightedOperation>> scenarioOperations = scenario.getOperations();
aurbroszniowski/Rainfall-core
src/main/java/io/rainfall/Execution.java
// Path: src/main/java/io/rainfall/statistics/StatisticsHolder.java // public abstract class StatisticsHolder<E extends Enum<E>> { // // public abstract Enum<E>[] getResultsReported(); // // public abstract Set<String> getStatisticsKeys(); // // public abstract Statistics<E> getStatistics(String name); // // public abstract Set<StatisticsCollector> getStatisticsCollectors(); // // public abstract Histogram fetchHistogram(final Enum<E> result); // // public abstract void reset(); // // public abstract long getCurrentTps(Enum result); // // public abstract void record(String name, long responseTimeInNs, Enum result); // // public abstract void increaseAssertionsErrorsCount(String name); // // public abstract void pause(); // // public abstract void resume(); // // public long getTimeInNs() { // return System.nanoTime(); // } // // public abstract long getStartTime(); // } // // Path: src/main/java/io/rainfall/utils/ConcurrentPseudoRandom.java // public class ConcurrentPseudoRandom { // // private final ThreadLocal<RandomFunction> randomFunction = new ThreadLocal<RandomFunction>() { // protected RandomFunction initialValue() { // return new RandomFunction(); // } // }; // // private RandomFunction getRandomFunction() { // return randomFunction.get(); // } // // public long nextLong() { // return getRandomFunction().nextLong(); // } // // public long nextLong(final long seed) { // return getRandomFunction().nextLong(seed); // } // // public float nextFloat() { // return getRandomFunction().nextFloat(); // } // // public float nextFloat(final long seed) { // return getRandomFunction().nextFloat(seed); // } // // public float nextFloat(float max) { // return max * getRandomFunction().nextFloat(); // } // // private class RandomFunction { // // long seed = 8682522807148012L ^ System.nanoTime(); // // public long nextLong() { // long nb = nextLong(this.seed); // this.seed = this.seed * 181783497276652981L; // return nb; // } // // public long nextLong(long seed) { // seed ^= (seed << 21); // seed ^= (seed >>> 35); // seed ^= (seed << 4); // return seed; // } // // public float nextFloat() { // float nb = nextFloat(this.seed); // this.seed = this.seed * 181783497276652981L; // return nb; // } // // // Float.intBitsToFloat(nextInt()) ??? // public float nextFloat(final long next) { // return Math.abs(((nextLong(next)) % 100000) / 100000f); // } // } // } // // Path: src/main/java/io/rainfall/utils/RangeMap.java // public class RangeMap<E> { // // private final Map<Float, E> values = new HashMap<Float, E>(); // private final List<Range> keys = new LinkedList<Range>(); // private Float higherBound = 0.0f; // private final ConcurrentPseudoRandom rnd = new ConcurrentPseudoRandom(); // // public synchronized void put(final Float weight, final E value) { // if (weight > 0) { // values.put(higherBound, value); // keys.add(new Range(higherBound, higherBound + weight, higherBound)); // higherBound += weight; // } // } // // public E get(final float key) { // for (Range range : keys) { // the Iterator is way better for the LinkedList that doesn't implement RandomAccess // if (range.contains(key)) // return values.get(range.getKey()); // } // return null; // } // // public Float getHigherBound() { // return higherBound; // } // // public Collection<E> getAll() { // return values.values(); // } // // public E getNextRandom(ConcurrentPseudoRandom concurrentPseudoRandom) { // return get(concurrentPseudoRandom.nextFloat(higherBound)); // } // // public class Range { // private float low; // private float high; // private Float key; // // public Range(final float low, final float high, final Float key) { // this.low = low; // this.high = high; // this.key = key; // } // // public boolean contains(final float key) { // return (this.low <= key && this.high > key); // } // // public Float getKey() { // return key; // } // } // }
import io.rainfall.statistics.StatisticsHolder; import io.rainfall.utils.ConcurrentPseudoRandom; import io.rainfall.utils.RangeMap; import java.util.List; import java.util.Map;
/* * Copyright (c) 2014-2022 Aurélien Broszniowski * * 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.rainfall; /** * This executes a {@link Scenario}, with the specific {@link Configuration}, and {@link Assertion} * * @author Aurelien Broszniowski */ public abstract class Execution { public enum ExecutionState { UNKNOWN, BEGINNING, ENDING } /** * Provide an easy way to mark all operations as underway. * * @param scenario the test scenario * @param state phase of execution of the scenario */ public void markExecutionState(Scenario scenario, ExecutionState state) { final Map<String, RangeMap<WeightedOperation>> scenarioOperations = scenario.getOperations(); for (RangeMap<WeightedOperation> operationRangeMap : scenarioOperations.values()) { for (WeightedOperation op : operationRangeMap.getAll()) { op.markExecutionState(state); } } }
// Path: src/main/java/io/rainfall/statistics/StatisticsHolder.java // public abstract class StatisticsHolder<E extends Enum<E>> { // // public abstract Enum<E>[] getResultsReported(); // // public abstract Set<String> getStatisticsKeys(); // // public abstract Statistics<E> getStatistics(String name); // // public abstract Set<StatisticsCollector> getStatisticsCollectors(); // // public abstract Histogram fetchHistogram(final Enum<E> result); // // public abstract void reset(); // // public abstract long getCurrentTps(Enum result); // // public abstract void record(String name, long responseTimeInNs, Enum result); // // public abstract void increaseAssertionsErrorsCount(String name); // // public abstract void pause(); // // public abstract void resume(); // // public long getTimeInNs() { // return System.nanoTime(); // } // // public abstract long getStartTime(); // } // // Path: src/main/java/io/rainfall/utils/ConcurrentPseudoRandom.java // public class ConcurrentPseudoRandom { // // private final ThreadLocal<RandomFunction> randomFunction = new ThreadLocal<RandomFunction>() { // protected RandomFunction initialValue() { // return new RandomFunction(); // } // }; // // private RandomFunction getRandomFunction() { // return randomFunction.get(); // } // // public long nextLong() { // return getRandomFunction().nextLong(); // } // // public long nextLong(final long seed) { // return getRandomFunction().nextLong(seed); // } // // public float nextFloat() { // return getRandomFunction().nextFloat(); // } // // public float nextFloat(final long seed) { // return getRandomFunction().nextFloat(seed); // } // // public float nextFloat(float max) { // return max * getRandomFunction().nextFloat(); // } // // private class RandomFunction { // // long seed = 8682522807148012L ^ System.nanoTime(); // // public long nextLong() { // long nb = nextLong(this.seed); // this.seed = this.seed * 181783497276652981L; // return nb; // } // // public long nextLong(long seed) { // seed ^= (seed << 21); // seed ^= (seed >>> 35); // seed ^= (seed << 4); // return seed; // } // // public float nextFloat() { // float nb = nextFloat(this.seed); // this.seed = this.seed * 181783497276652981L; // return nb; // } // // // Float.intBitsToFloat(nextInt()) ??? // public float nextFloat(final long next) { // return Math.abs(((nextLong(next)) % 100000) / 100000f); // } // } // } // // Path: src/main/java/io/rainfall/utils/RangeMap.java // public class RangeMap<E> { // // private final Map<Float, E> values = new HashMap<Float, E>(); // private final List<Range> keys = new LinkedList<Range>(); // private Float higherBound = 0.0f; // private final ConcurrentPseudoRandom rnd = new ConcurrentPseudoRandom(); // // public synchronized void put(final Float weight, final E value) { // if (weight > 0) { // values.put(higherBound, value); // keys.add(new Range(higherBound, higherBound + weight, higherBound)); // higherBound += weight; // } // } // // public E get(final float key) { // for (Range range : keys) { // the Iterator is way better for the LinkedList that doesn't implement RandomAccess // if (range.contains(key)) // return values.get(range.getKey()); // } // return null; // } // // public Float getHigherBound() { // return higherBound; // } // // public Collection<E> getAll() { // return values.values(); // } // // public E getNextRandom(ConcurrentPseudoRandom concurrentPseudoRandom) { // return get(concurrentPseudoRandom.nextFloat(higherBound)); // } // // public class Range { // private float low; // private float high; // private Float key; // // public Range(final float low, final float high, final Float key) { // this.low = low; // this.high = high; // this.key = key; // } // // public boolean contains(final float key) { // return (this.low <= key && this.high > key); // } // // public Float getKey() { // return key; // } // } // } // Path: src/main/java/io/rainfall/Execution.java import io.rainfall.statistics.StatisticsHolder; import io.rainfall.utils.ConcurrentPseudoRandom; import io.rainfall.utils.RangeMap; import java.util.List; import java.util.Map; /* * Copyright (c) 2014-2022 Aurélien Broszniowski * * 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.rainfall; /** * This executes a {@link Scenario}, with the specific {@link Configuration}, and {@link Assertion} * * @author Aurelien Broszniowski */ public abstract class Execution { public enum ExecutionState { UNKNOWN, BEGINNING, ENDING } /** * Provide an easy way to mark all operations as underway. * * @param scenario the test scenario * @param state phase of execution of the scenario */ public void markExecutionState(Scenario scenario, ExecutionState state) { final Map<String, RangeMap<WeightedOperation>> scenarioOperations = scenario.getOperations(); for (RangeMap<WeightedOperation> operationRangeMap : scenarioOperations.values()) { for (WeightedOperation op : operationRangeMap.getAll()) { op.markExecutionState(state); } } }
protected ConcurrentPseudoRandom weightRnd = new ConcurrentPseudoRandom();
aurbroszniowski/Rainfall-core
src/main/java/io/rainfall/Execution.java
// Path: src/main/java/io/rainfall/statistics/StatisticsHolder.java // public abstract class StatisticsHolder<E extends Enum<E>> { // // public abstract Enum<E>[] getResultsReported(); // // public abstract Set<String> getStatisticsKeys(); // // public abstract Statistics<E> getStatistics(String name); // // public abstract Set<StatisticsCollector> getStatisticsCollectors(); // // public abstract Histogram fetchHistogram(final Enum<E> result); // // public abstract void reset(); // // public abstract long getCurrentTps(Enum result); // // public abstract void record(String name, long responseTimeInNs, Enum result); // // public abstract void increaseAssertionsErrorsCount(String name); // // public abstract void pause(); // // public abstract void resume(); // // public long getTimeInNs() { // return System.nanoTime(); // } // // public abstract long getStartTime(); // } // // Path: src/main/java/io/rainfall/utils/ConcurrentPseudoRandom.java // public class ConcurrentPseudoRandom { // // private final ThreadLocal<RandomFunction> randomFunction = new ThreadLocal<RandomFunction>() { // protected RandomFunction initialValue() { // return new RandomFunction(); // } // }; // // private RandomFunction getRandomFunction() { // return randomFunction.get(); // } // // public long nextLong() { // return getRandomFunction().nextLong(); // } // // public long nextLong(final long seed) { // return getRandomFunction().nextLong(seed); // } // // public float nextFloat() { // return getRandomFunction().nextFloat(); // } // // public float nextFloat(final long seed) { // return getRandomFunction().nextFloat(seed); // } // // public float nextFloat(float max) { // return max * getRandomFunction().nextFloat(); // } // // private class RandomFunction { // // long seed = 8682522807148012L ^ System.nanoTime(); // // public long nextLong() { // long nb = nextLong(this.seed); // this.seed = this.seed * 181783497276652981L; // return nb; // } // // public long nextLong(long seed) { // seed ^= (seed << 21); // seed ^= (seed >>> 35); // seed ^= (seed << 4); // return seed; // } // // public float nextFloat() { // float nb = nextFloat(this.seed); // this.seed = this.seed * 181783497276652981L; // return nb; // } // // // Float.intBitsToFloat(nextInt()) ??? // public float nextFloat(final long next) { // return Math.abs(((nextLong(next)) % 100000) / 100000f); // } // } // } // // Path: src/main/java/io/rainfall/utils/RangeMap.java // public class RangeMap<E> { // // private final Map<Float, E> values = new HashMap<Float, E>(); // private final List<Range> keys = new LinkedList<Range>(); // private Float higherBound = 0.0f; // private final ConcurrentPseudoRandom rnd = new ConcurrentPseudoRandom(); // // public synchronized void put(final Float weight, final E value) { // if (weight > 0) { // values.put(higherBound, value); // keys.add(new Range(higherBound, higherBound + weight, higherBound)); // higherBound += weight; // } // } // // public E get(final float key) { // for (Range range : keys) { // the Iterator is way better for the LinkedList that doesn't implement RandomAccess // if (range.contains(key)) // return values.get(range.getKey()); // } // return null; // } // // public Float getHigherBound() { // return higherBound; // } // // public Collection<E> getAll() { // return values.values(); // } // // public E getNextRandom(ConcurrentPseudoRandom concurrentPseudoRandom) { // return get(concurrentPseudoRandom.nextFloat(higherBound)); // } // // public class Range { // private float low; // private float high; // private Float key; // // public Range(final float low, final float high, final Float key) { // this.low = low; // this.high = high; // this.key = key; // } // // public boolean contains(final float key) { // return (this.low <= key && this.high > key); // } // // public Float getKey() { // return key; // } // } // }
import io.rainfall.statistics.StatisticsHolder; import io.rainfall.utils.ConcurrentPseudoRandom; import io.rainfall.utils.RangeMap; import java.util.List; import java.util.Map;
/* * Copyright (c) 2014-2022 Aurélien Broszniowski * * 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.rainfall; /** * This executes a {@link Scenario}, with the specific {@link Configuration}, and {@link Assertion} * * @author Aurelien Broszniowski */ public abstract class Execution { public enum ExecutionState { UNKNOWN, BEGINNING, ENDING } /** * Provide an easy way to mark all operations as underway. * * @param scenario the test scenario * @param state phase of execution of the scenario */ public void markExecutionState(Scenario scenario, ExecutionState state) { final Map<String, RangeMap<WeightedOperation>> scenarioOperations = scenario.getOperations(); for (RangeMap<WeightedOperation> operationRangeMap : scenarioOperations.values()) { for (WeightedOperation op : operationRangeMap.getAll()) { op.markExecutionState(state); } } } protected ConcurrentPseudoRandom weightRnd = new ConcurrentPseudoRandom();
// Path: src/main/java/io/rainfall/statistics/StatisticsHolder.java // public abstract class StatisticsHolder<E extends Enum<E>> { // // public abstract Enum<E>[] getResultsReported(); // // public abstract Set<String> getStatisticsKeys(); // // public abstract Statistics<E> getStatistics(String name); // // public abstract Set<StatisticsCollector> getStatisticsCollectors(); // // public abstract Histogram fetchHistogram(final Enum<E> result); // // public abstract void reset(); // // public abstract long getCurrentTps(Enum result); // // public abstract void record(String name, long responseTimeInNs, Enum result); // // public abstract void increaseAssertionsErrorsCount(String name); // // public abstract void pause(); // // public abstract void resume(); // // public long getTimeInNs() { // return System.nanoTime(); // } // // public abstract long getStartTime(); // } // // Path: src/main/java/io/rainfall/utils/ConcurrentPseudoRandom.java // public class ConcurrentPseudoRandom { // // private final ThreadLocal<RandomFunction> randomFunction = new ThreadLocal<RandomFunction>() { // protected RandomFunction initialValue() { // return new RandomFunction(); // } // }; // // private RandomFunction getRandomFunction() { // return randomFunction.get(); // } // // public long nextLong() { // return getRandomFunction().nextLong(); // } // // public long nextLong(final long seed) { // return getRandomFunction().nextLong(seed); // } // // public float nextFloat() { // return getRandomFunction().nextFloat(); // } // // public float nextFloat(final long seed) { // return getRandomFunction().nextFloat(seed); // } // // public float nextFloat(float max) { // return max * getRandomFunction().nextFloat(); // } // // private class RandomFunction { // // long seed = 8682522807148012L ^ System.nanoTime(); // // public long nextLong() { // long nb = nextLong(this.seed); // this.seed = this.seed * 181783497276652981L; // return nb; // } // // public long nextLong(long seed) { // seed ^= (seed << 21); // seed ^= (seed >>> 35); // seed ^= (seed << 4); // return seed; // } // // public float nextFloat() { // float nb = nextFloat(this.seed); // this.seed = this.seed * 181783497276652981L; // return nb; // } // // // Float.intBitsToFloat(nextInt()) ??? // public float nextFloat(final long next) { // return Math.abs(((nextLong(next)) % 100000) / 100000f); // } // } // } // // Path: src/main/java/io/rainfall/utils/RangeMap.java // public class RangeMap<E> { // // private final Map<Float, E> values = new HashMap<Float, E>(); // private final List<Range> keys = new LinkedList<Range>(); // private Float higherBound = 0.0f; // private final ConcurrentPseudoRandom rnd = new ConcurrentPseudoRandom(); // // public synchronized void put(final Float weight, final E value) { // if (weight > 0) { // values.put(higherBound, value); // keys.add(new Range(higherBound, higherBound + weight, higherBound)); // higherBound += weight; // } // } // // public E get(final float key) { // for (Range range : keys) { // the Iterator is way better for the LinkedList that doesn't implement RandomAccess // if (range.contains(key)) // return values.get(range.getKey()); // } // return null; // } // // public Float getHigherBound() { // return higherBound; // } // // public Collection<E> getAll() { // return values.values(); // } // // public E getNextRandom(ConcurrentPseudoRandom concurrentPseudoRandom) { // return get(concurrentPseudoRandom.nextFloat(higherBound)); // } // // public class Range { // private float low; // private float high; // private Float key; // // public Range(final float low, final float high, final Float key) { // this.low = low; // this.high = high; // this.key = key; // } // // public boolean contains(final float key) { // return (this.low <= key && this.high > key); // } // // public Float getKey() { // return key; // } // } // } // Path: src/main/java/io/rainfall/Execution.java import io.rainfall.statistics.StatisticsHolder; import io.rainfall.utils.ConcurrentPseudoRandom; import io.rainfall.utils.RangeMap; import java.util.List; import java.util.Map; /* * Copyright (c) 2014-2022 Aurélien Broszniowski * * 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.rainfall; /** * This executes a {@link Scenario}, with the specific {@link Configuration}, and {@link Assertion} * * @author Aurelien Broszniowski */ public abstract class Execution { public enum ExecutionState { UNKNOWN, BEGINNING, ENDING } /** * Provide an easy way to mark all operations as underway. * * @param scenario the test scenario * @param state phase of execution of the scenario */ public void markExecutionState(Scenario scenario, ExecutionState state) { final Map<String, RangeMap<WeightedOperation>> scenarioOperations = scenario.getOperations(); for (RangeMap<WeightedOperation> operationRangeMap : scenarioOperations.values()) { for (WeightedOperation op : operationRangeMap.getAll()) { op.markExecutionState(state); } } } protected ConcurrentPseudoRandom weightRnd = new ConcurrentPseudoRandom();
public abstract <E extends Enum<E>> void execute(final StatisticsHolder<E> statisticsHolder, final Scenario scenario,
aurbroszniowski/Rainfall-core
src/main/java/io/rainfall/execution/Executions.java
// Path: src/main/java/io/rainfall/Execution.java // public abstract class Execution { // // public enum ExecutionState { // UNKNOWN, // BEGINNING, // ENDING // } // // /** // * Provide an easy way to mark all operations as underway. // * // * @param scenario the test scenario // * @param state phase of execution of the scenario // */ // public void markExecutionState(Scenario scenario, ExecutionState state) { // final Map<String, RangeMap<WeightedOperation>> scenarioOperations = scenario.getOperations(); // for (RangeMap<WeightedOperation> operationRangeMap : scenarioOperations.values()) { // for (WeightedOperation op : operationRangeMap.getAll()) { // op.markExecutionState(state); // } // } // } // // protected ConcurrentPseudoRandom weightRnd = new ConcurrentPseudoRandom(); // // public abstract <E extends Enum<E>> void execute(final StatisticsHolder<E> statisticsHolder, final Scenario scenario, // final Map<Class<? extends Configuration>, Configuration> configurations, // final List<AssertionEvaluator> assertions) throws TestException; // // public abstract String toString(); // // } // // Path: src/main/java/io/rainfall/Unit.java // public interface Unit { // // } // // Path: src/main/java/io/rainfall/unit/Every.java // public class Every extends TimeMeasurement { // // public static Every every(int nb, TimeDivision timeDivision) { // return new Every(nb, timeDivision); // } // // public Every(int count, TimeDivision timeDivision) { // super(count, timeDivision); // } // // @Override // public String toString() { // return "every " + super.toString(); // } // } // // Path: src/main/java/io/rainfall/unit/From.java // public class From extends UnitMeasurement { // // public static From from(int count, Unit unit) { // return new From(count, unit); // } // // public From(final int count, final Unit unit) { // super(count, unit); // } // // @Override // public String toString() { // return "from " + super.toString(); // } // } // // Path: src/main/java/io/rainfall/unit/Over.java // public class Over extends TimeMeasurement { // // public static Over over(int count, TimeDivision timeDivision) { // return new Over(count, timeDivision); // } // // public Over(int count, TimeDivision timeDivision) { // super(count, timeDivision); // } // // @Override // public String toString() { // return "over " + super.toString(); // } // } // // Path: src/main/java/io/rainfall/unit/TimeDivision.java // public class TimeDivision implements Unit { // // private TimeUnit timeUnit; // // public static final TimeDivision seconds = new TimeDivision(TimeUnit.SECONDS); // // public static final TimeDivision minutes = new TimeDivision(TimeUnit.MINUTES); // // public TimeDivision(TimeUnit timeUnit) { // this.timeUnit = timeUnit; // } // // public TimeUnit getTimeUnit() { // return timeUnit; // } // // @Override // public String toString() { // return timeUnit.name().toLowerCase(); // } // } // // Path: src/main/java/io/rainfall/unit/To.java // public class To extends UnitMeasurement { // // public static To to(int count, Unit unit) { // return new To(count, unit); // } // // public To(int count, Unit unit) { // super(count, unit); // } // // @Override // public String toString() { // return "to " + super.toString(); // } // }
import io.rainfall.Execution; import io.rainfall.Unit; import io.rainfall.unit.Every; import io.rainfall.unit.From; import io.rainfall.unit.Over; import io.rainfall.unit.TimeDivision; import io.rainfall.unit.To; import java.util.function.Function;
/* * Copyright (c) 2014-2022 Aurélien Broszniowski * * 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.rainfall.execution; /** * @author Aurelien Broszniowski */ public class Executions { public static Execution once(int nb, Unit unit) { return new Times(nb); } public static Times times(long occurrences) { return new Times(occurrences); }
// Path: src/main/java/io/rainfall/Execution.java // public abstract class Execution { // // public enum ExecutionState { // UNKNOWN, // BEGINNING, // ENDING // } // // /** // * Provide an easy way to mark all operations as underway. // * // * @param scenario the test scenario // * @param state phase of execution of the scenario // */ // public void markExecutionState(Scenario scenario, ExecutionState state) { // final Map<String, RangeMap<WeightedOperation>> scenarioOperations = scenario.getOperations(); // for (RangeMap<WeightedOperation> operationRangeMap : scenarioOperations.values()) { // for (WeightedOperation op : operationRangeMap.getAll()) { // op.markExecutionState(state); // } // } // } // // protected ConcurrentPseudoRandom weightRnd = new ConcurrentPseudoRandom(); // // public abstract <E extends Enum<E>> void execute(final StatisticsHolder<E> statisticsHolder, final Scenario scenario, // final Map<Class<? extends Configuration>, Configuration> configurations, // final List<AssertionEvaluator> assertions) throws TestException; // // public abstract String toString(); // // } // // Path: src/main/java/io/rainfall/Unit.java // public interface Unit { // // } // // Path: src/main/java/io/rainfall/unit/Every.java // public class Every extends TimeMeasurement { // // public static Every every(int nb, TimeDivision timeDivision) { // return new Every(nb, timeDivision); // } // // public Every(int count, TimeDivision timeDivision) { // super(count, timeDivision); // } // // @Override // public String toString() { // return "every " + super.toString(); // } // } // // Path: src/main/java/io/rainfall/unit/From.java // public class From extends UnitMeasurement { // // public static From from(int count, Unit unit) { // return new From(count, unit); // } // // public From(final int count, final Unit unit) { // super(count, unit); // } // // @Override // public String toString() { // return "from " + super.toString(); // } // } // // Path: src/main/java/io/rainfall/unit/Over.java // public class Over extends TimeMeasurement { // // public static Over over(int count, TimeDivision timeDivision) { // return new Over(count, timeDivision); // } // // public Over(int count, TimeDivision timeDivision) { // super(count, timeDivision); // } // // @Override // public String toString() { // return "over " + super.toString(); // } // } // // Path: src/main/java/io/rainfall/unit/TimeDivision.java // public class TimeDivision implements Unit { // // private TimeUnit timeUnit; // // public static final TimeDivision seconds = new TimeDivision(TimeUnit.SECONDS); // // public static final TimeDivision minutes = new TimeDivision(TimeUnit.MINUTES); // // public TimeDivision(TimeUnit timeUnit) { // this.timeUnit = timeUnit; // } // // public TimeUnit getTimeUnit() { // return timeUnit; // } // // @Override // public String toString() { // return timeUnit.name().toLowerCase(); // } // } // // Path: src/main/java/io/rainfall/unit/To.java // public class To extends UnitMeasurement { // // public static To to(int count, Unit unit) { // return new To(count, unit); // } // // public To(int count, Unit unit) { // super(count, unit); // } // // @Override // public String toString() { // return "to " + super.toString(); // } // } // Path: src/main/java/io/rainfall/execution/Executions.java import io.rainfall.Execution; import io.rainfall.Unit; import io.rainfall.unit.Every; import io.rainfall.unit.From; import io.rainfall.unit.Over; import io.rainfall.unit.TimeDivision; import io.rainfall.unit.To; import java.util.function.Function; /* * Copyright (c) 2014-2022 Aurélien Broszniowski * * 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.rainfall.execution; /** * @author Aurelien Broszniowski */ public class Executions { public static Execution once(int nb, Unit unit) { return new Times(nb); } public static Times times(long occurrences) { return new Times(occurrences); }
public static InParallel inParallel(int count, Unit unit, Every every, Over over) {
aurbroszniowski/Rainfall-core
src/main/java/io/rainfall/execution/Executions.java
// Path: src/main/java/io/rainfall/Execution.java // public abstract class Execution { // // public enum ExecutionState { // UNKNOWN, // BEGINNING, // ENDING // } // // /** // * Provide an easy way to mark all operations as underway. // * // * @param scenario the test scenario // * @param state phase of execution of the scenario // */ // public void markExecutionState(Scenario scenario, ExecutionState state) { // final Map<String, RangeMap<WeightedOperation>> scenarioOperations = scenario.getOperations(); // for (RangeMap<WeightedOperation> operationRangeMap : scenarioOperations.values()) { // for (WeightedOperation op : operationRangeMap.getAll()) { // op.markExecutionState(state); // } // } // } // // protected ConcurrentPseudoRandom weightRnd = new ConcurrentPseudoRandom(); // // public abstract <E extends Enum<E>> void execute(final StatisticsHolder<E> statisticsHolder, final Scenario scenario, // final Map<Class<? extends Configuration>, Configuration> configurations, // final List<AssertionEvaluator> assertions) throws TestException; // // public abstract String toString(); // // } // // Path: src/main/java/io/rainfall/Unit.java // public interface Unit { // // } // // Path: src/main/java/io/rainfall/unit/Every.java // public class Every extends TimeMeasurement { // // public static Every every(int nb, TimeDivision timeDivision) { // return new Every(nb, timeDivision); // } // // public Every(int count, TimeDivision timeDivision) { // super(count, timeDivision); // } // // @Override // public String toString() { // return "every " + super.toString(); // } // } // // Path: src/main/java/io/rainfall/unit/From.java // public class From extends UnitMeasurement { // // public static From from(int count, Unit unit) { // return new From(count, unit); // } // // public From(final int count, final Unit unit) { // super(count, unit); // } // // @Override // public String toString() { // return "from " + super.toString(); // } // } // // Path: src/main/java/io/rainfall/unit/Over.java // public class Over extends TimeMeasurement { // // public static Over over(int count, TimeDivision timeDivision) { // return new Over(count, timeDivision); // } // // public Over(int count, TimeDivision timeDivision) { // super(count, timeDivision); // } // // @Override // public String toString() { // return "over " + super.toString(); // } // } // // Path: src/main/java/io/rainfall/unit/TimeDivision.java // public class TimeDivision implements Unit { // // private TimeUnit timeUnit; // // public static final TimeDivision seconds = new TimeDivision(TimeUnit.SECONDS); // // public static final TimeDivision minutes = new TimeDivision(TimeUnit.MINUTES); // // public TimeDivision(TimeUnit timeUnit) { // this.timeUnit = timeUnit; // } // // public TimeUnit getTimeUnit() { // return timeUnit; // } // // @Override // public String toString() { // return timeUnit.name().toLowerCase(); // } // } // // Path: src/main/java/io/rainfall/unit/To.java // public class To extends UnitMeasurement { // // public static To to(int count, Unit unit) { // return new To(count, unit); // } // // public To(int count, Unit unit) { // super(count, unit); // } // // @Override // public String toString() { // return "to " + super.toString(); // } // }
import io.rainfall.Execution; import io.rainfall.Unit; import io.rainfall.unit.Every; import io.rainfall.unit.From; import io.rainfall.unit.Over; import io.rainfall.unit.TimeDivision; import io.rainfall.unit.To; import java.util.function.Function;
/* * Copyright (c) 2014-2022 Aurélien Broszniowski * * 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.rainfall.execution; /** * @author Aurelien Broszniowski */ public class Executions { public static Execution once(int nb, Unit unit) { return new Times(nb); } public static Times times(long occurrences) { return new Times(occurrences); }
// Path: src/main/java/io/rainfall/Execution.java // public abstract class Execution { // // public enum ExecutionState { // UNKNOWN, // BEGINNING, // ENDING // } // // /** // * Provide an easy way to mark all operations as underway. // * // * @param scenario the test scenario // * @param state phase of execution of the scenario // */ // public void markExecutionState(Scenario scenario, ExecutionState state) { // final Map<String, RangeMap<WeightedOperation>> scenarioOperations = scenario.getOperations(); // for (RangeMap<WeightedOperation> operationRangeMap : scenarioOperations.values()) { // for (WeightedOperation op : operationRangeMap.getAll()) { // op.markExecutionState(state); // } // } // } // // protected ConcurrentPseudoRandom weightRnd = new ConcurrentPseudoRandom(); // // public abstract <E extends Enum<E>> void execute(final StatisticsHolder<E> statisticsHolder, final Scenario scenario, // final Map<Class<? extends Configuration>, Configuration> configurations, // final List<AssertionEvaluator> assertions) throws TestException; // // public abstract String toString(); // // } // // Path: src/main/java/io/rainfall/Unit.java // public interface Unit { // // } // // Path: src/main/java/io/rainfall/unit/Every.java // public class Every extends TimeMeasurement { // // public static Every every(int nb, TimeDivision timeDivision) { // return new Every(nb, timeDivision); // } // // public Every(int count, TimeDivision timeDivision) { // super(count, timeDivision); // } // // @Override // public String toString() { // return "every " + super.toString(); // } // } // // Path: src/main/java/io/rainfall/unit/From.java // public class From extends UnitMeasurement { // // public static From from(int count, Unit unit) { // return new From(count, unit); // } // // public From(final int count, final Unit unit) { // super(count, unit); // } // // @Override // public String toString() { // return "from " + super.toString(); // } // } // // Path: src/main/java/io/rainfall/unit/Over.java // public class Over extends TimeMeasurement { // // public static Over over(int count, TimeDivision timeDivision) { // return new Over(count, timeDivision); // } // // public Over(int count, TimeDivision timeDivision) { // super(count, timeDivision); // } // // @Override // public String toString() { // return "over " + super.toString(); // } // } // // Path: src/main/java/io/rainfall/unit/TimeDivision.java // public class TimeDivision implements Unit { // // private TimeUnit timeUnit; // // public static final TimeDivision seconds = new TimeDivision(TimeUnit.SECONDS); // // public static final TimeDivision minutes = new TimeDivision(TimeUnit.MINUTES); // // public TimeDivision(TimeUnit timeUnit) { // this.timeUnit = timeUnit; // } // // public TimeUnit getTimeUnit() { // return timeUnit; // } // // @Override // public String toString() { // return timeUnit.name().toLowerCase(); // } // } // // Path: src/main/java/io/rainfall/unit/To.java // public class To extends UnitMeasurement { // // public static To to(int count, Unit unit) { // return new To(count, unit); // } // // public To(int count, Unit unit) { // super(count, unit); // } // // @Override // public String toString() { // return "to " + super.toString(); // } // } // Path: src/main/java/io/rainfall/execution/Executions.java import io.rainfall.Execution; import io.rainfall.Unit; import io.rainfall.unit.Every; import io.rainfall.unit.From; import io.rainfall.unit.Over; import io.rainfall.unit.TimeDivision; import io.rainfall.unit.To; import java.util.function.Function; /* * Copyright (c) 2014-2022 Aurélien Broszniowski * * 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.rainfall.execution; /** * @author Aurelien Broszniowski */ public class Executions { public static Execution once(int nb, Unit unit) { return new Times(nb); } public static Times times(long occurrences) { return new Times(occurrences); }
public static InParallel inParallel(int count, Unit unit, Every every, Over over) {
aurbroszniowski/Rainfall-core
src/main/java/io/rainfall/execution/Executions.java
// Path: src/main/java/io/rainfall/Execution.java // public abstract class Execution { // // public enum ExecutionState { // UNKNOWN, // BEGINNING, // ENDING // } // // /** // * Provide an easy way to mark all operations as underway. // * // * @param scenario the test scenario // * @param state phase of execution of the scenario // */ // public void markExecutionState(Scenario scenario, ExecutionState state) { // final Map<String, RangeMap<WeightedOperation>> scenarioOperations = scenario.getOperations(); // for (RangeMap<WeightedOperation> operationRangeMap : scenarioOperations.values()) { // for (WeightedOperation op : operationRangeMap.getAll()) { // op.markExecutionState(state); // } // } // } // // protected ConcurrentPseudoRandom weightRnd = new ConcurrentPseudoRandom(); // // public abstract <E extends Enum<E>> void execute(final StatisticsHolder<E> statisticsHolder, final Scenario scenario, // final Map<Class<? extends Configuration>, Configuration> configurations, // final List<AssertionEvaluator> assertions) throws TestException; // // public abstract String toString(); // // } // // Path: src/main/java/io/rainfall/Unit.java // public interface Unit { // // } // // Path: src/main/java/io/rainfall/unit/Every.java // public class Every extends TimeMeasurement { // // public static Every every(int nb, TimeDivision timeDivision) { // return new Every(nb, timeDivision); // } // // public Every(int count, TimeDivision timeDivision) { // super(count, timeDivision); // } // // @Override // public String toString() { // return "every " + super.toString(); // } // } // // Path: src/main/java/io/rainfall/unit/From.java // public class From extends UnitMeasurement { // // public static From from(int count, Unit unit) { // return new From(count, unit); // } // // public From(final int count, final Unit unit) { // super(count, unit); // } // // @Override // public String toString() { // return "from " + super.toString(); // } // } // // Path: src/main/java/io/rainfall/unit/Over.java // public class Over extends TimeMeasurement { // // public static Over over(int count, TimeDivision timeDivision) { // return new Over(count, timeDivision); // } // // public Over(int count, TimeDivision timeDivision) { // super(count, timeDivision); // } // // @Override // public String toString() { // return "over " + super.toString(); // } // } // // Path: src/main/java/io/rainfall/unit/TimeDivision.java // public class TimeDivision implements Unit { // // private TimeUnit timeUnit; // // public static final TimeDivision seconds = new TimeDivision(TimeUnit.SECONDS); // // public static final TimeDivision minutes = new TimeDivision(TimeUnit.MINUTES); // // public TimeDivision(TimeUnit timeUnit) { // this.timeUnit = timeUnit; // } // // public TimeUnit getTimeUnit() { // return timeUnit; // } // // @Override // public String toString() { // return timeUnit.name().toLowerCase(); // } // } // // Path: src/main/java/io/rainfall/unit/To.java // public class To extends UnitMeasurement { // // public static To to(int count, Unit unit) { // return new To(count, unit); // } // // public To(int count, Unit unit) { // super(count, unit); // } // // @Override // public String toString() { // return "to " + super.toString(); // } // }
import io.rainfall.Execution; import io.rainfall.Unit; import io.rainfall.unit.Every; import io.rainfall.unit.From; import io.rainfall.unit.Over; import io.rainfall.unit.TimeDivision; import io.rainfall.unit.To; import java.util.function.Function;
/* * Copyright (c) 2014-2022 Aurélien Broszniowski * * 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.rainfall.execution; /** * @author Aurelien Broszniowski */ public class Executions { public static Execution once(int nb, Unit unit) { return new Times(nb); } public static Times times(long occurrences) { return new Times(occurrences); } public static InParallel inParallel(int count, Unit unit, Every every, Over over) { return new InParallel(count, unit, every, over); }
// Path: src/main/java/io/rainfall/Execution.java // public abstract class Execution { // // public enum ExecutionState { // UNKNOWN, // BEGINNING, // ENDING // } // // /** // * Provide an easy way to mark all operations as underway. // * // * @param scenario the test scenario // * @param state phase of execution of the scenario // */ // public void markExecutionState(Scenario scenario, ExecutionState state) { // final Map<String, RangeMap<WeightedOperation>> scenarioOperations = scenario.getOperations(); // for (RangeMap<WeightedOperation> operationRangeMap : scenarioOperations.values()) { // for (WeightedOperation op : operationRangeMap.getAll()) { // op.markExecutionState(state); // } // } // } // // protected ConcurrentPseudoRandom weightRnd = new ConcurrentPseudoRandom(); // // public abstract <E extends Enum<E>> void execute(final StatisticsHolder<E> statisticsHolder, final Scenario scenario, // final Map<Class<? extends Configuration>, Configuration> configurations, // final List<AssertionEvaluator> assertions) throws TestException; // // public abstract String toString(); // // } // // Path: src/main/java/io/rainfall/Unit.java // public interface Unit { // // } // // Path: src/main/java/io/rainfall/unit/Every.java // public class Every extends TimeMeasurement { // // public static Every every(int nb, TimeDivision timeDivision) { // return new Every(nb, timeDivision); // } // // public Every(int count, TimeDivision timeDivision) { // super(count, timeDivision); // } // // @Override // public String toString() { // return "every " + super.toString(); // } // } // // Path: src/main/java/io/rainfall/unit/From.java // public class From extends UnitMeasurement { // // public static From from(int count, Unit unit) { // return new From(count, unit); // } // // public From(final int count, final Unit unit) { // super(count, unit); // } // // @Override // public String toString() { // return "from " + super.toString(); // } // } // // Path: src/main/java/io/rainfall/unit/Over.java // public class Over extends TimeMeasurement { // // public static Over over(int count, TimeDivision timeDivision) { // return new Over(count, timeDivision); // } // // public Over(int count, TimeDivision timeDivision) { // super(count, timeDivision); // } // // @Override // public String toString() { // return "over " + super.toString(); // } // } // // Path: src/main/java/io/rainfall/unit/TimeDivision.java // public class TimeDivision implements Unit { // // private TimeUnit timeUnit; // // public static final TimeDivision seconds = new TimeDivision(TimeUnit.SECONDS); // // public static final TimeDivision minutes = new TimeDivision(TimeUnit.MINUTES); // // public TimeDivision(TimeUnit timeUnit) { // this.timeUnit = timeUnit; // } // // public TimeUnit getTimeUnit() { // return timeUnit; // } // // @Override // public String toString() { // return timeUnit.name().toLowerCase(); // } // } // // Path: src/main/java/io/rainfall/unit/To.java // public class To extends UnitMeasurement { // // public static To to(int count, Unit unit) { // return new To(count, unit); // } // // public To(int count, Unit unit) { // super(count, unit); // } // // @Override // public String toString() { // return "to " + super.toString(); // } // } // Path: src/main/java/io/rainfall/execution/Executions.java import io.rainfall.Execution; import io.rainfall.Unit; import io.rainfall.unit.Every; import io.rainfall.unit.From; import io.rainfall.unit.Over; import io.rainfall.unit.TimeDivision; import io.rainfall.unit.To; import java.util.function.Function; /* * Copyright (c) 2014-2022 Aurélien Broszniowski * * 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.rainfall.execution; /** * @author Aurelien Broszniowski */ public class Executions { public static Execution once(int nb, Unit unit) { return new Times(nb); } public static Times times(long occurrences) { return new Times(occurrences); } public static InParallel inParallel(int count, Unit unit, Every every, Over over) { return new InParallel(count, unit, every, over); }
public static NothingFor nothingFor(int nb, TimeDivision timeDivision) {
aurbroszniowski/Rainfall-core
src/main/java/io/rainfall/execution/Executions.java
// Path: src/main/java/io/rainfall/Execution.java // public abstract class Execution { // // public enum ExecutionState { // UNKNOWN, // BEGINNING, // ENDING // } // // /** // * Provide an easy way to mark all operations as underway. // * // * @param scenario the test scenario // * @param state phase of execution of the scenario // */ // public void markExecutionState(Scenario scenario, ExecutionState state) { // final Map<String, RangeMap<WeightedOperation>> scenarioOperations = scenario.getOperations(); // for (RangeMap<WeightedOperation> operationRangeMap : scenarioOperations.values()) { // for (WeightedOperation op : operationRangeMap.getAll()) { // op.markExecutionState(state); // } // } // } // // protected ConcurrentPseudoRandom weightRnd = new ConcurrentPseudoRandom(); // // public abstract <E extends Enum<E>> void execute(final StatisticsHolder<E> statisticsHolder, final Scenario scenario, // final Map<Class<? extends Configuration>, Configuration> configurations, // final List<AssertionEvaluator> assertions) throws TestException; // // public abstract String toString(); // // } // // Path: src/main/java/io/rainfall/Unit.java // public interface Unit { // // } // // Path: src/main/java/io/rainfall/unit/Every.java // public class Every extends TimeMeasurement { // // public static Every every(int nb, TimeDivision timeDivision) { // return new Every(nb, timeDivision); // } // // public Every(int count, TimeDivision timeDivision) { // super(count, timeDivision); // } // // @Override // public String toString() { // return "every " + super.toString(); // } // } // // Path: src/main/java/io/rainfall/unit/From.java // public class From extends UnitMeasurement { // // public static From from(int count, Unit unit) { // return new From(count, unit); // } // // public From(final int count, final Unit unit) { // super(count, unit); // } // // @Override // public String toString() { // return "from " + super.toString(); // } // } // // Path: src/main/java/io/rainfall/unit/Over.java // public class Over extends TimeMeasurement { // // public static Over over(int count, TimeDivision timeDivision) { // return new Over(count, timeDivision); // } // // public Over(int count, TimeDivision timeDivision) { // super(count, timeDivision); // } // // @Override // public String toString() { // return "over " + super.toString(); // } // } // // Path: src/main/java/io/rainfall/unit/TimeDivision.java // public class TimeDivision implements Unit { // // private TimeUnit timeUnit; // // public static final TimeDivision seconds = new TimeDivision(TimeUnit.SECONDS); // // public static final TimeDivision minutes = new TimeDivision(TimeUnit.MINUTES); // // public TimeDivision(TimeUnit timeUnit) { // this.timeUnit = timeUnit; // } // // public TimeUnit getTimeUnit() { // return timeUnit; // } // // @Override // public String toString() { // return timeUnit.name().toLowerCase(); // } // } // // Path: src/main/java/io/rainfall/unit/To.java // public class To extends UnitMeasurement { // // public static To to(int count, Unit unit) { // return new To(count, unit); // } // // public To(int count, Unit unit) { // super(count, unit); // } // // @Override // public String toString() { // return "to " + super.toString(); // } // }
import io.rainfall.Execution; import io.rainfall.Unit; import io.rainfall.unit.Every; import io.rainfall.unit.From; import io.rainfall.unit.Over; import io.rainfall.unit.TimeDivision; import io.rainfall.unit.To; import java.util.function.Function;
/* * Copyright (c) 2014-2022 Aurélien Broszniowski * * 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.rainfall.execution; /** * @author Aurelien Broszniowski */ public class Executions { public static Execution once(int nb, Unit unit) { return new Times(nb); } public static Times times(long occurrences) { return new Times(occurrences); } public static InParallel inParallel(int count, Unit unit, Every every, Over over) { return new InParallel(count, unit, every, over); } public static NothingFor nothingFor(int nb, TimeDivision timeDivision) { return new NothingFor(nb, timeDivision); }
// Path: src/main/java/io/rainfall/Execution.java // public abstract class Execution { // // public enum ExecutionState { // UNKNOWN, // BEGINNING, // ENDING // } // // /** // * Provide an easy way to mark all operations as underway. // * // * @param scenario the test scenario // * @param state phase of execution of the scenario // */ // public void markExecutionState(Scenario scenario, ExecutionState state) { // final Map<String, RangeMap<WeightedOperation>> scenarioOperations = scenario.getOperations(); // for (RangeMap<WeightedOperation> operationRangeMap : scenarioOperations.values()) { // for (WeightedOperation op : operationRangeMap.getAll()) { // op.markExecutionState(state); // } // } // } // // protected ConcurrentPseudoRandom weightRnd = new ConcurrentPseudoRandom(); // // public abstract <E extends Enum<E>> void execute(final StatisticsHolder<E> statisticsHolder, final Scenario scenario, // final Map<Class<? extends Configuration>, Configuration> configurations, // final List<AssertionEvaluator> assertions) throws TestException; // // public abstract String toString(); // // } // // Path: src/main/java/io/rainfall/Unit.java // public interface Unit { // // } // // Path: src/main/java/io/rainfall/unit/Every.java // public class Every extends TimeMeasurement { // // public static Every every(int nb, TimeDivision timeDivision) { // return new Every(nb, timeDivision); // } // // public Every(int count, TimeDivision timeDivision) { // super(count, timeDivision); // } // // @Override // public String toString() { // return "every " + super.toString(); // } // } // // Path: src/main/java/io/rainfall/unit/From.java // public class From extends UnitMeasurement { // // public static From from(int count, Unit unit) { // return new From(count, unit); // } // // public From(final int count, final Unit unit) { // super(count, unit); // } // // @Override // public String toString() { // return "from " + super.toString(); // } // } // // Path: src/main/java/io/rainfall/unit/Over.java // public class Over extends TimeMeasurement { // // public static Over over(int count, TimeDivision timeDivision) { // return new Over(count, timeDivision); // } // // public Over(int count, TimeDivision timeDivision) { // super(count, timeDivision); // } // // @Override // public String toString() { // return "over " + super.toString(); // } // } // // Path: src/main/java/io/rainfall/unit/TimeDivision.java // public class TimeDivision implements Unit { // // private TimeUnit timeUnit; // // public static final TimeDivision seconds = new TimeDivision(TimeUnit.SECONDS); // // public static final TimeDivision minutes = new TimeDivision(TimeUnit.MINUTES); // // public TimeDivision(TimeUnit timeUnit) { // this.timeUnit = timeUnit; // } // // public TimeUnit getTimeUnit() { // return timeUnit; // } // // @Override // public String toString() { // return timeUnit.name().toLowerCase(); // } // } // // Path: src/main/java/io/rainfall/unit/To.java // public class To extends UnitMeasurement { // // public static To to(int count, Unit unit) { // return new To(count, unit); // } // // public To(int count, Unit unit) { // super(count, unit); // } // // @Override // public String toString() { // return "to " + super.toString(); // } // } // Path: src/main/java/io/rainfall/execution/Executions.java import io.rainfall.Execution; import io.rainfall.Unit; import io.rainfall.unit.Every; import io.rainfall.unit.From; import io.rainfall.unit.Over; import io.rainfall.unit.TimeDivision; import io.rainfall.unit.To; import java.util.function.Function; /* * Copyright (c) 2014-2022 Aurélien Broszniowski * * 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.rainfall.execution; /** * @author Aurelien Broszniowski */ public class Executions { public static Execution once(int nb, Unit unit) { return new Times(nb); } public static Times times(long occurrences) { return new Times(occurrences); } public static InParallel inParallel(int count, Unit unit, Every every, Over over) { return new InParallel(count, unit, every, over); } public static NothingFor nothingFor(int nb, TimeDivision timeDivision) { return new NothingFor(nb, timeDivision); }
public static Ramp ramp(From from, To to, Over over) {
aurbroszniowski/Rainfall-core
src/main/java/io/rainfall/execution/Executions.java
// Path: src/main/java/io/rainfall/Execution.java // public abstract class Execution { // // public enum ExecutionState { // UNKNOWN, // BEGINNING, // ENDING // } // // /** // * Provide an easy way to mark all operations as underway. // * // * @param scenario the test scenario // * @param state phase of execution of the scenario // */ // public void markExecutionState(Scenario scenario, ExecutionState state) { // final Map<String, RangeMap<WeightedOperation>> scenarioOperations = scenario.getOperations(); // for (RangeMap<WeightedOperation> operationRangeMap : scenarioOperations.values()) { // for (WeightedOperation op : operationRangeMap.getAll()) { // op.markExecutionState(state); // } // } // } // // protected ConcurrentPseudoRandom weightRnd = new ConcurrentPseudoRandom(); // // public abstract <E extends Enum<E>> void execute(final StatisticsHolder<E> statisticsHolder, final Scenario scenario, // final Map<Class<? extends Configuration>, Configuration> configurations, // final List<AssertionEvaluator> assertions) throws TestException; // // public abstract String toString(); // // } // // Path: src/main/java/io/rainfall/Unit.java // public interface Unit { // // } // // Path: src/main/java/io/rainfall/unit/Every.java // public class Every extends TimeMeasurement { // // public static Every every(int nb, TimeDivision timeDivision) { // return new Every(nb, timeDivision); // } // // public Every(int count, TimeDivision timeDivision) { // super(count, timeDivision); // } // // @Override // public String toString() { // return "every " + super.toString(); // } // } // // Path: src/main/java/io/rainfall/unit/From.java // public class From extends UnitMeasurement { // // public static From from(int count, Unit unit) { // return new From(count, unit); // } // // public From(final int count, final Unit unit) { // super(count, unit); // } // // @Override // public String toString() { // return "from " + super.toString(); // } // } // // Path: src/main/java/io/rainfall/unit/Over.java // public class Over extends TimeMeasurement { // // public static Over over(int count, TimeDivision timeDivision) { // return new Over(count, timeDivision); // } // // public Over(int count, TimeDivision timeDivision) { // super(count, timeDivision); // } // // @Override // public String toString() { // return "over " + super.toString(); // } // } // // Path: src/main/java/io/rainfall/unit/TimeDivision.java // public class TimeDivision implements Unit { // // private TimeUnit timeUnit; // // public static final TimeDivision seconds = new TimeDivision(TimeUnit.SECONDS); // // public static final TimeDivision minutes = new TimeDivision(TimeUnit.MINUTES); // // public TimeDivision(TimeUnit timeUnit) { // this.timeUnit = timeUnit; // } // // public TimeUnit getTimeUnit() { // return timeUnit; // } // // @Override // public String toString() { // return timeUnit.name().toLowerCase(); // } // } // // Path: src/main/java/io/rainfall/unit/To.java // public class To extends UnitMeasurement { // // public static To to(int count, Unit unit) { // return new To(count, unit); // } // // public To(int count, Unit unit) { // super(count, unit); // } // // @Override // public String toString() { // return "to " + super.toString(); // } // }
import io.rainfall.Execution; import io.rainfall.Unit; import io.rainfall.unit.Every; import io.rainfall.unit.From; import io.rainfall.unit.Over; import io.rainfall.unit.TimeDivision; import io.rainfall.unit.To; import java.util.function.Function;
/* * Copyright (c) 2014-2022 Aurélien Broszniowski * * 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.rainfall.execution; /** * @author Aurelien Broszniowski */ public class Executions { public static Execution once(int nb, Unit unit) { return new Times(nb); } public static Times times(long occurrences) { return new Times(occurrences); } public static InParallel inParallel(int count, Unit unit, Every every, Over over) { return new InParallel(count, unit, every, over); } public static NothingFor nothingFor(int nb, TimeDivision timeDivision) { return new NothingFor(nb, timeDivision); }
// Path: src/main/java/io/rainfall/Execution.java // public abstract class Execution { // // public enum ExecutionState { // UNKNOWN, // BEGINNING, // ENDING // } // // /** // * Provide an easy way to mark all operations as underway. // * // * @param scenario the test scenario // * @param state phase of execution of the scenario // */ // public void markExecutionState(Scenario scenario, ExecutionState state) { // final Map<String, RangeMap<WeightedOperation>> scenarioOperations = scenario.getOperations(); // for (RangeMap<WeightedOperation> operationRangeMap : scenarioOperations.values()) { // for (WeightedOperation op : operationRangeMap.getAll()) { // op.markExecutionState(state); // } // } // } // // protected ConcurrentPseudoRandom weightRnd = new ConcurrentPseudoRandom(); // // public abstract <E extends Enum<E>> void execute(final StatisticsHolder<E> statisticsHolder, final Scenario scenario, // final Map<Class<? extends Configuration>, Configuration> configurations, // final List<AssertionEvaluator> assertions) throws TestException; // // public abstract String toString(); // // } // // Path: src/main/java/io/rainfall/Unit.java // public interface Unit { // // } // // Path: src/main/java/io/rainfall/unit/Every.java // public class Every extends TimeMeasurement { // // public static Every every(int nb, TimeDivision timeDivision) { // return new Every(nb, timeDivision); // } // // public Every(int count, TimeDivision timeDivision) { // super(count, timeDivision); // } // // @Override // public String toString() { // return "every " + super.toString(); // } // } // // Path: src/main/java/io/rainfall/unit/From.java // public class From extends UnitMeasurement { // // public static From from(int count, Unit unit) { // return new From(count, unit); // } // // public From(final int count, final Unit unit) { // super(count, unit); // } // // @Override // public String toString() { // return "from " + super.toString(); // } // } // // Path: src/main/java/io/rainfall/unit/Over.java // public class Over extends TimeMeasurement { // // public static Over over(int count, TimeDivision timeDivision) { // return new Over(count, timeDivision); // } // // public Over(int count, TimeDivision timeDivision) { // super(count, timeDivision); // } // // @Override // public String toString() { // return "over " + super.toString(); // } // } // // Path: src/main/java/io/rainfall/unit/TimeDivision.java // public class TimeDivision implements Unit { // // private TimeUnit timeUnit; // // public static final TimeDivision seconds = new TimeDivision(TimeUnit.SECONDS); // // public static final TimeDivision minutes = new TimeDivision(TimeUnit.MINUTES); // // public TimeDivision(TimeUnit timeUnit) { // this.timeUnit = timeUnit; // } // // public TimeUnit getTimeUnit() { // return timeUnit; // } // // @Override // public String toString() { // return timeUnit.name().toLowerCase(); // } // } // // Path: src/main/java/io/rainfall/unit/To.java // public class To extends UnitMeasurement { // // public static To to(int count, Unit unit) { // return new To(count, unit); // } // // public To(int count, Unit unit) { // super(count, unit); // } // // @Override // public String toString() { // return "to " + super.toString(); // } // } // Path: src/main/java/io/rainfall/execution/Executions.java import io.rainfall.Execution; import io.rainfall.Unit; import io.rainfall.unit.Every; import io.rainfall.unit.From; import io.rainfall.unit.Over; import io.rainfall.unit.TimeDivision; import io.rainfall.unit.To; import java.util.function.Function; /* * Copyright (c) 2014-2022 Aurélien Broszniowski * * 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.rainfall.execution; /** * @author Aurelien Broszniowski */ public class Executions { public static Execution once(int nb, Unit unit) { return new Times(nb); } public static Times times(long occurrences) { return new Times(occurrences); } public static InParallel inParallel(int count, Unit unit, Every every, Over over) { return new InParallel(count, unit, every, over); } public static NothingFor nothingFor(int nb, TimeDivision timeDivision) { return new NothingFor(nb, timeDivision); }
public static Ramp ramp(From from, To to, Over over) {
osiegmar/logback-gelf
src/test/java/de/siegmar/logbackgelf/CustomGelfEncoderTest.java
// Path: src/test/java/de/siegmar/logbackgelf/GelfEncoderTest.java // public static void basicValidation(final JsonNode jsonNode) { // coreValidation(jsonNode); // assertNotNull(jsonNode.get("_thread_name").textValue()); // assertEquals(LOGGER_NAME, jsonNode.get("_logger_name").textValue()); // } // // Path: src/test/java/de/siegmar/logbackgelf/GelfEncoderTest.java // public static LoggingEvent simpleLoggingEvent(final Logger logger, final Throwable e) { // return new LoggingEvent( // LOGGER_NAME, // logger, // Level.DEBUG, // "message {}", // e, // new Object[]{1}); // } // // Path: src/test/java/de/siegmar/logbackgelf/custom/CustomGelfEncoder.java // public class CustomGelfEncoder extends GelfEncoder { // // @Override // protected byte[] gelfMessageToJson(final GelfMessage gelfMessage) { // final byte[] json = super.gelfMessageToJson(gelfMessage); // final String sha256 = Hashing.sha256().hashBytes(json).toString(); // gelfMessage.getAdditionalFields().put("sha256", sha256); // return super.gelfMessageToJson(gelfMessage); // } // // }
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.spi.LoggingEvent; import de.siegmar.logbackgelf.custom.CustomGelfEncoder; import static de.siegmar.logbackgelf.GelfEncoderTest.basicValidation; import static de.siegmar.logbackgelf.GelfEncoderTest.simpleLoggingEvent; import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import java.nio.charset.StandardCharsets; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory;
/* * Logback GELF - zero dependencies Logback GELF appender library. * Copyright (C) 2016 Oliver Siegmar * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package de.siegmar.logbackgelf; public class CustomGelfEncoderTest { private static final String LOGGER_NAME = GelfEncoderTest.class.getCanonicalName(); private static final String THREAD_NAME = "thread name"; private static final long TIMESTAMP = 1577359700000L;
// Path: src/test/java/de/siegmar/logbackgelf/GelfEncoderTest.java // public static void basicValidation(final JsonNode jsonNode) { // coreValidation(jsonNode); // assertNotNull(jsonNode.get("_thread_name").textValue()); // assertEquals(LOGGER_NAME, jsonNode.get("_logger_name").textValue()); // } // // Path: src/test/java/de/siegmar/logbackgelf/GelfEncoderTest.java // public static LoggingEvent simpleLoggingEvent(final Logger logger, final Throwable e) { // return new LoggingEvent( // LOGGER_NAME, // logger, // Level.DEBUG, // "message {}", // e, // new Object[]{1}); // } // // Path: src/test/java/de/siegmar/logbackgelf/custom/CustomGelfEncoder.java // public class CustomGelfEncoder extends GelfEncoder { // // @Override // protected byte[] gelfMessageToJson(final GelfMessage gelfMessage) { // final byte[] json = super.gelfMessageToJson(gelfMessage); // final String sha256 = Hashing.sha256().hashBytes(json).toString(); // gelfMessage.getAdditionalFields().put("sha256", sha256); // return super.gelfMessageToJson(gelfMessage); // } // // } // Path: src/test/java/de/siegmar/logbackgelf/CustomGelfEncoderTest.java import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.spi.LoggingEvent; import de.siegmar.logbackgelf.custom.CustomGelfEncoder; import static de.siegmar.logbackgelf.GelfEncoderTest.basicValidation; import static de.siegmar.logbackgelf.GelfEncoderTest.simpleLoggingEvent; import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import java.nio.charset.StandardCharsets; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; /* * Logback GELF - zero dependencies Logback GELF appender library. * Copyright (C) 2016 Oliver Siegmar * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package de.siegmar.logbackgelf; public class CustomGelfEncoderTest { private static final String LOGGER_NAME = GelfEncoderTest.class.getCanonicalName(); private static final String THREAD_NAME = "thread name"; private static final long TIMESTAMP = 1577359700000L;
private final CustomGelfEncoder encoder = new CustomGelfEncoder();
osiegmar/logback-gelf
src/test/java/de/siegmar/logbackgelf/CustomGelfEncoderTest.java
// Path: src/test/java/de/siegmar/logbackgelf/GelfEncoderTest.java // public static void basicValidation(final JsonNode jsonNode) { // coreValidation(jsonNode); // assertNotNull(jsonNode.get("_thread_name").textValue()); // assertEquals(LOGGER_NAME, jsonNode.get("_logger_name").textValue()); // } // // Path: src/test/java/de/siegmar/logbackgelf/GelfEncoderTest.java // public static LoggingEvent simpleLoggingEvent(final Logger logger, final Throwable e) { // return new LoggingEvent( // LOGGER_NAME, // logger, // Level.DEBUG, // "message {}", // e, // new Object[]{1}); // } // // Path: src/test/java/de/siegmar/logbackgelf/custom/CustomGelfEncoder.java // public class CustomGelfEncoder extends GelfEncoder { // // @Override // protected byte[] gelfMessageToJson(final GelfMessage gelfMessage) { // final byte[] json = super.gelfMessageToJson(gelfMessage); // final String sha256 = Hashing.sha256().hashBytes(json).toString(); // gelfMessage.getAdditionalFields().put("sha256", sha256); // return super.gelfMessageToJson(gelfMessage); // } // // }
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.spi.LoggingEvent; import de.siegmar.logbackgelf.custom.CustomGelfEncoder; import static de.siegmar.logbackgelf.GelfEncoderTest.basicValidation; import static de.siegmar.logbackgelf.GelfEncoderTest.simpleLoggingEvent; import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import java.nio.charset.StandardCharsets; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory;
/* * Logback GELF - zero dependencies Logback GELF appender library. * Copyright (C) 2016 Oliver Siegmar * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package de.siegmar.logbackgelf; public class CustomGelfEncoderTest { private static final String LOGGER_NAME = GelfEncoderTest.class.getCanonicalName(); private static final String THREAD_NAME = "thread name"; private static final long TIMESTAMP = 1577359700000L; private final CustomGelfEncoder encoder = new CustomGelfEncoder(); @BeforeEach public void before() { encoder.setContext(new LoggerContext()); encoder.setOriginHost("localhost"); } @Test public void custom() throws IOException { encoder.start(); final LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); final Logger logger = lc.getLogger(LOGGER_NAME);
// Path: src/test/java/de/siegmar/logbackgelf/GelfEncoderTest.java // public static void basicValidation(final JsonNode jsonNode) { // coreValidation(jsonNode); // assertNotNull(jsonNode.get("_thread_name").textValue()); // assertEquals(LOGGER_NAME, jsonNode.get("_logger_name").textValue()); // } // // Path: src/test/java/de/siegmar/logbackgelf/GelfEncoderTest.java // public static LoggingEvent simpleLoggingEvent(final Logger logger, final Throwable e) { // return new LoggingEvent( // LOGGER_NAME, // logger, // Level.DEBUG, // "message {}", // e, // new Object[]{1}); // } // // Path: src/test/java/de/siegmar/logbackgelf/custom/CustomGelfEncoder.java // public class CustomGelfEncoder extends GelfEncoder { // // @Override // protected byte[] gelfMessageToJson(final GelfMessage gelfMessage) { // final byte[] json = super.gelfMessageToJson(gelfMessage); // final String sha256 = Hashing.sha256().hashBytes(json).toString(); // gelfMessage.getAdditionalFields().put("sha256", sha256); // return super.gelfMessageToJson(gelfMessage); // } // // } // Path: src/test/java/de/siegmar/logbackgelf/CustomGelfEncoderTest.java import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.spi.LoggingEvent; import de.siegmar.logbackgelf.custom.CustomGelfEncoder; import static de.siegmar.logbackgelf.GelfEncoderTest.basicValidation; import static de.siegmar.logbackgelf.GelfEncoderTest.simpleLoggingEvent; import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import java.nio.charset.StandardCharsets; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; /* * Logback GELF - zero dependencies Logback GELF appender library. * Copyright (C) 2016 Oliver Siegmar * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package de.siegmar.logbackgelf; public class CustomGelfEncoderTest { private static final String LOGGER_NAME = GelfEncoderTest.class.getCanonicalName(); private static final String THREAD_NAME = "thread name"; private static final long TIMESTAMP = 1577359700000L; private final CustomGelfEncoder encoder = new CustomGelfEncoder(); @BeforeEach public void before() { encoder.setContext(new LoggerContext()); encoder.setOriginHost("localhost"); } @Test public void custom() throws IOException { encoder.start(); final LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); final Logger logger = lc.getLogger(LOGGER_NAME);
final LoggingEvent event = simpleLoggingEvent(logger, null);
osiegmar/logback-gelf
src/test/java/de/siegmar/logbackgelf/CustomGelfEncoderTest.java
// Path: src/test/java/de/siegmar/logbackgelf/GelfEncoderTest.java // public static void basicValidation(final JsonNode jsonNode) { // coreValidation(jsonNode); // assertNotNull(jsonNode.get("_thread_name").textValue()); // assertEquals(LOGGER_NAME, jsonNode.get("_logger_name").textValue()); // } // // Path: src/test/java/de/siegmar/logbackgelf/GelfEncoderTest.java // public static LoggingEvent simpleLoggingEvent(final Logger logger, final Throwable e) { // return new LoggingEvent( // LOGGER_NAME, // logger, // Level.DEBUG, // "message {}", // e, // new Object[]{1}); // } // // Path: src/test/java/de/siegmar/logbackgelf/custom/CustomGelfEncoder.java // public class CustomGelfEncoder extends GelfEncoder { // // @Override // protected byte[] gelfMessageToJson(final GelfMessage gelfMessage) { // final byte[] json = super.gelfMessageToJson(gelfMessage); // final String sha256 = Hashing.sha256().hashBytes(json).toString(); // gelfMessage.getAdditionalFields().put("sha256", sha256); // return super.gelfMessageToJson(gelfMessage); // } // // }
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.spi.LoggingEvent; import de.siegmar.logbackgelf.custom.CustomGelfEncoder; import static de.siegmar.logbackgelf.GelfEncoderTest.basicValidation; import static de.siegmar.logbackgelf.GelfEncoderTest.simpleLoggingEvent; import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import java.nio.charset.StandardCharsets; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory;
/* * Logback GELF - zero dependencies Logback GELF appender library. * Copyright (C) 2016 Oliver Siegmar * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package de.siegmar.logbackgelf; public class CustomGelfEncoderTest { private static final String LOGGER_NAME = GelfEncoderTest.class.getCanonicalName(); private static final String THREAD_NAME = "thread name"; private static final long TIMESTAMP = 1577359700000L; private final CustomGelfEncoder encoder = new CustomGelfEncoder(); @BeforeEach public void before() { encoder.setContext(new LoggerContext()); encoder.setOriginHost("localhost"); } @Test public void custom() throws IOException { encoder.start(); final LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); final Logger logger = lc.getLogger(LOGGER_NAME); final LoggingEvent event = simpleLoggingEvent(logger, null); event.setTimeStamp(TIMESTAMP); event.setThreadName(THREAD_NAME); final String logMsg = encodeToStr(event); final ObjectMapper om = new ObjectMapper(); final JsonNode jsonNode = om.readTree(logMsg);
// Path: src/test/java/de/siegmar/logbackgelf/GelfEncoderTest.java // public static void basicValidation(final JsonNode jsonNode) { // coreValidation(jsonNode); // assertNotNull(jsonNode.get("_thread_name").textValue()); // assertEquals(LOGGER_NAME, jsonNode.get("_logger_name").textValue()); // } // // Path: src/test/java/de/siegmar/logbackgelf/GelfEncoderTest.java // public static LoggingEvent simpleLoggingEvent(final Logger logger, final Throwable e) { // return new LoggingEvent( // LOGGER_NAME, // logger, // Level.DEBUG, // "message {}", // e, // new Object[]{1}); // } // // Path: src/test/java/de/siegmar/logbackgelf/custom/CustomGelfEncoder.java // public class CustomGelfEncoder extends GelfEncoder { // // @Override // protected byte[] gelfMessageToJson(final GelfMessage gelfMessage) { // final byte[] json = super.gelfMessageToJson(gelfMessage); // final String sha256 = Hashing.sha256().hashBytes(json).toString(); // gelfMessage.getAdditionalFields().put("sha256", sha256); // return super.gelfMessageToJson(gelfMessage); // } // // } // Path: src/test/java/de/siegmar/logbackgelf/CustomGelfEncoderTest.java import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.spi.LoggingEvent; import de.siegmar.logbackgelf.custom.CustomGelfEncoder; import static de.siegmar.logbackgelf.GelfEncoderTest.basicValidation; import static de.siegmar.logbackgelf.GelfEncoderTest.simpleLoggingEvent; import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import java.nio.charset.StandardCharsets; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; /* * Logback GELF - zero dependencies Logback GELF appender library. * Copyright (C) 2016 Oliver Siegmar * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package de.siegmar.logbackgelf; public class CustomGelfEncoderTest { private static final String LOGGER_NAME = GelfEncoderTest.class.getCanonicalName(); private static final String THREAD_NAME = "thread name"; private static final long TIMESTAMP = 1577359700000L; private final CustomGelfEncoder encoder = new CustomGelfEncoder(); @BeforeEach public void before() { encoder.setContext(new LoggerContext()); encoder.setOriginHost("localhost"); } @Test public void custom() throws IOException { encoder.start(); final LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); final Logger logger = lc.getLogger(LOGGER_NAME); final LoggingEvent event = simpleLoggingEvent(logger, null); event.setTimeStamp(TIMESTAMP); event.setThreadName(THREAD_NAME); final String logMsg = encodeToStr(event); final ObjectMapper om = new ObjectMapper(); final JsonNode jsonNode = om.readTree(logMsg);
basicValidation(jsonNode);
osiegmar/logback-gelf
src/main/java/de/siegmar/logbackgelf/GelfEncoder.java
// Path: src/main/java/de/siegmar/logbackgelf/mappers/CallerDataFieldMapper.java // public class CallerDataFieldMapper implements GelfFieldMapper<Object> { // // @Override // public void mapField(final ILoggingEvent event, final BiConsumer<String, Object> valueHandler) { // Optional.ofNullable(event.getCallerData()) // .filter(s -> s.length > 0) // .map(s -> s[0]) // .ifPresent(first -> { // valueHandler.accept("source_file_name", first.getFileName()); // valueHandler.accept("source_method_name", first.getMethodName()); // valueHandler.accept("source_class_name", first.getClassName()); // valueHandler.accept("source_line_number", first.getLineNumber()); // }); // } // // } // // Path: src/main/java/de/siegmar/logbackgelf/mappers/MarkerFieldMapper.java // public class MarkerFieldMapper extends AbstractFixedNameFieldMapper<String> { // // public MarkerFieldMapper(final String fieldName) { // super(fieldName); // } // // @Override // protected Optional<String> getValue(final ILoggingEvent event) { // return Optional.ofNullable(event.getMarker()) // .map(MarkerFieldMapper::buildMarkerStr); // } // // private static String buildMarkerStr(final Marker marker) { // if (!marker.hasReferences()) { // return marker.getName(); // } // // final StringBuilder sb = new StringBuilder(marker.getName()); // // final Iterator<Marker> it = marker.iterator(); // do { // sb.append(", ").append(it.next().getName()); // } while (it.hasNext()); // // return sb.toString(); // } // // } // // Path: src/main/java/de/siegmar/logbackgelf/mappers/MdcDataFieldMapper.java // public class MdcDataFieldMapper implements GelfFieldMapper<String> { // // @Override // public void mapField(final ILoggingEvent event, final BiConsumer<String, String> valueHandler) { // Optional.ofNullable(event.getMDCPropertyMap()) // .ifPresent(p -> p.forEach(valueHandler)); // } // // } // // Path: src/main/java/de/siegmar/logbackgelf/mappers/RootExceptionDataFieldMapper.java // public class RootExceptionDataFieldMapper implements GelfFieldMapper<Object> { // // @Override // public void mapField(final ILoggingEvent event, final BiConsumer<String, Object> valueHandler) { // Optional.ofNullable(getRootException(event.getThrowableProxy())) // .ifPresent(rootException -> { // valueHandler.accept("root_cause_class_name", rootException.getClassName()); // valueHandler.accept("root_cause_message", rootException.getMessage()); // }); // } // // private IThrowableProxy getRootException(final IThrowableProxy throwableProxy) { // if (throwableProxy == null) { // return null; // } // // IThrowableProxy rootCause = throwableProxy; // while (rootCause.getCause() != null) { // rootCause = rootCause.getCause(); // } // // return rootCause; // } // // } // // Path: src/main/java/de/siegmar/logbackgelf/mappers/SimpleFieldMapper.java // public class SimpleFieldMapper<T> extends AbstractFixedNameFieldMapper<T> { // // private final Function<ILoggingEvent, T> valueGetter; // // public SimpleFieldMapper(final String fieldName, final Function<ILoggingEvent, T> valueGetter) { // super(fieldName); // this.valueGetter = valueGetter; // } // // @Override // protected Optional<T> getValue(final ILoggingEvent event) { // return Optional.ofNullable(valueGetter.apply(event)); // } // // }
import java.math.BigDecimal; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import ch.qos.logback.classic.PatternLayout; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.classic.util.LevelToSyslogSeverity; import ch.qos.logback.core.encoder.EncoderBase; import de.siegmar.logbackgelf.mappers.CallerDataFieldMapper; import de.siegmar.logbackgelf.mappers.MarkerFieldMapper; import de.siegmar.logbackgelf.mappers.MdcDataFieldMapper; import de.siegmar.logbackgelf.mappers.RootExceptionDataFieldMapper; import de.siegmar.logbackgelf.mappers.SimpleFieldMapper;
@Override public void start() { if (originHost == null || originHost.trim().isEmpty()) { try { originHost = InetUtil.getLocalHostName(); } catch (final UnknownHostException e) { addWarn("Could not determine local hostname", e); originHost = "unknown"; } } if (shortPatternLayout == null) { shortPatternLayout = buildPattern(DEFAULT_SHORT_PATTERN); } if (fullPatternLayout == null) { fullPatternLayout = buildPattern(DEFAULT_FULL_PATTERN); } addBuiltInFieldMappers(); super.start(); } private PatternLayout buildPattern(final String pattern) { final PatternLayout patternLayout = new PatternLayout(); patternLayout.setContext(getContext()); patternLayout.setPattern(pattern); patternLayout.start(); return patternLayout; } private void addBuiltInFieldMappers() {
// Path: src/main/java/de/siegmar/logbackgelf/mappers/CallerDataFieldMapper.java // public class CallerDataFieldMapper implements GelfFieldMapper<Object> { // // @Override // public void mapField(final ILoggingEvent event, final BiConsumer<String, Object> valueHandler) { // Optional.ofNullable(event.getCallerData()) // .filter(s -> s.length > 0) // .map(s -> s[0]) // .ifPresent(first -> { // valueHandler.accept("source_file_name", first.getFileName()); // valueHandler.accept("source_method_name", first.getMethodName()); // valueHandler.accept("source_class_name", first.getClassName()); // valueHandler.accept("source_line_number", first.getLineNumber()); // }); // } // // } // // Path: src/main/java/de/siegmar/logbackgelf/mappers/MarkerFieldMapper.java // public class MarkerFieldMapper extends AbstractFixedNameFieldMapper<String> { // // public MarkerFieldMapper(final String fieldName) { // super(fieldName); // } // // @Override // protected Optional<String> getValue(final ILoggingEvent event) { // return Optional.ofNullable(event.getMarker()) // .map(MarkerFieldMapper::buildMarkerStr); // } // // private static String buildMarkerStr(final Marker marker) { // if (!marker.hasReferences()) { // return marker.getName(); // } // // final StringBuilder sb = new StringBuilder(marker.getName()); // // final Iterator<Marker> it = marker.iterator(); // do { // sb.append(", ").append(it.next().getName()); // } while (it.hasNext()); // // return sb.toString(); // } // // } // // Path: src/main/java/de/siegmar/logbackgelf/mappers/MdcDataFieldMapper.java // public class MdcDataFieldMapper implements GelfFieldMapper<String> { // // @Override // public void mapField(final ILoggingEvent event, final BiConsumer<String, String> valueHandler) { // Optional.ofNullable(event.getMDCPropertyMap()) // .ifPresent(p -> p.forEach(valueHandler)); // } // // } // // Path: src/main/java/de/siegmar/logbackgelf/mappers/RootExceptionDataFieldMapper.java // public class RootExceptionDataFieldMapper implements GelfFieldMapper<Object> { // // @Override // public void mapField(final ILoggingEvent event, final BiConsumer<String, Object> valueHandler) { // Optional.ofNullable(getRootException(event.getThrowableProxy())) // .ifPresent(rootException -> { // valueHandler.accept("root_cause_class_name", rootException.getClassName()); // valueHandler.accept("root_cause_message", rootException.getMessage()); // }); // } // // private IThrowableProxy getRootException(final IThrowableProxy throwableProxy) { // if (throwableProxy == null) { // return null; // } // // IThrowableProxy rootCause = throwableProxy; // while (rootCause.getCause() != null) { // rootCause = rootCause.getCause(); // } // // return rootCause; // } // // } // // Path: src/main/java/de/siegmar/logbackgelf/mappers/SimpleFieldMapper.java // public class SimpleFieldMapper<T> extends AbstractFixedNameFieldMapper<T> { // // private final Function<ILoggingEvent, T> valueGetter; // // public SimpleFieldMapper(final String fieldName, final Function<ILoggingEvent, T> valueGetter) { // super(fieldName); // this.valueGetter = valueGetter; // } // // @Override // protected Optional<T> getValue(final ILoggingEvent event) { // return Optional.ofNullable(valueGetter.apply(event)); // } // // } // Path: src/main/java/de/siegmar/logbackgelf/GelfEncoder.java import java.math.BigDecimal; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import ch.qos.logback.classic.PatternLayout; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.classic.util.LevelToSyslogSeverity; import ch.qos.logback.core.encoder.EncoderBase; import de.siegmar.logbackgelf.mappers.CallerDataFieldMapper; import de.siegmar.logbackgelf.mappers.MarkerFieldMapper; import de.siegmar.logbackgelf.mappers.MdcDataFieldMapper; import de.siegmar.logbackgelf.mappers.RootExceptionDataFieldMapper; import de.siegmar.logbackgelf.mappers.SimpleFieldMapper; @Override public void start() { if (originHost == null || originHost.trim().isEmpty()) { try { originHost = InetUtil.getLocalHostName(); } catch (final UnknownHostException e) { addWarn("Could not determine local hostname", e); originHost = "unknown"; } } if (shortPatternLayout == null) { shortPatternLayout = buildPattern(DEFAULT_SHORT_PATTERN); } if (fullPatternLayout == null) { fullPatternLayout = buildPattern(DEFAULT_FULL_PATTERN); } addBuiltInFieldMappers(); super.start(); } private PatternLayout buildPattern(final String pattern) { final PatternLayout patternLayout = new PatternLayout(); patternLayout.setContext(getContext()); patternLayout.setPattern(pattern); patternLayout.start(); return patternLayout; } private void addBuiltInFieldMappers() {
builtInFieldMappers.add(new SimpleFieldMapper<>(loggerNameKey, ILoggingEvent::getLoggerName));
osiegmar/logback-gelf
src/main/java/de/siegmar/logbackgelf/GelfEncoder.java
// Path: src/main/java/de/siegmar/logbackgelf/mappers/CallerDataFieldMapper.java // public class CallerDataFieldMapper implements GelfFieldMapper<Object> { // // @Override // public void mapField(final ILoggingEvent event, final BiConsumer<String, Object> valueHandler) { // Optional.ofNullable(event.getCallerData()) // .filter(s -> s.length > 0) // .map(s -> s[0]) // .ifPresent(first -> { // valueHandler.accept("source_file_name", first.getFileName()); // valueHandler.accept("source_method_name", first.getMethodName()); // valueHandler.accept("source_class_name", first.getClassName()); // valueHandler.accept("source_line_number", first.getLineNumber()); // }); // } // // } // // Path: src/main/java/de/siegmar/logbackgelf/mappers/MarkerFieldMapper.java // public class MarkerFieldMapper extends AbstractFixedNameFieldMapper<String> { // // public MarkerFieldMapper(final String fieldName) { // super(fieldName); // } // // @Override // protected Optional<String> getValue(final ILoggingEvent event) { // return Optional.ofNullable(event.getMarker()) // .map(MarkerFieldMapper::buildMarkerStr); // } // // private static String buildMarkerStr(final Marker marker) { // if (!marker.hasReferences()) { // return marker.getName(); // } // // final StringBuilder sb = new StringBuilder(marker.getName()); // // final Iterator<Marker> it = marker.iterator(); // do { // sb.append(", ").append(it.next().getName()); // } while (it.hasNext()); // // return sb.toString(); // } // // } // // Path: src/main/java/de/siegmar/logbackgelf/mappers/MdcDataFieldMapper.java // public class MdcDataFieldMapper implements GelfFieldMapper<String> { // // @Override // public void mapField(final ILoggingEvent event, final BiConsumer<String, String> valueHandler) { // Optional.ofNullable(event.getMDCPropertyMap()) // .ifPresent(p -> p.forEach(valueHandler)); // } // // } // // Path: src/main/java/de/siegmar/logbackgelf/mappers/RootExceptionDataFieldMapper.java // public class RootExceptionDataFieldMapper implements GelfFieldMapper<Object> { // // @Override // public void mapField(final ILoggingEvent event, final BiConsumer<String, Object> valueHandler) { // Optional.ofNullable(getRootException(event.getThrowableProxy())) // .ifPresent(rootException -> { // valueHandler.accept("root_cause_class_name", rootException.getClassName()); // valueHandler.accept("root_cause_message", rootException.getMessage()); // }); // } // // private IThrowableProxy getRootException(final IThrowableProxy throwableProxy) { // if (throwableProxy == null) { // return null; // } // // IThrowableProxy rootCause = throwableProxy; // while (rootCause.getCause() != null) { // rootCause = rootCause.getCause(); // } // // return rootCause; // } // // } // // Path: src/main/java/de/siegmar/logbackgelf/mappers/SimpleFieldMapper.java // public class SimpleFieldMapper<T> extends AbstractFixedNameFieldMapper<T> { // // private final Function<ILoggingEvent, T> valueGetter; // // public SimpleFieldMapper(final String fieldName, final Function<ILoggingEvent, T> valueGetter) { // super(fieldName); // this.valueGetter = valueGetter; // } // // @Override // protected Optional<T> getValue(final ILoggingEvent event) { // return Optional.ofNullable(valueGetter.apply(event)); // } // // }
import java.math.BigDecimal; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import ch.qos.logback.classic.PatternLayout; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.classic.util.LevelToSyslogSeverity; import ch.qos.logback.core.encoder.EncoderBase; import de.siegmar.logbackgelf.mappers.CallerDataFieldMapper; import de.siegmar.logbackgelf.mappers.MarkerFieldMapper; import de.siegmar.logbackgelf.mappers.MdcDataFieldMapper; import de.siegmar.logbackgelf.mappers.RootExceptionDataFieldMapper; import de.siegmar.logbackgelf.mappers.SimpleFieldMapper;
} if (fullPatternLayout == null) { fullPatternLayout = buildPattern(DEFAULT_FULL_PATTERN); } addBuiltInFieldMappers(); super.start(); } private PatternLayout buildPattern(final String pattern) { final PatternLayout patternLayout = new PatternLayout(); patternLayout.setContext(getContext()); patternLayout.setPattern(pattern); patternLayout.start(); return patternLayout; } private void addBuiltInFieldMappers() { builtInFieldMappers.add(new SimpleFieldMapper<>(loggerNameKey, ILoggingEvent::getLoggerName)); builtInFieldMappers.add(new SimpleFieldMapper<>(threadNameKey, ILoggingEvent::getThreadName)); if (includeLevelName) { builtInFieldMappers.add(new SimpleFieldMapper<>(levelNameKey, event -> event.getLevel().toString())); } if (includeRawMessage) { builtInFieldMappers.add(new SimpleFieldMapper<>("raw_message", ILoggingEvent::getMessage)); } if (includeCallerData) {
// Path: src/main/java/de/siegmar/logbackgelf/mappers/CallerDataFieldMapper.java // public class CallerDataFieldMapper implements GelfFieldMapper<Object> { // // @Override // public void mapField(final ILoggingEvent event, final BiConsumer<String, Object> valueHandler) { // Optional.ofNullable(event.getCallerData()) // .filter(s -> s.length > 0) // .map(s -> s[0]) // .ifPresent(first -> { // valueHandler.accept("source_file_name", first.getFileName()); // valueHandler.accept("source_method_name", first.getMethodName()); // valueHandler.accept("source_class_name", first.getClassName()); // valueHandler.accept("source_line_number", first.getLineNumber()); // }); // } // // } // // Path: src/main/java/de/siegmar/logbackgelf/mappers/MarkerFieldMapper.java // public class MarkerFieldMapper extends AbstractFixedNameFieldMapper<String> { // // public MarkerFieldMapper(final String fieldName) { // super(fieldName); // } // // @Override // protected Optional<String> getValue(final ILoggingEvent event) { // return Optional.ofNullable(event.getMarker()) // .map(MarkerFieldMapper::buildMarkerStr); // } // // private static String buildMarkerStr(final Marker marker) { // if (!marker.hasReferences()) { // return marker.getName(); // } // // final StringBuilder sb = new StringBuilder(marker.getName()); // // final Iterator<Marker> it = marker.iterator(); // do { // sb.append(", ").append(it.next().getName()); // } while (it.hasNext()); // // return sb.toString(); // } // // } // // Path: src/main/java/de/siegmar/logbackgelf/mappers/MdcDataFieldMapper.java // public class MdcDataFieldMapper implements GelfFieldMapper<String> { // // @Override // public void mapField(final ILoggingEvent event, final BiConsumer<String, String> valueHandler) { // Optional.ofNullable(event.getMDCPropertyMap()) // .ifPresent(p -> p.forEach(valueHandler)); // } // // } // // Path: src/main/java/de/siegmar/logbackgelf/mappers/RootExceptionDataFieldMapper.java // public class RootExceptionDataFieldMapper implements GelfFieldMapper<Object> { // // @Override // public void mapField(final ILoggingEvent event, final BiConsumer<String, Object> valueHandler) { // Optional.ofNullable(getRootException(event.getThrowableProxy())) // .ifPresent(rootException -> { // valueHandler.accept("root_cause_class_name", rootException.getClassName()); // valueHandler.accept("root_cause_message", rootException.getMessage()); // }); // } // // private IThrowableProxy getRootException(final IThrowableProxy throwableProxy) { // if (throwableProxy == null) { // return null; // } // // IThrowableProxy rootCause = throwableProxy; // while (rootCause.getCause() != null) { // rootCause = rootCause.getCause(); // } // // return rootCause; // } // // } // // Path: src/main/java/de/siegmar/logbackgelf/mappers/SimpleFieldMapper.java // public class SimpleFieldMapper<T> extends AbstractFixedNameFieldMapper<T> { // // private final Function<ILoggingEvent, T> valueGetter; // // public SimpleFieldMapper(final String fieldName, final Function<ILoggingEvent, T> valueGetter) { // super(fieldName); // this.valueGetter = valueGetter; // } // // @Override // protected Optional<T> getValue(final ILoggingEvent event) { // return Optional.ofNullable(valueGetter.apply(event)); // } // // } // Path: src/main/java/de/siegmar/logbackgelf/GelfEncoder.java import java.math.BigDecimal; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import ch.qos.logback.classic.PatternLayout; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.classic.util.LevelToSyslogSeverity; import ch.qos.logback.core.encoder.EncoderBase; import de.siegmar.logbackgelf.mappers.CallerDataFieldMapper; import de.siegmar.logbackgelf.mappers.MarkerFieldMapper; import de.siegmar.logbackgelf.mappers.MdcDataFieldMapper; import de.siegmar.logbackgelf.mappers.RootExceptionDataFieldMapper; import de.siegmar.logbackgelf.mappers.SimpleFieldMapper; } if (fullPatternLayout == null) { fullPatternLayout = buildPattern(DEFAULT_FULL_PATTERN); } addBuiltInFieldMappers(); super.start(); } private PatternLayout buildPattern(final String pattern) { final PatternLayout patternLayout = new PatternLayout(); patternLayout.setContext(getContext()); patternLayout.setPattern(pattern); patternLayout.start(); return patternLayout; } private void addBuiltInFieldMappers() { builtInFieldMappers.add(new SimpleFieldMapper<>(loggerNameKey, ILoggingEvent::getLoggerName)); builtInFieldMappers.add(new SimpleFieldMapper<>(threadNameKey, ILoggingEvent::getThreadName)); if (includeLevelName) { builtInFieldMappers.add(new SimpleFieldMapper<>(levelNameKey, event -> event.getLevel().toString())); } if (includeRawMessage) { builtInFieldMappers.add(new SimpleFieldMapper<>("raw_message", ILoggingEvent::getMessage)); } if (includeCallerData) {
builtInFieldMappers.add(new CallerDataFieldMapper());
osiegmar/logback-gelf
src/main/java/de/siegmar/logbackgelf/GelfEncoder.java
// Path: src/main/java/de/siegmar/logbackgelf/mappers/CallerDataFieldMapper.java // public class CallerDataFieldMapper implements GelfFieldMapper<Object> { // // @Override // public void mapField(final ILoggingEvent event, final BiConsumer<String, Object> valueHandler) { // Optional.ofNullable(event.getCallerData()) // .filter(s -> s.length > 0) // .map(s -> s[0]) // .ifPresent(first -> { // valueHandler.accept("source_file_name", first.getFileName()); // valueHandler.accept("source_method_name", first.getMethodName()); // valueHandler.accept("source_class_name", first.getClassName()); // valueHandler.accept("source_line_number", first.getLineNumber()); // }); // } // // } // // Path: src/main/java/de/siegmar/logbackgelf/mappers/MarkerFieldMapper.java // public class MarkerFieldMapper extends AbstractFixedNameFieldMapper<String> { // // public MarkerFieldMapper(final String fieldName) { // super(fieldName); // } // // @Override // protected Optional<String> getValue(final ILoggingEvent event) { // return Optional.ofNullable(event.getMarker()) // .map(MarkerFieldMapper::buildMarkerStr); // } // // private static String buildMarkerStr(final Marker marker) { // if (!marker.hasReferences()) { // return marker.getName(); // } // // final StringBuilder sb = new StringBuilder(marker.getName()); // // final Iterator<Marker> it = marker.iterator(); // do { // sb.append(", ").append(it.next().getName()); // } while (it.hasNext()); // // return sb.toString(); // } // // } // // Path: src/main/java/de/siegmar/logbackgelf/mappers/MdcDataFieldMapper.java // public class MdcDataFieldMapper implements GelfFieldMapper<String> { // // @Override // public void mapField(final ILoggingEvent event, final BiConsumer<String, String> valueHandler) { // Optional.ofNullable(event.getMDCPropertyMap()) // .ifPresent(p -> p.forEach(valueHandler)); // } // // } // // Path: src/main/java/de/siegmar/logbackgelf/mappers/RootExceptionDataFieldMapper.java // public class RootExceptionDataFieldMapper implements GelfFieldMapper<Object> { // // @Override // public void mapField(final ILoggingEvent event, final BiConsumer<String, Object> valueHandler) { // Optional.ofNullable(getRootException(event.getThrowableProxy())) // .ifPresent(rootException -> { // valueHandler.accept("root_cause_class_name", rootException.getClassName()); // valueHandler.accept("root_cause_message", rootException.getMessage()); // }); // } // // private IThrowableProxy getRootException(final IThrowableProxy throwableProxy) { // if (throwableProxy == null) { // return null; // } // // IThrowableProxy rootCause = throwableProxy; // while (rootCause.getCause() != null) { // rootCause = rootCause.getCause(); // } // // return rootCause; // } // // } // // Path: src/main/java/de/siegmar/logbackgelf/mappers/SimpleFieldMapper.java // public class SimpleFieldMapper<T> extends AbstractFixedNameFieldMapper<T> { // // private final Function<ILoggingEvent, T> valueGetter; // // public SimpleFieldMapper(final String fieldName, final Function<ILoggingEvent, T> valueGetter) { // super(fieldName); // this.valueGetter = valueGetter; // } // // @Override // protected Optional<T> getValue(final ILoggingEvent event) { // return Optional.ofNullable(valueGetter.apply(event)); // } // // }
import java.math.BigDecimal; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import ch.qos.logback.classic.PatternLayout; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.classic.util.LevelToSyslogSeverity; import ch.qos.logback.core.encoder.EncoderBase; import de.siegmar.logbackgelf.mappers.CallerDataFieldMapper; import de.siegmar.logbackgelf.mappers.MarkerFieldMapper; import de.siegmar.logbackgelf.mappers.MdcDataFieldMapper; import de.siegmar.logbackgelf.mappers.RootExceptionDataFieldMapper; import de.siegmar.logbackgelf.mappers.SimpleFieldMapper;
addBuiltInFieldMappers(); super.start(); } private PatternLayout buildPattern(final String pattern) { final PatternLayout patternLayout = new PatternLayout(); patternLayout.setContext(getContext()); patternLayout.setPattern(pattern); patternLayout.start(); return patternLayout; } private void addBuiltInFieldMappers() { builtInFieldMappers.add(new SimpleFieldMapper<>(loggerNameKey, ILoggingEvent::getLoggerName)); builtInFieldMappers.add(new SimpleFieldMapper<>(threadNameKey, ILoggingEvent::getThreadName)); if (includeLevelName) { builtInFieldMappers.add(new SimpleFieldMapper<>(levelNameKey, event -> event.getLevel().toString())); } if (includeRawMessage) { builtInFieldMappers.add(new SimpleFieldMapper<>("raw_message", ILoggingEvent::getMessage)); } if (includeCallerData) { builtInFieldMappers.add(new CallerDataFieldMapper()); } if (includeRootCauseData) {
// Path: src/main/java/de/siegmar/logbackgelf/mappers/CallerDataFieldMapper.java // public class CallerDataFieldMapper implements GelfFieldMapper<Object> { // // @Override // public void mapField(final ILoggingEvent event, final BiConsumer<String, Object> valueHandler) { // Optional.ofNullable(event.getCallerData()) // .filter(s -> s.length > 0) // .map(s -> s[0]) // .ifPresent(first -> { // valueHandler.accept("source_file_name", first.getFileName()); // valueHandler.accept("source_method_name", first.getMethodName()); // valueHandler.accept("source_class_name", first.getClassName()); // valueHandler.accept("source_line_number", first.getLineNumber()); // }); // } // // } // // Path: src/main/java/de/siegmar/logbackgelf/mappers/MarkerFieldMapper.java // public class MarkerFieldMapper extends AbstractFixedNameFieldMapper<String> { // // public MarkerFieldMapper(final String fieldName) { // super(fieldName); // } // // @Override // protected Optional<String> getValue(final ILoggingEvent event) { // return Optional.ofNullable(event.getMarker()) // .map(MarkerFieldMapper::buildMarkerStr); // } // // private static String buildMarkerStr(final Marker marker) { // if (!marker.hasReferences()) { // return marker.getName(); // } // // final StringBuilder sb = new StringBuilder(marker.getName()); // // final Iterator<Marker> it = marker.iterator(); // do { // sb.append(", ").append(it.next().getName()); // } while (it.hasNext()); // // return sb.toString(); // } // // } // // Path: src/main/java/de/siegmar/logbackgelf/mappers/MdcDataFieldMapper.java // public class MdcDataFieldMapper implements GelfFieldMapper<String> { // // @Override // public void mapField(final ILoggingEvent event, final BiConsumer<String, String> valueHandler) { // Optional.ofNullable(event.getMDCPropertyMap()) // .ifPresent(p -> p.forEach(valueHandler)); // } // // } // // Path: src/main/java/de/siegmar/logbackgelf/mappers/RootExceptionDataFieldMapper.java // public class RootExceptionDataFieldMapper implements GelfFieldMapper<Object> { // // @Override // public void mapField(final ILoggingEvent event, final BiConsumer<String, Object> valueHandler) { // Optional.ofNullable(getRootException(event.getThrowableProxy())) // .ifPresent(rootException -> { // valueHandler.accept("root_cause_class_name", rootException.getClassName()); // valueHandler.accept("root_cause_message", rootException.getMessage()); // }); // } // // private IThrowableProxy getRootException(final IThrowableProxy throwableProxy) { // if (throwableProxy == null) { // return null; // } // // IThrowableProxy rootCause = throwableProxy; // while (rootCause.getCause() != null) { // rootCause = rootCause.getCause(); // } // // return rootCause; // } // // } // // Path: src/main/java/de/siegmar/logbackgelf/mappers/SimpleFieldMapper.java // public class SimpleFieldMapper<T> extends AbstractFixedNameFieldMapper<T> { // // private final Function<ILoggingEvent, T> valueGetter; // // public SimpleFieldMapper(final String fieldName, final Function<ILoggingEvent, T> valueGetter) { // super(fieldName); // this.valueGetter = valueGetter; // } // // @Override // protected Optional<T> getValue(final ILoggingEvent event) { // return Optional.ofNullable(valueGetter.apply(event)); // } // // } // Path: src/main/java/de/siegmar/logbackgelf/GelfEncoder.java import java.math.BigDecimal; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import ch.qos.logback.classic.PatternLayout; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.classic.util.LevelToSyslogSeverity; import ch.qos.logback.core.encoder.EncoderBase; import de.siegmar.logbackgelf.mappers.CallerDataFieldMapper; import de.siegmar.logbackgelf.mappers.MarkerFieldMapper; import de.siegmar.logbackgelf.mappers.MdcDataFieldMapper; import de.siegmar.logbackgelf.mappers.RootExceptionDataFieldMapper; import de.siegmar.logbackgelf.mappers.SimpleFieldMapper; addBuiltInFieldMappers(); super.start(); } private PatternLayout buildPattern(final String pattern) { final PatternLayout patternLayout = new PatternLayout(); patternLayout.setContext(getContext()); patternLayout.setPattern(pattern); patternLayout.start(); return patternLayout; } private void addBuiltInFieldMappers() { builtInFieldMappers.add(new SimpleFieldMapper<>(loggerNameKey, ILoggingEvent::getLoggerName)); builtInFieldMappers.add(new SimpleFieldMapper<>(threadNameKey, ILoggingEvent::getThreadName)); if (includeLevelName) { builtInFieldMappers.add(new SimpleFieldMapper<>(levelNameKey, event -> event.getLevel().toString())); } if (includeRawMessage) { builtInFieldMappers.add(new SimpleFieldMapper<>("raw_message", ILoggingEvent::getMessage)); } if (includeCallerData) { builtInFieldMappers.add(new CallerDataFieldMapper()); } if (includeRootCauseData) {
builtInFieldMappers.add(new RootExceptionDataFieldMapper());
osiegmar/logback-gelf
src/main/java/de/siegmar/logbackgelf/GelfEncoder.java
// Path: src/main/java/de/siegmar/logbackgelf/mappers/CallerDataFieldMapper.java // public class CallerDataFieldMapper implements GelfFieldMapper<Object> { // // @Override // public void mapField(final ILoggingEvent event, final BiConsumer<String, Object> valueHandler) { // Optional.ofNullable(event.getCallerData()) // .filter(s -> s.length > 0) // .map(s -> s[0]) // .ifPresent(first -> { // valueHandler.accept("source_file_name", first.getFileName()); // valueHandler.accept("source_method_name", first.getMethodName()); // valueHandler.accept("source_class_name", first.getClassName()); // valueHandler.accept("source_line_number", first.getLineNumber()); // }); // } // // } // // Path: src/main/java/de/siegmar/logbackgelf/mappers/MarkerFieldMapper.java // public class MarkerFieldMapper extends AbstractFixedNameFieldMapper<String> { // // public MarkerFieldMapper(final String fieldName) { // super(fieldName); // } // // @Override // protected Optional<String> getValue(final ILoggingEvent event) { // return Optional.ofNullable(event.getMarker()) // .map(MarkerFieldMapper::buildMarkerStr); // } // // private static String buildMarkerStr(final Marker marker) { // if (!marker.hasReferences()) { // return marker.getName(); // } // // final StringBuilder sb = new StringBuilder(marker.getName()); // // final Iterator<Marker> it = marker.iterator(); // do { // sb.append(", ").append(it.next().getName()); // } while (it.hasNext()); // // return sb.toString(); // } // // } // // Path: src/main/java/de/siegmar/logbackgelf/mappers/MdcDataFieldMapper.java // public class MdcDataFieldMapper implements GelfFieldMapper<String> { // // @Override // public void mapField(final ILoggingEvent event, final BiConsumer<String, String> valueHandler) { // Optional.ofNullable(event.getMDCPropertyMap()) // .ifPresent(p -> p.forEach(valueHandler)); // } // // } // // Path: src/main/java/de/siegmar/logbackgelf/mappers/RootExceptionDataFieldMapper.java // public class RootExceptionDataFieldMapper implements GelfFieldMapper<Object> { // // @Override // public void mapField(final ILoggingEvent event, final BiConsumer<String, Object> valueHandler) { // Optional.ofNullable(getRootException(event.getThrowableProxy())) // .ifPresent(rootException -> { // valueHandler.accept("root_cause_class_name", rootException.getClassName()); // valueHandler.accept("root_cause_message", rootException.getMessage()); // }); // } // // private IThrowableProxy getRootException(final IThrowableProxy throwableProxy) { // if (throwableProxy == null) { // return null; // } // // IThrowableProxy rootCause = throwableProxy; // while (rootCause.getCause() != null) { // rootCause = rootCause.getCause(); // } // // return rootCause; // } // // } // // Path: src/main/java/de/siegmar/logbackgelf/mappers/SimpleFieldMapper.java // public class SimpleFieldMapper<T> extends AbstractFixedNameFieldMapper<T> { // // private final Function<ILoggingEvent, T> valueGetter; // // public SimpleFieldMapper(final String fieldName, final Function<ILoggingEvent, T> valueGetter) { // super(fieldName); // this.valueGetter = valueGetter; // } // // @Override // protected Optional<T> getValue(final ILoggingEvent event) { // return Optional.ofNullable(valueGetter.apply(event)); // } // // }
import java.math.BigDecimal; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import ch.qos.logback.classic.PatternLayout; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.classic.util.LevelToSyslogSeverity; import ch.qos.logback.core.encoder.EncoderBase; import de.siegmar.logbackgelf.mappers.CallerDataFieldMapper; import de.siegmar.logbackgelf.mappers.MarkerFieldMapper; import de.siegmar.logbackgelf.mappers.MdcDataFieldMapper; import de.siegmar.logbackgelf.mappers.RootExceptionDataFieldMapper; import de.siegmar.logbackgelf.mappers.SimpleFieldMapper;
private PatternLayout buildPattern(final String pattern) { final PatternLayout patternLayout = new PatternLayout(); patternLayout.setContext(getContext()); patternLayout.setPattern(pattern); patternLayout.start(); return patternLayout; } private void addBuiltInFieldMappers() { builtInFieldMappers.add(new SimpleFieldMapper<>(loggerNameKey, ILoggingEvent::getLoggerName)); builtInFieldMappers.add(new SimpleFieldMapper<>(threadNameKey, ILoggingEvent::getThreadName)); if (includeLevelName) { builtInFieldMappers.add(new SimpleFieldMapper<>(levelNameKey, event -> event.getLevel().toString())); } if (includeRawMessage) { builtInFieldMappers.add(new SimpleFieldMapper<>("raw_message", ILoggingEvent::getMessage)); } if (includeCallerData) { builtInFieldMappers.add(new CallerDataFieldMapper()); } if (includeRootCauseData) { builtInFieldMappers.add(new RootExceptionDataFieldMapper()); } if (includeMarker) {
// Path: src/main/java/de/siegmar/logbackgelf/mappers/CallerDataFieldMapper.java // public class CallerDataFieldMapper implements GelfFieldMapper<Object> { // // @Override // public void mapField(final ILoggingEvent event, final BiConsumer<String, Object> valueHandler) { // Optional.ofNullable(event.getCallerData()) // .filter(s -> s.length > 0) // .map(s -> s[0]) // .ifPresent(first -> { // valueHandler.accept("source_file_name", first.getFileName()); // valueHandler.accept("source_method_name", first.getMethodName()); // valueHandler.accept("source_class_name", first.getClassName()); // valueHandler.accept("source_line_number", first.getLineNumber()); // }); // } // // } // // Path: src/main/java/de/siegmar/logbackgelf/mappers/MarkerFieldMapper.java // public class MarkerFieldMapper extends AbstractFixedNameFieldMapper<String> { // // public MarkerFieldMapper(final String fieldName) { // super(fieldName); // } // // @Override // protected Optional<String> getValue(final ILoggingEvent event) { // return Optional.ofNullable(event.getMarker()) // .map(MarkerFieldMapper::buildMarkerStr); // } // // private static String buildMarkerStr(final Marker marker) { // if (!marker.hasReferences()) { // return marker.getName(); // } // // final StringBuilder sb = new StringBuilder(marker.getName()); // // final Iterator<Marker> it = marker.iterator(); // do { // sb.append(", ").append(it.next().getName()); // } while (it.hasNext()); // // return sb.toString(); // } // // } // // Path: src/main/java/de/siegmar/logbackgelf/mappers/MdcDataFieldMapper.java // public class MdcDataFieldMapper implements GelfFieldMapper<String> { // // @Override // public void mapField(final ILoggingEvent event, final BiConsumer<String, String> valueHandler) { // Optional.ofNullable(event.getMDCPropertyMap()) // .ifPresent(p -> p.forEach(valueHandler)); // } // // } // // Path: src/main/java/de/siegmar/logbackgelf/mappers/RootExceptionDataFieldMapper.java // public class RootExceptionDataFieldMapper implements GelfFieldMapper<Object> { // // @Override // public void mapField(final ILoggingEvent event, final BiConsumer<String, Object> valueHandler) { // Optional.ofNullable(getRootException(event.getThrowableProxy())) // .ifPresent(rootException -> { // valueHandler.accept("root_cause_class_name", rootException.getClassName()); // valueHandler.accept("root_cause_message", rootException.getMessage()); // }); // } // // private IThrowableProxy getRootException(final IThrowableProxy throwableProxy) { // if (throwableProxy == null) { // return null; // } // // IThrowableProxy rootCause = throwableProxy; // while (rootCause.getCause() != null) { // rootCause = rootCause.getCause(); // } // // return rootCause; // } // // } // // Path: src/main/java/de/siegmar/logbackgelf/mappers/SimpleFieldMapper.java // public class SimpleFieldMapper<T> extends AbstractFixedNameFieldMapper<T> { // // private final Function<ILoggingEvent, T> valueGetter; // // public SimpleFieldMapper(final String fieldName, final Function<ILoggingEvent, T> valueGetter) { // super(fieldName); // this.valueGetter = valueGetter; // } // // @Override // protected Optional<T> getValue(final ILoggingEvent event) { // return Optional.ofNullable(valueGetter.apply(event)); // } // // } // Path: src/main/java/de/siegmar/logbackgelf/GelfEncoder.java import java.math.BigDecimal; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import ch.qos.logback.classic.PatternLayout; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.classic.util.LevelToSyslogSeverity; import ch.qos.logback.core.encoder.EncoderBase; import de.siegmar.logbackgelf.mappers.CallerDataFieldMapper; import de.siegmar.logbackgelf.mappers.MarkerFieldMapper; import de.siegmar.logbackgelf.mappers.MdcDataFieldMapper; import de.siegmar.logbackgelf.mappers.RootExceptionDataFieldMapper; import de.siegmar.logbackgelf.mappers.SimpleFieldMapper; private PatternLayout buildPattern(final String pattern) { final PatternLayout patternLayout = new PatternLayout(); patternLayout.setContext(getContext()); patternLayout.setPattern(pattern); patternLayout.start(); return patternLayout; } private void addBuiltInFieldMappers() { builtInFieldMappers.add(new SimpleFieldMapper<>(loggerNameKey, ILoggingEvent::getLoggerName)); builtInFieldMappers.add(new SimpleFieldMapper<>(threadNameKey, ILoggingEvent::getThreadName)); if (includeLevelName) { builtInFieldMappers.add(new SimpleFieldMapper<>(levelNameKey, event -> event.getLevel().toString())); } if (includeRawMessage) { builtInFieldMappers.add(new SimpleFieldMapper<>("raw_message", ILoggingEvent::getMessage)); } if (includeCallerData) { builtInFieldMappers.add(new CallerDataFieldMapper()); } if (includeRootCauseData) { builtInFieldMappers.add(new RootExceptionDataFieldMapper()); } if (includeMarker) {
builtInFieldMappers.add(new MarkerFieldMapper("marker"));
osiegmar/logback-gelf
src/main/java/de/siegmar/logbackgelf/GelfEncoder.java
// Path: src/main/java/de/siegmar/logbackgelf/mappers/CallerDataFieldMapper.java // public class CallerDataFieldMapper implements GelfFieldMapper<Object> { // // @Override // public void mapField(final ILoggingEvent event, final BiConsumer<String, Object> valueHandler) { // Optional.ofNullable(event.getCallerData()) // .filter(s -> s.length > 0) // .map(s -> s[0]) // .ifPresent(first -> { // valueHandler.accept("source_file_name", first.getFileName()); // valueHandler.accept("source_method_name", first.getMethodName()); // valueHandler.accept("source_class_name", first.getClassName()); // valueHandler.accept("source_line_number", first.getLineNumber()); // }); // } // // } // // Path: src/main/java/de/siegmar/logbackgelf/mappers/MarkerFieldMapper.java // public class MarkerFieldMapper extends AbstractFixedNameFieldMapper<String> { // // public MarkerFieldMapper(final String fieldName) { // super(fieldName); // } // // @Override // protected Optional<String> getValue(final ILoggingEvent event) { // return Optional.ofNullable(event.getMarker()) // .map(MarkerFieldMapper::buildMarkerStr); // } // // private static String buildMarkerStr(final Marker marker) { // if (!marker.hasReferences()) { // return marker.getName(); // } // // final StringBuilder sb = new StringBuilder(marker.getName()); // // final Iterator<Marker> it = marker.iterator(); // do { // sb.append(", ").append(it.next().getName()); // } while (it.hasNext()); // // return sb.toString(); // } // // } // // Path: src/main/java/de/siegmar/logbackgelf/mappers/MdcDataFieldMapper.java // public class MdcDataFieldMapper implements GelfFieldMapper<String> { // // @Override // public void mapField(final ILoggingEvent event, final BiConsumer<String, String> valueHandler) { // Optional.ofNullable(event.getMDCPropertyMap()) // .ifPresent(p -> p.forEach(valueHandler)); // } // // } // // Path: src/main/java/de/siegmar/logbackgelf/mappers/RootExceptionDataFieldMapper.java // public class RootExceptionDataFieldMapper implements GelfFieldMapper<Object> { // // @Override // public void mapField(final ILoggingEvent event, final BiConsumer<String, Object> valueHandler) { // Optional.ofNullable(getRootException(event.getThrowableProxy())) // .ifPresent(rootException -> { // valueHandler.accept("root_cause_class_name", rootException.getClassName()); // valueHandler.accept("root_cause_message", rootException.getMessage()); // }); // } // // private IThrowableProxy getRootException(final IThrowableProxy throwableProxy) { // if (throwableProxy == null) { // return null; // } // // IThrowableProxy rootCause = throwableProxy; // while (rootCause.getCause() != null) { // rootCause = rootCause.getCause(); // } // // return rootCause; // } // // } // // Path: src/main/java/de/siegmar/logbackgelf/mappers/SimpleFieldMapper.java // public class SimpleFieldMapper<T> extends AbstractFixedNameFieldMapper<T> { // // private final Function<ILoggingEvent, T> valueGetter; // // public SimpleFieldMapper(final String fieldName, final Function<ILoggingEvent, T> valueGetter) { // super(fieldName); // this.valueGetter = valueGetter; // } // // @Override // protected Optional<T> getValue(final ILoggingEvent event) { // return Optional.ofNullable(valueGetter.apply(event)); // } // // }
import java.math.BigDecimal; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import ch.qos.logback.classic.PatternLayout; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.classic.util.LevelToSyslogSeverity; import ch.qos.logback.core.encoder.EncoderBase; import de.siegmar.logbackgelf.mappers.CallerDataFieldMapper; import de.siegmar.logbackgelf.mappers.MarkerFieldMapper; import de.siegmar.logbackgelf.mappers.MdcDataFieldMapper; import de.siegmar.logbackgelf.mappers.RootExceptionDataFieldMapper; import de.siegmar.logbackgelf.mappers.SimpleFieldMapper;
patternLayout.setPattern(pattern); patternLayout.start(); return patternLayout; } private void addBuiltInFieldMappers() { builtInFieldMappers.add(new SimpleFieldMapper<>(loggerNameKey, ILoggingEvent::getLoggerName)); builtInFieldMappers.add(new SimpleFieldMapper<>(threadNameKey, ILoggingEvent::getThreadName)); if (includeLevelName) { builtInFieldMappers.add(new SimpleFieldMapper<>(levelNameKey, event -> event.getLevel().toString())); } if (includeRawMessage) { builtInFieldMappers.add(new SimpleFieldMapper<>("raw_message", ILoggingEvent::getMessage)); } if (includeCallerData) { builtInFieldMappers.add(new CallerDataFieldMapper()); } if (includeRootCauseData) { builtInFieldMappers.add(new RootExceptionDataFieldMapper()); } if (includeMarker) { builtInFieldMappers.add(new MarkerFieldMapper("marker")); } if (includeMdcData) {
// Path: src/main/java/de/siegmar/logbackgelf/mappers/CallerDataFieldMapper.java // public class CallerDataFieldMapper implements GelfFieldMapper<Object> { // // @Override // public void mapField(final ILoggingEvent event, final BiConsumer<String, Object> valueHandler) { // Optional.ofNullable(event.getCallerData()) // .filter(s -> s.length > 0) // .map(s -> s[0]) // .ifPresent(first -> { // valueHandler.accept("source_file_name", first.getFileName()); // valueHandler.accept("source_method_name", first.getMethodName()); // valueHandler.accept("source_class_name", first.getClassName()); // valueHandler.accept("source_line_number", first.getLineNumber()); // }); // } // // } // // Path: src/main/java/de/siegmar/logbackgelf/mappers/MarkerFieldMapper.java // public class MarkerFieldMapper extends AbstractFixedNameFieldMapper<String> { // // public MarkerFieldMapper(final String fieldName) { // super(fieldName); // } // // @Override // protected Optional<String> getValue(final ILoggingEvent event) { // return Optional.ofNullable(event.getMarker()) // .map(MarkerFieldMapper::buildMarkerStr); // } // // private static String buildMarkerStr(final Marker marker) { // if (!marker.hasReferences()) { // return marker.getName(); // } // // final StringBuilder sb = new StringBuilder(marker.getName()); // // final Iterator<Marker> it = marker.iterator(); // do { // sb.append(", ").append(it.next().getName()); // } while (it.hasNext()); // // return sb.toString(); // } // // } // // Path: src/main/java/de/siegmar/logbackgelf/mappers/MdcDataFieldMapper.java // public class MdcDataFieldMapper implements GelfFieldMapper<String> { // // @Override // public void mapField(final ILoggingEvent event, final BiConsumer<String, String> valueHandler) { // Optional.ofNullable(event.getMDCPropertyMap()) // .ifPresent(p -> p.forEach(valueHandler)); // } // // } // // Path: src/main/java/de/siegmar/logbackgelf/mappers/RootExceptionDataFieldMapper.java // public class RootExceptionDataFieldMapper implements GelfFieldMapper<Object> { // // @Override // public void mapField(final ILoggingEvent event, final BiConsumer<String, Object> valueHandler) { // Optional.ofNullable(getRootException(event.getThrowableProxy())) // .ifPresent(rootException -> { // valueHandler.accept("root_cause_class_name", rootException.getClassName()); // valueHandler.accept("root_cause_message", rootException.getMessage()); // }); // } // // private IThrowableProxy getRootException(final IThrowableProxy throwableProxy) { // if (throwableProxy == null) { // return null; // } // // IThrowableProxy rootCause = throwableProxy; // while (rootCause.getCause() != null) { // rootCause = rootCause.getCause(); // } // // return rootCause; // } // // } // // Path: src/main/java/de/siegmar/logbackgelf/mappers/SimpleFieldMapper.java // public class SimpleFieldMapper<T> extends AbstractFixedNameFieldMapper<T> { // // private final Function<ILoggingEvent, T> valueGetter; // // public SimpleFieldMapper(final String fieldName, final Function<ILoggingEvent, T> valueGetter) { // super(fieldName); // this.valueGetter = valueGetter; // } // // @Override // protected Optional<T> getValue(final ILoggingEvent event) { // return Optional.ofNullable(valueGetter.apply(event)); // } // // } // Path: src/main/java/de/siegmar/logbackgelf/GelfEncoder.java import java.math.BigDecimal; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import ch.qos.logback.classic.PatternLayout; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.classic.util.LevelToSyslogSeverity; import ch.qos.logback.core.encoder.EncoderBase; import de.siegmar.logbackgelf.mappers.CallerDataFieldMapper; import de.siegmar.logbackgelf.mappers.MarkerFieldMapper; import de.siegmar.logbackgelf.mappers.MdcDataFieldMapper; import de.siegmar.logbackgelf.mappers.RootExceptionDataFieldMapper; import de.siegmar.logbackgelf.mappers.SimpleFieldMapper; patternLayout.setPattern(pattern); patternLayout.start(); return patternLayout; } private void addBuiltInFieldMappers() { builtInFieldMappers.add(new SimpleFieldMapper<>(loggerNameKey, ILoggingEvent::getLoggerName)); builtInFieldMappers.add(new SimpleFieldMapper<>(threadNameKey, ILoggingEvent::getThreadName)); if (includeLevelName) { builtInFieldMappers.add(new SimpleFieldMapper<>(levelNameKey, event -> event.getLevel().toString())); } if (includeRawMessage) { builtInFieldMappers.add(new SimpleFieldMapper<>("raw_message", ILoggingEvent::getMessage)); } if (includeCallerData) { builtInFieldMappers.add(new CallerDataFieldMapper()); } if (includeRootCauseData) { builtInFieldMappers.add(new RootExceptionDataFieldMapper()); } if (includeMarker) { builtInFieldMappers.add(new MarkerFieldMapper("marker")); } if (includeMdcData) {
builtInFieldMappers.add(new MdcDataFieldMapper());
Brownshome/script-wars
server/brownshome/scriptwars/site/StartupHooks.java
// Path: server/brownshome/scriptwars/server/Server.java // public class Server { // public static final Logger LOG = Logger.getLogger("brownshome.scriptwars.server"); // // private static volatile boolean stop = false; // // public static void initialize() { // try { // GameType.addType(TankGame.class, Difficulty.EASY); // } catch (GameCreationException gce) { // Server.LOG.log(Level.SEVERE, "Improperly built game files.", gce); // } // } // // public static Collection<GameType> getGames() { // return GameType.getGameTypes(); // } // // public static void shutdown() { // stop = true; // UDPConnectionHandler.instance().closeConnectionHandler(); // TCPConnectionHandler.instance().closeConnectionHandler(); // MemoryConnectionHandler.instance().closeConnectionHandler(); // } // // public static boolean shouldStop() { // return stop; // } // }
import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; import brownshome.scriptwars.server.Server;
package brownshome.scriptwars.site; @WebListener public class StartupHooks implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent sce) {
// Path: server/brownshome/scriptwars/server/Server.java // public class Server { // public static final Logger LOG = Logger.getLogger("brownshome.scriptwars.server"); // // private static volatile boolean stop = false; // // public static void initialize() { // try { // GameType.addType(TankGame.class, Difficulty.EASY); // } catch (GameCreationException gce) { // Server.LOG.log(Level.SEVERE, "Improperly built game files.", gce); // } // } // // public static Collection<GameType> getGames() { // return GameType.getGameTypes(); // } // // public static void shutdown() { // stop = true; // UDPConnectionHandler.instance().closeConnectionHandler(); // TCPConnectionHandler.instance().closeConnectionHandler(); // MemoryConnectionHandler.instance().closeConnectionHandler(); // } // // public static boolean shouldStop() { // return stop; // } // } // Path: server/brownshome/scriptwars/site/StartupHooks.java import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; import brownshome.scriptwars.server.Server; package brownshome.scriptwars.site; @WebListener public class StartupHooks implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent sce) {
Server.initialize();
Brownshome/script-wars
server/brownshome/scriptwars/game/Game.java
// Path: server/brownshome/scriptwars/server/Server.java // public class Server { // public static final Logger LOG = Logger.getLogger("brownshome.scriptwars.server"); // // private static volatile boolean stop = false; // // public static void initialize() { // try { // GameType.addType(TankGame.class, Difficulty.EASY); // } catch (GameCreationException gce) { // Server.LOG.log(Level.SEVERE, "Improperly built game files.", gce); // } // } // // public static Collection<GameType> getGames() { // return GameType.getGameTypes(); // } // // public static void shutdown() { // stop = true; // UDPConnectionHandler.instance().closeConnectionHandler(); // TCPConnectionHandler.instance().closeConnectionHandler(); // MemoryConnectionHandler.instance().closeConnectionHandler(); // } // // public static boolean shouldStop() { // return stop; // } // }
import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.function.Function; import java.util.logging.Level; import brownshome.scriptwars.connection.*; import brownshome.scriptwars.server.Server;
if(!playerIDPool.isRequested(player.getSlot())) { throw new InvalidIDException(); } playerIDPool.makeActive(player.getSlot()); players[player.getSlot()] = player; activePlayers.add(player); if(state == GameState.WAITING && !isJudgeGame) start(); if(isJudgeGame) { synchronized(this) { notifyAll(); } } onPlayerChange(); } /** This is the main method that is called from the game thread * * This method is synchronised on the game object, making it so that no network operations can occur while the game is not sleeping * * FOR INTERNAL USE ONLY */ private synchronized void gameLoop() { int tickCount = 0;
// Path: server/brownshome/scriptwars/server/Server.java // public class Server { // public static final Logger LOG = Logger.getLogger("brownshome.scriptwars.server"); // // private static volatile boolean stop = false; // // public static void initialize() { // try { // GameType.addType(TankGame.class, Difficulty.EASY); // } catch (GameCreationException gce) { // Server.LOG.log(Level.SEVERE, "Improperly built game files.", gce); // } // } // // public static Collection<GameType> getGames() { // return GameType.getGameTypes(); // } // // public static void shutdown() { // stop = true; // UDPConnectionHandler.instance().closeConnectionHandler(); // TCPConnectionHandler.instance().closeConnectionHandler(); // MemoryConnectionHandler.instance().closeConnectionHandler(); // } // // public static boolean shouldStop() { // return stop; // } // } // Path: server/brownshome/scriptwars/game/Game.java import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.function.Function; import java.util.logging.Level; import brownshome.scriptwars.connection.*; import brownshome.scriptwars.server.Server; if(!playerIDPool.isRequested(player.getSlot())) { throw new InvalidIDException(); } playerIDPool.makeActive(player.getSlot()); players[player.getSlot()] = player; activePlayers.add(player); if(state == GameState.WAITING && !isJudgeGame) start(); if(isJudgeGame) { synchronized(this) { notifyAll(); } } onPlayerChange(); } /** This is the main method that is called from the game thread * * This method is synchronised on the game object, making it so that no network operations can occur while the game is not sleeping * * FOR INTERNAL USE ONLY */ private synchronized void gameLoop() { int tickCount = 0;
while((!isFinite() || tickCount++ < lifeSpan) && !Server.shouldStop()) {
Brownshome/script-wars
server/brownshome/scriptwars/game/tanks/TankStats.java
// Path: client/java/brownshome/scriptwars/game/Player.java // public class Player<CONNECTION> { // public static final Color[] colours = { // Color.RED, // Color.GREEN, // Color.CYAN, // Color.BLUE, // Color.MAGENTA, // Color.PINK, // Color.YELLOW.darker(), // Color.BLACK, // Color.DARK_GRAY, // Color.ORANGE.darker() // }; // // private static final int TIMEOUT = 20; // // private final String name; // private final int slot; // private int missedPackets = 0; // // private final CONNECTION connection; // private final Game game; // private final ConnectionHandler<CONNECTION> connectionHandler; // // /** The time that this player joined the game */ // private final LocalTime join; // private boolean isAdded = false; // // /** The score of the player in the current game. */ // private volatile int score = 0; // // public static <CONNECTION> Player<CONNECTION> getPlayerFromID(int ID) { // int playerCode = ID & 0xff; // int gameCode = (ID >> 8) & 0xff; // // Game game = Game.getGame(gameCode); // if(game == null) return null; // return game.getPlayer(playerCode); // } // // public Player(int ID, String name, ConnectionHandler<CONNECTION> connectionHandler, CONNECTION connection) throws InvalidIDException { // int protocol = (ID >> 16) & 0xff; // int playerCode = ID & 0xff; // int gameCode = (ID >> 8) & 0xff; // // game = Game.getGame(gameCode); // this.connectionHandler = connectionHandler; // this.name = name; // this.connection = connection; // this.join = LocalTime.now().truncatedTo(ChronoUnit.SECONDS); // this.slot = playerCode; // // if(game == null) { // sendError("Invalid game slot"); // throw new InvalidIDException(); // } // // if(connectionHandler.getProtocolByte() != protocol) { // sendInvalidIDError(); // throw new InvalidIDException(); // } // } // // public int getID() { // return connectionHandler.getProtocolByte() << 16 | game.getSlot() << 8 | slot; // } // // public String getTimeJoined() { // return join.toString(); // } // // public String getName() { // return name; // } // // public int getSlot() { // return slot; // } // // public void sendData(ByteBuffer buffer) { // connectionHandler.sendData(connection, buffer); // } // // public void timeOut() { // Server.LOG.info("Player " + name + " timed out."); // silentTimeOut(); // connectionHandler.sendTimeOut(connection); // } // // /** Times out the player without sending a packet, used when the connection is terminated externally */ // public void silentTimeOut() { // removePlayer(); // } // // public void sendInvalidIDError() { // sendError(ConnectionHandler.getInvalidIDError(game)); // } // // public void sendError(String string) { // connectionHandler.sendError(connection, string); // removePlayer(); // } // // public boolean isServerSide() { // return connectionHandler instanceof MemoryConnectionHandler; // } // // public void endGame() { // connectionHandler.sendEndGame(connection); // removePlayer(); // } // // public void droppedPacket() { // if(missPacket()) { // timeOut(); // } // } // // private boolean missPacket() { // return ++missedPackets >= TIMEOUT; // } // // /** Only ever call this from one thread, the game thread */ // public void setScore(int i) { // score = i; // game.flagScores(); // } // // public int getScore() { // return score; // } // // public boolean isCorrectProtocol(int protocol) { // return connectionHandler.getProtocolByte() == protocol; // } // // public void incommingData(ByteBuffer passingBuffer) { // game.incommingData(passingBuffer, this); // } // // public ConnectionHandler<CONNECTION> getConnectionHander() { // return connectionHandler; // } // // public BufferedImage getIcon(Function<String, File> pathTranslator) throws IOException { // return game.getIcon(this, s -> pathTranslator.apply(game.getType().getName() + "/" + s)); // } // // public CONNECTION getConnection() { // return connection; // } // // public Game getGame() { // return game; // } // // public void removePlayer() { // if(isAdded) // game.removePlayer(this); // // isAdded = false; // } // // public void addPlayer() throws InvalidIDException { // assert !isAdded; // // game.addPlayer(this); // isAdded = true; // } // }
import brownshome.scriptwars.game.Player;
package brownshome.scriptwars.game.tanks; public class TankStats { private int kills = 0; private int deaths = 0; private int shotsFired = 0; private int ammoPickedUp = 0; private int movesMade = 0; private int movesFailed = 0;
// Path: client/java/brownshome/scriptwars/game/Player.java // public class Player<CONNECTION> { // public static final Color[] colours = { // Color.RED, // Color.GREEN, // Color.CYAN, // Color.BLUE, // Color.MAGENTA, // Color.PINK, // Color.YELLOW.darker(), // Color.BLACK, // Color.DARK_GRAY, // Color.ORANGE.darker() // }; // // private static final int TIMEOUT = 20; // // private final String name; // private final int slot; // private int missedPackets = 0; // // private final CONNECTION connection; // private final Game game; // private final ConnectionHandler<CONNECTION> connectionHandler; // // /** The time that this player joined the game */ // private final LocalTime join; // private boolean isAdded = false; // // /** The score of the player in the current game. */ // private volatile int score = 0; // // public static <CONNECTION> Player<CONNECTION> getPlayerFromID(int ID) { // int playerCode = ID & 0xff; // int gameCode = (ID >> 8) & 0xff; // // Game game = Game.getGame(gameCode); // if(game == null) return null; // return game.getPlayer(playerCode); // } // // public Player(int ID, String name, ConnectionHandler<CONNECTION> connectionHandler, CONNECTION connection) throws InvalidIDException { // int protocol = (ID >> 16) & 0xff; // int playerCode = ID & 0xff; // int gameCode = (ID >> 8) & 0xff; // // game = Game.getGame(gameCode); // this.connectionHandler = connectionHandler; // this.name = name; // this.connection = connection; // this.join = LocalTime.now().truncatedTo(ChronoUnit.SECONDS); // this.slot = playerCode; // // if(game == null) { // sendError("Invalid game slot"); // throw new InvalidIDException(); // } // // if(connectionHandler.getProtocolByte() != protocol) { // sendInvalidIDError(); // throw new InvalidIDException(); // } // } // // public int getID() { // return connectionHandler.getProtocolByte() << 16 | game.getSlot() << 8 | slot; // } // // public String getTimeJoined() { // return join.toString(); // } // // public String getName() { // return name; // } // // public int getSlot() { // return slot; // } // // public void sendData(ByteBuffer buffer) { // connectionHandler.sendData(connection, buffer); // } // // public void timeOut() { // Server.LOG.info("Player " + name + " timed out."); // silentTimeOut(); // connectionHandler.sendTimeOut(connection); // } // // /** Times out the player without sending a packet, used when the connection is terminated externally */ // public void silentTimeOut() { // removePlayer(); // } // // public void sendInvalidIDError() { // sendError(ConnectionHandler.getInvalidIDError(game)); // } // // public void sendError(String string) { // connectionHandler.sendError(connection, string); // removePlayer(); // } // // public boolean isServerSide() { // return connectionHandler instanceof MemoryConnectionHandler; // } // // public void endGame() { // connectionHandler.sendEndGame(connection); // removePlayer(); // } // // public void droppedPacket() { // if(missPacket()) { // timeOut(); // } // } // // private boolean missPacket() { // return ++missedPackets >= TIMEOUT; // } // // /** Only ever call this from one thread, the game thread */ // public void setScore(int i) { // score = i; // game.flagScores(); // } // // public int getScore() { // return score; // } // // public boolean isCorrectProtocol(int protocol) { // return connectionHandler.getProtocolByte() == protocol; // } // // public void incommingData(ByteBuffer passingBuffer) { // game.incommingData(passingBuffer, this); // } // // public ConnectionHandler<CONNECTION> getConnectionHander() { // return connectionHandler; // } // // public BufferedImage getIcon(Function<String, File> pathTranslator) throws IOException { // return game.getIcon(this, s -> pathTranslator.apply(game.getType().getName() + "/" + s)); // } // // public CONNECTION getConnection() { // return connection; // } // // public Game getGame() { // return game; // } // // public void removePlayer() { // if(isAdded) // game.removePlayer(this); // // isAdded = false; // } // // public void addPlayer() throws InvalidIDException { // assert !isAdded; // // game.addPlayer(this); // isAdded = true; // } // } // Path: server/brownshome/scriptwars/game/tanks/TankStats.java import brownshome.scriptwars.game.Player; package brownshome.scriptwars.game.tanks; public class TankStats { private int kills = 0; private int deaths = 0; private int shotsFired = 0; private int ammoPickedUp = 0; private int movesMade = 0; private int movesFailed = 0;
private Player<?> player;
Brownshome/script-wars
server/brownshome/scriptwars/connection/UDPConnectionHandler.java
// Path: server/brownshome/scriptwars/connection/InvalidIDException.java // public class InvalidIDException extends Exception {} // // Path: server/brownshome/scriptwars/server/Server.java // public class Server { // public static final Logger LOG = Logger.getLogger("brownshome.scriptwars.server"); // // private static volatile boolean stop = false; // // public static void initialize() { // try { // GameType.addType(TankGame.class, Difficulty.EASY); // } catch (GameCreationException gce) { // Server.LOG.log(Level.SEVERE, "Improperly built game files.", gce); // } // } // // public static Collection<GameType> getGames() { // return GameType.getGameTypes(); // } // // public static void shutdown() { // stop = true; // UDPConnectionHandler.instance().closeConnectionHandler(); // TCPConnectionHandler.instance().closeConnectionHandler(); // MemoryConnectionHandler.instance().closeConnectionHandler(); // } // // public static boolean shouldStop() { // return stop; // } // }
import java.io.IOException; import java.net.*; import java.nio.ByteBuffer; import java.nio.channels.*; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.logging.Level; import brownshome.scriptwars.connection.InvalidIDException; import brownshome.scriptwars.game.*; import brownshome.scriptwars.server.Server;
package brownshome.scriptwars.connection; /** * Communicates over UDP with the client library. Each packet received is formatted as follows. * * int: ID * var: data * * If there is no data the packet is only seen as a keepalive or the start of a connection. * */ public class UDPConnectionHandler extends ConnectionHandler<SocketAddress> { private static UDPConnectionHandler instance; public static UDPConnectionHandler instance() { if(instance == null) { instance = new UDPConnectionHandler(); } return instance; } public static final int PORT = 35565; public static final int UPD_PROTOCOL_BYTE = 1; private DatagramChannel channel; private UDPConnectionHandler() { try { channel = DatagramChannel.open(); channel.socket().bind(new InetSocketAddress(PORT)); } catch (IOException e) {
// Path: server/brownshome/scriptwars/connection/InvalidIDException.java // public class InvalidIDException extends Exception {} // // Path: server/brownshome/scriptwars/server/Server.java // public class Server { // public static final Logger LOG = Logger.getLogger("brownshome.scriptwars.server"); // // private static volatile boolean stop = false; // // public static void initialize() { // try { // GameType.addType(TankGame.class, Difficulty.EASY); // } catch (GameCreationException gce) { // Server.LOG.log(Level.SEVERE, "Improperly built game files.", gce); // } // } // // public static Collection<GameType> getGames() { // return GameType.getGameTypes(); // } // // public static void shutdown() { // stop = true; // UDPConnectionHandler.instance().closeConnectionHandler(); // TCPConnectionHandler.instance().closeConnectionHandler(); // MemoryConnectionHandler.instance().closeConnectionHandler(); // } // // public static boolean shouldStop() { // return stop; // } // } // Path: server/brownshome/scriptwars/connection/UDPConnectionHandler.java import java.io.IOException; import java.net.*; import java.nio.ByteBuffer; import java.nio.channels.*; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.logging.Level; import brownshome.scriptwars.connection.InvalidIDException; import brownshome.scriptwars.game.*; import brownshome.scriptwars.server.Server; package brownshome.scriptwars.connection; /** * Communicates over UDP with the client library. Each packet received is formatted as follows. * * int: ID * var: data * * If there is no data the packet is only seen as a keepalive or the start of a connection. * */ public class UDPConnectionHandler extends ConnectionHandler<SocketAddress> { private static UDPConnectionHandler instance; public static UDPConnectionHandler instance() { if(instance == null) { instance = new UDPConnectionHandler(); } return instance; } public static final int PORT = 35565; public static final int UPD_PROTOCOL_BYTE = 1; private DatagramChannel channel; private UDPConnectionHandler() { try { channel = DatagramChannel.open(); channel.socket().bind(new InetSocketAddress(PORT)); } catch (IOException e) {
Server.LOG.log(Level.SEVERE, "Unable to connect to port", e);
Brownshome/script-wars
server/brownshome/scriptwars/connection/UDPConnectionHandler.java
// Path: server/brownshome/scriptwars/connection/InvalidIDException.java // public class InvalidIDException extends Exception {} // // Path: server/brownshome/scriptwars/server/Server.java // public class Server { // public static final Logger LOG = Logger.getLogger("brownshome.scriptwars.server"); // // private static volatile boolean stop = false; // // public static void initialize() { // try { // GameType.addType(TankGame.class, Difficulty.EASY); // } catch (GameCreationException gce) { // Server.LOG.log(Level.SEVERE, "Improperly built game files.", gce); // } // } // // public static Collection<GameType> getGames() { // return GameType.getGameTypes(); // } // // public static void shutdown() { // stop = true; // UDPConnectionHandler.instance().closeConnectionHandler(); // TCPConnectionHandler.instance().closeConnectionHandler(); // MemoryConnectionHandler.instance().closeConnectionHandler(); // } // // public static boolean shouldStop() { // return stop; // } // }
import java.io.IOException; import java.net.*; import java.nio.ByteBuffer; import java.nio.channels.*; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.logging.Level; import brownshome.scriptwars.connection.InvalidIDException; import brownshome.scriptwars.game.*; import brownshome.scriptwars.server.Server;
@Override public void closeConnectionHandler() { try { channel.close(); } catch (IOException e) { Server.LOG.log(Level.SEVERE, "Unable to close the UDP Listener", e); } } private void listenLoop() { byte[] buffer = new byte[1024]; ByteBuffer passingBuffer = ByteBuffer.wrap(buffer); SocketAddress address = null; while(true) { boolean recieved = false; try { passingBuffer.clear(); address = channel.receive(passingBuffer); passingBuffer.flip(); recieved = true; int ID = passingBuffer.getInt(); Player<SocketAddress> player = Player.getPlayerFromID(ID); if(player == null) { try { player = new Player<>(ID, ConnectionUtil.bufferToString(passingBuffer), this, address);
// Path: server/brownshome/scriptwars/connection/InvalidIDException.java // public class InvalidIDException extends Exception {} // // Path: server/brownshome/scriptwars/server/Server.java // public class Server { // public static final Logger LOG = Logger.getLogger("brownshome.scriptwars.server"); // // private static volatile boolean stop = false; // // public static void initialize() { // try { // GameType.addType(TankGame.class, Difficulty.EASY); // } catch (GameCreationException gce) { // Server.LOG.log(Level.SEVERE, "Improperly built game files.", gce); // } // } // // public static Collection<GameType> getGames() { // return GameType.getGameTypes(); // } // // public static void shutdown() { // stop = true; // UDPConnectionHandler.instance().closeConnectionHandler(); // TCPConnectionHandler.instance().closeConnectionHandler(); // MemoryConnectionHandler.instance().closeConnectionHandler(); // } // // public static boolean shouldStop() { // return stop; // } // } // Path: server/brownshome/scriptwars/connection/UDPConnectionHandler.java import java.io.IOException; import java.net.*; import java.nio.ByteBuffer; import java.nio.channels.*; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.logging.Level; import brownshome.scriptwars.connection.InvalidIDException; import brownshome.scriptwars.game.*; import brownshome.scriptwars.server.Server; @Override public void closeConnectionHandler() { try { channel.close(); } catch (IOException e) { Server.LOG.log(Level.SEVERE, "Unable to close the UDP Listener", e); } } private void listenLoop() { byte[] buffer = new byte[1024]; ByteBuffer passingBuffer = ByteBuffer.wrap(buffer); SocketAddress address = null; while(true) { boolean recieved = false; try { passingBuffer.clear(); address = channel.receive(passingBuffer); passingBuffer.flip(); recieved = true; int ID = passingBuffer.getInt(); Player<SocketAddress> player = Player.getPlayerFromID(ID); if(player == null) { try { player = new Player<>(ID, ConnectionUtil.bufferToString(passingBuffer), this, address);
} catch(InvalidIDException pe) {
Brownshome/script-wars
client/java/brownshome/scriptwars/game/Player.java
// Path: server/brownshome/scriptwars/connection/ConnectionHandler.java // public abstract class ConnectionHandler<CONNECTION> { // protected abstract void sendRawData(CONNECTION id, ByteBuffer... data); // // public abstract int getProtocolByte(); // public abstract void closeConnectionHandler(); // // public void sendTimeOut(CONNECTION connection) { // sendRawData(connection, ByteBuffer.wrap(new byte[] {2})); // closeConnection(connection); // } // // public void sendEndGame(CONNECTION connection) { // sendRawData(connection, ByteBuffer.wrap(new byte[] {1})); // closeConnection(connection); // } // // public void sendError(CONNECTION connection, String message) { // sendRawData(connection, ByteBuffer.wrap(new byte[] {-1}), ConnectionUtil.stringToBuffer(message)); // closeConnection(connection); // } // // public void sendData(CONNECTION connection, ByteBuffer data) { // sendRawData(connection, ByteBuffer.wrap(new byte[] {0}), data); // } // // public static String getInvalidIDError(Game game) { // try { // return "That ID is old, or invalid. Here is a now valid ID " + game.getType().getUserID() // + " (This may or may not be the same ID)"; // } catch(GameCreationException e) { // return "That has not been requested. Unable to genenerate a new one."; // } // } // // protected void closeConnection(CONNECTION connection) {} // } // // Path: server/brownshome/scriptwars/connection/InvalidIDException.java // public class InvalidIDException extends Exception {} // // Path: server/brownshome/scriptwars/connection/MemoryConnectionHandler.java // public class MemoryConnectionHandler extends ConnectionHandler<SynchronousQueue<ByteBuffer>> { // private static MemoryConnectionHandler instance; // // public static MemoryConnectionHandler instance() { // if(instance == null) { // instance = new MemoryConnectionHandler(); // } // // return instance; // } // // private final int MEMORY_PROTOCOL_BYTE = 3; // // @Override // protected void sendRawData(SynchronousQueue<ByteBuffer> queue, ByteBuffer... data) { // int length = 0; // for(ByteBuffer b : data) { // length += b.remaining(); // } // ByteBuffer total = ByteBuffer.allocate(length); // for(ByteBuffer b : data) { // total.put(b); // } // total.flip(); // // //If the packet is not ready to be received drop it. // queue.offer(total); // } // // @Override // public int getProtocolByte() { // return MEMORY_PROTOCOL_BYTE; // } // // @Override // public void closeConnectionHandler() {} // // public Consumer<ByteBuffer> join(ByteBuffer firstPacket, SynchronousQueue<ByteBuffer> input) throws InvalidIDException { // int ID = firstPacket.getInt(); // // if(Player.getPlayerFromID(ID) != null) { // throw new InvalidIDException(); // } // // Player<SynchronousQueue<ByteBuffer>> player = new Player<>(ID, ConnectionUtil.bufferToString(firstPacket), this, input); // // synchronized(player.getGame()) { // player.addPlayer(); // } // // return buffer -> handleData(buffer, player); // } // // private void handleData(ByteBuffer buffer, Player<SynchronousQueue<ByteBuffer>> player) { // try { // synchronized(player.getGame()) { // player.incommingData(buffer); // } // } catch(Exception e) { // player.sendError(e.getMessage()); // } // } // } // // Path: server/brownshome/scriptwars/server/Server.java // public class Server { // public static final Logger LOG = Logger.getLogger("brownshome.scriptwars.server"); // // private static volatile boolean stop = false; // // public static void initialize() { // try { // GameType.addType(TankGame.class, Difficulty.EASY); // } catch (GameCreationException gce) { // Server.LOG.log(Level.SEVERE, "Improperly built game files.", gce); // } // } // // public static Collection<GameType> getGames() { // return GameType.getGameTypes(); // } // // public static void shutdown() { // stop = true; // UDPConnectionHandler.instance().closeConnectionHandler(); // TCPConnectionHandler.instance().closeConnectionHandler(); // MemoryConnectionHandler.instance().closeConnectionHandler(); // } // // public static boolean shouldStop() { // return stop; // } // }
import java.awt.Color; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.time.LocalTime; import java.time.temporal.ChronoUnit; import java.util.function.Function; import brownshome.scriptwars.connection.ConnectionHandler; import brownshome.scriptwars.connection.InvalidIDException; import brownshome.scriptwars.connection.MemoryConnectionHandler; import brownshome.scriptwars.server.Server;
package brownshome.scriptwars.game; //This class needs to be in the common package for compilation of uses of the Tank class. Not sure why. //Any use of this class will result in ClassNotFoundExceptions /** Holds the identifying information for each connected member. * This class is suitable for using as a key in a Map */ public class Player<CONNECTION> { public static final Color[] colours = { Color.RED, Color.GREEN, Color.CYAN, Color.BLUE, Color.MAGENTA, Color.PINK, Color.YELLOW.darker(), Color.BLACK, Color.DARK_GRAY, Color.ORANGE.darker() }; private static final int TIMEOUT = 20; private final String name; private final int slot; private int missedPackets = 0; private final CONNECTION connection; private final Game game;
// Path: server/brownshome/scriptwars/connection/ConnectionHandler.java // public abstract class ConnectionHandler<CONNECTION> { // protected abstract void sendRawData(CONNECTION id, ByteBuffer... data); // // public abstract int getProtocolByte(); // public abstract void closeConnectionHandler(); // // public void sendTimeOut(CONNECTION connection) { // sendRawData(connection, ByteBuffer.wrap(new byte[] {2})); // closeConnection(connection); // } // // public void sendEndGame(CONNECTION connection) { // sendRawData(connection, ByteBuffer.wrap(new byte[] {1})); // closeConnection(connection); // } // // public void sendError(CONNECTION connection, String message) { // sendRawData(connection, ByteBuffer.wrap(new byte[] {-1}), ConnectionUtil.stringToBuffer(message)); // closeConnection(connection); // } // // public void sendData(CONNECTION connection, ByteBuffer data) { // sendRawData(connection, ByteBuffer.wrap(new byte[] {0}), data); // } // // public static String getInvalidIDError(Game game) { // try { // return "That ID is old, or invalid. Here is a now valid ID " + game.getType().getUserID() // + " (This may or may not be the same ID)"; // } catch(GameCreationException e) { // return "That has not been requested. Unable to genenerate a new one."; // } // } // // protected void closeConnection(CONNECTION connection) {} // } // // Path: server/brownshome/scriptwars/connection/InvalidIDException.java // public class InvalidIDException extends Exception {} // // Path: server/brownshome/scriptwars/connection/MemoryConnectionHandler.java // public class MemoryConnectionHandler extends ConnectionHandler<SynchronousQueue<ByteBuffer>> { // private static MemoryConnectionHandler instance; // // public static MemoryConnectionHandler instance() { // if(instance == null) { // instance = new MemoryConnectionHandler(); // } // // return instance; // } // // private final int MEMORY_PROTOCOL_BYTE = 3; // // @Override // protected void sendRawData(SynchronousQueue<ByteBuffer> queue, ByteBuffer... data) { // int length = 0; // for(ByteBuffer b : data) { // length += b.remaining(); // } // ByteBuffer total = ByteBuffer.allocate(length); // for(ByteBuffer b : data) { // total.put(b); // } // total.flip(); // // //If the packet is not ready to be received drop it. // queue.offer(total); // } // // @Override // public int getProtocolByte() { // return MEMORY_PROTOCOL_BYTE; // } // // @Override // public void closeConnectionHandler() {} // // public Consumer<ByteBuffer> join(ByteBuffer firstPacket, SynchronousQueue<ByteBuffer> input) throws InvalidIDException { // int ID = firstPacket.getInt(); // // if(Player.getPlayerFromID(ID) != null) { // throw new InvalidIDException(); // } // // Player<SynchronousQueue<ByteBuffer>> player = new Player<>(ID, ConnectionUtil.bufferToString(firstPacket), this, input); // // synchronized(player.getGame()) { // player.addPlayer(); // } // // return buffer -> handleData(buffer, player); // } // // private void handleData(ByteBuffer buffer, Player<SynchronousQueue<ByteBuffer>> player) { // try { // synchronized(player.getGame()) { // player.incommingData(buffer); // } // } catch(Exception e) { // player.sendError(e.getMessage()); // } // } // } // // Path: server/brownshome/scriptwars/server/Server.java // public class Server { // public static final Logger LOG = Logger.getLogger("brownshome.scriptwars.server"); // // private static volatile boolean stop = false; // // public static void initialize() { // try { // GameType.addType(TankGame.class, Difficulty.EASY); // } catch (GameCreationException gce) { // Server.LOG.log(Level.SEVERE, "Improperly built game files.", gce); // } // } // // public static Collection<GameType> getGames() { // return GameType.getGameTypes(); // } // // public static void shutdown() { // stop = true; // UDPConnectionHandler.instance().closeConnectionHandler(); // TCPConnectionHandler.instance().closeConnectionHandler(); // MemoryConnectionHandler.instance().closeConnectionHandler(); // } // // public static boolean shouldStop() { // return stop; // } // } // Path: client/java/brownshome/scriptwars/game/Player.java import java.awt.Color; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.time.LocalTime; import java.time.temporal.ChronoUnit; import java.util.function.Function; import brownshome.scriptwars.connection.ConnectionHandler; import brownshome.scriptwars.connection.InvalidIDException; import brownshome.scriptwars.connection.MemoryConnectionHandler; import brownshome.scriptwars.server.Server; package brownshome.scriptwars.game; //This class needs to be in the common package for compilation of uses of the Tank class. Not sure why. //Any use of this class will result in ClassNotFoundExceptions /** Holds the identifying information for each connected member. * This class is suitable for using as a key in a Map */ public class Player<CONNECTION> { public static final Color[] colours = { Color.RED, Color.GREEN, Color.CYAN, Color.BLUE, Color.MAGENTA, Color.PINK, Color.YELLOW.darker(), Color.BLACK, Color.DARK_GRAY, Color.ORANGE.darker() }; private static final int TIMEOUT = 20; private final String name; private final int slot; private int missedPackets = 0; private final CONNECTION connection; private final Game game;
private final ConnectionHandler<CONNECTION> connectionHandler;
Brownshome/script-wars
client/java/brownshome/scriptwars/game/GridItem.java
// Path: client/java/brownshome/scriptwars/game/tanks/Coordinates.java // public class Coordinates { // private final int x; // private final int y; // // public Coordinates(int x, int y){ // this.x = x; // this.y = y; // } // // public Coordinates(Network network) { // this(network.getByte(), network.getByte()); //The execution order here is guaranteed // } // // public int getX() { // return x; // } // // public int getY() { // return y; // } // // @Override // public boolean equals(Object obj) { // if(!(obj instanceof Coordinates)) { // return false; // } // // Coordinates other = (Coordinates) obj; // // return other.x == x && other.y == y; // } // // @Override // public int hashCode() { // return x ^ (y * 31); //TODO distribute high order bits better // } // // @Override // public String toString() { // return "(" + x + ", " + y + ")"; // } // // public static Coordinates getRandom(int maxX, int maxY) { // return new Coordinates((int) (Math.random() * maxX), (int) (Math.random() * maxY)); // } // }
import brownshome.scriptwars.game.tanks.Coordinates;
package brownshome.scriptwars.game; public interface GridItem { byte code();
// Path: client/java/brownshome/scriptwars/game/tanks/Coordinates.java // public class Coordinates { // private final int x; // private final int y; // // public Coordinates(int x, int y){ // this.x = x; // this.y = y; // } // // public Coordinates(Network network) { // this(network.getByte(), network.getByte()); //The execution order here is guaranteed // } // // public int getX() { // return x; // } // // public int getY() { // return y; // } // // @Override // public boolean equals(Object obj) { // if(!(obj instanceof Coordinates)) { // return false; // } // // Coordinates other = (Coordinates) obj; // // return other.x == x && other.y == y; // } // // @Override // public int hashCode() { // return x ^ (y * 31); //TODO distribute high order bits better // } // // @Override // public String toString() { // return "(" + x + ", " + y + ")"; // } // // public static Coordinates getRandom(int maxX, int maxY) { // return new Coordinates((int) (Math.random() * maxX), (int) (Math.random() * maxY)); // } // } // Path: client/java/brownshome/scriptwars/game/GridItem.java import brownshome.scriptwars.game.tanks.Coordinates; package brownshome.scriptwars.game; public interface GridItem { byte code();
Coordinates start();
simonjrp/ESCAPE
ESCAPE/src/se/chalmers/dat255/group22/escape/adapters/CategoryAdapter.java
// Path: ESCAPE/src/se/chalmers/dat255/group22/escape/objects/Category.java // public class Category { // // private String name; // // // TODO Colors are now saved as string, change in further implementations // private String baseColor; // private String importantColor; // // Bool used in listviews. true if this category should be displayed. Note // // that this should not be saved inte database. // private boolean shouldBeDisplayed; // // /** // * Creates a new category // * // * @param name // * the category name // * @param baseColor // * the base color used for this category // * @param importantColor // */ // public Category(String name, String baseColor, String importantColor) { // this.name = name; // this.baseColor = baseColor; // this.importantColor = importantColor; // this.shouldBeDisplayed = true; // } // // /** // * @return the name // */ // public String getName() { // return name; // } // // /** // * @return the baseColor // */ // public String getBaseColor() { // return baseColor; // } // // /** // * @return the importantColor // */ // public String getImportantColor() { // return importantColor; // } // // /** // * A boolean for if this category should be displayed or not. Default value // * is true. Note that this variable should not be saved into database! // * // * @return true if category should be displayed // */ // public boolean getShouldBeDisplayed() { // return shouldBeDisplayed; // } // // /** // * @param name // * the name to set // */ // public void setName(String name) { // this.name = name; // } // // /** // * @param baseColor // * the baseColor to set // */ // public void setBaseColor(String baseColor) { // this.baseColor = baseColor; // } // // /** // * @param importantColor // * the importantColor to set // */ // public void setImportantColor(String importantColor) { // this.importantColor = importantColor; // } // // /** // * A boolean for if this category should be displayed or not. Default value // * is true. Note that this variable should not be saved into database! // * // * @param display // * true if category should be displayed // */ // public void setShouldBeDisplayed(boolean display) { // this.shouldBeDisplayed = display; // } // // /* // * (non-Javadoc) // * // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "Category [name=" + name + ", baseColor=" + baseColor // + ", importantColor=" + importantColor + "]"; // } // // /* // * (non-Javadoc) // * // * @see java.lang.Object#hashCode() // */ // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((name == null) ? 0 : name.hashCode()); // return result; // } // // /* // * (non-Javadoc) // * // * @see java.lang.Object#equals(java.lang.Object) // */ // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // Category other = (Category) obj; // if (name == null) { // if (other.name != null) { // return false; // } // } else if (!name.equals(other.name)) { // return false; // } // return true; // } // }
import java.util.ArrayList; import java.util.List; import se.chalmers.dat255.group22.escape.R; import se.chalmers.dat255.group22.escape.objects.Category; import android.content.Context; import android.database.DataSetObserver; import android.graphics.Color; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.LinearLayout; import android.widget.ListAdapter;
package se.chalmers.dat255.group22.escape.adapters; /** * An adapter for displaying checkboxes with * {@link se.chalmers.dat255.group22.escape.objects.Category}. Checkboxes are * used to set the categories shouldBeDisplayed boolean value. * * @author Carl Jansson */ public class CategoryAdapter implements ListAdapter { // The context this adapter is used in private Context context; // The tasks in the list
// Path: ESCAPE/src/se/chalmers/dat255/group22/escape/objects/Category.java // public class Category { // // private String name; // // // TODO Colors are now saved as string, change in further implementations // private String baseColor; // private String importantColor; // // Bool used in listviews. true if this category should be displayed. Note // // that this should not be saved inte database. // private boolean shouldBeDisplayed; // // /** // * Creates a new category // * // * @param name // * the category name // * @param baseColor // * the base color used for this category // * @param importantColor // */ // public Category(String name, String baseColor, String importantColor) { // this.name = name; // this.baseColor = baseColor; // this.importantColor = importantColor; // this.shouldBeDisplayed = true; // } // // /** // * @return the name // */ // public String getName() { // return name; // } // // /** // * @return the baseColor // */ // public String getBaseColor() { // return baseColor; // } // // /** // * @return the importantColor // */ // public String getImportantColor() { // return importantColor; // } // // /** // * A boolean for if this category should be displayed or not. Default value // * is true. Note that this variable should not be saved into database! // * // * @return true if category should be displayed // */ // public boolean getShouldBeDisplayed() { // return shouldBeDisplayed; // } // // /** // * @param name // * the name to set // */ // public void setName(String name) { // this.name = name; // } // // /** // * @param baseColor // * the baseColor to set // */ // public void setBaseColor(String baseColor) { // this.baseColor = baseColor; // } // // /** // * @param importantColor // * the importantColor to set // */ // public void setImportantColor(String importantColor) { // this.importantColor = importantColor; // } // // /** // * A boolean for if this category should be displayed or not. Default value // * is true. Note that this variable should not be saved into database! // * // * @param display // * true if category should be displayed // */ // public void setShouldBeDisplayed(boolean display) { // this.shouldBeDisplayed = display; // } // // /* // * (non-Javadoc) // * // * @see java.lang.Object#toString() // */ // @Override // public String toString() { // return "Category [name=" + name + ", baseColor=" + baseColor // + ", importantColor=" + importantColor + "]"; // } // // /* // * (non-Javadoc) // * // * @see java.lang.Object#hashCode() // */ // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((name == null) ? 0 : name.hashCode()); // return result; // } // // /* // * (non-Javadoc) // * // * @see java.lang.Object#equals(java.lang.Object) // */ // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // Category other = (Category) obj; // if (name == null) { // if (other.name != null) { // return false; // } // } else if (!name.equals(other.name)) { // return false; // } // return true; // } // } // Path: ESCAPE/src/se/chalmers/dat255/group22/escape/adapters/CategoryAdapter.java import java.util.ArrayList; import java.util.List; import se.chalmers.dat255.group22.escape.R; import se.chalmers.dat255.group22.escape.objects.Category; import android.content.Context; import android.database.DataSetObserver; import android.graphics.Color; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.LinearLayout; import android.widget.ListAdapter; package se.chalmers.dat255.group22.escape.adapters; /** * An adapter for displaying checkboxes with * {@link se.chalmers.dat255.group22.escape.objects.Category}. Checkboxes are * used to set the categories shouldBeDisplayed boolean value. * * @author Carl Jansson */ public class CategoryAdapter implements ListAdapter { // The context this adapter is used in private Context context; // The tasks in the list
private List<Category> theCategories;
simonjrp/ESCAPE
ESCAPE/src/se/chalmers/dat255/group22/escape/utils/GetPlaces.java
// Path: ESCAPE/src/se/chalmers/dat255/group22/escape/utils/Constants.java // public static final String APPTAG = "ESCAPE";
import static se.chalmers.dat255.group22.escape.utils.Constants.APPTAG; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Locale; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import se.chalmers.dat255.group22.escape.R; import android.content.Context; import android.os.AsyncTask; import android.util.Log; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView;
package se.chalmers.dat255.group22.escape.utils; /** * @author tholene */ public class GetPlaces extends AsyncTask<String, Void, ArrayList<String>> { private AutoCompleteTextView autoCompleteTextView; private ArrayAdapter<String> adapter; private Context context; public GetPlaces(AutoCompleteTextView autoCompleteTextView, ArrayAdapter<String> adapter, Context context) { this.autoCompleteTextView = autoCompleteTextView; this.adapter = adapter; this.context = context; } @Override // three dots is java for an array of strings protected ArrayList<String> doInBackground(String... args) {
// Path: ESCAPE/src/se/chalmers/dat255/group22/escape/utils/Constants.java // public static final String APPTAG = "ESCAPE"; // Path: ESCAPE/src/se/chalmers/dat255/group22/escape/utils/GetPlaces.java import static se.chalmers.dat255.group22.escape.utils.Constants.APPTAG; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Locale; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import se.chalmers.dat255.group22.escape.R; import android.content.Context; import android.os.AsyncTask; import android.util.Log; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; package se.chalmers.dat255.group22.escape.utils; /** * @author tholene */ public class GetPlaces extends AsyncTask<String, Void, ArrayList<String>> { private AutoCompleteTextView autoCompleteTextView; private ArrayAdapter<String> adapter; private Context context; public GetPlaces(AutoCompleteTextView autoCompleteTextView, ArrayAdapter<String> adapter, Context context) { this.autoCompleteTextView = autoCompleteTextView; this.adapter = adapter; this.context = context; } @Override // three dots is java for an array of strings protected ArrayList<String> doInBackground(String... args) {
Log.d(APPTAG, "doInBackground");
simonjrp/ESCAPE
ESCAPE_Test/src/se/chalmers/dat255/group22/escape/test/TestCheckDateUtils.java
// Path: ESCAPE/src/se/chalmers/dat255/group22/escape/utils/CheckDateUtils.java // public class CheckDateUtils { // // /** // * Method to check if a date is today. Also returns true if the date is // * earlier than today // * // * @param theDate // * the date to see if it is today // * @return true if theDate is today or earlier // */ // public static boolean isToday(Date theDate) { // // Get a calendar with the events start time // GregorianCalendar theCalendar = new GregorianCalendar(); // theCalendar.setTime(theDate); // // Get a calendar with current system time to compare with // Calendar systemCalendar = Calendar.getInstance(); // // If it should return true only if today and not before use == instead // // of >= // return systemCalendar.get(Calendar.YEAR) >= theCalendar // .get(Calendar.YEAR) // && systemCalendar.get(Calendar.DAY_OF_YEAR) >= theCalendar // .get(Calendar.DAY_OF_YEAR); // } // // /** // * Method to check if a date is tomorrow // * // * @param theDate // * the date to see if it is tomorrow // * @return true of it is tomorrow // */ // public static boolean isTomorrow(Date theDate) { // // Get a calendar with the events start time // GregorianCalendar theCalendar = new GregorianCalendar(); // theCalendar.setTime(theDate); // // Get a calendar with current system time and change its value so it // // can be used in comparison with the given date. // Calendar tmpDate = Calendar.getInstance(); // tmpDate.roll(Calendar.DAY_OF_YEAR, true); // // return tmpDate.get(Calendar.YEAR) == theCalendar.get(Calendar.YEAR) // && tmpDate.get(Calendar.DAY_OF_YEAR) == theCalendar // .get(Calendar.DAY_OF_YEAR); // } // // /** // * Method to check if a date is this week. Note that it checks if it is this // * week and not 7 days ahead! // * // * @param theDate // * the date to see if it is this week // * @return true if it is this week // */ // public static boolean isThisWeek(Date theDate) { // // Get a calendar with the events start time // GregorianCalendar theCalendar = new GregorianCalendar(); // theCalendar.setTime(theDate); // // Get a calendar with current system time // Calendar tmpDate = Calendar.getInstance(); // // return tmpDate.get(Calendar.YEAR) == theCalendar.get(Calendar.YEAR) // && tmpDate.get(Calendar.WEEK_OF_YEAR) == theCalendar // .get(Calendar.WEEK_OF_YEAR); // } // // /** // * Method to see if a date has already passed. the time of the day has no // * relevance. // * // * @param theDate // * the date to see if it has passed // * @return true if the date has passed // */ // public static boolean dateHasPassed(Date theDate) { // // Get a calendar with the events start time // GregorianCalendar theCalendar = new GregorianCalendar(); // theCalendar.setTime(theDate); // // Get a calendar with current system time to compare with // Calendar systemCalendar = Calendar.getInstance(); // // If it should return true only if today and not before use == instead // // of >= // return systemCalendar.get(Calendar.YEAR) > theCalendar // .get(Calendar.YEAR) // || (systemCalendar.get(Calendar.YEAR) == theCalendar // .get(Calendar.YEAR) && systemCalendar // .get(Calendar.DAY_OF_YEAR) > theCalendar // .get(Calendar.DAY_OF_YEAR)); // } // }
import static org.junit.Assert.assertEquals; import java.sql.Date; import java.util.Calendar; import org.junit.BeforeClass; import org.junit.Test; import se.chalmers.dat255.group22.escape.utils.CheckDateUtils;
case Calendar.TUESDAY: firstDayInWeek = yesterday; lastDayInWeek = new Date(tmpDate.getTimeInMillis()+5*DAYINMILLIS); break; case Calendar.WEDNESDAY: firstDayInWeek = new Date(tmpDate.getTimeInMillis()-2*DAYINMILLIS); lastDayInWeek = new Date(tmpDate.getTimeInMillis()+4*DAYINMILLIS); break; case Calendar.THURSDAY: firstDayInWeek = new Date(tmpDate.getTimeInMillis()-3*DAYINMILLIS); lastDayInWeek = new Date(tmpDate.getTimeInMillis()+3*DAYINMILLIS); break; case Calendar.FRIDAY: firstDayInWeek = new Date(tmpDate.getTimeInMillis()-4*DAYINMILLIS); lastDayInWeek = new Date(tmpDate.getTimeInMillis()+2*DAYINMILLIS); break; case Calendar.SATURDAY: firstDayInWeek = new Date(tmpDate.getTimeInMillis()-5*DAYINMILLIS); lastDayInWeek = tomorrow; break; case Calendar.SUNDAY: firstDayInWeek = new Date(tmpDate.getTimeInMillis()-6*DAYINMILLIS); lastDayInWeek = today; break; } } @Test public void testIsToday() { // yesterday should be true!
// Path: ESCAPE/src/se/chalmers/dat255/group22/escape/utils/CheckDateUtils.java // public class CheckDateUtils { // // /** // * Method to check if a date is today. Also returns true if the date is // * earlier than today // * // * @param theDate // * the date to see if it is today // * @return true if theDate is today or earlier // */ // public static boolean isToday(Date theDate) { // // Get a calendar with the events start time // GregorianCalendar theCalendar = new GregorianCalendar(); // theCalendar.setTime(theDate); // // Get a calendar with current system time to compare with // Calendar systemCalendar = Calendar.getInstance(); // // If it should return true only if today and not before use == instead // // of >= // return systemCalendar.get(Calendar.YEAR) >= theCalendar // .get(Calendar.YEAR) // && systemCalendar.get(Calendar.DAY_OF_YEAR) >= theCalendar // .get(Calendar.DAY_OF_YEAR); // } // // /** // * Method to check if a date is tomorrow // * // * @param theDate // * the date to see if it is tomorrow // * @return true of it is tomorrow // */ // public static boolean isTomorrow(Date theDate) { // // Get a calendar with the events start time // GregorianCalendar theCalendar = new GregorianCalendar(); // theCalendar.setTime(theDate); // // Get a calendar with current system time and change its value so it // // can be used in comparison with the given date. // Calendar tmpDate = Calendar.getInstance(); // tmpDate.roll(Calendar.DAY_OF_YEAR, true); // // return tmpDate.get(Calendar.YEAR) == theCalendar.get(Calendar.YEAR) // && tmpDate.get(Calendar.DAY_OF_YEAR) == theCalendar // .get(Calendar.DAY_OF_YEAR); // } // // /** // * Method to check if a date is this week. Note that it checks if it is this // * week and not 7 days ahead! // * // * @param theDate // * the date to see if it is this week // * @return true if it is this week // */ // public static boolean isThisWeek(Date theDate) { // // Get a calendar with the events start time // GregorianCalendar theCalendar = new GregorianCalendar(); // theCalendar.setTime(theDate); // // Get a calendar with current system time // Calendar tmpDate = Calendar.getInstance(); // // return tmpDate.get(Calendar.YEAR) == theCalendar.get(Calendar.YEAR) // && tmpDate.get(Calendar.WEEK_OF_YEAR) == theCalendar // .get(Calendar.WEEK_OF_YEAR); // } // // /** // * Method to see if a date has already passed. the time of the day has no // * relevance. // * // * @param theDate // * the date to see if it has passed // * @return true if the date has passed // */ // public static boolean dateHasPassed(Date theDate) { // // Get a calendar with the events start time // GregorianCalendar theCalendar = new GregorianCalendar(); // theCalendar.setTime(theDate); // // Get a calendar with current system time to compare with // Calendar systemCalendar = Calendar.getInstance(); // // If it should return true only if today and not before use == instead // // of >= // return systemCalendar.get(Calendar.YEAR) > theCalendar // .get(Calendar.YEAR) // || (systemCalendar.get(Calendar.YEAR) == theCalendar // .get(Calendar.YEAR) && systemCalendar // .get(Calendar.DAY_OF_YEAR) > theCalendar // .get(Calendar.DAY_OF_YEAR)); // } // } // Path: ESCAPE_Test/src/se/chalmers/dat255/group22/escape/test/TestCheckDateUtils.java import static org.junit.Assert.assertEquals; import java.sql.Date; import java.util.Calendar; import org.junit.BeforeClass; import org.junit.Test; import se.chalmers.dat255.group22.escape.utils.CheckDateUtils; case Calendar.TUESDAY: firstDayInWeek = yesterday; lastDayInWeek = new Date(tmpDate.getTimeInMillis()+5*DAYINMILLIS); break; case Calendar.WEDNESDAY: firstDayInWeek = new Date(tmpDate.getTimeInMillis()-2*DAYINMILLIS); lastDayInWeek = new Date(tmpDate.getTimeInMillis()+4*DAYINMILLIS); break; case Calendar.THURSDAY: firstDayInWeek = new Date(tmpDate.getTimeInMillis()-3*DAYINMILLIS); lastDayInWeek = new Date(tmpDate.getTimeInMillis()+3*DAYINMILLIS); break; case Calendar.FRIDAY: firstDayInWeek = new Date(tmpDate.getTimeInMillis()-4*DAYINMILLIS); lastDayInWeek = new Date(tmpDate.getTimeInMillis()+2*DAYINMILLIS); break; case Calendar.SATURDAY: firstDayInWeek = new Date(tmpDate.getTimeInMillis()-5*DAYINMILLIS); lastDayInWeek = tomorrow; break; case Calendar.SUNDAY: firstDayInWeek = new Date(tmpDate.getTimeInMillis()-6*DAYINMILLIS); lastDayInWeek = today; break; } } @Test public void testIsToday() { // yesterday should be true!
assertEquals(true, CheckDateUtils.isToday(yesterday));
Slikey/EffectLib
src/main/java/de/slikey/effectlib/math/SequenceTransform.java
// Path: src/main/java/de/slikey/effectlib/util/ConfigUtils.java // public class ConfigUtils { // public static Collection<ConfigurationSection> getNodeList(ConfigurationSection node, String path) { // Collection<ConfigurationSection> results = new ArrayList<ConfigurationSection>(); // List<Map<?, ?>> mapList = node.getMapList(path); // for (Map<?, ?> map : mapList) { // results.add(toConfigurationSection(map)); // } // // return results; // } // // @Deprecated // public static ConfigurationSection toNodeList(Map<?, ?> nodeMap) { // return toConfigurationSection(nodeMap); // } // // public static ConfigurationSection toConfigurationSection(Map<?, ?> nodeMap) { // ConfigurationSection newSection = new MemoryConfiguration(); // for (Map.Entry<?, ?> entry : nodeMap.entrySet()) { // set(newSection, entry.getKey().toString(), entry.getValue()); // } // // return newSection; // } // // public static ConfigurationSection toStringConfiguration(Map<String, String> stringMap) { // if (stringMap == null) { // return null; // } // ConfigurationSection configMap = new MemoryConfiguration(); // for (Map.Entry<String, String> entry : stringMap.entrySet()) { // configMap.set(entry.getKey(), entry.getValue()); // } // // return configMap; // } // // // public static void set(ConfigurationSection node, String path, Object value) // { // if (value == null) { // node.set(path, null); // return; // } // // boolean isTrue = value.equals("true"); // boolean isFalse = value.equals("false"); // if (isTrue || isFalse) { // node.set(path, isTrue); // } else { // try { // Integer i = (value instanceof Integer) ? (Integer)value : Integer.parseInt(value.toString()); // node.set(path, i); // } catch (Exception ex) { // try { // Double d; // if (value instanceof Double) { // d = (Double)value; // } else if (value instanceof Float) { // d = (double)(Float)value; // } else { // d = Double.parseDouble(value.toString()); // } // node.set(path, d); // } catch (Exception ex2) { // node.set(path, value); // } // } // } // } // // public static ConfigurationSection getConfigurationSection(ConfigurationSection base, String key) // { // ConfigurationSection section = base.getConfigurationSection(key); // if (section != null) { // return section; // } // Object value = base.get(key); // if (value == null) return null; // // if (value instanceof ConfigurationSection) // { // return (ConfigurationSection)value; // } // // if (value instanceof Map) // { // ConfigurationSection newChild = base.createSection(key); // @SuppressWarnings("unchecked") // Map<String, Object> map = (Map<String, Object>)value; // for (Map.Entry<String, Object> entry : map.entrySet()) // { // newChild.set(entry.getKey(), entry.getValue()); // } // base.set(key, newChild); // return newChild; // } // // return null; // } // // public static boolean isMaxValue(String stringValue) { // return stringValue.equalsIgnoreCase("infinite") // || stringValue.equalsIgnoreCase("forever") // || stringValue.equalsIgnoreCase("infinity") // || stringValue.equalsIgnoreCase("max"); // } // }
import de.slikey.effectlib.util.ConfigUtils; import org.bukkit.configuration.ConfigurationSection; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List;
package de.slikey.effectlib.math; public class SequenceTransform implements Transform { private List<Sequence> steps; private static class Sequence { private final Transform transform; private final double start; public Sequence(ConfigurationSection configuration) { this.transform = Transforms.loadTransform(configuration, "transform"); this.start = configuration.getDouble("start", 0); } public double getStart() { return start; } public double get(double t) { return transform.get(t); } }; @Override public void load(ConfigurationSection parameters) { steps = new ArrayList<Sequence>();
// Path: src/main/java/de/slikey/effectlib/util/ConfigUtils.java // public class ConfigUtils { // public static Collection<ConfigurationSection> getNodeList(ConfigurationSection node, String path) { // Collection<ConfigurationSection> results = new ArrayList<ConfigurationSection>(); // List<Map<?, ?>> mapList = node.getMapList(path); // for (Map<?, ?> map : mapList) { // results.add(toConfigurationSection(map)); // } // // return results; // } // // @Deprecated // public static ConfigurationSection toNodeList(Map<?, ?> nodeMap) { // return toConfigurationSection(nodeMap); // } // // public static ConfigurationSection toConfigurationSection(Map<?, ?> nodeMap) { // ConfigurationSection newSection = new MemoryConfiguration(); // for (Map.Entry<?, ?> entry : nodeMap.entrySet()) { // set(newSection, entry.getKey().toString(), entry.getValue()); // } // // return newSection; // } // // public static ConfigurationSection toStringConfiguration(Map<String, String> stringMap) { // if (stringMap == null) { // return null; // } // ConfigurationSection configMap = new MemoryConfiguration(); // for (Map.Entry<String, String> entry : stringMap.entrySet()) { // configMap.set(entry.getKey(), entry.getValue()); // } // // return configMap; // } // // // public static void set(ConfigurationSection node, String path, Object value) // { // if (value == null) { // node.set(path, null); // return; // } // // boolean isTrue = value.equals("true"); // boolean isFalse = value.equals("false"); // if (isTrue || isFalse) { // node.set(path, isTrue); // } else { // try { // Integer i = (value instanceof Integer) ? (Integer)value : Integer.parseInt(value.toString()); // node.set(path, i); // } catch (Exception ex) { // try { // Double d; // if (value instanceof Double) { // d = (Double)value; // } else if (value instanceof Float) { // d = (double)(Float)value; // } else { // d = Double.parseDouble(value.toString()); // } // node.set(path, d); // } catch (Exception ex2) { // node.set(path, value); // } // } // } // } // // public static ConfigurationSection getConfigurationSection(ConfigurationSection base, String key) // { // ConfigurationSection section = base.getConfigurationSection(key); // if (section != null) { // return section; // } // Object value = base.get(key); // if (value == null) return null; // // if (value instanceof ConfigurationSection) // { // return (ConfigurationSection)value; // } // // if (value instanceof Map) // { // ConfigurationSection newChild = base.createSection(key); // @SuppressWarnings("unchecked") // Map<String, Object> map = (Map<String, Object>)value; // for (Map.Entry<String, Object> entry : map.entrySet()) // { // newChild.set(entry.getKey(), entry.getValue()); // } // base.set(key, newChild); // return newChild; // } // // return null; // } // // public static boolean isMaxValue(String stringValue) { // return stringValue.equalsIgnoreCase("infinite") // || stringValue.equalsIgnoreCase("forever") // || stringValue.equalsIgnoreCase("infinity") // || stringValue.equalsIgnoreCase("max"); // } // } // Path: src/main/java/de/slikey/effectlib/math/SequenceTransform.java import de.slikey.effectlib.util.ConfigUtils; import org.bukkit.configuration.ConfigurationSection; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; package de.slikey.effectlib.math; public class SequenceTransform implements Transform { private List<Sequence> steps; private static class Sequence { private final Transform transform; private final double start; public Sequence(ConfigurationSection configuration) { this.transform = Transforms.loadTransform(configuration, "transform"); this.start = configuration.getDouble("start", 0); } public double getStart() { return start; } public double get(double t) { return transform.get(t); } }; @Override public void load(ConfigurationSection parameters) { steps = new ArrayList<Sequence>();
Collection<ConfigurationSection> stepConfigurations = ConfigUtils.getNodeList(parameters, "steps");
Slikey/EffectLib
src/main/java/de/slikey/effectlib/math/VectorTransform.java
// Path: src/main/java/de/slikey/effectlib/util/VectorUtils.java // public final class VectorUtils { // // private VectorUtils() { // } // // public static final Vector rotateAroundAxisX(Vector v, double angle) { // double y, z, cos, sin; // cos = Math.cos(angle); // sin = Math.sin(angle); // y = v.getY() * cos - v.getZ() * sin; // z = v.getY() * sin + v.getZ() * cos; // return v.setY(y).setZ(z); // } // // public static final Vector rotateAroundAxisY(Vector v, double angle) { // double x, z, cos, sin; // cos = Math.cos(angle); // sin = Math.sin(angle); // x = v.getX() * cos + v.getZ() * sin; // z = v.getX() * -sin + v.getZ() * cos; // return v.setX(x).setZ(z); // } // // public static final Vector rotateAroundAxisZ(Vector v, double angle) { // double x, y, cos, sin; // cos = Math.cos(angle); // sin = Math.sin(angle); // x = v.getX() * cos - v.getY() * sin; // y = v.getX() * sin + v.getY() * cos; // return v.setX(x).setY(y); // } // // public static final Vector rotateVector(Vector v, double angleX, double angleY, double angleZ) { // // double x = v.getX(), y = v.getY(), z = v.getZ(); // // double cosX = Math.cos(angleX), sinX = Math.sin(angleX), cosY = // // Math.cos(angleY), sinY = Math.sin(angleY), cosZ = Math.cos(angleZ), // // sinZ = Math.sin(angleZ); // // double nx, ny, nz; // // nx = (x * cosY + z * sinY) * (x * cosZ - y * sinZ); // // ny = (y * cosX - z * sinX) * (x * sinZ + y * cosZ); // // nz = (y * sinX + z * cosX) * (-x * sinY + z * cosY); // // return v.setX(nx).setY(ny).setZ(nz); // // Having some strange behavior up there.. Have to look in it later. TODO // rotateAroundAxisX(v, angleX); // rotateAroundAxisY(v, angleY); // rotateAroundAxisZ(v, angleZ); // return v; // } // // /** // * Rotate a vector about a location using that location's direction // * // * @param v // * @param location // * @return // */ // public static final Vector rotateVector(Vector v, Location location) { // return rotateVector(v, location.getYaw(), location.getPitch()); // } // // /** // * This handles non-unit vectors, with yaw and pitch instead of X,Y,Z angles. // * // * Thanks to SexyToad! // * // * @param v // * @param yawDegrees // * @param pitchDegrees // * @return // */ // public static final Vector rotateVector(Vector v, float yawDegrees, float pitchDegrees) { // double yaw = Math.toRadians(-1 * (yawDegrees + 90)); // double pitch = Math.toRadians(-pitchDegrees); // // double cosYaw = Math.cos(yaw); // double cosPitch = Math.cos(pitch); // double sinYaw = Math.sin(yaw); // double sinPitch = Math.sin(pitch); // // double initialX, initialY, initialZ; // double x, y, z; // // // Z_Axis rotation (Pitch) // initialX = v.getX(); // initialY = v.getY(); // x = initialX * cosPitch - initialY * sinPitch; // y = initialX * sinPitch + initialY * cosPitch; // // // Y_Axis rotation (Yaw) // initialZ = v.getZ(); // initialX = x; // z = initialZ * cosYaw - initialX * sinYaw; // x = initialZ * sinYaw + initialX * cosYaw; // // return new Vector(x, y, z); // } // // public static final double angleToXAxis(Vector vector) { // return Math.atan2(vector.getX(), vector.getY()); // } // }
import de.slikey.effectlib.util.VectorUtils; import org.bukkit.Location; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.util.Vector;
package de.slikey.effectlib.math; public class VectorTransform { private Transform xTransform; private Transform yTransform; private Transform zTransform; private boolean orient; public VectorTransform(ConfigurationSection configuration) { xTransform = Transforms.loadTransform(configuration, "x"); yTransform = Transforms.loadTransform(configuration, "y"); zTransform = Transforms.loadTransform(configuration, "z"); orient = configuration.getBoolean("orient", true); } public Vector get(Location source, double t) { // This returns a unit vector with the new direction calculated via the equations Double xValue = xTransform.get(t); Double yValue = yTransform.get(t); Double zValue = zTransform.get(t); Vector result = new Vector(xValue, yValue, zValue); // Rotates to player's direction if (orient && source != null) {
// Path: src/main/java/de/slikey/effectlib/util/VectorUtils.java // public final class VectorUtils { // // private VectorUtils() { // } // // public static final Vector rotateAroundAxisX(Vector v, double angle) { // double y, z, cos, sin; // cos = Math.cos(angle); // sin = Math.sin(angle); // y = v.getY() * cos - v.getZ() * sin; // z = v.getY() * sin + v.getZ() * cos; // return v.setY(y).setZ(z); // } // // public static final Vector rotateAroundAxisY(Vector v, double angle) { // double x, z, cos, sin; // cos = Math.cos(angle); // sin = Math.sin(angle); // x = v.getX() * cos + v.getZ() * sin; // z = v.getX() * -sin + v.getZ() * cos; // return v.setX(x).setZ(z); // } // // public static final Vector rotateAroundAxisZ(Vector v, double angle) { // double x, y, cos, sin; // cos = Math.cos(angle); // sin = Math.sin(angle); // x = v.getX() * cos - v.getY() * sin; // y = v.getX() * sin + v.getY() * cos; // return v.setX(x).setY(y); // } // // public static final Vector rotateVector(Vector v, double angleX, double angleY, double angleZ) { // // double x = v.getX(), y = v.getY(), z = v.getZ(); // // double cosX = Math.cos(angleX), sinX = Math.sin(angleX), cosY = // // Math.cos(angleY), sinY = Math.sin(angleY), cosZ = Math.cos(angleZ), // // sinZ = Math.sin(angleZ); // // double nx, ny, nz; // // nx = (x * cosY + z * sinY) * (x * cosZ - y * sinZ); // // ny = (y * cosX - z * sinX) * (x * sinZ + y * cosZ); // // nz = (y * sinX + z * cosX) * (-x * sinY + z * cosY); // // return v.setX(nx).setY(ny).setZ(nz); // // Having some strange behavior up there.. Have to look in it later. TODO // rotateAroundAxisX(v, angleX); // rotateAroundAxisY(v, angleY); // rotateAroundAxisZ(v, angleZ); // return v; // } // // /** // * Rotate a vector about a location using that location's direction // * // * @param v // * @param location // * @return // */ // public static final Vector rotateVector(Vector v, Location location) { // return rotateVector(v, location.getYaw(), location.getPitch()); // } // // /** // * This handles non-unit vectors, with yaw and pitch instead of X,Y,Z angles. // * // * Thanks to SexyToad! // * // * @param v // * @param yawDegrees // * @param pitchDegrees // * @return // */ // public static final Vector rotateVector(Vector v, float yawDegrees, float pitchDegrees) { // double yaw = Math.toRadians(-1 * (yawDegrees + 90)); // double pitch = Math.toRadians(-pitchDegrees); // // double cosYaw = Math.cos(yaw); // double cosPitch = Math.cos(pitch); // double sinYaw = Math.sin(yaw); // double sinPitch = Math.sin(pitch); // // double initialX, initialY, initialZ; // double x, y, z; // // // Z_Axis rotation (Pitch) // initialX = v.getX(); // initialY = v.getY(); // x = initialX * cosPitch - initialY * sinPitch; // y = initialX * sinPitch + initialY * cosPitch; // // // Y_Axis rotation (Yaw) // initialZ = v.getZ(); // initialX = x; // z = initialZ * cosYaw - initialX * sinYaw; // x = initialZ * sinYaw + initialX * cosYaw; // // return new Vector(x, y, z); // } // // public static final double angleToXAxis(Vector vector) { // return Math.atan2(vector.getX(), vector.getY()); // } // } // Path: src/main/java/de/slikey/effectlib/math/VectorTransform.java import de.slikey.effectlib.util.VectorUtils; import org.bukkit.Location; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.util.Vector; package de.slikey.effectlib.math; public class VectorTransform { private Transform xTransform; private Transform yTransform; private Transform zTransform; private boolean orient; public VectorTransform(ConfigurationSection configuration) { xTransform = Transforms.loadTransform(configuration, "x"); yTransform = Transforms.loadTransform(configuration, "y"); zTransform = Transforms.loadTransform(configuration, "z"); orient = configuration.getBoolean("orient", true); } public Vector get(Location source, double t) { // This returns a unit vector with the new direction calculated via the equations Double xValue = xTransform.get(t); Double yValue = yTransform.get(t); Double zValue = zTransform.get(t); Vector result = new Vector(xValue, yValue, zValue); // Rotates to player's direction if (orient && source != null) {
result = VectorUtils.rotateVector(result, source);
jwoolston/Android-Webcam
library/src/main/java/com/jwoolston/android/uvc/interfaces/streaming/UncompressedVideoFormat.java
// Path: library/src/main/java/com/jwoolston/android/uvc/util/Hexdump.java // public class Hexdump { // private final static char[] HEX_DIGITS = { // '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' // }; // // public static String dumpHexString(byte[] array) { // return dumpHexString(array, 0, array.length); // } // // public static String dumpHexString(byte[] array, int offset, int length) { // StringBuilder result = new StringBuilder(); // // byte[] line = new byte[16]; // int lineIndex = 0; // // result.append("\n0x"); // result.append(toHexString(offset)); // // for (int i = offset; i < offset + length; i++) { // if (lineIndex == 16) { // result.append(" "); // // for (int j = 0; j < 16; j++) { // if (line[j] > ' ' && line[j] < '~') { // result.append(new String(line, j, 1)); // } else { // result.append("."); // } // } // // result.append("\n0x"); // result.append(toHexString(i)); // lineIndex = 0; // } // // byte b = array[i]; // result.append(" "); // result.append(HEX_DIGITS[(b >>> 4) & 0x0F]); // result.append(HEX_DIGITS[b & 0x0F]); // // line[lineIndex++] = b; // } // // if (lineIndex != 16) { // int count = (16 - lineIndex) * 3; // count++; // for (int i = 0; i < count; i++) { // result.append(" "); // } // // for (int i = 0; i < lineIndex; i++) { // if (line[i] > ' ' && line[i] < '~') { // result.append(new String(line, i, 1)); // } else { // result.append("."); // } // } // } // // return result.toString(); // } // // public static String toHexString(byte b) { // return toHexString(toByteArray(b)); // } // // public static String toHexString(byte[] array) { // return toHexString(array, 0, array.length); // } // // public static String toHexString(byte[] array, int offset, int length) { // char[] buf = new char[length * 2]; // // int bufIndex = 0; // for (int i = offset; i < offset + length; i++) { // byte b = array[i]; // buf[bufIndex++] = HEX_DIGITS[(b >>> 4) & 0x0F]; // buf[bufIndex++] = HEX_DIGITS[b & 0x0F]; // } // // return new String(buf); // } // // public static String toHexString(int i) { // return toHexString(toByteArray(i)); // } // // public static byte[] toByteArray(byte b) { // byte[] array = new byte[1]; // array[0] = b; // return array; // } // // public static byte[] toByteArray(int i) { // byte[] array = new byte[4]; // // array[3] = (byte) (i & 0xFF); // array[2] = (byte) ((i >> 8) & 0xFF); // array[1] = (byte) ((i >> 16) & 0xFF); // array[0] = (byte) ((i >> 24) & 0xFF); // // return array; // } // // private static int toByte(char c) { // if (c >= '0' && c <= '9') // return (c - '0'); // if (c >= 'A' && c <= 'F') // return (c - 'A' + 10); // if (c >= 'a' && c <= 'f') // return (c - 'a' + 10); // // throw new RuntimeException("Invalid hex char '" + c + "'"); // } // // public static byte[] hexStringToByteArray(String hexString) { // int length = hexString.length(); // byte[] buffer = new byte[length / 2]; // // for (int i = 0; i < length; i += 2) { // buffer[i / 2] = (byte) ((toByte(hexString.charAt(i)) << 4) | toByte(hexString // .charAt(i + 1))); // } // // return buffer; // } // }
import android.support.annotation.NonNull; import com.jwoolston.android.uvc.util.Hexdump; import timber.log.Timber;
private static final int bmInterlaceFlags = 25; private static final int bCopyProtect = 26; private final String guid; private final int bitsPerPixel; public void addUncompressedVideoFrame(@NonNull UncompressedVideoFrame frame) { Timber.d("Adding video frame: %s", frame); videoFrames.add(frame); } public UncompressedVideoFormat(@NonNull byte[] descriptor) throws IllegalArgumentException { super(descriptor); if (descriptor.length < LENGTH) { throw new IllegalArgumentException( "The provided discriptor is not long enough for an Uncompressed Video Format."); } formatIndex = (0xFF & descriptor[bFormatIndex]); numberFrames = (0xFF & descriptor[bNumFrameDescriptors]); byte[] GUIDBytes = new byte[16]; System.arraycopy(descriptor, guidFormat, GUIDBytes, 0, GUIDBytes.length); bitsPerPixel = (0xFF & descriptor[bBitsPerPixel]); defaultFrameIndex = (0xFF & descriptor[bDefaultFrameIndex]); aspectRatioX = (0xFF & descriptor[bAspectRatioX]); aspectRatioY = (0xFF & descriptor[bAspectRatioY]); interlaceFlags = descriptor[bmInterlaceFlags]; copyProtect = descriptor[bCopyProtect] != 0; // Parse the GUID bytes to String final StringBuilder builder = new StringBuilder();
// Path: library/src/main/java/com/jwoolston/android/uvc/util/Hexdump.java // public class Hexdump { // private final static char[] HEX_DIGITS = { // '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' // }; // // public static String dumpHexString(byte[] array) { // return dumpHexString(array, 0, array.length); // } // // public static String dumpHexString(byte[] array, int offset, int length) { // StringBuilder result = new StringBuilder(); // // byte[] line = new byte[16]; // int lineIndex = 0; // // result.append("\n0x"); // result.append(toHexString(offset)); // // for (int i = offset; i < offset + length; i++) { // if (lineIndex == 16) { // result.append(" "); // // for (int j = 0; j < 16; j++) { // if (line[j] > ' ' && line[j] < '~') { // result.append(new String(line, j, 1)); // } else { // result.append("."); // } // } // // result.append("\n0x"); // result.append(toHexString(i)); // lineIndex = 0; // } // // byte b = array[i]; // result.append(" "); // result.append(HEX_DIGITS[(b >>> 4) & 0x0F]); // result.append(HEX_DIGITS[b & 0x0F]); // // line[lineIndex++] = b; // } // // if (lineIndex != 16) { // int count = (16 - lineIndex) * 3; // count++; // for (int i = 0; i < count; i++) { // result.append(" "); // } // // for (int i = 0; i < lineIndex; i++) { // if (line[i] > ' ' && line[i] < '~') { // result.append(new String(line, i, 1)); // } else { // result.append("."); // } // } // } // // return result.toString(); // } // // public static String toHexString(byte b) { // return toHexString(toByteArray(b)); // } // // public static String toHexString(byte[] array) { // return toHexString(array, 0, array.length); // } // // public static String toHexString(byte[] array, int offset, int length) { // char[] buf = new char[length * 2]; // // int bufIndex = 0; // for (int i = offset; i < offset + length; i++) { // byte b = array[i]; // buf[bufIndex++] = HEX_DIGITS[(b >>> 4) & 0x0F]; // buf[bufIndex++] = HEX_DIGITS[b & 0x0F]; // } // // return new String(buf); // } // // public static String toHexString(int i) { // return toHexString(toByteArray(i)); // } // // public static byte[] toByteArray(byte b) { // byte[] array = new byte[1]; // array[0] = b; // return array; // } // // public static byte[] toByteArray(int i) { // byte[] array = new byte[4]; // // array[3] = (byte) (i & 0xFF); // array[2] = (byte) ((i >> 8) & 0xFF); // array[1] = (byte) ((i >> 16) & 0xFF); // array[0] = (byte) ((i >> 24) & 0xFF); // // return array; // } // // private static int toByte(char c) { // if (c >= '0' && c <= '9') // return (c - '0'); // if (c >= 'A' && c <= 'F') // return (c - 'A' + 10); // if (c >= 'a' && c <= 'f') // return (c - 'a' + 10); // // throw new RuntimeException("Invalid hex char '" + c + "'"); // } // // public static byte[] hexStringToByteArray(String hexString) { // int length = hexString.length(); // byte[] buffer = new byte[length / 2]; // // for (int i = 0; i < length; i += 2) { // buffer[i / 2] = (byte) ((toByte(hexString.charAt(i)) << 4) | toByte(hexString // .charAt(i + 1))); // } // // return buffer; // } // } // Path: library/src/main/java/com/jwoolston/android/uvc/interfaces/streaming/UncompressedVideoFormat.java import android.support.annotation.NonNull; import com.jwoolston.android.uvc.util.Hexdump; import timber.log.Timber; private static final int bmInterlaceFlags = 25; private static final int bCopyProtect = 26; private final String guid; private final int bitsPerPixel; public void addUncompressedVideoFrame(@NonNull UncompressedVideoFrame frame) { Timber.d("Adding video frame: %s", frame); videoFrames.add(frame); } public UncompressedVideoFormat(@NonNull byte[] descriptor) throws IllegalArgumentException { super(descriptor); if (descriptor.length < LENGTH) { throw new IllegalArgumentException( "The provided discriptor is not long enough for an Uncompressed Video Format."); } formatIndex = (0xFF & descriptor[bFormatIndex]); numberFrames = (0xFF & descriptor[bNumFrameDescriptors]); byte[] GUIDBytes = new byte[16]; System.arraycopy(descriptor, guidFormat, GUIDBytes, 0, GUIDBytes.length); bitsPerPixel = (0xFF & descriptor[bBitsPerPixel]); defaultFrameIndex = (0xFF & descriptor[bDefaultFrameIndex]); aspectRatioX = (0xFF & descriptor[bAspectRatioX]); aspectRatioY = (0xFF & descriptor[bAspectRatioY]); interlaceFlags = descriptor[bmInterlaceFlags]; copyProtect = descriptor[bCopyProtect] != 0; // Parse the GUID bytes to String final StringBuilder builder = new StringBuilder();
builder.append(Hexdump.toHexString(GUIDBytes[3])).append(Hexdump.toHexString(GUIDBytes[2]))
jwoolston/Android-Webcam
library/src/main/java/com/jwoolston/android/uvc/interfaces/terminals/CameraTerminal.java
// Path: library/src/main/java/com/jwoolston/android/uvc/interfaces/VideoClassInterface.java // public abstract class VideoClassInterface extends UvcInterface { // // VideoClassInterface(UsbInterface usbInterface, byte[] descriptor) { // super(usbInterface, descriptor); // } // // public static enum VC_INF_SUBTYPE { // VC_DESCRIPTOR_UNDEFINED(0x00), // VC_HEADER(0x01), // VC_INPUT_TERMINAL(0x02), // VC_OUTPUT_TERMINAL(0x03), // VC_SELECTOR_UNIT(0x04), // VC_PROCESSING_UNIT(0x05), // VC_EXTENSION_UNIT(0x06), // VC_ENCODING_UNIT(0x07); // // public final byte subtype; // // private VC_INF_SUBTYPE(int subtype) { // this.subtype = (byte) (subtype & 0xFF); // } // // public static VC_INF_SUBTYPE getSubtype(byte subtype) { // for (VC_INF_SUBTYPE s : VC_INF_SUBTYPE.values()) { // if (s.subtype == subtype) { // return s; // } // } // return null; // } // } // }
import android.support.annotation.NonNull; import com.jwoolston.android.uvc.interfaces.VideoClassInterface; import java.util.Collections; import java.util.HashSet; import java.util.Set;
package com.jwoolston.android.uvc.interfaces.terminals; /** * The Camera Terminal (CT) controls mechanical (or equivalent digital) features of the device component that * transmits the video stream. As such, it is only applicable to video capture devices with controllable lens or * sensor characteristics. A Camera Terminal is always represented as an Input Terminal with a single output pin. It * provides support for the following features. * * <br>-Scanning Mode (Progressive or Interlaced) * <br>-Auto-Exposure Mode * <br>-Auto-Exposure Priority * <br>-Exposure Time * <br>-Focus * <br>-Auto-Focus * <br>-Simple Focus * <br>-Iris * <br>-Zoom * <br>-Pan * <br>-Roll * <br>-Tilt * <br>-Digital Windowing * <br>-Region of Interest * * Support for any particular control is optional. The Focus control can optionally provide support for an auto * setting (with an on/off state). If the auto setting is supported and set to the on state, the device will provide * automatic focus adjustment, and read requests will reflect the automatically set value. Attempts to * programmatically set the Focus control when in auto mode shall result in protocol STALL with an error code of * <b>bRequestErrorCode</b> = “Wrong State”. When leaving Auto-Focus mode (entering manual focus mode), the control * shall remain at the value that was in effect just before the transition. * * @author Jared Woolston (Jared.Woolston@gmail.com) * @see <a href=http://www.usb.org/developers/docs/devclass_docs/USB_Video_Class_1_5.zip>UVC 1.5 Class * Specification §2.3.3</a> */ public class CameraTerminal extends VideoInputTerminal { private static final int LENGTH_DESCRIPTOR = 18; private static final int wObjectiveFocalLengthMin = 8; private static final int wObjectiveFocalLengthMax = 10; private static final int wOcularFocalLength = 12; private static final int bControlSize = 14; private static final int bmControls = 15; private final int objectiveFocalLengthMin; private final int objectiveFocalLengthMax; private final int objectiveFocalLength; private final int ocularFocalLength; private final Set<Control> controlSet; public static boolean isCameraTerminal(byte[] descriptor) { if (descriptor.length != LENGTH_DESCRIPTOR) { return false; }
// Path: library/src/main/java/com/jwoolston/android/uvc/interfaces/VideoClassInterface.java // public abstract class VideoClassInterface extends UvcInterface { // // VideoClassInterface(UsbInterface usbInterface, byte[] descriptor) { // super(usbInterface, descriptor); // } // // public static enum VC_INF_SUBTYPE { // VC_DESCRIPTOR_UNDEFINED(0x00), // VC_HEADER(0x01), // VC_INPUT_TERMINAL(0x02), // VC_OUTPUT_TERMINAL(0x03), // VC_SELECTOR_UNIT(0x04), // VC_PROCESSING_UNIT(0x05), // VC_EXTENSION_UNIT(0x06), // VC_ENCODING_UNIT(0x07); // // public final byte subtype; // // private VC_INF_SUBTYPE(int subtype) { // this.subtype = (byte) (subtype & 0xFF); // } // // public static VC_INF_SUBTYPE getSubtype(byte subtype) { // for (VC_INF_SUBTYPE s : VC_INF_SUBTYPE.values()) { // if (s.subtype == subtype) { // return s; // } // } // return null; // } // } // } // Path: library/src/main/java/com/jwoolston/android/uvc/interfaces/terminals/CameraTerminal.java import android.support.annotation.NonNull; import com.jwoolston.android.uvc.interfaces.VideoClassInterface; import java.util.Collections; import java.util.HashSet; import java.util.Set; package com.jwoolston.android.uvc.interfaces.terminals; /** * The Camera Terminal (CT) controls mechanical (or equivalent digital) features of the device component that * transmits the video stream. As such, it is only applicable to video capture devices with controllable lens or * sensor characteristics. A Camera Terminal is always represented as an Input Terminal with a single output pin. It * provides support for the following features. * * <br>-Scanning Mode (Progressive or Interlaced) * <br>-Auto-Exposure Mode * <br>-Auto-Exposure Priority * <br>-Exposure Time * <br>-Focus * <br>-Auto-Focus * <br>-Simple Focus * <br>-Iris * <br>-Zoom * <br>-Pan * <br>-Roll * <br>-Tilt * <br>-Digital Windowing * <br>-Region of Interest * * Support for any particular control is optional. The Focus control can optionally provide support for an auto * setting (with an on/off state). If the auto setting is supported and set to the on state, the device will provide * automatic focus adjustment, and read requests will reflect the automatically set value. Attempts to * programmatically set the Focus control when in auto mode shall result in protocol STALL with an error code of * <b>bRequestErrorCode</b> = “Wrong State”. When leaving Auto-Focus mode (entering manual focus mode), the control * shall remain at the value that was in effect just before the transition. * * @author Jared Woolston (Jared.Woolston@gmail.com) * @see <a href=http://www.usb.org/developers/docs/devclass_docs/USB_Video_Class_1_5.zip>UVC 1.5 Class * Specification §2.3.3</a> */ public class CameraTerminal extends VideoInputTerminal { private static final int LENGTH_DESCRIPTOR = 18; private static final int wObjectiveFocalLengthMin = 8; private static final int wObjectiveFocalLengthMax = 10; private static final int wOcularFocalLength = 12; private static final int bControlSize = 14; private static final int bmControls = 15; private final int objectiveFocalLengthMin; private final int objectiveFocalLengthMax; private final int objectiveFocalLength; private final int ocularFocalLength; private final Set<Control> controlSet; public static boolean isCameraTerminal(byte[] descriptor) { if (descriptor.length != LENGTH_DESCRIPTOR) { return false; }
if (descriptor[bDescriptorSubtype] != VideoClassInterface.VC_INF_SUBTYPE.VC_INPUT_TERMINAL.subtype) {
jwoolston/Android-Webcam
library/src/main/java/com/jwoolston/android/uvc/interfaces/units/VideoSelectorUnit.java
// Path: library/src/main/java/com/jwoolston/android/uvc/interfaces/VideoClassInterface.java // public abstract class VideoClassInterface extends UvcInterface { // // VideoClassInterface(UsbInterface usbInterface, byte[] descriptor) { // super(usbInterface, descriptor); // } // // public static enum VC_INF_SUBTYPE { // VC_DESCRIPTOR_UNDEFINED(0x00), // VC_HEADER(0x01), // VC_INPUT_TERMINAL(0x02), // VC_OUTPUT_TERMINAL(0x03), // VC_SELECTOR_UNIT(0x04), // VC_PROCESSING_UNIT(0x05), // VC_EXTENSION_UNIT(0x06), // VC_ENCODING_UNIT(0x07); // // public final byte subtype; // // private VC_INF_SUBTYPE(int subtype) { // this.subtype = (byte) (subtype & 0xFF); // } // // public static VC_INF_SUBTYPE getSubtype(byte subtype) { // for (VC_INF_SUBTYPE s : VC_INF_SUBTYPE.values()) { // if (s.subtype == subtype) { // return s; // } // } // return null; // } // } // }
import com.jwoolston.android.uvc.interfaces.VideoClassInterface; import java.util.Arrays;
package com.jwoolston.android.uvc.interfaces.units; /** * The Selector Unit (SU) selects from n input data streams and routes them unaltered to the single output stream. It * represents a source selector, capable of selecting among a number of sources. It has an Input Pin for each source * stream and a single Output Pin * * @author Jared Woolston (Jared.Woolston@gmail.com) * @see <a href=http://www.usb.org/developers/docs/devclass_docs/USB_Video_Class_1_5.zip>UVC 1.5 Class * Specification §2.3.4</a> */ public class VideoSelectorUnit extends VideoUnit { private static final int MIN_LENGTH = 6; private static final int bNrInPins = 4; private static final int baSourceID = 5; private static final int iSelector = 5; private final int numInPins; private final int[] sourceIDs; private final int selectorValue; public static boolean isVideoSelectorUnit(byte[] descriptor) { return (descriptor.length >= MIN_LENGTH
// Path: library/src/main/java/com/jwoolston/android/uvc/interfaces/VideoClassInterface.java // public abstract class VideoClassInterface extends UvcInterface { // // VideoClassInterface(UsbInterface usbInterface, byte[] descriptor) { // super(usbInterface, descriptor); // } // // public static enum VC_INF_SUBTYPE { // VC_DESCRIPTOR_UNDEFINED(0x00), // VC_HEADER(0x01), // VC_INPUT_TERMINAL(0x02), // VC_OUTPUT_TERMINAL(0x03), // VC_SELECTOR_UNIT(0x04), // VC_PROCESSING_UNIT(0x05), // VC_EXTENSION_UNIT(0x06), // VC_ENCODING_UNIT(0x07); // // public final byte subtype; // // private VC_INF_SUBTYPE(int subtype) { // this.subtype = (byte) (subtype & 0xFF); // } // // public static VC_INF_SUBTYPE getSubtype(byte subtype) { // for (VC_INF_SUBTYPE s : VC_INF_SUBTYPE.values()) { // if (s.subtype == subtype) { // return s; // } // } // return null; // } // } // } // Path: library/src/main/java/com/jwoolston/android/uvc/interfaces/units/VideoSelectorUnit.java import com.jwoolston.android.uvc.interfaces.VideoClassInterface; import java.util.Arrays; package com.jwoolston.android.uvc.interfaces.units; /** * The Selector Unit (SU) selects from n input data streams and routes them unaltered to the single output stream. It * represents a source selector, capable of selecting among a number of sources. It has an Input Pin for each source * stream and a single Output Pin * * @author Jared Woolston (Jared.Woolston@gmail.com) * @see <a href=http://www.usb.org/developers/docs/devclass_docs/USB_Video_Class_1_5.zip>UVC 1.5 Class * Specification §2.3.4</a> */ public class VideoSelectorUnit extends VideoUnit { private static final int MIN_LENGTH = 6; private static final int bNrInPins = 4; private static final int baSourceID = 5; private static final int iSelector = 5; private final int numInPins; private final int[] sourceIDs; private final int selectorValue; public static boolean isVideoSelectorUnit(byte[] descriptor) { return (descriptor.length >= MIN_LENGTH
& descriptor[bDescriptorSubtype] == VideoClassInterface.VC_INF_SUBTYPE.VC_SELECTOR_UNIT.subtype);
jwoolston/Android-Webcam
library/src/main/java/com/jwoolston/android/uvc/WebcamImpl.java
// Path: library/src/main/java/com/jwoolston/android/uvc/interfaces/streaming/VideoFormat.java // public class VideoFormat<T extends VideoFrame> { // // protected int formatIndex; // protected int numberFrames; // protected int defaultFrameIndex; // protected int aspectRatioX; // protected int aspectRatioY; // protected byte interlaceFlags; // protected boolean copyProtect; // // private VideoColorMatchingDescriptor colorMatchingDescriptor; // // protected final Set<T> videoFrames = new HashSet<>(); // // VideoFormat(@NonNull byte[] descriptor) throws IllegalArgumentException { // // } // // public void setColorMatchingDescriptor(VideoColorMatchingDescriptor descriptor) { // colorMatchingDescriptor = descriptor; // } // // public VideoColorMatchingDescriptor getColorMatchingDescriptor() { // return colorMatchingDescriptor; // } // // public int getFormatIndex() { // return formatIndex; // } // // public int getNumberFrames() { // return numberFrames; // } // // public int getDefaultFrameIndex() { // return defaultFrameIndex; // } // // @NonNull // public Set<T> getVideoFrames() { // return videoFrames; // } // // public int getAspectRatioX() { // return aspectRatioX; // } // // public int getAspectRatioY() { // return aspectRatioY; // } // // public byte getInterlaceFlags() { // return interlaceFlags; // } // // public boolean isCopyProtect() { // return copyProtect; // } // // public VideoFrame getDefaultFrame() throws IllegalStateException { // for (VideoFrame frame : videoFrames) { // if (frame.getFrameIndex() == getDefaultFrameIndex()) { // return frame; // } // } // throw new IllegalStateException("No default frame was found!"); // } // }
import android.content.Context; import android.hardware.usb.UsbDevice; import android.net.Uri; import android.support.annotation.NonNull; import com.jwoolston.android.libusb.DevicePermissionDenied; import com.jwoolston.android.uvc.interfaces.streaming.VideoFormat; import java.util.List;
package com.jwoolston.android.uvc; /** * @author Jared Woolston (Jared.Woolston@gmail.com) */ class WebcamImpl implements Webcam { private final Context context; private final UsbDevice device; private final WebcamConnection webcamConnection; WebcamImpl(Context context, UsbDevice device) throws UnknownDeviceException, DevicePermissionDenied { this.context = context; this.device = device; webcamConnection = new WebcamConnection(context.getApplicationContext(), device); } @NonNull @Override public UsbDevice getDevice() { return device; } @Override public boolean isConnected() { return webcamConnection.isConnected(); } /** * Retrieves the list of available {@link VideoFormat}s. * * @return The available {@link VideoFormat}s on the device. */
// Path: library/src/main/java/com/jwoolston/android/uvc/interfaces/streaming/VideoFormat.java // public class VideoFormat<T extends VideoFrame> { // // protected int formatIndex; // protected int numberFrames; // protected int defaultFrameIndex; // protected int aspectRatioX; // protected int aspectRatioY; // protected byte interlaceFlags; // protected boolean copyProtect; // // private VideoColorMatchingDescriptor colorMatchingDescriptor; // // protected final Set<T> videoFrames = new HashSet<>(); // // VideoFormat(@NonNull byte[] descriptor) throws IllegalArgumentException { // // } // // public void setColorMatchingDescriptor(VideoColorMatchingDescriptor descriptor) { // colorMatchingDescriptor = descriptor; // } // // public VideoColorMatchingDescriptor getColorMatchingDescriptor() { // return colorMatchingDescriptor; // } // // public int getFormatIndex() { // return formatIndex; // } // // public int getNumberFrames() { // return numberFrames; // } // // public int getDefaultFrameIndex() { // return defaultFrameIndex; // } // // @NonNull // public Set<T> getVideoFrames() { // return videoFrames; // } // // public int getAspectRatioX() { // return aspectRatioX; // } // // public int getAspectRatioY() { // return aspectRatioY; // } // // public byte getInterlaceFlags() { // return interlaceFlags; // } // // public boolean isCopyProtect() { // return copyProtect; // } // // public VideoFrame getDefaultFrame() throws IllegalStateException { // for (VideoFrame frame : videoFrames) { // if (frame.getFrameIndex() == getDefaultFrameIndex()) { // return frame; // } // } // throw new IllegalStateException("No default frame was found!"); // } // } // Path: library/src/main/java/com/jwoolston/android/uvc/WebcamImpl.java import android.content.Context; import android.hardware.usb.UsbDevice; import android.net.Uri; import android.support.annotation.NonNull; import com.jwoolston.android.libusb.DevicePermissionDenied; import com.jwoolston.android.uvc.interfaces.streaming.VideoFormat; import java.util.List; package com.jwoolston.android.uvc; /** * @author Jared Woolston (Jared.Woolston@gmail.com) */ class WebcamImpl implements Webcam { private final Context context; private final UsbDevice device; private final WebcamConnection webcamConnection; WebcamImpl(Context context, UsbDevice device) throws UnknownDeviceException, DevicePermissionDenied { this.context = context; this.device = device; webcamConnection = new WebcamConnection(context.getApplicationContext(), device); } @NonNull @Override public UsbDevice getDevice() { return device; } @Override public boolean isConnected() { return webcamConnection.isConnected(); } /** * Retrieves the list of available {@link VideoFormat}s. * * @return The available {@link VideoFormat}s on the device. */
public List<VideoFormat> getAvailableFormats() {
jwoolston/Android-Webcam
library/src/main/java/com/jwoolston/android/uvc/interfaces/streaming/MJPEGVideoFormat.java
// Path: library/src/main/java/com/jwoolston/android/uvc/util/Hexdump.java // public class Hexdump { // private final static char[] HEX_DIGITS = { // '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' // }; // // public static String dumpHexString(byte[] array) { // return dumpHexString(array, 0, array.length); // } // // public static String dumpHexString(byte[] array, int offset, int length) { // StringBuilder result = new StringBuilder(); // // byte[] line = new byte[16]; // int lineIndex = 0; // // result.append("\n0x"); // result.append(toHexString(offset)); // // for (int i = offset; i < offset + length; i++) { // if (lineIndex == 16) { // result.append(" "); // // for (int j = 0; j < 16; j++) { // if (line[j] > ' ' && line[j] < '~') { // result.append(new String(line, j, 1)); // } else { // result.append("."); // } // } // // result.append("\n0x"); // result.append(toHexString(i)); // lineIndex = 0; // } // // byte b = array[i]; // result.append(" "); // result.append(HEX_DIGITS[(b >>> 4) & 0x0F]); // result.append(HEX_DIGITS[b & 0x0F]); // // line[lineIndex++] = b; // } // // if (lineIndex != 16) { // int count = (16 - lineIndex) * 3; // count++; // for (int i = 0; i < count; i++) { // result.append(" "); // } // // for (int i = 0; i < lineIndex; i++) { // if (line[i] > ' ' && line[i] < '~') { // result.append(new String(line, i, 1)); // } else { // result.append("."); // } // } // } // // return result.toString(); // } // // public static String toHexString(byte b) { // return toHexString(toByteArray(b)); // } // // public static String toHexString(byte[] array) { // return toHexString(array, 0, array.length); // } // // public static String toHexString(byte[] array, int offset, int length) { // char[] buf = new char[length * 2]; // // int bufIndex = 0; // for (int i = offset; i < offset + length; i++) { // byte b = array[i]; // buf[bufIndex++] = HEX_DIGITS[(b >>> 4) & 0x0F]; // buf[bufIndex++] = HEX_DIGITS[b & 0x0F]; // } // // return new String(buf); // } // // public static String toHexString(int i) { // return toHexString(toByteArray(i)); // } // // public static byte[] toByteArray(byte b) { // byte[] array = new byte[1]; // array[0] = b; // return array; // } // // public static byte[] toByteArray(int i) { // byte[] array = new byte[4]; // // array[3] = (byte) (i & 0xFF); // array[2] = (byte) ((i >> 8) & 0xFF); // array[1] = (byte) ((i >> 16) & 0xFF); // array[0] = (byte) ((i >> 24) & 0xFF); // // return array; // } // // private static int toByte(char c) { // if (c >= '0' && c <= '9') // return (c - '0'); // if (c >= 'A' && c <= 'F') // return (c - 'A' + 10); // if (c >= 'a' && c <= 'f') // return (c - 'a' + 10); // // throw new RuntimeException("Invalid hex char '" + c + "'"); // } // // public static byte[] hexStringToByteArray(String hexString) { // int length = hexString.length(); // byte[] buffer = new byte[length / 2]; // // for (int i = 0; i < length; i += 2) { // buffer[i / 2] = (byte) ((toByte(hexString.charAt(i)) << 4) | toByte(hexString // .charAt(i + 1))); // } // // return buffer; // } // }
import android.support.annotation.NonNull; import com.jwoolston.android.uvc.util.Hexdump; import timber.log.Timber;
if (descriptor.length < LENGTH) { throw new IllegalArgumentException("The provided descriptor is not long enough for an MJPEG Video Format."); } formatIndex = (0xFF & descriptor[bFormatIndex]); numberFrames = (0xFF & descriptor[bNumFrameDescriptors]); fixedSampleSize = descriptor[bmFlags] != 0; defaultFrameIndex = (0xFF & descriptor[bDefaultFrameIndex]); aspectRatioX = (0xFF & descriptor[bAspectRatioX]); aspectRatioY = (0xFF & descriptor[bAspectRatioY]); interlaceFlags = descriptor[bmInterlaceFlags]; copyProtect = descriptor[bCopyProtect] != 0; } public void addMJPEGVideoFrame(@NonNull MJPEGVideoFrame frame) { Timber.d("Adding video frame: %s", frame); videoFrames.add(frame); } public boolean getFixedSampleSize() { return fixedSampleSize; } @Override public String toString() { return "MJPEGVideoFormat{" + "formatIndex=" + formatIndex + ", numberFrames=" + numberFrames + ", fixedSampleSize=" + fixedSampleSize + ", defaultFrameIndex=" + defaultFrameIndex + ", AspectRatio=" + aspectRatioX + ":" + aspectRatioY +
// Path: library/src/main/java/com/jwoolston/android/uvc/util/Hexdump.java // public class Hexdump { // private final static char[] HEX_DIGITS = { // '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' // }; // // public static String dumpHexString(byte[] array) { // return dumpHexString(array, 0, array.length); // } // // public static String dumpHexString(byte[] array, int offset, int length) { // StringBuilder result = new StringBuilder(); // // byte[] line = new byte[16]; // int lineIndex = 0; // // result.append("\n0x"); // result.append(toHexString(offset)); // // for (int i = offset; i < offset + length; i++) { // if (lineIndex == 16) { // result.append(" "); // // for (int j = 0; j < 16; j++) { // if (line[j] > ' ' && line[j] < '~') { // result.append(new String(line, j, 1)); // } else { // result.append("."); // } // } // // result.append("\n0x"); // result.append(toHexString(i)); // lineIndex = 0; // } // // byte b = array[i]; // result.append(" "); // result.append(HEX_DIGITS[(b >>> 4) & 0x0F]); // result.append(HEX_DIGITS[b & 0x0F]); // // line[lineIndex++] = b; // } // // if (lineIndex != 16) { // int count = (16 - lineIndex) * 3; // count++; // for (int i = 0; i < count; i++) { // result.append(" "); // } // // for (int i = 0; i < lineIndex; i++) { // if (line[i] > ' ' && line[i] < '~') { // result.append(new String(line, i, 1)); // } else { // result.append("."); // } // } // } // // return result.toString(); // } // // public static String toHexString(byte b) { // return toHexString(toByteArray(b)); // } // // public static String toHexString(byte[] array) { // return toHexString(array, 0, array.length); // } // // public static String toHexString(byte[] array, int offset, int length) { // char[] buf = new char[length * 2]; // // int bufIndex = 0; // for (int i = offset; i < offset + length; i++) { // byte b = array[i]; // buf[bufIndex++] = HEX_DIGITS[(b >>> 4) & 0x0F]; // buf[bufIndex++] = HEX_DIGITS[b & 0x0F]; // } // // return new String(buf); // } // // public static String toHexString(int i) { // return toHexString(toByteArray(i)); // } // // public static byte[] toByteArray(byte b) { // byte[] array = new byte[1]; // array[0] = b; // return array; // } // // public static byte[] toByteArray(int i) { // byte[] array = new byte[4]; // // array[3] = (byte) (i & 0xFF); // array[2] = (byte) ((i >> 8) & 0xFF); // array[1] = (byte) ((i >> 16) & 0xFF); // array[0] = (byte) ((i >> 24) & 0xFF); // // return array; // } // // private static int toByte(char c) { // if (c >= '0' && c <= '9') // return (c - '0'); // if (c >= 'A' && c <= 'F') // return (c - 'A' + 10); // if (c >= 'a' && c <= 'f') // return (c - 'a' + 10); // // throw new RuntimeException("Invalid hex char '" + c + "'"); // } // // public static byte[] hexStringToByteArray(String hexString) { // int length = hexString.length(); // byte[] buffer = new byte[length / 2]; // // for (int i = 0; i < length; i += 2) { // buffer[i / 2] = (byte) ((toByte(hexString.charAt(i)) << 4) | toByte(hexString // .charAt(i + 1))); // } // // return buffer; // } // } // Path: library/src/main/java/com/jwoolston/android/uvc/interfaces/streaming/MJPEGVideoFormat.java import android.support.annotation.NonNull; import com.jwoolston.android.uvc.util.Hexdump; import timber.log.Timber; if (descriptor.length < LENGTH) { throw new IllegalArgumentException("The provided descriptor is not long enough for an MJPEG Video Format."); } formatIndex = (0xFF & descriptor[bFormatIndex]); numberFrames = (0xFF & descriptor[bNumFrameDescriptors]); fixedSampleSize = descriptor[bmFlags] != 0; defaultFrameIndex = (0xFF & descriptor[bDefaultFrameIndex]); aspectRatioX = (0xFF & descriptor[bAspectRatioX]); aspectRatioY = (0xFF & descriptor[bAspectRatioY]); interlaceFlags = descriptor[bmInterlaceFlags]; copyProtect = descriptor[bCopyProtect] != 0; } public void addMJPEGVideoFrame(@NonNull MJPEGVideoFrame frame) { Timber.d("Adding video frame: %s", frame); videoFrames.add(frame); } public boolean getFixedSampleSize() { return fixedSampleSize; } @Override public String toString() { return "MJPEGVideoFormat{" + "formatIndex=" + formatIndex + ", numberFrames=" + numberFrames + ", fixedSampleSize=" + fixedSampleSize + ", defaultFrameIndex=" + defaultFrameIndex + ", AspectRatio=" + aspectRatioX + ":" + aspectRatioY +
", interlaceFlags=0x" + Hexdump.toHexString(interlaceFlags) +
jwoolston/Android-Webcam
library/src/main/java/com/jwoolston/android/uvc/interfaces/terminals/VideoOutputTerminal.java
// Path: library/src/main/java/com/jwoolston/android/uvc/interfaces/VideoClassInterface.java // public abstract class VideoClassInterface extends UvcInterface { // // VideoClassInterface(UsbInterface usbInterface, byte[] descriptor) { // super(usbInterface, descriptor); // } // // public static enum VC_INF_SUBTYPE { // VC_DESCRIPTOR_UNDEFINED(0x00), // VC_HEADER(0x01), // VC_INPUT_TERMINAL(0x02), // VC_OUTPUT_TERMINAL(0x03), // VC_SELECTOR_UNIT(0x04), // VC_PROCESSING_UNIT(0x05), // VC_EXTENSION_UNIT(0x06), // VC_ENCODING_UNIT(0x07); // // public final byte subtype; // // private VC_INF_SUBTYPE(int subtype) { // this.subtype = (byte) (subtype & 0xFF); // } // // public static VC_INF_SUBTYPE getSubtype(byte subtype) { // for (VC_INF_SUBTYPE s : VC_INF_SUBTYPE.values()) { // if (s.subtype == subtype) { // return s; // } // } // return null; // } // } // }
import com.jwoolston.android.uvc.interfaces.VideoClassInterface;
package com.jwoolston.android.uvc.interfaces.terminals; /** * The Output Terminal (OT) is used as an interface between Units inside the video function and the "outside world". * It serves as an outlet for video information, flowing out of the video function. Its function is to represent a * sink of outgoing data. The video data stream enters the Output Terminal through a single Input Pin. * An Output Terminal can represent outputs from the video function other than USB IN endpoints. A Liquid Crystal * Display (LCD) screen built into a video device or a composite video out connector are examples of such an output. * However, if the video stream is leaving the video function by means of a USB IN endpoint, there is a one-to-one * relationship between that endpoint and its associated Output Terminal. The class-specific Input Header descriptor * contains a field that holds a direct reference to this Output Terminal (see section 3.9.2.1, “Input Header * Descriptor”). The Host needs to use both the endpoint descriptors and the Output Terminal descriptor to fully * understand the characteristics and capabilities of the Output Terminal. Stream-related parameters are stored in * the endpoint descriptors. Control-related parameters are stored in the Terminal descriptor. * * @author Jared Woolston (Jared.Woolston@gmail.com) * @see <a href=http://www.usb.org/developers/docs/devclass_docs/USB_Video_Class_1_5.zip>UVC 1.5 Class * Specification §2.3.2</a> */ public class VideoOutputTerminal extends VideoTerminal { protected static final int MIN_LENGTH = 9; protected static final int bSourceID = 7; protected static final int iTerminal = 8; private final int sourceID; public static boolean isOutputTerminal(byte[] descriptor) { return (descriptor.length >= MIN_LENGTH
// Path: library/src/main/java/com/jwoolston/android/uvc/interfaces/VideoClassInterface.java // public abstract class VideoClassInterface extends UvcInterface { // // VideoClassInterface(UsbInterface usbInterface, byte[] descriptor) { // super(usbInterface, descriptor); // } // // public static enum VC_INF_SUBTYPE { // VC_DESCRIPTOR_UNDEFINED(0x00), // VC_HEADER(0x01), // VC_INPUT_TERMINAL(0x02), // VC_OUTPUT_TERMINAL(0x03), // VC_SELECTOR_UNIT(0x04), // VC_PROCESSING_UNIT(0x05), // VC_EXTENSION_UNIT(0x06), // VC_ENCODING_UNIT(0x07); // // public final byte subtype; // // private VC_INF_SUBTYPE(int subtype) { // this.subtype = (byte) (subtype & 0xFF); // } // // public static VC_INF_SUBTYPE getSubtype(byte subtype) { // for (VC_INF_SUBTYPE s : VC_INF_SUBTYPE.values()) { // if (s.subtype == subtype) { // return s; // } // } // return null; // } // } // } // Path: library/src/main/java/com/jwoolston/android/uvc/interfaces/terminals/VideoOutputTerminal.java import com.jwoolston.android.uvc.interfaces.VideoClassInterface; package com.jwoolston.android.uvc.interfaces.terminals; /** * The Output Terminal (OT) is used as an interface between Units inside the video function and the "outside world". * It serves as an outlet for video information, flowing out of the video function. Its function is to represent a * sink of outgoing data. The video data stream enters the Output Terminal through a single Input Pin. * An Output Terminal can represent outputs from the video function other than USB IN endpoints. A Liquid Crystal * Display (LCD) screen built into a video device or a composite video out connector are examples of such an output. * However, if the video stream is leaving the video function by means of a USB IN endpoint, there is a one-to-one * relationship between that endpoint and its associated Output Terminal. The class-specific Input Header descriptor * contains a field that holds a direct reference to this Output Terminal (see section 3.9.2.1, “Input Header * Descriptor”). The Host needs to use both the endpoint descriptors and the Output Terminal descriptor to fully * understand the characteristics and capabilities of the Output Terminal. Stream-related parameters are stored in * the endpoint descriptors. Control-related parameters are stored in the Terminal descriptor. * * @author Jared Woolston (Jared.Woolston@gmail.com) * @see <a href=http://www.usb.org/developers/docs/devclass_docs/USB_Video_Class_1_5.zip>UVC 1.5 Class * Specification §2.3.2</a> */ public class VideoOutputTerminal extends VideoTerminal { protected static final int MIN_LENGTH = 9; protected static final int bSourceID = 7; protected static final int iTerminal = 8; private final int sourceID; public static boolean isOutputTerminal(byte[] descriptor) { return (descriptor.length >= MIN_LENGTH
&& descriptor[bDescriptorSubtype] == VideoClassInterface.VC_INF_SUBTYPE.VC_OUTPUT_TERMINAL.subtype);
jwoolston/Android-Webcam
library/src/main/java/com/jwoolston/android/uvc/interfaces/units/VideoUnit.java
// Path: library/src/main/java/com/jwoolston/android/uvc/interfaces/VideoClassInterface.java // public abstract class VideoClassInterface extends UvcInterface { // // VideoClassInterface(UsbInterface usbInterface, byte[] descriptor) { // super(usbInterface, descriptor); // } // // public static enum VC_INF_SUBTYPE { // VC_DESCRIPTOR_UNDEFINED(0x00), // VC_HEADER(0x01), // VC_INPUT_TERMINAL(0x02), // VC_OUTPUT_TERMINAL(0x03), // VC_SELECTOR_UNIT(0x04), // VC_PROCESSING_UNIT(0x05), // VC_EXTENSION_UNIT(0x06), // VC_ENCODING_UNIT(0x07); // // public final byte subtype; // // private VC_INF_SUBTYPE(int subtype) { // this.subtype = (byte) (subtype & 0xFF); // } // // public static VC_INF_SUBTYPE getSubtype(byte subtype) { // for (VC_INF_SUBTYPE s : VC_INF_SUBTYPE.values()) { // if (s.subtype == subtype) { // return s; // } // } // return null; // } // } // } // // Path: library/src/main/java/com/jwoolston/android/uvc/interfaces/Descriptor.java // public static enum Type { // DEVICE(0x01), // CONFIGURATION(0x02), // STRING(0x03), // INTERFACE(0x04), // ENDPOINT(0x05), // DEVICE_QUALIFIER(0x06), // INTERFACE_ASSOCIATION(0x0B), // CS_UNDEFINED(0x20), // CS_DEVICE(0x21), // CS_CONFIGURATION(0x22), // CS_STRING(0x23), // CS_INTERFACE(0x24), // CS_ENDPOINT(0x25); // // public final byte type; // // private Type(int type) { // this.type = (byte) (type & 0xFF); // } // // public static Type getType(byte[] raw) { // for (Type t : Type.values()) { // if (t.type == raw[INDEX_DESCRIPTOR_TYPE]) { // return t; // } // } // throw new IllegalArgumentException("Unknown descriptor? " + Hexdump.dumpHexString(raw)); // } // }
import com.jwoolston.android.uvc.interfaces.VideoClassInterface; import com.jwoolston.android.uvc.interfaces.Descriptor.Type;
package com.jwoolston.android.uvc.interfaces.units; /** * @author Jared Woolston (Jared.Woolston@gmail.com) */ public class VideoUnit { protected static final int bLength = 0; protected static final int bDescriptorType = 1; protected static final int bDescriptorSubtype = 2; protected static final int bUnitID = 3; private final int mUnitID; public static boolean isVideoUnit(byte[] descriptor) {
// Path: library/src/main/java/com/jwoolston/android/uvc/interfaces/VideoClassInterface.java // public abstract class VideoClassInterface extends UvcInterface { // // VideoClassInterface(UsbInterface usbInterface, byte[] descriptor) { // super(usbInterface, descriptor); // } // // public static enum VC_INF_SUBTYPE { // VC_DESCRIPTOR_UNDEFINED(0x00), // VC_HEADER(0x01), // VC_INPUT_TERMINAL(0x02), // VC_OUTPUT_TERMINAL(0x03), // VC_SELECTOR_UNIT(0x04), // VC_PROCESSING_UNIT(0x05), // VC_EXTENSION_UNIT(0x06), // VC_ENCODING_UNIT(0x07); // // public final byte subtype; // // private VC_INF_SUBTYPE(int subtype) { // this.subtype = (byte) (subtype & 0xFF); // } // // public static VC_INF_SUBTYPE getSubtype(byte subtype) { // for (VC_INF_SUBTYPE s : VC_INF_SUBTYPE.values()) { // if (s.subtype == subtype) { // return s; // } // } // return null; // } // } // } // // Path: library/src/main/java/com/jwoolston/android/uvc/interfaces/Descriptor.java // public static enum Type { // DEVICE(0x01), // CONFIGURATION(0x02), // STRING(0x03), // INTERFACE(0x04), // ENDPOINT(0x05), // DEVICE_QUALIFIER(0x06), // INTERFACE_ASSOCIATION(0x0B), // CS_UNDEFINED(0x20), // CS_DEVICE(0x21), // CS_CONFIGURATION(0x22), // CS_STRING(0x23), // CS_INTERFACE(0x24), // CS_ENDPOINT(0x25); // // public final byte type; // // private Type(int type) { // this.type = (byte) (type & 0xFF); // } // // public static Type getType(byte[] raw) { // for (Type t : Type.values()) { // if (t.type == raw[INDEX_DESCRIPTOR_TYPE]) { // return t; // } // } // throw new IllegalArgumentException("Unknown descriptor? " + Hexdump.dumpHexString(raw)); // } // } // Path: library/src/main/java/com/jwoolston/android/uvc/interfaces/units/VideoUnit.java import com.jwoolston.android.uvc.interfaces.VideoClassInterface; import com.jwoolston.android.uvc.interfaces.Descriptor.Type; package com.jwoolston.android.uvc.interfaces.units; /** * @author Jared Woolston (Jared.Woolston@gmail.com) */ public class VideoUnit { protected static final int bLength = 0; protected static final int bDescriptorType = 1; protected static final int bDescriptorSubtype = 2; protected static final int bUnitID = 3; private final int mUnitID; public static boolean isVideoUnit(byte[] descriptor) {
if (descriptor[bDescriptorType] != Type.CS_INTERFACE.type) return false;
jwoolston/Android-Webcam
library/src/main/java/com/jwoolston/android/uvc/interfaces/units/VideoUnit.java
// Path: library/src/main/java/com/jwoolston/android/uvc/interfaces/VideoClassInterface.java // public abstract class VideoClassInterface extends UvcInterface { // // VideoClassInterface(UsbInterface usbInterface, byte[] descriptor) { // super(usbInterface, descriptor); // } // // public static enum VC_INF_SUBTYPE { // VC_DESCRIPTOR_UNDEFINED(0x00), // VC_HEADER(0x01), // VC_INPUT_TERMINAL(0x02), // VC_OUTPUT_TERMINAL(0x03), // VC_SELECTOR_UNIT(0x04), // VC_PROCESSING_UNIT(0x05), // VC_EXTENSION_UNIT(0x06), // VC_ENCODING_UNIT(0x07); // // public final byte subtype; // // private VC_INF_SUBTYPE(int subtype) { // this.subtype = (byte) (subtype & 0xFF); // } // // public static VC_INF_SUBTYPE getSubtype(byte subtype) { // for (VC_INF_SUBTYPE s : VC_INF_SUBTYPE.values()) { // if (s.subtype == subtype) { // return s; // } // } // return null; // } // } // } // // Path: library/src/main/java/com/jwoolston/android/uvc/interfaces/Descriptor.java // public static enum Type { // DEVICE(0x01), // CONFIGURATION(0x02), // STRING(0x03), // INTERFACE(0x04), // ENDPOINT(0x05), // DEVICE_QUALIFIER(0x06), // INTERFACE_ASSOCIATION(0x0B), // CS_UNDEFINED(0x20), // CS_DEVICE(0x21), // CS_CONFIGURATION(0x22), // CS_STRING(0x23), // CS_INTERFACE(0x24), // CS_ENDPOINT(0x25); // // public final byte type; // // private Type(int type) { // this.type = (byte) (type & 0xFF); // } // // public static Type getType(byte[] raw) { // for (Type t : Type.values()) { // if (t.type == raw[INDEX_DESCRIPTOR_TYPE]) { // return t; // } // } // throw new IllegalArgumentException("Unknown descriptor? " + Hexdump.dumpHexString(raw)); // } // }
import com.jwoolston.android.uvc.interfaces.VideoClassInterface; import com.jwoolston.android.uvc.interfaces.Descriptor.Type;
package com.jwoolston.android.uvc.interfaces.units; /** * @author Jared Woolston (Jared.Woolston@gmail.com) */ public class VideoUnit { protected static final int bLength = 0; protected static final int bDescriptorType = 1; protected static final int bDescriptorSubtype = 2; protected static final int bUnitID = 3; private final int mUnitID; public static boolean isVideoUnit(byte[] descriptor) { if (descriptor[bDescriptorType] != Type.CS_INTERFACE.type) return false; final byte subtype = descriptor[bDescriptorSubtype];
// Path: library/src/main/java/com/jwoolston/android/uvc/interfaces/VideoClassInterface.java // public abstract class VideoClassInterface extends UvcInterface { // // VideoClassInterface(UsbInterface usbInterface, byte[] descriptor) { // super(usbInterface, descriptor); // } // // public static enum VC_INF_SUBTYPE { // VC_DESCRIPTOR_UNDEFINED(0x00), // VC_HEADER(0x01), // VC_INPUT_TERMINAL(0x02), // VC_OUTPUT_TERMINAL(0x03), // VC_SELECTOR_UNIT(0x04), // VC_PROCESSING_UNIT(0x05), // VC_EXTENSION_UNIT(0x06), // VC_ENCODING_UNIT(0x07); // // public final byte subtype; // // private VC_INF_SUBTYPE(int subtype) { // this.subtype = (byte) (subtype & 0xFF); // } // // public static VC_INF_SUBTYPE getSubtype(byte subtype) { // for (VC_INF_SUBTYPE s : VC_INF_SUBTYPE.values()) { // if (s.subtype == subtype) { // return s; // } // } // return null; // } // } // } // // Path: library/src/main/java/com/jwoolston/android/uvc/interfaces/Descriptor.java // public static enum Type { // DEVICE(0x01), // CONFIGURATION(0x02), // STRING(0x03), // INTERFACE(0x04), // ENDPOINT(0x05), // DEVICE_QUALIFIER(0x06), // INTERFACE_ASSOCIATION(0x0B), // CS_UNDEFINED(0x20), // CS_DEVICE(0x21), // CS_CONFIGURATION(0x22), // CS_STRING(0x23), // CS_INTERFACE(0x24), // CS_ENDPOINT(0x25); // // public final byte type; // // private Type(int type) { // this.type = (byte) (type & 0xFF); // } // // public static Type getType(byte[] raw) { // for (Type t : Type.values()) { // if (t.type == raw[INDEX_DESCRIPTOR_TYPE]) { // return t; // } // } // throw new IllegalArgumentException("Unknown descriptor? " + Hexdump.dumpHexString(raw)); // } // } // Path: library/src/main/java/com/jwoolston/android/uvc/interfaces/units/VideoUnit.java import com.jwoolston.android.uvc.interfaces.VideoClassInterface; import com.jwoolston.android.uvc.interfaces.Descriptor.Type; package com.jwoolston.android.uvc.interfaces.units; /** * @author Jared Woolston (Jared.Woolston@gmail.com) */ public class VideoUnit { protected static final int bLength = 0; protected static final int bDescriptorType = 1; protected static final int bDescriptorSubtype = 2; protected static final int bUnitID = 3; private final int mUnitID; public static boolean isVideoUnit(byte[] descriptor) { if (descriptor[bDescriptorType] != Type.CS_INTERFACE.type) return false; final byte subtype = descriptor[bDescriptorSubtype];
return (subtype == VideoClassInterface.VC_INF_SUBTYPE.VC_SELECTOR_UNIT.subtype ||
jwoolston/Android-Webcam
library/src/main/java/com/jwoolston/android/uvc/interfaces/VideoIAD.java
// Path: library/src/main/java/com/jwoolston/android/uvc/interfaces/Descriptor.java // public static enum VideoSubclass { // SC_UNDEFINED(0x00), // SC_VIDEOCONTROL(0x01), // SC_VIDEOSTREAMING(0x02), // SC_VIDEO_INTERFACE_COLLECTION(0x03); // // public final byte subclass; // // private VideoSubclass(int subclass) { // this.subclass = (byte) (subclass & 0xFF); // } // // public static VideoSubclass getVideoSubclass(byte subclass) { // for (VideoSubclass s : VideoSubclass.values()) { // if (s.subclass == subclass) { // return s; // } // } // return null; // } // }
import android.util.SparseArray; import com.jwoolston.android.uvc.interfaces.Descriptor.VideoSubclass; import timber.log.Timber;
package com.jwoolston.android.uvc.interfaces; /** * @author Jared Woolston (Jared.Woolston@gmail.com) */ public class VideoIAD extends InterfaceAssociationDescriptor { private SparseArray<VideoClassInterface> interfaces; VideoIAD(byte[] descriptor) throws IllegalArgumentException { super(descriptor);
// Path: library/src/main/java/com/jwoolston/android/uvc/interfaces/Descriptor.java // public static enum VideoSubclass { // SC_UNDEFINED(0x00), // SC_VIDEOCONTROL(0x01), // SC_VIDEOSTREAMING(0x02), // SC_VIDEO_INTERFACE_COLLECTION(0x03); // // public final byte subclass; // // private VideoSubclass(int subclass) { // this.subclass = (byte) (subclass & 0xFF); // } // // public static VideoSubclass getVideoSubclass(byte subclass) { // for (VideoSubclass s : VideoSubclass.values()) { // if (s.subclass == subclass) { // return s; // } // } // return null; // } // } // Path: library/src/main/java/com/jwoolston/android/uvc/interfaces/VideoIAD.java import android.util.SparseArray; import com.jwoolston.android.uvc.interfaces.Descriptor.VideoSubclass; import timber.log.Timber; package com.jwoolston.android.uvc.interfaces; /** * @author Jared Woolston (Jared.Woolston@gmail.com) */ public class VideoIAD extends InterfaceAssociationDescriptor { private SparseArray<VideoClassInterface> interfaces; VideoIAD(byte[] descriptor) throws IllegalArgumentException { super(descriptor);
if (VideoSubclass.getVideoSubclass(descriptor[bFunctionSubClass])
jwoolston/Android-Webcam
library/src/main/java/com/jwoolston/android/uvc/interfaces/units/VideoEncodingUnit.java
// Path: library/src/main/java/com/jwoolston/android/uvc/interfaces/VideoClassInterface.java // public abstract class VideoClassInterface extends UvcInterface { // // VideoClassInterface(UsbInterface usbInterface, byte[] descriptor) { // super(usbInterface, descriptor); // } // // public static enum VC_INF_SUBTYPE { // VC_DESCRIPTOR_UNDEFINED(0x00), // VC_HEADER(0x01), // VC_INPUT_TERMINAL(0x02), // VC_OUTPUT_TERMINAL(0x03), // VC_SELECTOR_UNIT(0x04), // VC_PROCESSING_UNIT(0x05), // VC_EXTENSION_UNIT(0x06), // VC_ENCODING_UNIT(0x07); // // public final byte subtype; // // private VC_INF_SUBTYPE(int subtype) { // this.subtype = (byte) (subtype & 0xFF); // } // // public static VC_INF_SUBTYPE getSubtype(byte subtype) { // for (VC_INF_SUBTYPE s : VC_INF_SUBTYPE.values()) { // if (s.subtype == subtype) { // return s; // } // } // return null; // } // } // }
import com.jwoolston.android.uvc.interfaces.VideoClassInterface; import java.util.Collections; import java.util.HashSet; import java.util.Set; import timber.log.Timber;
package com.jwoolston.android.uvc.interfaces.units; /** * The Encoding Unit controls attributes of the encoder that encodes the video being streamed through it. It has a * single input and multiple output pins. It provides support for the following features which can be used before or * after streaming has started. * * <br>-Select Layer * <br>-Video Resolution * <br>-Profile and Toolset * <br>-Minimum Frame Interval * <br>-Slice Mode * <br>-Rate Control Mode * <br>-Average Bitrate Control * <br>-CPB Size Control * <br>-Peak Bit Rate * <br>-Quantization Parameter * <br>-Synchronization and Long Term Reference Frame * <br>-Long Term Reference Buffers * <br>-Long Term Picture * <br>-Valid Long Term Pictures * <br>-LevelIDC * <br>-SEI Message * <br>-QP Range * <br>-Priority ID * <br>-Start or Stop Layer * <br>-Error Resiliency * * Support for the Encoding Unit control is optional and only applicable to devices with onboard video encoders. The * Select Layer control also allows control of individual streams for devices that support simulcast transport of * more than one stream. Individual payloads may specialize the behavior of each of these controls to align with the * feature set defined by the associated encoder, e.g. H.264. This specialized behavior is defined in the associated * payload specification. * * @author Jared Woolston (Jared.Woolston@gmail.com) * @see <a href=http://www.usb.org/developers/docs/devclass_docs/USB_Video_Class_1_5.zip>UVC 1.5 Class * Specification §2.3.6</a> */ public class VideoEncodingUnit extends VideoUnit { private static final int LENGTH = 13; private static final int bSourceID = 4; private static final int iEncoding = 5; private static final int bmControls = 7; private static final int bmControlsRuntime = 10; private final int mSourceID; private final int mIndexEncoding; private final Set<CONTROL> mControlSet; private final Set<CONTROL> mRuntimeControlSet; public static boolean isVideoEncodingUnit(byte[] descriptor) { return (descriptor.length >= LENGTH
// Path: library/src/main/java/com/jwoolston/android/uvc/interfaces/VideoClassInterface.java // public abstract class VideoClassInterface extends UvcInterface { // // VideoClassInterface(UsbInterface usbInterface, byte[] descriptor) { // super(usbInterface, descriptor); // } // // public static enum VC_INF_SUBTYPE { // VC_DESCRIPTOR_UNDEFINED(0x00), // VC_HEADER(0x01), // VC_INPUT_TERMINAL(0x02), // VC_OUTPUT_TERMINAL(0x03), // VC_SELECTOR_UNIT(0x04), // VC_PROCESSING_UNIT(0x05), // VC_EXTENSION_UNIT(0x06), // VC_ENCODING_UNIT(0x07); // // public final byte subtype; // // private VC_INF_SUBTYPE(int subtype) { // this.subtype = (byte) (subtype & 0xFF); // } // // public static VC_INF_SUBTYPE getSubtype(byte subtype) { // for (VC_INF_SUBTYPE s : VC_INF_SUBTYPE.values()) { // if (s.subtype == subtype) { // return s; // } // } // return null; // } // } // } // Path: library/src/main/java/com/jwoolston/android/uvc/interfaces/units/VideoEncodingUnit.java import com.jwoolston.android.uvc.interfaces.VideoClassInterface; import java.util.Collections; import java.util.HashSet; import java.util.Set; import timber.log.Timber; package com.jwoolston.android.uvc.interfaces.units; /** * The Encoding Unit controls attributes of the encoder that encodes the video being streamed through it. It has a * single input and multiple output pins. It provides support for the following features which can be used before or * after streaming has started. * * <br>-Select Layer * <br>-Video Resolution * <br>-Profile and Toolset * <br>-Minimum Frame Interval * <br>-Slice Mode * <br>-Rate Control Mode * <br>-Average Bitrate Control * <br>-CPB Size Control * <br>-Peak Bit Rate * <br>-Quantization Parameter * <br>-Synchronization and Long Term Reference Frame * <br>-Long Term Reference Buffers * <br>-Long Term Picture * <br>-Valid Long Term Pictures * <br>-LevelIDC * <br>-SEI Message * <br>-QP Range * <br>-Priority ID * <br>-Start or Stop Layer * <br>-Error Resiliency * * Support for the Encoding Unit control is optional and only applicable to devices with onboard video encoders. The * Select Layer control also allows control of individual streams for devices that support simulcast transport of * more than one stream. Individual payloads may specialize the behavior of each of these controls to align with the * feature set defined by the associated encoder, e.g. H.264. This specialized behavior is defined in the associated * payload specification. * * @author Jared Woolston (Jared.Woolston@gmail.com) * @see <a href=http://www.usb.org/developers/docs/devclass_docs/USB_Video_Class_1_5.zip>UVC 1.5 Class * Specification §2.3.6</a> */ public class VideoEncodingUnit extends VideoUnit { private static final int LENGTH = 13; private static final int bSourceID = 4; private static final int iEncoding = 5; private static final int bmControls = 7; private static final int bmControlsRuntime = 10; private final int mSourceID; private final int mIndexEncoding; private final Set<CONTROL> mControlSet; private final Set<CONTROL> mRuntimeControlSet; public static boolean isVideoEncodingUnit(byte[] descriptor) { return (descriptor.length >= LENGTH
& descriptor[bDescriptorSubtype] == VideoClassInterface.VC_INF_SUBTYPE.VC_ENCODING_UNIT.subtype);
jwoolston/Android-Webcam
library/src/main/java/com/jwoolston/android/uvc/interfaces/InterfaceAssociationDescriptor.java
// Path: library/src/main/java/com/jwoolston/android/uvc/interfaces/Descriptor.java // public static enum Protocol { // PC_PROTOCOL_UNDEFINED(0x00), // PC_PROTOCOL_15(0x01); // // public final byte protocol; // // private Protocol(int protocol) { // this.protocol = (byte) (protocol & 0xFF); // } // }
import com.jwoolston.android.uvc.interfaces.Descriptor.Protocol; import timber.log.Timber;
package com.jwoolston.android.uvc.interfaces; /** * @author Jared Woolston (Jared.Woolston@gmail.com) */ public abstract class InterfaceAssociationDescriptor { private static final int LENGTH_DESCRIPTOR = 8; protected static final int bFirstInterface = 2; protected static final int bInterfaceCount = 3; protected static final int bFunctionClass = 4; protected static final int bFunctionSubClass = 5; protected static final int bFunctionProtocol = 6; protected static final int iFunction = 7; private final int firstInterface; private final int interfaceCount; private final int indexFunction; protected static InterfaceAssociationDescriptor parseIAD(byte[] descriptor) throws IllegalArgumentException { Timber.d("Parsing Interface Association Descriptor."); if (descriptor.length < LENGTH_DESCRIPTOR) { throw new IllegalArgumentException("The provided descriptor is not long enough. Have " + descriptor.length + " need " + LENGTH_DESCRIPTOR); } if (descriptor[bFunctionClass] == Descriptor.VIDEO_CLASS_CODE) {
// Path: library/src/main/java/com/jwoolston/android/uvc/interfaces/Descriptor.java // public static enum Protocol { // PC_PROTOCOL_UNDEFINED(0x00), // PC_PROTOCOL_15(0x01); // // public final byte protocol; // // private Protocol(int protocol) { // this.protocol = (byte) (protocol & 0xFF); // } // } // Path: library/src/main/java/com/jwoolston/android/uvc/interfaces/InterfaceAssociationDescriptor.java import com.jwoolston.android.uvc.interfaces.Descriptor.Protocol; import timber.log.Timber; package com.jwoolston.android.uvc.interfaces; /** * @author Jared Woolston (Jared.Woolston@gmail.com) */ public abstract class InterfaceAssociationDescriptor { private static final int LENGTH_DESCRIPTOR = 8; protected static final int bFirstInterface = 2; protected static final int bInterfaceCount = 3; protected static final int bFunctionClass = 4; protected static final int bFunctionSubClass = 5; protected static final int bFunctionProtocol = 6; protected static final int iFunction = 7; private final int firstInterface; private final int interfaceCount; private final int indexFunction; protected static InterfaceAssociationDescriptor parseIAD(byte[] descriptor) throws IllegalArgumentException { Timber.d("Parsing Interface Association Descriptor."); if (descriptor.length < LENGTH_DESCRIPTOR) { throw new IllegalArgumentException("The provided descriptor is not long enough. Have " + descriptor.length + " need " + LENGTH_DESCRIPTOR); } if (descriptor[bFunctionClass] == Descriptor.VIDEO_CLASS_CODE) {
if (descriptor[bFunctionProtocol] != Protocol.PC_PROTOCOL_UNDEFINED.protocol) {
jwoolston/Android-Webcam
library/src/main/java/com/jwoolston/android/uvc/requests/streaming/VSInterfaceControlRequest.java
// Path: library/src/main/java/com/jwoolston/android/uvc/requests/Request.java // public enum Request { // // RC_UNDEFINED((byte) 0x00), // SET_CUR((byte) 0x01), // SET_CUR_ALL((byte) 0x11), // GET_CUR((byte) 0x81), // GET_MIN((byte) 0x82), // GET_MAX((byte) 0x83), // GET_RES((byte) 0x84), // GET_LEN((byte) 0x85), // GET_INFO((byte) 0x86), // GET_DEF((byte) 0x87), // GET_CUR_ALL((byte) 0x91), // GET_MIN_ALL((byte) 0x92), // GET_MAX_ALL((byte) 0x93), // GET_RES_ALL((byte) 0x94), // GET_DEF_ALL((byte) 0x97); // // public final byte code; // // Request(byte code) { // this.code = code; // } // // @Override // public String toString() { // return (name() + "(0x" + Integer.toHexString(0xFF & code) + ')'); // } // } // // Path: library/src/main/java/com/jwoolston/android/uvc/requests/VideoClassRequest.java // public abstract class VideoClassRequest { // // protected static final byte SET_REQUEST_INF_ENTITY = 0x21; // Set Request type targeting entity or interface // protected static final byte SET_REQUEST_ENDPOINT = 0x22; // Set Request type targeting endpoint // protected static final byte GET_REQUEST_INF_ENTITY = (byte) 0xA1; // Get Request type targeting entity or interface // protected static final byte GET_REQUEST_ENDPOINT = (byte) 0xA2; // Get Request type targeting endpoint // // private final byte requestType; // private final Request request; // // private short wValue; // private short wIndex; // private byte[] data; // // protected static short getIndex(VideoTerminal terminal, VideoClassInterface classInterface) { // return (short) (((0xFF & terminal.getTerminalID()) << 8) | (0xFF & classInterface.getUsbInterface().getId())); // } // // protected VideoClassRequest(byte requestType, @NonNull Request request, short value, short index, // @NonNull byte[] data) { // this.requestType = requestType; // this.request = request; // wValue = value; // wIndex = index; // this.data = data; // } // // public byte getRequestType() { // return requestType; // } // // public byte getRequest() { // return request.code; // } // // public short getValue() { // return wValue; // } // // public short getIndex() { // return wIndex; // } // // public byte[] getData() { // return data; // } // // public int getLength() { // return data.length; // } // // @Override public String toString() { // final StringBuffer sb = new StringBuffer(getClass().getSimpleName()); // sb.append("{"); // sb.append("requestType=0x").append(Integer.toHexString(0xFF & requestType).toUpperCase(Locale.US)); // sb.append(", request=").append(request); // sb.append(", wValue=0x").append(Integer.toHexString(wValue).toUpperCase(Locale.US)); // sb.append(", wIndex=").append(wIndex); // sb.append(", data="); // if (data == null) { // sb.append("null"); // } else { // sb.append('['); // for (int i = 0; i < data.length; ++i) { // sb.append(i == 0 ? "" : ", ").append(data[i]); // } // sb.append(']'); // } // sb.append('}'); // return sb.toString(); // } // }
import android.support.annotation.NonNull; import com.jwoolston.android.uvc.requests.Request; import com.jwoolston.android.uvc.requests.VideoClassRequest;
package com.jwoolston.android.uvc.requests.streaming; /** * These requests are used to set or read an attribute of an interface Control inside the VideoStreaming interface of * the video function. * * The bRequest field indicates which attribute the request is manipulating. The MIN, MAX, and RES attributes are not * supported for the Set request. The wValue field specifies the Control Selector (CS) in the high byte, and the low * byte must be set to zero. The Control Selector indicates which type of Control this request is manipulating. If * the request specifies an unknown S to that endpoint, the control pipe must indicate a stall. * * @author Jared Woolston (Jared.Woolston@gmail.com) * @see <a href=http://www.usb.org/developers/docs/devclass_docs/USB_Video_Class_1_5.zip>UVC 1.5 Class * Specification §4.2.1</a> */ public abstract class VSInterfaceControlRequest extends VideoClassRequest { private static short valueFromControlSelector(@NonNull ControlSelector selector) { return ((short) (0xFFFF & (selector.code << 8))); }
// Path: library/src/main/java/com/jwoolston/android/uvc/requests/Request.java // public enum Request { // // RC_UNDEFINED((byte) 0x00), // SET_CUR((byte) 0x01), // SET_CUR_ALL((byte) 0x11), // GET_CUR((byte) 0x81), // GET_MIN((byte) 0x82), // GET_MAX((byte) 0x83), // GET_RES((byte) 0x84), // GET_LEN((byte) 0x85), // GET_INFO((byte) 0x86), // GET_DEF((byte) 0x87), // GET_CUR_ALL((byte) 0x91), // GET_MIN_ALL((byte) 0x92), // GET_MAX_ALL((byte) 0x93), // GET_RES_ALL((byte) 0x94), // GET_DEF_ALL((byte) 0x97); // // public final byte code; // // Request(byte code) { // this.code = code; // } // // @Override // public String toString() { // return (name() + "(0x" + Integer.toHexString(0xFF & code) + ')'); // } // } // // Path: library/src/main/java/com/jwoolston/android/uvc/requests/VideoClassRequest.java // public abstract class VideoClassRequest { // // protected static final byte SET_REQUEST_INF_ENTITY = 0x21; // Set Request type targeting entity or interface // protected static final byte SET_REQUEST_ENDPOINT = 0x22; // Set Request type targeting endpoint // protected static final byte GET_REQUEST_INF_ENTITY = (byte) 0xA1; // Get Request type targeting entity or interface // protected static final byte GET_REQUEST_ENDPOINT = (byte) 0xA2; // Get Request type targeting endpoint // // private final byte requestType; // private final Request request; // // private short wValue; // private short wIndex; // private byte[] data; // // protected static short getIndex(VideoTerminal terminal, VideoClassInterface classInterface) { // return (short) (((0xFF & terminal.getTerminalID()) << 8) | (0xFF & classInterface.getUsbInterface().getId())); // } // // protected VideoClassRequest(byte requestType, @NonNull Request request, short value, short index, // @NonNull byte[] data) { // this.requestType = requestType; // this.request = request; // wValue = value; // wIndex = index; // this.data = data; // } // // public byte getRequestType() { // return requestType; // } // // public byte getRequest() { // return request.code; // } // // public short getValue() { // return wValue; // } // // public short getIndex() { // return wIndex; // } // // public byte[] getData() { // return data; // } // // public int getLength() { // return data.length; // } // // @Override public String toString() { // final StringBuffer sb = new StringBuffer(getClass().getSimpleName()); // sb.append("{"); // sb.append("requestType=0x").append(Integer.toHexString(0xFF & requestType).toUpperCase(Locale.US)); // sb.append(", request=").append(request); // sb.append(", wValue=0x").append(Integer.toHexString(wValue).toUpperCase(Locale.US)); // sb.append(", wIndex=").append(wIndex); // sb.append(", data="); // if (data == null) { // sb.append("null"); // } else { // sb.append('['); // for (int i = 0; i < data.length; ++i) { // sb.append(i == 0 ? "" : ", ").append(data[i]); // } // sb.append(']'); // } // sb.append('}'); // return sb.toString(); // } // } // Path: library/src/main/java/com/jwoolston/android/uvc/requests/streaming/VSInterfaceControlRequest.java import android.support.annotation.NonNull; import com.jwoolston.android.uvc.requests.Request; import com.jwoolston.android.uvc.requests.VideoClassRequest; package com.jwoolston.android.uvc.requests.streaming; /** * These requests are used to set or read an attribute of an interface Control inside the VideoStreaming interface of * the video function. * * The bRequest field indicates which attribute the request is manipulating. The MIN, MAX, and RES attributes are not * supported for the Set request. The wValue field specifies the Control Selector (CS) in the high byte, and the low * byte must be set to zero. The Control Selector indicates which type of Control this request is manipulating. If * the request specifies an unknown S to that endpoint, the control pipe must indicate a stall. * * @author Jared Woolston (Jared.Woolston@gmail.com) * @see <a href=http://www.usb.org/developers/docs/devclass_docs/USB_Video_Class_1_5.zip>UVC 1.5 Class * Specification §4.2.1</a> */ public abstract class VSInterfaceControlRequest extends VideoClassRequest { private static short valueFromControlSelector(@NonNull ControlSelector selector) { return ((short) (0xFFFF & (selector.code << 8))); }
protected VSInterfaceControlRequest(@NonNull Request request, ControlSelector selector, short index,
jwoolston/Android-Webcam
library/src/main/java/com/jwoolston/android/uvc/interfaces/units/AVideoExtensionUnit.java
// Path: library/src/main/java/com/jwoolston/android/uvc/interfaces/VideoClassInterface.java // public abstract class VideoClassInterface extends UvcInterface { // // VideoClassInterface(UsbInterface usbInterface, byte[] descriptor) { // super(usbInterface, descriptor); // } // // public static enum VC_INF_SUBTYPE { // VC_DESCRIPTOR_UNDEFINED(0x00), // VC_HEADER(0x01), // VC_INPUT_TERMINAL(0x02), // VC_OUTPUT_TERMINAL(0x03), // VC_SELECTOR_UNIT(0x04), // VC_PROCESSING_UNIT(0x05), // VC_EXTENSION_UNIT(0x06), // VC_ENCODING_UNIT(0x07); // // public final byte subtype; // // private VC_INF_SUBTYPE(int subtype) { // this.subtype = (byte) (subtype & 0xFF); // } // // public static VC_INF_SUBTYPE getSubtype(byte subtype) { // for (VC_INF_SUBTYPE s : VC_INF_SUBTYPE.values()) { // if (s.subtype == subtype) { // return s; // } // } // return null; // } // } // }
import com.jwoolston.android.uvc.interfaces.VideoClassInterface;
package com.jwoolston.android.uvc.interfaces.units; /** * The Extension Unit (XU) is the method provided by this specification to add vendor-specific building blocks to the * specification. The Extension Unit can have one or more Input Pins and has a single Output Pin. * Although a generic host driver will not be able to determine what functionality is implemented in the Extension * Unit, it shall report the presence of these extensions to vendor-supplied client software, and provide a method * for sending control requests from the client software to the Unit, and receiving status from the unit. * * @author Jared Woolston (Jared.Woolston@gmail.com) * @see <a href=http://www.usb.org/developers/docs/devclass_docs/USB_Video_Class_1_5.zip>UVC 1.5 Class * Specification §2.3.7</a> */ public class AVideoExtensionUnit extends VideoUnit { private static final int MIN_LENGTH = 24; private static final int guidExtensionCode = 4; private static final int bNumControls = 20; private static final int bNrInPins = 21; // p private static final int baSourceID = 22; private static final int bControlSize = 22; // + p = n private static final int bmControls = 23; // + p private static final int iExtension = 23; // + descriptor[bNrInPins] + p + n private final byte[] mGUID = new byte[bNumControls - guidExtensionCode]; private final int mNumControls; private final int mNumInputPins; private final int[] mSourceIDs; private final byte[] mRawControlMask; private final int mIndexExtension; protected final int mControlSize; public static boolean isVideoExtensionUnit(byte[] descriptor) { return (descriptor.length >= MIN_LENGTH
// Path: library/src/main/java/com/jwoolston/android/uvc/interfaces/VideoClassInterface.java // public abstract class VideoClassInterface extends UvcInterface { // // VideoClassInterface(UsbInterface usbInterface, byte[] descriptor) { // super(usbInterface, descriptor); // } // // public static enum VC_INF_SUBTYPE { // VC_DESCRIPTOR_UNDEFINED(0x00), // VC_HEADER(0x01), // VC_INPUT_TERMINAL(0x02), // VC_OUTPUT_TERMINAL(0x03), // VC_SELECTOR_UNIT(0x04), // VC_PROCESSING_UNIT(0x05), // VC_EXTENSION_UNIT(0x06), // VC_ENCODING_UNIT(0x07); // // public final byte subtype; // // private VC_INF_SUBTYPE(int subtype) { // this.subtype = (byte) (subtype & 0xFF); // } // // public static VC_INF_SUBTYPE getSubtype(byte subtype) { // for (VC_INF_SUBTYPE s : VC_INF_SUBTYPE.values()) { // if (s.subtype == subtype) { // return s; // } // } // return null; // } // } // } // Path: library/src/main/java/com/jwoolston/android/uvc/interfaces/units/AVideoExtensionUnit.java import com.jwoolston.android.uvc.interfaces.VideoClassInterface; package com.jwoolston.android.uvc.interfaces.units; /** * The Extension Unit (XU) is the method provided by this specification to add vendor-specific building blocks to the * specification. The Extension Unit can have one or more Input Pins and has a single Output Pin. * Although a generic host driver will not be able to determine what functionality is implemented in the Extension * Unit, it shall report the presence of these extensions to vendor-supplied client software, and provide a method * for sending control requests from the client software to the Unit, and receiving status from the unit. * * @author Jared Woolston (Jared.Woolston@gmail.com) * @see <a href=http://www.usb.org/developers/docs/devclass_docs/USB_Video_Class_1_5.zip>UVC 1.5 Class * Specification §2.3.7</a> */ public class AVideoExtensionUnit extends VideoUnit { private static final int MIN_LENGTH = 24; private static final int guidExtensionCode = 4; private static final int bNumControls = 20; private static final int bNrInPins = 21; // p private static final int baSourceID = 22; private static final int bControlSize = 22; // + p = n private static final int bmControls = 23; // + p private static final int iExtension = 23; // + descriptor[bNrInPins] + p + n private final byte[] mGUID = new byte[bNumControls - guidExtensionCode]; private final int mNumControls; private final int mNumInputPins; private final int[] mSourceIDs; private final byte[] mRawControlMask; private final int mIndexExtension; protected final int mControlSize; public static boolean isVideoExtensionUnit(byte[] descriptor) { return (descriptor.length >= MIN_LENGTH
& descriptor[bDescriptorSubtype] == VideoClassInterface.VC_INF_SUBTYPE.VC_EXTENSION_UNIT.subtype);
jwoolston/Android-Webcam
library/src/main/java/com/jwoolston/android/uvc/interfaces/terminals/VideoTerminal.java
// Path: library/src/main/java/com/jwoolston/android/uvc/interfaces/VideoClassInterface.java // public abstract class VideoClassInterface extends UvcInterface { // // VideoClassInterface(UsbInterface usbInterface, byte[] descriptor) { // super(usbInterface, descriptor); // } // // public static enum VC_INF_SUBTYPE { // VC_DESCRIPTOR_UNDEFINED(0x00), // VC_HEADER(0x01), // VC_INPUT_TERMINAL(0x02), // VC_OUTPUT_TERMINAL(0x03), // VC_SELECTOR_UNIT(0x04), // VC_PROCESSING_UNIT(0x05), // VC_EXTENSION_UNIT(0x06), // VC_ENCODING_UNIT(0x07); // // public final byte subtype; // // private VC_INF_SUBTYPE(int subtype) { // this.subtype = (byte) (subtype & 0xFF); // } // // public static VC_INF_SUBTYPE getSubtype(byte subtype) { // for (VC_INF_SUBTYPE s : VC_INF_SUBTYPE.values()) { // if (s.subtype == subtype) { // return s; // } // } // return null; // } // } // }
import com.jwoolston.android.uvc.interfaces.VideoClassInterface;
package com.jwoolston.android.uvc.interfaces.terminals; /** * @author Jared Woolston (Jared.Woolston@gmail.com) */ public abstract class VideoTerminal { protected static final int bLength = 0; protected static final int bDescriptorType = 1; protected static final int bDescriptorSubtype = 2; protected static final int bTerminalID = 3; protected static final int wTerminalType = 4; protected static final int bAssocTerminal = 6; private final TerminalType terminalType; private final int terminalID; private final int associatedTerminalID; public static boolean isVideoTerminal(byte[] descriptor) {
// Path: library/src/main/java/com/jwoolston/android/uvc/interfaces/VideoClassInterface.java // public abstract class VideoClassInterface extends UvcInterface { // // VideoClassInterface(UsbInterface usbInterface, byte[] descriptor) { // super(usbInterface, descriptor); // } // // public static enum VC_INF_SUBTYPE { // VC_DESCRIPTOR_UNDEFINED(0x00), // VC_HEADER(0x01), // VC_INPUT_TERMINAL(0x02), // VC_OUTPUT_TERMINAL(0x03), // VC_SELECTOR_UNIT(0x04), // VC_PROCESSING_UNIT(0x05), // VC_EXTENSION_UNIT(0x06), // VC_ENCODING_UNIT(0x07); // // public final byte subtype; // // private VC_INF_SUBTYPE(int subtype) { // this.subtype = (byte) (subtype & 0xFF); // } // // public static VC_INF_SUBTYPE getSubtype(byte subtype) { // for (VC_INF_SUBTYPE s : VC_INF_SUBTYPE.values()) { // if (s.subtype == subtype) { // return s; // } // } // return null; // } // } // } // Path: library/src/main/java/com/jwoolston/android/uvc/interfaces/terminals/VideoTerminal.java import com.jwoolston.android.uvc.interfaces.VideoClassInterface; package com.jwoolston.android.uvc.interfaces.terminals; /** * @author Jared Woolston (Jared.Woolston@gmail.com) */ public abstract class VideoTerminal { protected static final int bLength = 0; protected static final int bDescriptorType = 1; protected static final int bDescriptorSubtype = 2; protected static final int bTerminalID = 3; protected static final int wTerminalType = 4; protected static final int bAssocTerminal = 6; private final TerminalType terminalType; private final int terminalID; private final int associatedTerminalID; public static boolean isVideoTerminal(byte[] descriptor) {
return (descriptor[bDescriptorSubtype] == VideoClassInterface.VC_INF_SUBTYPE.VC_INPUT_TERMINAL.subtype ||
jwoolston/Android-Webcam
library/src/main/java/com/jwoolston/android/uvc/Webcam.java
// Path: library/src/main/java/com/jwoolston/android/uvc/interfaces/streaming/VideoFormat.java // public class VideoFormat<T extends VideoFrame> { // // protected int formatIndex; // protected int numberFrames; // protected int defaultFrameIndex; // protected int aspectRatioX; // protected int aspectRatioY; // protected byte interlaceFlags; // protected boolean copyProtect; // // private VideoColorMatchingDescriptor colorMatchingDescriptor; // // protected final Set<T> videoFrames = new HashSet<>(); // // VideoFormat(@NonNull byte[] descriptor) throws IllegalArgumentException { // // } // // public void setColorMatchingDescriptor(VideoColorMatchingDescriptor descriptor) { // colorMatchingDescriptor = descriptor; // } // // public VideoColorMatchingDescriptor getColorMatchingDescriptor() { // return colorMatchingDescriptor; // } // // public int getFormatIndex() { // return formatIndex; // } // // public int getNumberFrames() { // return numberFrames; // } // // public int getDefaultFrameIndex() { // return defaultFrameIndex; // } // // @NonNull // public Set<T> getVideoFrames() { // return videoFrames; // } // // public int getAspectRatioX() { // return aspectRatioX; // } // // public int getAspectRatioY() { // return aspectRatioY; // } // // public byte getInterlaceFlags() { // return interlaceFlags; // } // // public boolean isCopyProtect() { // return copyProtect; // } // // public VideoFrame getDefaultFrame() throws IllegalStateException { // for (VideoFrame frame : videoFrames) { // if (frame.getFrameIndex() == getDefaultFrameIndex()) { // return frame; // } // } // throw new IllegalStateException("No default frame was found!"); // } // }
import android.content.Context; import android.hardware.usb.UsbDevice; import android.net.Uri; import android.support.annotation.NonNull; import com.jwoolston.android.uvc.interfaces.streaming.VideoFormat; import java.util.List;
package com.jwoolston.android.uvc; /** * @author Jared Woolston (Jared.Woolston@gmail.com) */ public interface Webcam { /** * The {@link UsbDevice} interface to this camera. * * @return camera {@link UsbDevice} */ @NonNull UsbDevice getDevice(); /** * Determine if an active connection to the camera exists. * * @return true if connected to the camera */ boolean isConnected(); /** * Begin streaming from the device and retrieve the {@link Uri} for the data stream for this {@link Webcam}. * * @param context {@link Context} The application context. * @param format The {@link VideoFormat} to stream in. * * @return {@link Uri} The data source {@link Uri}. * * @throws StreamCreationException Thrown if there is a problem establishing the stream buffer. */ @NonNull
// Path: library/src/main/java/com/jwoolston/android/uvc/interfaces/streaming/VideoFormat.java // public class VideoFormat<T extends VideoFrame> { // // protected int formatIndex; // protected int numberFrames; // protected int defaultFrameIndex; // protected int aspectRatioX; // protected int aspectRatioY; // protected byte interlaceFlags; // protected boolean copyProtect; // // private VideoColorMatchingDescriptor colorMatchingDescriptor; // // protected final Set<T> videoFrames = new HashSet<>(); // // VideoFormat(@NonNull byte[] descriptor) throws IllegalArgumentException { // // } // // public void setColorMatchingDescriptor(VideoColorMatchingDescriptor descriptor) { // colorMatchingDescriptor = descriptor; // } // // public VideoColorMatchingDescriptor getColorMatchingDescriptor() { // return colorMatchingDescriptor; // } // // public int getFormatIndex() { // return formatIndex; // } // // public int getNumberFrames() { // return numberFrames; // } // // public int getDefaultFrameIndex() { // return defaultFrameIndex; // } // // @NonNull // public Set<T> getVideoFrames() { // return videoFrames; // } // // public int getAspectRatioX() { // return aspectRatioX; // } // // public int getAspectRatioY() { // return aspectRatioY; // } // // public byte getInterlaceFlags() { // return interlaceFlags; // } // // public boolean isCopyProtect() { // return copyProtect; // } // // public VideoFrame getDefaultFrame() throws IllegalStateException { // for (VideoFrame frame : videoFrames) { // if (frame.getFrameIndex() == getDefaultFrameIndex()) { // return frame; // } // } // throw new IllegalStateException("No default frame was found!"); // } // } // Path: library/src/main/java/com/jwoolston/android/uvc/Webcam.java import android.content.Context; import android.hardware.usb.UsbDevice; import android.net.Uri; import android.support.annotation.NonNull; import com.jwoolston.android.uvc.interfaces.streaming.VideoFormat; import java.util.List; package com.jwoolston.android.uvc; /** * @author Jared Woolston (Jared.Woolston@gmail.com) */ public interface Webcam { /** * The {@link UsbDevice} interface to this camera. * * @return camera {@link UsbDevice} */ @NonNull UsbDevice getDevice(); /** * Determine if an active connection to the camera exists. * * @return true if connected to the camera */ boolean isConnected(); /** * Begin streaming from the device and retrieve the {@link Uri} for the data stream for this {@link Webcam}. * * @param context {@link Context} The application context. * @param format The {@link VideoFormat} to stream in. * * @return {@link Uri} The data source {@link Uri}. * * @throws StreamCreationException Thrown if there is a problem establishing the stream buffer. */ @NonNull
Uri beginStreaming(@NonNull Context context, @NonNull VideoFormat format) throws StreamCreationException;
jwoolston/Android-Webcam
library/src/main/java/com/jwoolston/android/uvc/requests/control/VCInterfaceControlRequest.java
// Path: library/src/main/java/com/jwoolston/android/uvc/requests/Request.java // public enum Request { // // RC_UNDEFINED((byte) 0x00), // SET_CUR((byte) 0x01), // SET_CUR_ALL((byte) 0x11), // GET_CUR((byte) 0x81), // GET_MIN((byte) 0x82), // GET_MAX((byte) 0x83), // GET_RES((byte) 0x84), // GET_LEN((byte) 0x85), // GET_INFO((byte) 0x86), // GET_DEF((byte) 0x87), // GET_CUR_ALL((byte) 0x91), // GET_MIN_ALL((byte) 0x92), // GET_MAX_ALL((byte) 0x93), // GET_RES_ALL((byte) 0x94), // GET_DEF_ALL((byte) 0x97); // // public final byte code; // // Request(byte code) { // this.code = code; // } // // @Override // public String toString() { // return (name() + "(0x" + Integer.toHexString(0xFF & code) + ')'); // } // } // // Path: library/src/main/java/com/jwoolston/android/uvc/requests/VideoClassRequest.java // public abstract class VideoClassRequest { // // protected static final byte SET_REQUEST_INF_ENTITY = 0x21; // Set Request type targeting entity or interface // protected static final byte SET_REQUEST_ENDPOINT = 0x22; // Set Request type targeting endpoint // protected static final byte GET_REQUEST_INF_ENTITY = (byte) 0xA1; // Get Request type targeting entity or interface // protected static final byte GET_REQUEST_ENDPOINT = (byte) 0xA2; // Get Request type targeting endpoint // // private final byte requestType; // private final Request request; // // private short wValue; // private short wIndex; // private byte[] data; // // protected static short getIndex(VideoTerminal terminal, VideoClassInterface classInterface) { // return (short) (((0xFF & terminal.getTerminalID()) << 8) | (0xFF & classInterface.getUsbInterface().getId())); // } // // protected VideoClassRequest(byte requestType, @NonNull Request request, short value, short index, // @NonNull byte[] data) { // this.requestType = requestType; // this.request = request; // wValue = value; // wIndex = index; // this.data = data; // } // // public byte getRequestType() { // return requestType; // } // // public byte getRequest() { // return request.code; // } // // public short getValue() { // return wValue; // } // // public short getIndex() { // return wIndex; // } // // public byte[] getData() { // return data; // } // // public int getLength() { // return data.length; // } // // @Override public String toString() { // final StringBuffer sb = new StringBuffer(getClass().getSimpleName()); // sb.append("{"); // sb.append("requestType=0x").append(Integer.toHexString(0xFF & requestType).toUpperCase(Locale.US)); // sb.append(", request=").append(request); // sb.append(", wValue=0x").append(Integer.toHexString(wValue).toUpperCase(Locale.US)); // sb.append(", wIndex=").append(wIndex); // sb.append(", data="); // if (data == null) { // sb.append("null"); // } else { // sb.append('['); // for (int i = 0; i < data.length; ++i) { // sb.append(i == 0 ? "" : ", ").append(data[i]); // } // sb.append(']'); // } // sb.append('}'); // return sb.toString(); // } // }
import android.support.annotation.NonNull; import com.jwoolston.android.uvc.requests.Request; import com.jwoolston.android.uvc.requests.VideoClassRequest;
package com.jwoolston.android.uvc.requests.control; /** * These requests are used to set or read an attribute of an interface Control inside the VideoControl interface of * the video function. * * The bRequest field indicates which attribute the request is manipulating. The MIN, MAX, and RES attributes are not * supported for the Set request. The wValue field specifies the Control Selector (CS) in the high byte, and the low * byte must be set to zero. The Control Selector indicates which type of Control this request is manipulating. If * the request specifies an unknown S to that endpoint, the control pipe must indicate a stall. * * @author Jared Woolston (Jared.Woolston@gmail.com) * @see <a href=http://www.usb.org/developers/docs/devclass_docs/USB_Video_Class_1_5.zip>UVC 1.5 Class * Specification §4.2.1</a> */ public abstract class VCInterfaceControlRequest extends VideoClassRequest { private static short valueFromControlSelector(@NonNull ControlSelector selector) { return ((short) (0xFFFF & (selector.code << 8))); }
// Path: library/src/main/java/com/jwoolston/android/uvc/requests/Request.java // public enum Request { // // RC_UNDEFINED((byte) 0x00), // SET_CUR((byte) 0x01), // SET_CUR_ALL((byte) 0x11), // GET_CUR((byte) 0x81), // GET_MIN((byte) 0x82), // GET_MAX((byte) 0x83), // GET_RES((byte) 0x84), // GET_LEN((byte) 0x85), // GET_INFO((byte) 0x86), // GET_DEF((byte) 0x87), // GET_CUR_ALL((byte) 0x91), // GET_MIN_ALL((byte) 0x92), // GET_MAX_ALL((byte) 0x93), // GET_RES_ALL((byte) 0x94), // GET_DEF_ALL((byte) 0x97); // // public final byte code; // // Request(byte code) { // this.code = code; // } // // @Override // public String toString() { // return (name() + "(0x" + Integer.toHexString(0xFF & code) + ')'); // } // } // // Path: library/src/main/java/com/jwoolston/android/uvc/requests/VideoClassRequest.java // public abstract class VideoClassRequest { // // protected static final byte SET_REQUEST_INF_ENTITY = 0x21; // Set Request type targeting entity or interface // protected static final byte SET_REQUEST_ENDPOINT = 0x22; // Set Request type targeting endpoint // protected static final byte GET_REQUEST_INF_ENTITY = (byte) 0xA1; // Get Request type targeting entity or interface // protected static final byte GET_REQUEST_ENDPOINT = (byte) 0xA2; // Get Request type targeting endpoint // // private final byte requestType; // private final Request request; // // private short wValue; // private short wIndex; // private byte[] data; // // protected static short getIndex(VideoTerminal terminal, VideoClassInterface classInterface) { // return (short) (((0xFF & terminal.getTerminalID()) << 8) | (0xFF & classInterface.getUsbInterface().getId())); // } // // protected VideoClassRequest(byte requestType, @NonNull Request request, short value, short index, // @NonNull byte[] data) { // this.requestType = requestType; // this.request = request; // wValue = value; // wIndex = index; // this.data = data; // } // // public byte getRequestType() { // return requestType; // } // // public byte getRequest() { // return request.code; // } // // public short getValue() { // return wValue; // } // // public short getIndex() { // return wIndex; // } // // public byte[] getData() { // return data; // } // // public int getLength() { // return data.length; // } // // @Override public String toString() { // final StringBuffer sb = new StringBuffer(getClass().getSimpleName()); // sb.append("{"); // sb.append("requestType=0x").append(Integer.toHexString(0xFF & requestType).toUpperCase(Locale.US)); // sb.append(", request=").append(request); // sb.append(", wValue=0x").append(Integer.toHexString(wValue).toUpperCase(Locale.US)); // sb.append(", wIndex=").append(wIndex); // sb.append(", data="); // if (data == null) { // sb.append("null"); // } else { // sb.append('['); // for (int i = 0; i < data.length; ++i) { // sb.append(i == 0 ? "" : ", ").append(data[i]); // } // sb.append(']'); // } // sb.append('}'); // return sb.toString(); // } // } // Path: library/src/main/java/com/jwoolston/android/uvc/requests/control/VCInterfaceControlRequest.java import android.support.annotation.NonNull; import com.jwoolston.android.uvc.requests.Request; import com.jwoolston.android.uvc.requests.VideoClassRequest; package com.jwoolston.android.uvc.requests.control; /** * These requests are used to set or read an attribute of an interface Control inside the VideoControl interface of * the video function. * * The bRequest field indicates which attribute the request is manipulating. The MIN, MAX, and RES attributes are not * supported for the Set request. The wValue field specifies the Control Selector (CS) in the high byte, and the low * byte must be set to zero. The Control Selector indicates which type of Control this request is manipulating. If * the request specifies an unknown S to that endpoint, the control pipe must indicate a stall. * * @author Jared Woolston (Jared.Woolston@gmail.com) * @see <a href=http://www.usb.org/developers/docs/devclass_docs/USB_Video_Class_1_5.zip>UVC 1.5 Class * Specification §4.2.1</a> */ public abstract class VCInterfaceControlRequest extends VideoClassRequest { private static short valueFromControlSelector(@NonNull ControlSelector selector) { return ((short) (0xFFFF & (selector.code << 8))); }
protected VCInterfaceControlRequest(@NonNull Request request, ControlSelector selector, short index,
jwoolston/Android-Webcam
library/src/main/java/com/jwoolston/android/uvc/interfaces/units/VideoProcessingUnit.java
// Path: library/src/main/java/com/jwoolston/android/uvc/interfaces/VideoClassInterface.java // public abstract class VideoClassInterface extends UvcInterface { // // VideoClassInterface(UsbInterface usbInterface, byte[] descriptor) { // super(usbInterface, descriptor); // } // // public static enum VC_INF_SUBTYPE { // VC_DESCRIPTOR_UNDEFINED(0x00), // VC_HEADER(0x01), // VC_INPUT_TERMINAL(0x02), // VC_OUTPUT_TERMINAL(0x03), // VC_SELECTOR_UNIT(0x04), // VC_PROCESSING_UNIT(0x05), // VC_EXTENSION_UNIT(0x06), // VC_ENCODING_UNIT(0x07); // // public final byte subtype; // // private VC_INF_SUBTYPE(int subtype) { // this.subtype = (byte) (subtype & 0xFF); // } // // public static VC_INF_SUBTYPE getSubtype(byte subtype) { // for (VC_INF_SUBTYPE s : VC_INF_SUBTYPE.values()) { // if (s.subtype == subtype) { // return s; // } // } // return null; // } // } // }
import com.jwoolston.android.uvc.interfaces.VideoClassInterface; import java.util.Set; import timber.log.Timber;
package com.jwoolston.android.uvc.interfaces.units; /** * The Processing Unit (PU) controls image attributes of the video being streamed through it. It has a single input * and output pin. It provides support for the following features: * <br><br><b>User Controls</b> * <br>- Brightness * <br>- Hue * <br>- Saturation * <br>- Sharpness * <br>- Gamma * <br>- Digital Multiplier (Zoom) * <br><br><b>Auto Controls</b> * <br>-White Balance Temperature * <br>-White Balance Component * <br>-Backlight Compensation * <br>-Contrast * <br><br><b>Other</b> * <br>-Gain * <br>-Power Line Frequency * <br>-Analog Video Standard * <br>-Analog Video Lock Status * * Support for any particular control is optional. In particular, if the device supports the White Balance function, * it shall implement either the White Balance Temperature control or the White Balance Component control, but not * both. The User Controls indicate properties that are governed by user preference and not subject to any automatic * adjustment by the device. The Auto Controls will provide support for an auto setting (with an on/off state). If * the auto setting for a particular control is supported and set to the on state, the device will provide automatic * adjustment of the control, and read requests to the related control will reflect the automatically set value. * Attempts to programmatically set the Focus control when in auto mode shall result in protocol STALL with an error * code of <b>bRequestErrorCode</b> = “Wrong State”. When leaving an auto mode, the related control shall remain at the * value that was in effect just before the transition. * * @author Jared Woolston (Jared.Woolston@gmail.com) * @see <a href=http://www.usb.org/developers/docs/devclass_docs/USB_Video_Class_1_5.zip>UVC 1.5 Class * Specification §2.3.5</a> */ public class VideoProcessingUnit extends VideoUnit { private static final int LENGTH = 11; //TODO: Spec says 13? private static final int bSourceID = 4; private static final int wMaxMultiplier = 5; private static final int bmControls = 8; private static final int iProcessing = 11; private static final int bmVideoStandards = 12; private final int mSourceID; /** * Represented multiplier is x100. For example, 4.5 is represented as 450. */ private final int mMaxMultiplier; private final int mIndexProcessing = 0; private final Set<CONTROL> mControlSet = null; private final Set<STANDARD> mStandardSet = null; public static boolean isVideoProcessingUnit(byte[] descriptor) { return (descriptor.length >= LENGTH
// Path: library/src/main/java/com/jwoolston/android/uvc/interfaces/VideoClassInterface.java // public abstract class VideoClassInterface extends UvcInterface { // // VideoClassInterface(UsbInterface usbInterface, byte[] descriptor) { // super(usbInterface, descriptor); // } // // public static enum VC_INF_SUBTYPE { // VC_DESCRIPTOR_UNDEFINED(0x00), // VC_HEADER(0x01), // VC_INPUT_TERMINAL(0x02), // VC_OUTPUT_TERMINAL(0x03), // VC_SELECTOR_UNIT(0x04), // VC_PROCESSING_UNIT(0x05), // VC_EXTENSION_UNIT(0x06), // VC_ENCODING_UNIT(0x07); // // public final byte subtype; // // private VC_INF_SUBTYPE(int subtype) { // this.subtype = (byte) (subtype & 0xFF); // } // // public static VC_INF_SUBTYPE getSubtype(byte subtype) { // for (VC_INF_SUBTYPE s : VC_INF_SUBTYPE.values()) { // if (s.subtype == subtype) { // return s; // } // } // return null; // } // } // } // Path: library/src/main/java/com/jwoolston/android/uvc/interfaces/units/VideoProcessingUnit.java import com.jwoolston.android.uvc.interfaces.VideoClassInterface; import java.util.Set; import timber.log.Timber; package com.jwoolston.android.uvc.interfaces.units; /** * The Processing Unit (PU) controls image attributes of the video being streamed through it. It has a single input * and output pin. It provides support for the following features: * <br><br><b>User Controls</b> * <br>- Brightness * <br>- Hue * <br>- Saturation * <br>- Sharpness * <br>- Gamma * <br>- Digital Multiplier (Zoom) * <br><br><b>Auto Controls</b> * <br>-White Balance Temperature * <br>-White Balance Component * <br>-Backlight Compensation * <br>-Contrast * <br><br><b>Other</b> * <br>-Gain * <br>-Power Line Frequency * <br>-Analog Video Standard * <br>-Analog Video Lock Status * * Support for any particular control is optional. In particular, if the device supports the White Balance function, * it shall implement either the White Balance Temperature control or the White Balance Component control, but not * both. The User Controls indicate properties that are governed by user preference and not subject to any automatic * adjustment by the device. The Auto Controls will provide support for an auto setting (with an on/off state). If * the auto setting for a particular control is supported and set to the on state, the device will provide automatic * adjustment of the control, and read requests to the related control will reflect the automatically set value. * Attempts to programmatically set the Focus control when in auto mode shall result in protocol STALL with an error * code of <b>bRequestErrorCode</b> = “Wrong State”. When leaving an auto mode, the related control shall remain at the * value that was in effect just before the transition. * * @author Jared Woolston (Jared.Woolston@gmail.com) * @see <a href=http://www.usb.org/developers/docs/devclass_docs/USB_Video_Class_1_5.zip>UVC 1.5 Class * Specification §2.3.5</a> */ public class VideoProcessingUnit extends VideoUnit { private static final int LENGTH = 11; //TODO: Spec says 13? private static final int bSourceID = 4; private static final int wMaxMultiplier = 5; private static final int bmControls = 8; private static final int iProcessing = 11; private static final int bmVideoStandards = 12; private final int mSourceID; /** * Represented multiplier is x100. For example, 4.5 is represented as 450. */ private final int mMaxMultiplier; private final int mIndexProcessing = 0; private final Set<CONTROL> mControlSet = null; private final Set<STANDARD> mStandardSet = null; public static boolean isVideoProcessingUnit(byte[] descriptor) { return (descriptor.length >= LENGTH
& descriptor[bDescriptorSubtype] == VideoClassInterface.VC_INF_SUBTYPE.VC_PROCESSING_UNIT.subtype);
jwoolston/Android-Webcam
library/src/main/java/com/jwoolston/android/uvc/interfaces/terminals/VideoInputTerminal.java
// Path: library/src/main/java/com/jwoolston/android/uvc/interfaces/VideoClassInterface.java // public abstract class VideoClassInterface extends UvcInterface { // // VideoClassInterface(UsbInterface usbInterface, byte[] descriptor) { // super(usbInterface, descriptor); // } // // public static enum VC_INF_SUBTYPE { // VC_DESCRIPTOR_UNDEFINED(0x00), // VC_HEADER(0x01), // VC_INPUT_TERMINAL(0x02), // VC_OUTPUT_TERMINAL(0x03), // VC_SELECTOR_UNIT(0x04), // VC_PROCESSING_UNIT(0x05), // VC_EXTENSION_UNIT(0x06), // VC_ENCODING_UNIT(0x07); // // public final byte subtype; // // private VC_INF_SUBTYPE(int subtype) { // this.subtype = (byte) (subtype & 0xFF); // } // // public static VC_INF_SUBTYPE getSubtype(byte subtype) { // for (VC_INF_SUBTYPE s : VC_INF_SUBTYPE.values()) { // if (s.subtype == subtype) { // return s; // } // } // return null; // } // } // }
import com.jwoolston.android.uvc.interfaces.VideoClassInterface;
package com.jwoolston.android.uvc.interfaces.terminals; /** * The Input Terminal (IT) is used as an interface between the video function’s "outside world" and other Units * inside the video function. It serves as a receptacle for data flowing into the video function. Its function is to * represent a source of incoming data after this data has been extracted from the data source. The data may include * audio and metadata associated with a video stream. These physical streams are grouped into a cluster of logical * streams, leaving the Input Terminal through a single Output Pin. * An Input Terminal can represent inputs to the video function other than USB OUT endpoints. A CCD sensor on a video * camera or a composite video input is an example of such a non-USB input. However, if the video stream is entering * the video function by means of a USB OUT endpoint, there is a one-to-one relationship between that endpoint and * its associated Input Terminal. The class-specific Output Header descriptor contains a field that holds a direct * reference to this Input Terminal (see section 3.9.2.2, “Output Header Descriptor”). The Host needs to use both the * endpoint descriptors and the Input Terminal descriptor to get a full understanding of the characteristics and * capabilities of the Input Terminal. Stream-related parameters are stored in the endpoint descriptors. * Control-related parameters are stored in the Terminal descriptor. * * @author Jared Woolston (Jared.Woolston@gmail.com) * @see <a href=http://www.usb.org/developers/docs/devclass_docs/USB_Video_Class_1_5.zip>UVC 1.5 Class * Specification §2.3.2</a> */ public class VideoInputTerminal extends VideoTerminal { protected static final int MIN_LENGTH = 8; protected static final int iTerminal = 7; public static boolean isInputTerminal(byte[] descriptor) { return (descriptor.length >= MIN_LENGTH
// Path: library/src/main/java/com/jwoolston/android/uvc/interfaces/VideoClassInterface.java // public abstract class VideoClassInterface extends UvcInterface { // // VideoClassInterface(UsbInterface usbInterface, byte[] descriptor) { // super(usbInterface, descriptor); // } // // public static enum VC_INF_SUBTYPE { // VC_DESCRIPTOR_UNDEFINED(0x00), // VC_HEADER(0x01), // VC_INPUT_TERMINAL(0x02), // VC_OUTPUT_TERMINAL(0x03), // VC_SELECTOR_UNIT(0x04), // VC_PROCESSING_UNIT(0x05), // VC_EXTENSION_UNIT(0x06), // VC_ENCODING_UNIT(0x07); // // public final byte subtype; // // private VC_INF_SUBTYPE(int subtype) { // this.subtype = (byte) (subtype & 0xFF); // } // // public static VC_INF_SUBTYPE getSubtype(byte subtype) { // for (VC_INF_SUBTYPE s : VC_INF_SUBTYPE.values()) { // if (s.subtype == subtype) { // return s; // } // } // return null; // } // } // } // Path: library/src/main/java/com/jwoolston/android/uvc/interfaces/terminals/VideoInputTerminal.java import com.jwoolston.android.uvc.interfaces.VideoClassInterface; package com.jwoolston.android.uvc.interfaces.terminals; /** * The Input Terminal (IT) is used as an interface between the video function’s "outside world" and other Units * inside the video function. It serves as a receptacle for data flowing into the video function. Its function is to * represent a source of incoming data after this data has been extracted from the data source. The data may include * audio and metadata associated with a video stream. These physical streams are grouped into a cluster of logical * streams, leaving the Input Terminal through a single Output Pin. * An Input Terminal can represent inputs to the video function other than USB OUT endpoints. A CCD sensor on a video * camera or a composite video input is an example of such a non-USB input. However, if the video stream is entering * the video function by means of a USB OUT endpoint, there is a one-to-one relationship between that endpoint and * its associated Input Terminal. The class-specific Output Header descriptor contains a field that holds a direct * reference to this Input Terminal (see section 3.9.2.2, “Output Header Descriptor”). The Host needs to use both the * endpoint descriptors and the Input Terminal descriptor to get a full understanding of the characteristics and * capabilities of the Input Terminal. Stream-related parameters are stored in the endpoint descriptors. * Control-related parameters are stored in the Terminal descriptor. * * @author Jared Woolston (Jared.Woolston@gmail.com) * @see <a href=http://www.usb.org/developers/docs/devclass_docs/USB_Video_Class_1_5.zip>UVC 1.5 Class * Specification §2.3.2</a> */ public class VideoInputTerminal extends VideoTerminal { protected static final int MIN_LENGTH = 8; protected static final int iTerminal = 7; public static boolean isInputTerminal(byte[] descriptor) { return (descriptor.length >= MIN_LENGTH
&& descriptor[bDescriptorSubtype] == VideoClassInterface.VC_INF_SUBTYPE.VC_INPUT_TERMINAL.subtype);
square/burst
burst-junit4/src/main/java/com/squareup/burst/BurstJUnit4.java
// Path: burst/src/main/java/com/squareup/burst/Util.java // static <T> T checkNotNull(T o, String message) { // if (o == null) { // throw new NullPointerException(message); // } // return o; // }
import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import org.junit.Test; import org.junit.runner.Runner; import org.junit.runner.manipulation.Filter; import org.junit.runner.manipulation.NoTestsRemainException; import org.junit.runners.Suite; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.InitializationError; import org.junit.runners.model.TestClass; import static com.squareup.burst.Util.checkNotNull; import static java.util.Collections.unmodifiableList;
package com.squareup.burst; /** * A suite associated with a particular test class. Its children are {@link BurstRunner}s, each * representing a particular variation of that class. */ public final class BurstJUnit4 extends Suite { public BurstJUnit4(Class<?> cls) throws InitializationError { super(cls, explode(cls)); } /* * ParentRunner's default filter implementation generates a hierarchy of test descriptions, * applies the filter to those descriptions, and removes any test nodes whose descriptions were * all filtered out. * <p> * This would be problematic for us since we generate non-standard test descriptions which include * parameter information. This implementation lets each {@link BurstRunner} child filter itself * via {@link BurstRunner#filter(Filter)}. */ @Override public void filter(Filter filter) throws NoTestsRemainException { List<Runner> filteredChildren = ParentRunnerSpy.getFilteredChildren(this); // Iterate over a clone so that we can safely mutate the original. for (Runner child : new ArrayList<>(filteredChildren)) { try { filter.apply(child); } catch (NoTestsRemainException e) { filteredChildren.remove(child); } } if (filteredChildren.isEmpty()) { throw new NoTestsRemainException(); } } static List<Runner> explode(Class<?> cls) throws InitializationError {
// Path: burst/src/main/java/com/squareup/burst/Util.java // static <T> T checkNotNull(T o, String message) { // if (o == null) { // throw new NullPointerException(message); // } // return o; // } // Path: burst-junit4/src/main/java/com/squareup/burst/BurstJUnit4.java import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import org.junit.Test; import org.junit.runner.Runner; import org.junit.runner.manipulation.Filter; import org.junit.runner.manipulation.NoTestsRemainException; import org.junit.runners.Suite; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.InitializationError; import org.junit.runners.model.TestClass; import static com.squareup.burst.Util.checkNotNull; import static java.util.Collections.unmodifiableList; package com.squareup.burst; /** * A suite associated with a particular test class. Its children are {@link BurstRunner}s, each * representing a particular variation of that class. */ public final class BurstJUnit4 extends Suite { public BurstJUnit4(Class<?> cls) throws InitializationError { super(cls, explode(cls)); } /* * ParentRunner's default filter implementation generates a hierarchy of test descriptions, * applies the filter to those descriptions, and removes any test nodes whose descriptions were * all filtered out. * <p> * This would be problematic for us since we generate non-standard test descriptions which include * parameter information. This implementation lets each {@link BurstRunner} child filter itself * via {@link BurstRunner#filter(Filter)}. */ @Override public void filter(Filter filter) throws NoTestsRemainException { List<Runner> filteredChildren = ParentRunnerSpy.getFilteredChildren(this); // Iterate over a clone so that we can safely mutate the original. for (Runner child : new ArrayList<>(filteredChildren)) { try { filter.apply(child); } catch (NoTestsRemainException e) { filteredChildren.remove(child); } } if (filteredChildren.isEmpty()) { throw new NoTestsRemainException(); } } static List<Runner> explode(Class<?> cls) throws InitializationError {
checkNotNull(cls, "cls");
square/burst
burst/src/main/java/com/squareup/burst/Burst.java
// Path: burst/src/main/java/com/squareup/burst/Util.java // static <T> T checkNotNull(T o, String message) { // if (o == null) { // throw new NullPointerException(message); // } // return o; // }
import com.squareup.burst.annotation.Name; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import static com.squareup.burst.Util.checkNotNull;
package com.squareup.burst; /** * Helper methods to facilitate exercising all variations of the declared parameters on test * constructors and methods. */ public final class Burst { private static final Enum<?>[][] NONE = new Enum<?>[1][0]; /** * Explode a list of argument values for invoking the specified constructor with all combinations * of its parameters. */ public static Enum<?>[][] explodeArguments(TestConstructor constructor) {
// Path: burst/src/main/java/com/squareup/burst/Util.java // static <T> T checkNotNull(T o, String message) { // if (o == null) { // throw new NullPointerException(message); // } // return o; // } // Path: burst/src/main/java/com/squareup/burst/Burst.java import com.squareup.burst.annotation.Name; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import static com.squareup.burst.Util.checkNotNull; package com.squareup.burst; /** * Helper methods to facilitate exercising all variations of the declared parameters on test * constructors and methods. */ public final class Burst { private static final Enum<?>[][] NONE = new Enum<?>[1][0]; /** * Explode a list of argument values for invoking the specified constructor with all combinations * of its parameters. */ public static Enum<?>[][] explodeArguments(TestConstructor constructor) {
checkNotNull(constructor, "constructor");
square/burst
burst/src/main/java/com/squareup/burst/TestConstructor.java
// Path: burst/src/main/java/com/squareup/burst/Util.java // static <T> T checkNotNull(T o, String message) { // if (o == null) { // throw new NullPointerException(message); // } // return o; // }
import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.util.Arrays; import static com.squareup.burst.Util.checkNotNull;
package com.squareup.burst; /** * A wrapper around {@link Constructor} that can also set fields reflectively. */ final class TestConstructor { private final Constructor<?> constructor; private final Field[] fields; public TestConstructor(Constructor<?> constructor, Field... fields) {
// Path: burst/src/main/java/com/squareup/burst/Util.java // static <T> T checkNotNull(T o, String message) { // if (o == null) { // throw new NullPointerException(message); // } // return o; // } // Path: burst/src/main/java/com/squareup/burst/TestConstructor.java import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.util.Arrays; import static com.squareup.burst.Util.checkNotNull; package com.squareup.burst; /** * A wrapper around {@link Constructor} that can also set fields reflectively. */ final class TestConstructor { private final Constructor<?> constructor; private final Field[] fields; public TestConstructor(Constructor<?> constructor, Field... fields) {
this.constructor = checkNotNull(constructor, "constructor");
square/burst
burst-junit4/src/main/java/com/squareup/burst/BurstMethod.java
// Path: burst-junit4/src/main/java/com/squareup/burst/BurstJUnit4.java // static String nameWithArguments(String name, Enum<?>[] arguments, // Annotation[][] argumentAnnotations) { // if (arguments.length == 0) { // return name; // } // return name + '[' + Burst.friendlyName(arguments, argumentAnnotations) + ']'; // } // // Path: burst/src/main/java/com/squareup/burst/Util.java // static <T> T checkNotNull(T o, String message) { // if (o == null) { // throw new NullPointerException(message); // } // return o; // }
import java.lang.reflect.Method; import org.junit.internal.runners.model.ReflectiveCallable; import org.junit.runners.model.FrameworkMethod; import static com.squareup.burst.BurstJUnit4.nameWithArguments; import static com.squareup.burst.Util.checkNotNull;
package com.squareup.burst; final class BurstMethod extends FrameworkMethod { private final Enum<?>[] methodArgs; BurstMethod(Method method, Enum<?>[] methodArgs) {
// Path: burst-junit4/src/main/java/com/squareup/burst/BurstJUnit4.java // static String nameWithArguments(String name, Enum<?>[] arguments, // Annotation[][] argumentAnnotations) { // if (arguments.length == 0) { // return name; // } // return name + '[' + Burst.friendlyName(arguments, argumentAnnotations) + ']'; // } // // Path: burst/src/main/java/com/squareup/burst/Util.java // static <T> T checkNotNull(T o, String message) { // if (o == null) { // throw new NullPointerException(message); // } // return o; // } // Path: burst-junit4/src/main/java/com/squareup/burst/BurstMethod.java import java.lang.reflect.Method; import org.junit.internal.runners.model.ReflectiveCallable; import org.junit.runners.model.FrameworkMethod; import static com.squareup.burst.BurstJUnit4.nameWithArguments; import static com.squareup.burst.Util.checkNotNull; package com.squareup.burst; final class BurstMethod extends FrameworkMethod { private final Enum<?>[] methodArgs; BurstMethod(Method method, Enum<?>[] methodArgs) {
super(checkNotNull(method, "method"));
square/burst
burst-junit4/src/main/java/com/squareup/burst/BurstMethod.java
// Path: burst-junit4/src/main/java/com/squareup/burst/BurstJUnit4.java // static String nameWithArguments(String name, Enum<?>[] arguments, // Annotation[][] argumentAnnotations) { // if (arguments.length == 0) { // return name; // } // return name + '[' + Burst.friendlyName(arguments, argumentAnnotations) + ']'; // } // // Path: burst/src/main/java/com/squareup/burst/Util.java // static <T> T checkNotNull(T o, String message) { // if (o == null) { // throw new NullPointerException(message); // } // return o; // }
import java.lang.reflect.Method; import org.junit.internal.runners.model.ReflectiveCallable; import org.junit.runners.model.FrameworkMethod; import static com.squareup.burst.BurstJUnit4.nameWithArguments; import static com.squareup.burst.Util.checkNotNull;
package com.squareup.burst; final class BurstMethod extends FrameworkMethod { private final Enum<?>[] methodArgs; BurstMethod(Method method, Enum<?>[] methodArgs) { super(checkNotNull(method, "method")); this.methodArgs = checkNotNull(methodArgs, "methodArgs"); } @Override public Object invokeExplosively(final Object target, Object... params) throws Throwable { checkNotNull(target, "target"); ReflectiveCallable callable = new ReflectiveCallable() { @Override protected Object runReflectiveCall() throws Throwable { return getMethod().invoke(target, methodArgs); } }; return callable.run(); } @Override public String getName() {
// Path: burst-junit4/src/main/java/com/squareup/burst/BurstJUnit4.java // static String nameWithArguments(String name, Enum<?>[] arguments, // Annotation[][] argumentAnnotations) { // if (arguments.length == 0) { // return name; // } // return name + '[' + Burst.friendlyName(arguments, argumentAnnotations) + ']'; // } // // Path: burst/src/main/java/com/squareup/burst/Util.java // static <T> T checkNotNull(T o, String message) { // if (o == null) { // throw new NullPointerException(message); // } // return o; // } // Path: burst-junit4/src/main/java/com/squareup/burst/BurstMethod.java import java.lang.reflect.Method; import org.junit.internal.runners.model.ReflectiveCallable; import org.junit.runners.model.FrameworkMethod; import static com.squareup.burst.BurstJUnit4.nameWithArguments; import static com.squareup.burst.Util.checkNotNull; package com.squareup.burst; final class BurstMethod extends FrameworkMethod { private final Enum<?>[] methodArgs; BurstMethod(Method method, Enum<?>[] methodArgs) { super(checkNotNull(method, "method")); this.methodArgs = checkNotNull(methodArgs, "methodArgs"); } @Override public Object invokeExplosively(final Object target, Object... params) throws Throwable { checkNotNull(target, "target"); ReflectiveCallable callable = new ReflectiveCallable() { @Override protected Object runReflectiveCall() throws Throwable { return getMethod().invoke(target, methodArgs); } }; return callable.run(); } @Override public String getName() {
return nameWithArguments(super.getName(), methodArgs, getMethod().getParameterAnnotations());
square/burst
burst-junit4/src/main/java/com/squareup/burst/BurstRunner.java
// Path: burst-junit4/src/main/java/com/squareup/burst/BurstJUnit4.java // static String nameWithArguments(String name, Enum<?>[] arguments, // Annotation[][] argumentAnnotations) { // if (arguments.length == 0) { // return name; // } // return name + '[' + Burst.friendlyName(arguments, argumentAnnotations) + ']'; // } // // Path: burst/src/main/java/com/squareup/burst/Util.java // static <T> T checkNotNull(T o, String message) { // if (o == null) { // throw new NullPointerException(message); // } // return o; // }
import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runner.manipulation.Filter; import org.junit.runner.manipulation.NoTestsRemainException; import org.junit.runners.BlockJUnit4ClassRunner; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.InitializationError; import org.junit.runners.model.Statement; import static com.squareup.burst.BurstJUnit4.nameWithArguments; import static com.squareup.burst.Util.checkNotNull;
package com.squareup.burst; /** * A set of tests associated with a particular variation of some test class. */ final class BurstRunner extends BlockJUnit4ClassRunner { private final TestConstructor constructor; private final Enum<?>[] constructorArgs; private final List<FrameworkMethod> methods; BurstRunner(Class<?> cls, TestConstructor constructor, Enum<?>[] constructorArgs, List<FrameworkMethod> methods) throws InitializationError {
// Path: burst-junit4/src/main/java/com/squareup/burst/BurstJUnit4.java // static String nameWithArguments(String name, Enum<?>[] arguments, // Annotation[][] argumentAnnotations) { // if (arguments.length == 0) { // return name; // } // return name + '[' + Burst.friendlyName(arguments, argumentAnnotations) + ']'; // } // // Path: burst/src/main/java/com/squareup/burst/Util.java // static <T> T checkNotNull(T o, String message) { // if (o == null) { // throw new NullPointerException(message); // } // return o; // } // Path: burst-junit4/src/main/java/com/squareup/burst/BurstRunner.java import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runner.manipulation.Filter; import org.junit.runner.manipulation.NoTestsRemainException; import org.junit.runners.BlockJUnit4ClassRunner; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.InitializationError; import org.junit.runners.model.Statement; import static com.squareup.burst.BurstJUnit4.nameWithArguments; import static com.squareup.burst.Util.checkNotNull; package com.squareup.burst; /** * A set of tests associated with a particular variation of some test class. */ final class BurstRunner extends BlockJUnit4ClassRunner { private final TestConstructor constructor; private final Enum<?>[] constructorArgs; private final List<FrameworkMethod> methods; BurstRunner(Class<?> cls, TestConstructor constructor, Enum<?>[] constructorArgs, List<FrameworkMethod> methods) throws InitializationError {
super(checkNotNull(cls, "cls"));
square/burst
burst-junit4/src/main/java/com/squareup/burst/BurstRunner.java
// Path: burst-junit4/src/main/java/com/squareup/burst/BurstJUnit4.java // static String nameWithArguments(String name, Enum<?>[] arguments, // Annotation[][] argumentAnnotations) { // if (arguments.length == 0) { // return name; // } // return name + '[' + Burst.friendlyName(arguments, argumentAnnotations) + ']'; // } // // Path: burst/src/main/java/com/squareup/burst/Util.java // static <T> T checkNotNull(T o, String message) { // if (o == null) { // throw new NullPointerException(message); // } // return o; // }
import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runner.manipulation.Filter; import org.junit.runner.manipulation.NoTestsRemainException; import org.junit.runners.BlockJUnit4ClassRunner; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.InitializationError; import org.junit.runners.model.Statement; import static com.squareup.burst.BurstJUnit4.nameWithArguments; import static com.squareup.burst.Util.checkNotNull;
package com.squareup.burst; /** * A set of tests associated with a particular variation of some test class. */ final class BurstRunner extends BlockJUnit4ClassRunner { private final TestConstructor constructor; private final Enum<?>[] constructorArgs; private final List<FrameworkMethod> methods; BurstRunner(Class<?> cls, TestConstructor constructor, Enum<?>[] constructorArgs, List<FrameworkMethod> methods) throws InitializationError { super(checkNotNull(cls, "cls")); this.constructor = checkNotNull(constructor, "constructor"); this.constructorArgs = checkNotNull(constructorArgs, "constructorArgs"); this.methods = checkNotNull(methods, "methods"); } @Override protected List<FrameworkMethod> getChildren() { return methods; } @Override protected String getName() {
// Path: burst-junit4/src/main/java/com/squareup/burst/BurstJUnit4.java // static String nameWithArguments(String name, Enum<?>[] arguments, // Annotation[][] argumentAnnotations) { // if (arguments.length == 0) { // return name; // } // return name + '[' + Burst.friendlyName(arguments, argumentAnnotations) + ']'; // } // // Path: burst/src/main/java/com/squareup/burst/Util.java // static <T> T checkNotNull(T o, String message) { // if (o == null) { // throw new NullPointerException(message); // } // return o; // } // Path: burst-junit4/src/main/java/com/squareup/burst/BurstRunner.java import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runner.manipulation.Filter; import org.junit.runner.manipulation.NoTestsRemainException; import org.junit.runners.BlockJUnit4ClassRunner; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.InitializationError; import org.junit.runners.model.Statement; import static com.squareup.burst.BurstJUnit4.nameWithArguments; import static com.squareup.burst.Util.checkNotNull; package com.squareup.burst; /** * A set of tests associated with a particular variation of some test class. */ final class BurstRunner extends BlockJUnit4ClassRunner { private final TestConstructor constructor; private final Enum<?>[] constructorArgs; private final List<FrameworkMethod> methods; BurstRunner(Class<?> cls, TestConstructor constructor, Enum<?>[] constructorArgs, List<FrameworkMethod> methods) throws InitializationError { super(checkNotNull(cls, "cls")); this.constructor = checkNotNull(constructor, "constructor"); this.constructorArgs = checkNotNull(constructorArgs, "constructorArgs"); this.methods = checkNotNull(methods, "methods"); } @Override protected List<FrameworkMethod> getChildren() { return methods; } @Override protected String getName() {
return nameWithArguments(super.getName(), constructorArgs,
IvanVolosyuk/diskusage
app/src/main/java/com/google/android/diskusage/datasource/debug/PortableStreamProtoWriterImpl.java
// Path: app/src/main/java/com/google/android/diskusage/proto/PortableStreamProto.java // @SuppressWarnings("hiding") // public final class PortableStreamProto extends // com.google.protobuf.nano.MessageNano { // // private static volatile PortableStreamProto[] _emptyArray; // public static PortableStreamProto[] emptyArray() { // // Lazily initializes the empty array // if (_emptyArray == null) { // synchronized ( // com.google.protobuf.nano.InternalNano.LAZY_INIT_LOCK) { // if (_emptyArray == null) { // _emptyArray = new PortableStreamProto[0]; // } // } // } // return _emptyArray; // } // // // optional bytes data = 1; // public byte[] data; // // // optional .PortableExceptionProto read_exception = 2; // public com.google.android.diskusage.proto.PortableExceptionProto readException; // // // optional .PortableExceptionProto close_exception = 3; // public com.google.android.diskusage.proto.PortableExceptionProto closeException; // // public PortableStreamProto() { // clear(); // } // // public PortableStreamProto clear() { // data = com.google.protobuf.nano.WireFormatNano.EMPTY_BYTES; // readException = null; // closeException = null; // cachedSize = -1; // return this; // } // // @Override // public void writeTo(com.google.protobuf.nano.CodedOutputByteBufferNano output) // throws java.io.IOException { // if (!java.util.Arrays.equals(this.data, com.google.protobuf.nano.WireFormatNano.EMPTY_BYTES)) { // output.writeBytes(1, this.data); // } // if (this.readException != null) { // output.writeMessage(2, this.readException); // } // if (this.closeException != null) { // output.writeMessage(3, this.closeException); // } // super.writeTo(output); // } // // @Override // protected int computeSerializedSize() { // int size = super.computeSerializedSize(); // if (!java.util.Arrays.equals(this.data, com.google.protobuf.nano.WireFormatNano.EMPTY_BYTES)) { // size += com.google.protobuf.nano.CodedOutputByteBufferNano // .computeBytesSize(1, this.data); // } // if (this.readException != null) { // size += com.google.protobuf.nano.CodedOutputByteBufferNano // .computeMessageSize(2, this.readException); // } // if (this.closeException != null) { // size += com.google.protobuf.nano.CodedOutputByteBufferNano // .computeMessageSize(3, this.closeException); // } // return size; // } // // @Override // public PortableStreamProto mergeFrom( // com.google.protobuf.nano.CodedInputByteBufferNano input) // throws java.io.IOException { // while (true) { // int tag = input.readTag(); // switch (tag) { // case 0: // return this; // default: { // if (!com.google.protobuf.nano.WireFormatNano.parseUnknownField(input, tag)) { // return this; // } // break; // } // case 10: { // this.data = input.readBytes(); // break; // } // case 18: { // if (this.readException == null) { // this.readException = new com.google.android.diskusage.proto.PortableExceptionProto(); // } // input.readMessage(this.readException); // break; // } // case 26: { // if (this.closeException == null) { // this.closeException = new com.google.android.diskusage.proto.PortableExceptionProto(); // } // input.readMessage(this.closeException); // break; // } // } // } // } // // public static PortableStreamProto parseFrom(byte[] data) // throws com.google.protobuf.nano.InvalidProtocolBufferNanoException { // return com.google.protobuf.nano.MessageNano.mergeFrom(new PortableStreamProto(), data); // } // // public static PortableStreamProto parseFrom( // com.google.protobuf.nano.CodedInputByteBufferNano input) // throws java.io.IOException { // return new PortableStreamProto().mergeFrom(input); // } // }
import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import com.google.android.diskusage.proto.PortableStreamProto;
package com.google.android.diskusage.datasource.debug; public class PortableStreamProtoWriterImpl extends InputStream { interface CloseCallback {
// Path: app/src/main/java/com/google/android/diskusage/proto/PortableStreamProto.java // @SuppressWarnings("hiding") // public final class PortableStreamProto extends // com.google.protobuf.nano.MessageNano { // // private static volatile PortableStreamProto[] _emptyArray; // public static PortableStreamProto[] emptyArray() { // // Lazily initializes the empty array // if (_emptyArray == null) { // synchronized ( // com.google.protobuf.nano.InternalNano.LAZY_INIT_LOCK) { // if (_emptyArray == null) { // _emptyArray = new PortableStreamProto[0]; // } // } // } // return _emptyArray; // } // // // optional bytes data = 1; // public byte[] data; // // // optional .PortableExceptionProto read_exception = 2; // public com.google.android.diskusage.proto.PortableExceptionProto readException; // // // optional .PortableExceptionProto close_exception = 3; // public com.google.android.diskusage.proto.PortableExceptionProto closeException; // // public PortableStreamProto() { // clear(); // } // // public PortableStreamProto clear() { // data = com.google.protobuf.nano.WireFormatNano.EMPTY_BYTES; // readException = null; // closeException = null; // cachedSize = -1; // return this; // } // // @Override // public void writeTo(com.google.protobuf.nano.CodedOutputByteBufferNano output) // throws java.io.IOException { // if (!java.util.Arrays.equals(this.data, com.google.protobuf.nano.WireFormatNano.EMPTY_BYTES)) { // output.writeBytes(1, this.data); // } // if (this.readException != null) { // output.writeMessage(2, this.readException); // } // if (this.closeException != null) { // output.writeMessage(3, this.closeException); // } // super.writeTo(output); // } // // @Override // protected int computeSerializedSize() { // int size = super.computeSerializedSize(); // if (!java.util.Arrays.equals(this.data, com.google.protobuf.nano.WireFormatNano.EMPTY_BYTES)) { // size += com.google.protobuf.nano.CodedOutputByteBufferNano // .computeBytesSize(1, this.data); // } // if (this.readException != null) { // size += com.google.protobuf.nano.CodedOutputByteBufferNano // .computeMessageSize(2, this.readException); // } // if (this.closeException != null) { // size += com.google.protobuf.nano.CodedOutputByteBufferNano // .computeMessageSize(3, this.closeException); // } // return size; // } // // @Override // public PortableStreamProto mergeFrom( // com.google.protobuf.nano.CodedInputByteBufferNano input) // throws java.io.IOException { // while (true) { // int tag = input.readTag(); // switch (tag) { // case 0: // return this; // default: { // if (!com.google.protobuf.nano.WireFormatNano.parseUnknownField(input, tag)) { // return this; // } // break; // } // case 10: { // this.data = input.readBytes(); // break; // } // case 18: { // if (this.readException == null) { // this.readException = new com.google.android.diskusage.proto.PortableExceptionProto(); // } // input.readMessage(this.readException); // break; // } // case 26: { // if (this.closeException == null) { // this.closeException = new com.google.android.diskusage.proto.PortableExceptionProto(); // } // input.readMessage(this.closeException); // break; // } // } // } // } // // public static PortableStreamProto parseFrom(byte[] data) // throws com.google.protobuf.nano.InvalidProtocolBufferNanoException { // return com.google.protobuf.nano.MessageNano.mergeFrom(new PortableStreamProto(), data); // } // // public static PortableStreamProto parseFrom( // com.google.protobuf.nano.CodedInputByteBufferNano input) // throws java.io.IOException { // return new PortableStreamProto().mergeFrom(input); // } // } // Path: app/src/main/java/com/google/android/diskusage/datasource/debug/PortableStreamProtoWriterImpl.java import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import com.google.android.diskusage.proto.PortableStreamProto; package com.google.android.diskusage.datasource.debug; public class PortableStreamProtoWriterImpl extends InputStream { interface CloseCallback {
void onClose(PortableStreamProto proto);
IvanVolosyuk/diskusage
app/src/main/java/com/google/android/diskusage/datasource/fast/NativeScannerStream.java
// Path: app/src/main/java/com/google/android/diskusage/datasource/DataSource.java // public abstract class DataSource { // private static DataSource currentDataSource = new DefaultDataSource(); // // public static DataSource get() { // return currentDataSource; // } // // public static void override(DataSource dataSource) { // LoadableActivity.resetStoredStates(); // currentDataSource = dataSource; // } // // public abstract int getAndroidVersion(); // // public abstract List<PkgInfo> getInstalledPackages(PackageManager pm); // // public abstract StatFsSource statFs(String mountPoint); // // @TargetApi(Build.VERSION_CODES.FROYO) // public abstract PortableFile getExternalFilesDir(Context context); // @TargetApi(Build.VERSION_CODES.KITKAT) // public abstract PortableFile[] getExternalFilesDirs(Context context); // // public abstract PortableFile getExternalStorageDirectory(); // // public abstract InputStream createNativeScanner( // Context context, String path, // boolean rootRequired) throws IOException, InterruptedException; // // public abstract boolean isDeviceRooted(); // // public abstract LegacyFile createLegacyScanFile(String root); // // public final BufferedReader getProcReader() throws IOException { // return new BufferedReader(new InputStreamReader(getProc())); // } // // public abstract InputStream getProc() throws IOException; // // public abstract void getPackageSizeInfo( // PkgInfo pkgInfo, // Method getPackageSizeInfo, // PackageManager pm, // AppStatsCallback callback) throws Exception; // // public abstract PortableFile getParentFile(PortableFile file); // }
import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import android.annotation.TargetApi; import android.content.Context; import android.os.Build; import android.os.Build.VERSION_CODES; import com.google.android.diskusage.datasource.DataSource;
throws IOException { return is.read(buffer, byteOffset, byteCount); } @Override public void close() throws IOException { is.close(); try { process.waitFor(); } catch (InterruptedException e) { throw new IOException(e.getMessage()); } } static class Factory { private final Context context; private static boolean remove = true; Factory(Context context) { this.context = context; } public NativeScannerStream create(String path, boolean rootRequired) throws IOException, InterruptedException { return runScanner(path, rootRequired); } private NativeScannerStream runScanner(String root, boolean rootRequired) throws IOException, InterruptedException { String binaryName = "scan";
// Path: app/src/main/java/com/google/android/diskusage/datasource/DataSource.java // public abstract class DataSource { // private static DataSource currentDataSource = new DefaultDataSource(); // // public static DataSource get() { // return currentDataSource; // } // // public static void override(DataSource dataSource) { // LoadableActivity.resetStoredStates(); // currentDataSource = dataSource; // } // // public abstract int getAndroidVersion(); // // public abstract List<PkgInfo> getInstalledPackages(PackageManager pm); // // public abstract StatFsSource statFs(String mountPoint); // // @TargetApi(Build.VERSION_CODES.FROYO) // public abstract PortableFile getExternalFilesDir(Context context); // @TargetApi(Build.VERSION_CODES.KITKAT) // public abstract PortableFile[] getExternalFilesDirs(Context context); // // public abstract PortableFile getExternalStorageDirectory(); // // public abstract InputStream createNativeScanner( // Context context, String path, // boolean rootRequired) throws IOException, InterruptedException; // // public abstract boolean isDeviceRooted(); // // public abstract LegacyFile createLegacyScanFile(String root); // // public final BufferedReader getProcReader() throws IOException { // return new BufferedReader(new InputStreamReader(getProc())); // } // // public abstract InputStream getProc() throws IOException; // // public abstract void getPackageSizeInfo( // PkgInfo pkgInfo, // Method getPackageSizeInfo, // PackageManager pm, // AppStatsCallback callback) throws Exception; // // public abstract PortableFile getParentFile(PortableFile file); // } // Path: app/src/main/java/com/google/android/diskusage/datasource/fast/NativeScannerStream.java import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import android.annotation.TargetApi; import android.content.Context; import android.os.Build; import android.os.Build.VERSION_CODES; import com.google.android.diskusage.datasource.DataSource; throws IOException { return is.read(buffer, byteOffset, byteCount); } @Override public void close() throws IOException { is.close(); try { process.waitFor(); } catch (InterruptedException e) { throw new IOException(e.getMessage()); } } static class Factory { private final Context context; private static boolean remove = true; Factory(Context context) { this.context = context; } public NativeScannerStream create(String path, boolean rootRequired) throws IOException, InterruptedException { return runScanner(path, rootRequired); } private NativeScannerStream runScanner(String root, boolean rootRequired) throws IOException, InterruptedException { String binaryName = "scan";
final int sdkVersion = DataSource.get().getAndroidVersion();
IvanVolosyuk/diskusage
app/src/main/java/com/google/android/diskusage/MountPoint.java
// Path: app/src/main/java/com/google/android/diskusage/datasource/DataSource.java // public abstract class DataSource { // private static DataSource currentDataSource = new DefaultDataSource(); // // public static DataSource get() { // return currentDataSource; // } // // public static void override(DataSource dataSource) { // LoadableActivity.resetStoredStates(); // currentDataSource = dataSource; // } // // public abstract int getAndroidVersion(); // // public abstract List<PkgInfo> getInstalledPackages(PackageManager pm); // // public abstract StatFsSource statFs(String mountPoint); // // @TargetApi(Build.VERSION_CODES.FROYO) // public abstract PortableFile getExternalFilesDir(Context context); // @TargetApi(Build.VERSION_CODES.KITKAT) // public abstract PortableFile[] getExternalFilesDirs(Context context); // // public abstract PortableFile getExternalStorageDirectory(); // // public abstract InputStream createNativeScanner( // Context context, String path, // boolean rootRequired) throws IOException, InterruptedException; // // public abstract boolean isDeviceRooted(); // // public abstract LegacyFile createLegacyScanFile(String root); // // public final BufferedReader getProcReader() throws IOException { // return new BufferedReader(new InputStreamReader(getProc())); // } // // public abstract InputStream getProc() throws IOException; // // public abstract void getPackageSizeInfo( // PkgInfo pkgInfo, // Method getPackageSizeInfo, // PackageManager pm, // AppStatsCallback callback) throws Exception; // // public abstract PortableFile getParentFile(PortableFile file); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/PortableFile.java // public interface PortableFile { // @TargetApi(Build.VERSION_CODES.LOLLIPOP) // boolean isExternalStorageEmulated(); // @TargetApi(Build.VERSION_CODES.LOLLIPOP) // boolean isExternalStorageRemovable(); // // /** Retries with getAbsolutePath() on IOException */ // String getCanonicalPath(); // String getAbsolutePath(); // // @TargetApi(Build.VERSION_CODES.GINGERBREAD) // long getTotalSpace(); // }
import android.content.Context; import android.util.Log; import com.google.android.diskusage.datasource.DataSource; import com.google.android.diskusage.datasource.PortableFile; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap;
public boolean hasApps() { return forceHasApps; } private static List<MountPoint> mountPoints = new ArrayList<>(); private static Map<String,MountPoint> mountPointForKey = new HashMap<>(); int getChecksum() { return RootMountPoint.checksum; } public static MountPoint getForKey(Context context, String key) { initMountPoints(context); MountPoint mountPoint = mountPointForKey.get(key); if (mountPoint != null) { return mountPoint; } return RootMountPoint.getForKey(context, key); } public static List<MountPoint> getMountPoints(Context context) { initMountPoints(context); RootMountPoint.initMountPoints(context); return mountPoints; } private static void initMountPoints(Context context) { if (init) return; init = true;
// Path: app/src/main/java/com/google/android/diskusage/datasource/DataSource.java // public abstract class DataSource { // private static DataSource currentDataSource = new DefaultDataSource(); // // public static DataSource get() { // return currentDataSource; // } // // public static void override(DataSource dataSource) { // LoadableActivity.resetStoredStates(); // currentDataSource = dataSource; // } // // public abstract int getAndroidVersion(); // // public abstract List<PkgInfo> getInstalledPackages(PackageManager pm); // // public abstract StatFsSource statFs(String mountPoint); // // @TargetApi(Build.VERSION_CODES.FROYO) // public abstract PortableFile getExternalFilesDir(Context context); // @TargetApi(Build.VERSION_CODES.KITKAT) // public abstract PortableFile[] getExternalFilesDirs(Context context); // // public abstract PortableFile getExternalStorageDirectory(); // // public abstract InputStream createNativeScanner( // Context context, String path, // boolean rootRequired) throws IOException, InterruptedException; // // public abstract boolean isDeviceRooted(); // // public abstract LegacyFile createLegacyScanFile(String root); // // public final BufferedReader getProcReader() throws IOException { // return new BufferedReader(new InputStreamReader(getProc())); // } // // public abstract InputStream getProc() throws IOException; // // public abstract void getPackageSizeInfo( // PkgInfo pkgInfo, // Method getPackageSizeInfo, // PackageManager pm, // AppStatsCallback callback) throws Exception; // // public abstract PortableFile getParentFile(PortableFile file); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/PortableFile.java // public interface PortableFile { // @TargetApi(Build.VERSION_CODES.LOLLIPOP) // boolean isExternalStorageEmulated(); // @TargetApi(Build.VERSION_CODES.LOLLIPOP) // boolean isExternalStorageRemovable(); // // /** Retries with getAbsolutePath() on IOException */ // String getCanonicalPath(); // String getAbsolutePath(); // // @TargetApi(Build.VERSION_CODES.GINGERBREAD) // long getTotalSpace(); // } // Path: app/src/main/java/com/google/android/diskusage/MountPoint.java import android.content.Context; import android.util.Log; import com.google.android.diskusage.datasource.DataSource; import com.google.android.diskusage.datasource.PortableFile; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; public boolean hasApps() { return forceHasApps; } private static List<MountPoint> mountPoints = new ArrayList<>(); private static Map<String,MountPoint> mountPointForKey = new HashMap<>(); int getChecksum() { return RootMountPoint.checksum; } public static MountPoint getForKey(Context context, String key) { initMountPoints(context); MountPoint mountPoint = mountPointForKey.get(key); if (mountPoint != null) { return mountPoint; } return RootMountPoint.getForKey(context, key); } public static List<MountPoint> getMountPoints(Context context) { initMountPoints(context); RootMountPoint.initMountPoints(context); return mountPoints; } private static void initMountPoints(Context context) { if (init) return; init = true;
for (PortableFile dir : DataSource.get().getExternalFilesDirs(context)) {
IvanVolosyuk/diskusage
app/src/main/java/com/google/android/diskusage/MountPoint.java
// Path: app/src/main/java/com/google/android/diskusage/datasource/DataSource.java // public abstract class DataSource { // private static DataSource currentDataSource = new DefaultDataSource(); // // public static DataSource get() { // return currentDataSource; // } // // public static void override(DataSource dataSource) { // LoadableActivity.resetStoredStates(); // currentDataSource = dataSource; // } // // public abstract int getAndroidVersion(); // // public abstract List<PkgInfo> getInstalledPackages(PackageManager pm); // // public abstract StatFsSource statFs(String mountPoint); // // @TargetApi(Build.VERSION_CODES.FROYO) // public abstract PortableFile getExternalFilesDir(Context context); // @TargetApi(Build.VERSION_CODES.KITKAT) // public abstract PortableFile[] getExternalFilesDirs(Context context); // // public abstract PortableFile getExternalStorageDirectory(); // // public abstract InputStream createNativeScanner( // Context context, String path, // boolean rootRequired) throws IOException, InterruptedException; // // public abstract boolean isDeviceRooted(); // // public abstract LegacyFile createLegacyScanFile(String root); // // public final BufferedReader getProcReader() throws IOException { // return new BufferedReader(new InputStreamReader(getProc())); // } // // public abstract InputStream getProc() throws IOException; // // public abstract void getPackageSizeInfo( // PkgInfo pkgInfo, // Method getPackageSizeInfo, // PackageManager pm, // AppStatsCallback callback) throws Exception; // // public abstract PortableFile getParentFile(PortableFile file); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/PortableFile.java // public interface PortableFile { // @TargetApi(Build.VERSION_CODES.LOLLIPOP) // boolean isExternalStorageEmulated(); // @TargetApi(Build.VERSION_CODES.LOLLIPOP) // boolean isExternalStorageRemovable(); // // /** Retries with getAbsolutePath() on IOException */ // String getCanonicalPath(); // String getAbsolutePath(); // // @TargetApi(Build.VERSION_CODES.GINGERBREAD) // long getTotalSpace(); // }
import android.content.Context; import android.util.Log; import com.google.android.diskusage.datasource.DataSource; import com.google.android.diskusage.datasource.PortableFile; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap;
public boolean hasApps() { return forceHasApps; } private static List<MountPoint> mountPoints = new ArrayList<>(); private static Map<String,MountPoint> mountPointForKey = new HashMap<>(); int getChecksum() { return RootMountPoint.checksum; } public static MountPoint getForKey(Context context, String key) { initMountPoints(context); MountPoint mountPoint = mountPointForKey.get(key); if (mountPoint != null) { return mountPoint; } return RootMountPoint.getForKey(context, key); } public static List<MountPoint> getMountPoints(Context context) { initMountPoints(context); RootMountPoint.initMountPoints(context); return mountPoints; } private static void initMountPoints(Context context) { if (init) return; init = true;
// Path: app/src/main/java/com/google/android/diskusage/datasource/DataSource.java // public abstract class DataSource { // private static DataSource currentDataSource = new DefaultDataSource(); // // public static DataSource get() { // return currentDataSource; // } // // public static void override(DataSource dataSource) { // LoadableActivity.resetStoredStates(); // currentDataSource = dataSource; // } // // public abstract int getAndroidVersion(); // // public abstract List<PkgInfo> getInstalledPackages(PackageManager pm); // // public abstract StatFsSource statFs(String mountPoint); // // @TargetApi(Build.VERSION_CODES.FROYO) // public abstract PortableFile getExternalFilesDir(Context context); // @TargetApi(Build.VERSION_CODES.KITKAT) // public abstract PortableFile[] getExternalFilesDirs(Context context); // // public abstract PortableFile getExternalStorageDirectory(); // // public abstract InputStream createNativeScanner( // Context context, String path, // boolean rootRequired) throws IOException, InterruptedException; // // public abstract boolean isDeviceRooted(); // // public abstract LegacyFile createLegacyScanFile(String root); // // public final BufferedReader getProcReader() throws IOException { // return new BufferedReader(new InputStreamReader(getProc())); // } // // public abstract InputStream getProc() throws IOException; // // public abstract void getPackageSizeInfo( // PkgInfo pkgInfo, // Method getPackageSizeInfo, // PackageManager pm, // AppStatsCallback callback) throws Exception; // // public abstract PortableFile getParentFile(PortableFile file); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/PortableFile.java // public interface PortableFile { // @TargetApi(Build.VERSION_CODES.LOLLIPOP) // boolean isExternalStorageEmulated(); // @TargetApi(Build.VERSION_CODES.LOLLIPOP) // boolean isExternalStorageRemovable(); // // /** Retries with getAbsolutePath() on IOException */ // String getCanonicalPath(); // String getAbsolutePath(); // // @TargetApi(Build.VERSION_CODES.GINGERBREAD) // long getTotalSpace(); // } // Path: app/src/main/java/com/google/android/diskusage/MountPoint.java import android.content.Context; import android.util.Log; import com.google.android.diskusage.datasource.DataSource; import com.google.android.diskusage.datasource.PortableFile; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; public boolean hasApps() { return forceHasApps; } private static List<MountPoint> mountPoints = new ArrayList<>(); private static Map<String,MountPoint> mountPointForKey = new HashMap<>(); int getChecksum() { return RootMountPoint.checksum; } public static MountPoint getForKey(Context context, String key) { initMountPoints(context); MountPoint mountPoint = mountPointForKey.get(key); if (mountPoint != null) { return mountPoint; } return RootMountPoint.getForKey(context, key); } public static List<MountPoint> getMountPoints(Context context) { initMountPoints(context); RootMountPoint.initMountPoints(context); return mountPoints; } private static void initMountPoints(Context context) { if (init) return; init = true;
for (PortableFile dir : DataSource.get().getExternalFilesDirs(context)) {
IvanVolosyuk/diskusage
app/src/main/java/com/google/android/diskusage/datasource/fast/DefaultDataSource.java
// Path: app/src/main/java/com/google/android/diskusage/datasource/AppStatsCallback.java // public interface AppStatsCallback { // void onGetStatsCompleted(AppStats stats, boolean succeeded); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/DataSource.java // public abstract class DataSource { // private static DataSource currentDataSource = new DefaultDataSource(); // // public static DataSource get() { // return currentDataSource; // } // // public static void override(DataSource dataSource) { // LoadableActivity.resetStoredStates(); // currentDataSource = dataSource; // } // // public abstract int getAndroidVersion(); // // public abstract List<PkgInfo> getInstalledPackages(PackageManager pm); // // public abstract StatFsSource statFs(String mountPoint); // // @TargetApi(Build.VERSION_CODES.FROYO) // public abstract PortableFile getExternalFilesDir(Context context); // @TargetApi(Build.VERSION_CODES.KITKAT) // public abstract PortableFile[] getExternalFilesDirs(Context context); // // public abstract PortableFile getExternalStorageDirectory(); // // public abstract InputStream createNativeScanner( // Context context, String path, // boolean rootRequired) throws IOException, InterruptedException; // // public abstract boolean isDeviceRooted(); // // public abstract LegacyFile createLegacyScanFile(String root); // // public final BufferedReader getProcReader() throws IOException { // return new BufferedReader(new InputStreamReader(getProc())); // } // // public abstract InputStream getProc() throws IOException; // // public abstract void getPackageSizeInfo( // PkgInfo pkgInfo, // Method getPackageSizeInfo, // PackageManager pm, // AppStatsCallback callback) throws Exception; // // public abstract PortableFile getParentFile(PortableFile file); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/LegacyFile.java // public interface LegacyFile { // String getName(); // String getCannonicalPath() throws IOException; // // boolean isLink(); // boolean isFile(); // long length(); // // LegacyFile[] listFiles(); // String[] list(); // // LegacyFile getChild(String string); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/PkgInfo.java // public interface PkgInfo { // String getPackageName(); // AppInfo getApplicationInfo(); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/PortableFile.java // public interface PortableFile { // @TargetApi(Build.VERSION_CODES.LOLLIPOP) // boolean isExternalStorageEmulated(); // @TargetApi(Build.VERSION_CODES.LOLLIPOP) // boolean isExternalStorageRemovable(); // // /** Retries with getAbsolutePath() on IOException */ // String getCanonicalPath(); // String getAbsolutePath(); // // @TargetApi(Build.VERSION_CODES.GINGERBREAD) // long getTotalSpace(); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/StatFsSource.java // public interface StatFsSource { // // @Deprecated // int getAvailableBlocks(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getAvailableBlocksLong(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getAvailableBytes(); // // @Deprecated // public int getBlockCount(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getBlockCountLong(); // // @Deprecated // public int getBlockSize(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getBlockSizeLong(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getFreeBytes(); // // @Deprecated // public int getFreeBlocks(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getFreeBlocksLong(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getTotalBytes(); // }
import com.google.android.diskusage.datasource.AppStatsCallback; import com.google.android.diskusage.datasource.DataSource; import com.google.android.diskusage.datasource.LegacyFile; import com.google.android.diskusage.datasource.PkgInfo; import com.google.android.diskusage.datasource.PortableFile; import com.google.android.diskusage.datasource.StatFsSource; import android.annotation.TargetApi; import android.content.Context; import android.content.pm.IPackageStatsObserver; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageStats; import android.os.Build; import android.os.Environment; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List;
package com.google.android.diskusage.datasource.fast; public class DefaultDataSource extends DataSource { @Override public InputStream getProc() throws IOException { return new FileInputStream(new File("/proc/mounts")); } @Override public int getAndroidVersion() { return Integer.parseInt(Build.VERSION.SDK); } @Override
// Path: app/src/main/java/com/google/android/diskusage/datasource/AppStatsCallback.java // public interface AppStatsCallback { // void onGetStatsCompleted(AppStats stats, boolean succeeded); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/DataSource.java // public abstract class DataSource { // private static DataSource currentDataSource = new DefaultDataSource(); // // public static DataSource get() { // return currentDataSource; // } // // public static void override(DataSource dataSource) { // LoadableActivity.resetStoredStates(); // currentDataSource = dataSource; // } // // public abstract int getAndroidVersion(); // // public abstract List<PkgInfo> getInstalledPackages(PackageManager pm); // // public abstract StatFsSource statFs(String mountPoint); // // @TargetApi(Build.VERSION_CODES.FROYO) // public abstract PortableFile getExternalFilesDir(Context context); // @TargetApi(Build.VERSION_CODES.KITKAT) // public abstract PortableFile[] getExternalFilesDirs(Context context); // // public abstract PortableFile getExternalStorageDirectory(); // // public abstract InputStream createNativeScanner( // Context context, String path, // boolean rootRequired) throws IOException, InterruptedException; // // public abstract boolean isDeviceRooted(); // // public abstract LegacyFile createLegacyScanFile(String root); // // public final BufferedReader getProcReader() throws IOException { // return new BufferedReader(new InputStreamReader(getProc())); // } // // public abstract InputStream getProc() throws IOException; // // public abstract void getPackageSizeInfo( // PkgInfo pkgInfo, // Method getPackageSizeInfo, // PackageManager pm, // AppStatsCallback callback) throws Exception; // // public abstract PortableFile getParentFile(PortableFile file); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/LegacyFile.java // public interface LegacyFile { // String getName(); // String getCannonicalPath() throws IOException; // // boolean isLink(); // boolean isFile(); // long length(); // // LegacyFile[] listFiles(); // String[] list(); // // LegacyFile getChild(String string); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/PkgInfo.java // public interface PkgInfo { // String getPackageName(); // AppInfo getApplicationInfo(); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/PortableFile.java // public interface PortableFile { // @TargetApi(Build.VERSION_CODES.LOLLIPOP) // boolean isExternalStorageEmulated(); // @TargetApi(Build.VERSION_CODES.LOLLIPOP) // boolean isExternalStorageRemovable(); // // /** Retries with getAbsolutePath() on IOException */ // String getCanonicalPath(); // String getAbsolutePath(); // // @TargetApi(Build.VERSION_CODES.GINGERBREAD) // long getTotalSpace(); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/StatFsSource.java // public interface StatFsSource { // // @Deprecated // int getAvailableBlocks(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getAvailableBlocksLong(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getAvailableBytes(); // // @Deprecated // public int getBlockCount(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getBlockCountLong(); // // @Deprecated // public int getBlockSize(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getBlockSizeLong(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getFreeBytes(); // // @Deprecated // public int getFreeBlocks(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getFreeBlocksLong(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getTotalBytes(); // } // Path: app/src/main/java/com/google/android/diskusage/datasource/fast/DefaultDataSource.java import com.google.android.diskusage.datasource.AppStatsCallback; import com.google.android.diskusage.datasource.DataSource; import com.google.android.diskusage.datasource.LegacyFile; import com.google.android.diskusage.datasource.PkgInfo; import com.google.android.diskusage.datasource.PortableFile; import com.google.android.diskusage.datasource.StatFsSource; import android.annotation.TargetApi; import android.content.Context; import android.content.pm.IPackageStatsObserver; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageStats; import android.os.Build; import android.os.Environment; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; package com.google.android.diskusage.datasource.fast; public class DefaultDataSource extends DataSource { @Override public InputStream getProc() throws IOException { return new FileInputStream(new File("/proc/mounts")); } @Override public int getAndroidVersion() { return Integer.parseInt(Build.VERSION.SDK); } @Override
public List<PkgInfo> getInstalledPackages(PackageManager pm) {
IvanVolosyuk/diskusage
app/src/main/java/com/google/android/diskusage/datasource/fast/DefaultDataSource.java
// Path: app/src/main/java/com/google/android/diskusage/datasource/AppStatsCallback.java // public interface AppStatsCallback { // void onGetStatsCompleted(AppStats stats, boolean succeeded); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/DataSource.java // public abstract class DataSource { // private static DataSource currentDataSource = new DefaultDataSource(); // // public static DataSource get() { // return currentDataSource; // } // // public static void override(DataSource dataSource) { // LoadableActivity.resetStoredStates(); // currentDataSource = dataSource; // } // // public abstract int getAndroidVersion(); // // public abstract List<PkgInfo> getInstalledPackages(PackageManager pm); // // public abstract StatFsSource statFs(String mountPoint); // // @TargetApi(Build.VERSION_CODES.FROYO) // public abstract PortableFile getExternalFilesDir(Context context); // @TargetApi(Build.VERSION_CODES.KITKAT) // public abstract PortableFile[] getExternalFilesDirs(Context context); // // public abstract PortableFile getExternalStorageDirectory(); // // public abstract InputStream createNativeScanner( // Context context, String path, // boolean rootRequired) throws IOException, InterruptedException; // // public abstract boolean isDeviceRooted(); // // public abstract LegacyFile createLegacyScanFile(String root); // // public final BufferedReader getProcReader() throws IOException { // return new BufferedReader(new InputStreamReader(getProc())); // } // // public abstract InputStream getProc() throws IOException; // // public abstract void getPackageSizeInfo( // PkgInfo pkgInfo, // Method getPackageSizeInfo, // PackageManager pm, // AppStatsCallback callback) throws Exception; // // public abstract PortableFile getParentFile(PortableFile file); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/LegacyFile.java // public interface LegacyFile { // String getName(); // String getCannonicalPath() throws IOException; // // boolean isLink(); // boolean isFile(); // long length(); // // LegacyFile[] listFiles(); // String[] list(); // // LegacyFile getChild(String string); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/PkgInfo.java // public interface PkgInfo { // String getPackageName(); // AppInfo getApplicationInfo(); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/PortableFile.java // public interface PortableFile { // @TargetApi(Build.VERSION_CODES.LOLLIPOP) // boolean isExternalStorageEmulated(); // @TargetApi(Build.VERSION_CODES.LOLLIPOP) // boolean isExternalStorageRemovable(); // // /** Retries with getAbsolutePath() on IOException */ // String getCanonicalPath(); // String getAbsolutePath(); // // @TargetApi(Build.VERSION_CODES.GINGERBREAD) // long getTotalSpace(); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/StatFsSource.java // public interface StatFsSource { // // @Deprecated // int getAvailableBlocks(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getAvailableBlocksLong(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getAvailableBytes(); // // @Deprecated // public int getBlockCount(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getBlockCountLong(); // // @Deprecated // public int getBlockSize(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getBlockSizeLong(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getFreeBytes(); // // @Deprecated // public int getFreeBlocks(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getFreeBlocksLong(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getTotalBytes(); // }
import com.google.android.diskusage.datasource.AppStatsCallback; import com.google.android.diskusage.datasource.DataSource; import com.google.android.diskusage.datasource.LegacyFile; import com.google.android.diskusage.datasource.PkgInfo; import com.google.android.diskusage.datasource.PortableFile; import com.google.android.diskusage.datasource.StatFsSource; import android.annotation.TargetApi; import android.content.Context; import android.content.pm.IPackageStatsObserver; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageStats; import android.os.Build; import android.os.Environment; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List;
package com.google.android.diskusage.datasource.fast; public class DefaultDataSource extends DataSource { @Override public InputStream getProc() throws IOException { return new FileInputStream(new File("/proc/mounts")); } @Override public int getAndroidVersion() { return Integer.parseInt(Build.VERSION.SDK); } @Override public List<PkgInfo> getInstalledPackages(PackageManager pm) { final List<PackageInfo> installedPackages = pm.getInstalledPackages( PackageManager.GET_META_DATA | PackageManager.GET_UNINSTALLED_PACKAGES); List<PkgInfo> packageInfos = new ArrayList<PkgInfo>(); for (PackageInfo info : installedPackages) { packageInfos.add(new PkgInfoImpl(info, pm)); } return packageInfos; } @Override
// Path: app/src/main/java/com/google/android/diskusage/datasource/AppStatsCallback.java // public interface AppStatsCallback { // void onGetStatsCompleted(AppStats stats, boolean succeeded); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/DataSource.java // public abstract class DataSource { // private static DataSource currentDataSource = new DefaultDataSource(); // // public static DataSource get() { // return currentDataSource; // } // // public static void override(DataSource dataSource) { // LoadableActivity.resetStoredStates(); // currentDataSource = dataSource; // } // // public abstract int getAndroidVersion(); // // public abstract List<PkgInfo> getInstalledPackages(PackageManager pm); // // public abstract StatFsSource statFs(String mountPoint); // // @TargetApi(Build.VERSION_CODES.FROYO) // public abstract PortableFile getExternalFilesDir(Context context); // @TargetApi(Build.VERSION_CODES.KITKAT) // public abstract PortableFile[] getExternalFilesDirs(Context context); // // public abstract PortableFile getExternalStorageDirectory(); // // public abstract InputStream createNativeScanner( // Context context, String path, // boolean rootRequired) throws IOException, InterruptedException; // // public abstract boolean isDeviceRooted(); // // public abstract LegacyFile createLegacyScanFile(String root); // // public final BufferedReader getProcReader() throws IOException { // return new BufferedReader(new InputStreamReader(getProc())); // } // // public abstract InputStream getProc() throws IOException; // // public abstract void getPackageSizeInfo( // PkgInfo pkgInfo, // Method getPackageSizeInfo, // PackageManager pm, // AppStatsCallback callback) throws Exception; // // public abstract PortableFile getParentFile(PortableFile file); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/LegacyFile.java // public interface LegacyFile { // String getName(); // String getCannonicalPath() throws IOException; // // boolean isLink(); // boolean isFile(); // long length(); // // LegacyFile[] listFiles(); // String[] list(); // // LegacyFile getChild(String string); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/PkgInfo.java // public interface PkgInfo { // String getPackageName(); // AppInfo getApplicationInfo(); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/PortableFile.java // public interface PortableFile { // @TargetApi(Build.VERSION_CODES.LOLLIPOP) // boolean isExternalStorageEmulated(); // @TargetApi(Build.VERSION_CODES.LOLLIPOP) // boolean isExternalStorageRemovable(); // // /** Retries with getAbsolutePath() on IOException */ // String getCanonicalPath(); // String getAbsolutePath(); // // @TargetApi(Build.VERSION_CODES.GINGERBREAD) // long getTotalSpace(); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/StatFsSource.java // public interface StatFsSource { // // @Deprecated // int getAvailableBlocks(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getAvailableBlocksLong(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getAvailableBytes(); // // @Deprecated // public int getBlockCount(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getBlockCountLong(); // // @Deprecated // public int getBlockSize(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getBlockSizeLong(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getFreeBytes(); // // @Deprecated // public int getFreeBlocks(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getFreeBlocksLong(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getTotalBytes(); // } // Path: app/src/main/java/com/google/android/diskusage/datasource/fast/DefaultDataSource.java import com.google.android.diskusage.datasource.AppStatsCallback; import com.google.android.diskusage.datasource.DataSource; import com.google.android.diskusage.datasource.LegacyFile; import com.google.android.diskusage.datasource.PkgInfo; import com.google.android.diskusage.datasource.PortableFile; import com.google.android.diskusage.datasource.StatFsSource; import android.annotation.TargetApi; import android.content.Context; import android.content.pm.IPackageStatsObserver; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageStats; import android.os.Build; import android.os.Environment; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; package com.google.android.diskusage.datasource.fast; public class DefaultDataSource extends DataSource { @Override public InputStream getProc() throws IOException { return new FileInputStream(new File("/proc/mounts")); } @Override public int getAndroidVersion() { return Integer.parseInt(Build.VERSION.SDK); } @Override public List<PkgInfo> getInstalledPackages(PackageManager pm) { final List<PackageInfo> installedPackages = pm.getInstalledPackages( PackageManager.GET_META_DATA | PackageManager.GET_UNINSTALLED_PACKAGES); List<PkgInfo> packageInfos = new ArrayList<PkgInfo>(); for (PackageInfo info : installedPackages) { packageInfos.add(new PkgInfoImpl(info, pm)); } return packageInfos; } @Override
public StatFsSource statFs(String mountPoint) {
IvanVolosyuk/diskusage
app/src/main/java/com/google/android/diskusage/datasource/fast/DefaultDataSource.java
// Path: app/src/main/java/com/google/android/diskusage/datasource/AppStatsCallback.java // public interface AppStatsCallback { // void onGetStatsCompleted(AppStats stats, boolean succeeded); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/DataSource.java // public abstract class DataSource { // private static DataSource currentDataSource = new DefaultDataSource(); // // public static DataSource get() { // return currentDataSource; // } // // public static void override(DataSource dataSource) { // LoadableActivity.resetStoredStates(); // currentDataSource = dataSource; // } // // public abstract int getAndroidVersion(); // // public abstract List<PkgInfo> getInstalledPackages(PackageManager pm); // // public abstract StatFsSource statFs(String mountPoint); // // @TargetApi(Build.VERSION_CODES.FROYO) // public abstract PortableFile getExternalFilesDir(Context context); // @TargetApi(Build.VERSION_CODES.KITKAT) // public abstract PortableFile[] getExternalFilesDirs(Context context); // // public abstract PortableFile getExternalStorageDirectory(); // // public abstract InputStream createNativeScanner( // Context context, String path, // boolean rootRequired) throws IOException, InterruptedException; // // public abstract boolean isDeviceRooted(); // // public abstract LegacyFile createLegacyScanFile(String root); // // public final BufferedReader getProcReader() throws IOException { // return new BufferedReader(new InputStreamReader(getProc())); // } // // public abstract InputStream getProc() throws IOException; // // public abstract void getPackageSizeInfo( // PkgInfo pkgInfo, // Method getPackageSizeInfo, // PackageManager pm, // AppStatsCallback callback) throws Exception; // // public abstract PortableFile getParentFile(PortableFile file); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/LegacyFile.java // public interface LegacyFile { // String getName(); // String getCannonicalPath() throws IOException; // // boolean isLink(); // boolean isFile(); // long length(); // // LegacyFile[] listFiles(); // String[] list(); // // LegacyFile getChild(String string); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/PkgInfo.java // public interface PkgInfo { // String getPackageName(); // AppInfo getApplicationInfo(); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/PortableFile.java // public interface PortableFile { // @TargetApi(Build.VERSION_CODES.LOLLIPOP) // boolean isExternalStorageEmulated(); // @TargetApi(Build.VERSION_CODES.LOLLIPOP) // boolean isExternalStorageRemovable(); // // /** Retries with getAbsolutePath() on IOException */ // String getCanonicalPath(); // String getAbsolutePath(); // // @TargetApi(Build.VERSION_CODES.GINGERBREAD) // long getTotalSpace(); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/StatFsSource.java // public interface StatFsSource { // // @Deprecated // int getAvailableBlocks(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getAvailableBlocksLong(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getAvailableBytes(); // // @Deprecated // public int getBlockCount(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getBlockCountLong(); // // @Deprecated // public int getBlockSize(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getBlockSizeLong(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getFreeBytes(); // // @Deprecated // public int getFreeBlocks(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getFreeBlocksLong(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getTotalBytes(); // }
import com.google.android.diskusage.datasource.AppStatsCallback; import com.google.android.diskusage.datasource.DataSource; import com.google.android.diskusage.datasource.LegacyFile; import com.google.android.diskusage.datasource.PkgInfo; import com.google.android.diskusage.datasource.PortableFile; import com.google.android.diskusage.datasource.StatFsSource; import android.annotation.TargetApi; import android.content.Context; import android.content.pm.IPackageStatsObserver; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageStats; import android.os.Build; import android.os.Environment; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List;
package com.google.android.diskusage.datasource.fast; public class DefaultDataSource extends DataSource { @Override public InputStream getProc() throws IOException { return new FileInputStream(new File("/proc/mounts")); } @Override public int getAndroidVersion() { return Integer.parseInt(Build.VERSION.SDK); } @Override public List<PkgInfo> getInstalledPackages(PackageManager pm) { final List<PackageInfo> installedPackages = pm.getInstalledPackages( PackageManager.GET_META_DATA | PackageManager.GET_UNINSTALLED_PACKAGES); List<PkgInfo> packageInfos = new ArrayList<PkgInfo>(); for (PackageInfo info : installedPackages) { packageInfos.add(new PkgInfoImpl(info, pm)); } return packageInfos; } @Override public StatFsSource statFs(String mountPoint) { return new StatFsSourceImpl(mountPoint); } @TargetApi(Build.VERSION_CODES.FROYO) @Override
// Path: app/src/main/java/com/google/android/diskusage/datasource/AppStatsCallback.java // public interface AppStatsCallback { // void onGetStatsCompleted(AppStats stats, boolean succeeded); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/DataSource.java // public abstract class DataSource { // private static DataSource currentDataSource = new DefaultDataSource(); // // public static DataSource get() { // return currentDataSource; // } // // public static void override(DataSource dataSource) { // LoadableActivity.resetStoredStates(); // currentDataSource = dataSource; // } // // public abstract int getAndroidVersion(); // // public abstract List<PkgInfo> getInstalledPackages(PackageManager pm); // // public abstract StatFsSource statFs(String mountPoint); // // @TargetApi(Build.VERSION_CODES.FROYO) // public abstract PortableFile getExternalFilesDir(Context context); // @TargetApi(Build.VERSION_CODES.KITKAT) // public abstract PortableFile[] getExternalFilesDirs(Context context); // // public abstract PortableFile getExternalStorageDirectory(); // // public abstract InputStream createNativeScanner( // Context context, String path, // boolean rootRequired) throws IOException, InterruptedException; // // public abstract boolean isDeviceRooted(); // // public abstract LegacyFile createLegacyScanFile(String root); // // public final BufferedReader getProcReader() throws IOException { // return new BufferedReader(new InputStreamReader(getProc())); // } // // public abstract InputStream getProc() throws IOException; // // public abstract void getPackageSizeInfo( // PkgInfo pkgInfo, // Method getPackageSizeInfo, // PackageManager pm, // AppStatsCallback callback) throws Exception; // // public abstract PortableFile getParentFile(PortableFile file); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/LegacyFile.java // public interface LegacyFile { // String getName(); // String getCannonicalPath() throws IOException; // // boolean isLink(); // boolean isFile(); // long length(); // // LegacyFile[] listFiles(); // String[] list(); // // LegacyFile getChild(String string); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/PkgInfo.java // public interface PkgInfo { // String getPackageName(); // AppInfo getApplicationInfo(); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/PortableFile.java // public interface PortableFile { // @TargetApi(Build.VERSION_CODES.LOLLIPOP) // boolean isExternalStorageEmulated(); // @TargetApi(Build.VERSION_CODES.LOLLIPOP) // boolean isExternalStorageRemovable(); // // /** Retries with getAbsolutePath() on IOException */ // String getCanonicalPath(); // String getAbsolutePath(); // // @TargetApi(Build.VERSION_CODES.GINGERBREAD) // long getTotalSpace(); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/StatFsSource.java // public interface StatFsSource { // // @Deprecated // int getAvailableBlocks(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getAvailableBlocksLong(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getAvailableBytes(); // // @Deprecated // public int getBlockCount(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getBlockCountLong(); // // @Deprecated // public int getBlockSize(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getBlockSizeLong(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getFreeBytes(); // // @Deprecated // public int getFreeBlocks(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getFreeBlocksLong(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getTotalBytes(); // } // Path: app/src/main/java/com/google/android/diskusage/datasource/fast/DefaultDataSource.java import com.google.android.diskusage.datasource.AppStatsCallback; import com.google.android.diskusage.datasource.DataSource; import com.google.android.diskusage.datasource.LegacyFile; import com.google.android.diskusage.datasource.PkgInfo; import com.google.android.diskusage.datasource.PortableFile; import com.google.android.diskusage.datasource.StatFsSource; import android.annotation.TargetApi; import android.content.Context; import android.content.pm.IPackageStatsObserver; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageStats; import android.os.Build; import android.os.Environment; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; package com.google.android.diskusage.datasource.fast; public class DefaultDataSource extends DataSource { @Override public InputStream getProc() throws IOException { return new FileInputStream(new File("/proc/mounts")); } @Override public int getAndroidVersion() { return Integer.parseInt(Build.VERSION.SDK); } @Override public List<PkgInfo> getInstalledPackages(PackageManager pm) { final List<PackageInfo> installedPackages = pm.getInstalledPackages( PackageManager.GET_META_DATA | PackageManager.GET_UNINSTALLED_PACKAGES); List<PkgInfo> packageInfos = new ArrayList<PkgInfo>(); for (PackageInfo info : installedPackages) { packageInfos.add(new PkgInfoImpl(info, pm)); } return packageInfos; } @Override public StatFsSource statFs(String mountPoint) { return new StatFsSourceImpl(mountPoint); } @TargetApi(Build.VERSION_CODES.FROYO) @Override
public PortableFile getExternalFilesDir(Context context) {
IvanVolosyuk/diskusage
app/src/main/java/com/google/android/diskusage/datasource/fast/DefaultDataSource.java
// Path: app/src/main/java/com/google/android/diskusage/datasource/AppStatsCallback.java // public interface AppStatsCallback { // void onGetStatsCompleted(AppStats stats, boolean succeeded); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/DataSource.java // public abstract class DataSource { // private static DataSource currentDataSource = new DefaultDataSource(); // // public static DataSource get() { // return currentDataSource; // } // // public static void override(DataSource dataSource) { // LoadableActivity.resetStoredStates(); // currentDataSource = dataSource; // } // // public abstract int getAndroidVersion(); // // public abstract List<PkgInfo> getInstalledPackages(PackageManager pm); // // public abstract StatFsSource statFs(String mountPoint); // // @TargetApi(Build.VERSION_CODES.FROYO) // public abstract PortableFile getExternalFilesDir(Context context); // @TargetApi(Build.VERSION_CODES.KITKAT) // public abstract PortableFile[] getExternalFilesDirs(Context context); // // public abstract PortableFile getExternalStorageDirectory(); // // public abstract InputStream createNativeScanner( // Context context, String path, // boolean rootRequired) throws IOException, InterruptedException; // // public abstract boolean isDeviceRooted(); // // public abstract LegacyFile createLegacyScanFile(String root); // // public final BufferedReader getProcReader() throws IOException { // return new BufferedReader(new InputStreamReader(getProc())); // } // // public abstract InputStream getProc() throws IOException; // // public abstract void getPackageSizeInfo( // PkgInfo pkgInfo, // Method getPackageSizeInfo, // PackageManager pm, // AppStatsCallback callback) throws Exception; // // public abstract PortableFile getParentFile(PortableFile file); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/LegacyFile.java // public interface LegacyFile { // String getName(); // String getCannonicalPath() throws IOException; // // boolean isLink(); // boolean isFile(); // long length(); // // LegacyFile[] listFiles(); // String[] list(); // // LegacyFile getChild(String string); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/PkgInfo.java // public interface PkgInfo { // String getPackageName(); // AppInfo getApplicationInfo(); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/PortableFile.java // public interface PortableFile { // @TargetApi(Build.VERSION_CODES.LOLLIPOP) // boolean isExternalStorageEmulated(); // @TargetApi(Build.VERSION_CODES.LOLLIPOP) // boolean isExternalStorageRemovable(); // // /** Retries with getAbsolutePath() on IOException */ // String getCanonicalPath(); // String getAbsolutePath(); // // @TargetApi(Build.VERSION_CODES.GINGERBREAD) // long getTotalSpace(); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/StatFsSource.java // public interface StatFsSource { // // @Deprecated // int getAvailableBlocks(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getAvailableBlocksLong(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getAvailableBytes(); // // @Deprecated // public int getBlockCount(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getBlockCountLong(); // // @Deprecated // public int getBlockSize(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getBlockSizeLong(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getFreeBytes(); // // @Deprecated // public int getFreeBlocks(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getFreeBlocksLong(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getTotalBytes(); // }
import com.google.android.diskusage.datasource.AppStatsCallback; import com.google.android.diskusage.datasource.DataSource; import com.google.android.diskusage.datasource.LegacyFile; import com.google.android.diskusage.datasource.PkgInfo; import com.google.android.diskusage.datasource.PortableFile; import com.google.android.diskusage.datasource.StatFsSource; import android.annotation.TargetApi; import android.content.Context; import android.content.pm.IPackageStatsObserver; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageStats; import android.os.Build; import android.os.Environment; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List;
@Override public InputStream createNativeScanner( Context context, String path, boolean rootRequired) throws IOException, InterruptedException { return new NativeScannerStream.Factory(context).create(path, rootRequired); } @Override public boolean isDeviceRooted() { String pathEnv = System.getenv("PATH"); if (pathEnv != null) { String[] searchPaths = pathEnv.split(":"); for (String path : searchPaths) { if (path.length() == 0) { continue; } String suPath = path + "/su"; File suFile = new File(suPath); if (suFile.exists() && !suFile.isDirectory()) { return true; } } } return new File("/system/bin/su").isFile() || new File("/system/xbin/su").isFile(); } @Override
// Path: app/src/main/java/com/google/android/diskusage/datasource/AppStatsCallback.java // public interface AppStatsCallback { // void onGetStatsCompleted(AppStats stats, boolean succeeded); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/DataSource.java // public abstract class DataSource { // private static DataSource currentDataSource = new DefaultDataSource(); // // public static DataSource get() { // return currentDataSource; // } // // public static void override(DataSource dataSource) { // LoadableActivity.resetStoredStates(); // currentDataSource = dataSource; // } // // public abstract int getAndroidVersion(); // // public abstract List<PkgInfo> getInstalledPackages(PackageManager pm); // // public abstract StatFsSource statFs(String mountPoint); // // @TargetApi(Build.VERSION_CODES.FROYO) // public abstract PortableFile getExternalFilesDir(Context context); // @TargetApi(Build.VERSION_CODES.KITKAT) // public abstract PortableFile[] getExternalFilesDirs(Context context); // // public abstract PortableFile getExternalStorageDirectory(); // // public abstract InputStream createNativeScanner( // Context context, String path, // boolean rootRequired) throws IOException, InterruptedException; // // public abstract boolean isDeviceRooted(); // // public abstract LegacyFile createLegacyScanFile(String root); // // public final BufferedReader getProcReader() throws IOException { // return new BufferedReader(new InputStreamReader(getProc())); // } // // public abstract InputStream getProc() throws IOException; // // public abstract void getPackageSizeInfo( // PkgInfo pkgInfo, // Method getPackageSizeInfo, // PackageManager pm, // AppStatsCallback callback) throws Exception; // // public abstract PortableFile getParentFile(PortableFile file); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/LegacyFile.java // public interface LegacyFile { // String getName(); // String getCannonicalPath() throws IOException; // // boolean isLink(); // boolean isFile(); // long length(); // // LegacyFile[] listFiles(); // String[] list(); // // LegacyFile getChild(String string); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/PkgInfo.java // public interface PkgInfo { // String getPackageName(); // AppInfo getApplicationInfo(); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/PortableFile.java // public interface PortableFile { // @TargetApi(Build.VERSION_CODES.LOLLIPOP) // boolean isExternalStorageEmulated(); // @TargetApi(Build.VERSION_CODES.LOLLIPOP) // boolean isExternalStorageRemovable(); // // /** Retries with getAbsolutePath() on IOException */ // String getCanonicalPath(); // String getAbsolutePath(); // // @TargetApi(Build.VERSION_CODES.GINGERBREAD) // long getTotalSpace(); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/StatFsSource.java // public interface StatFsSource { // // @Deprecated // int getAvailableBlocks(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getAvailableBlocksLong(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getAvailableBytes(); // // @Deprecated // public int getBlockCount(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getBlockCountLong(); // // @Deprecated // public int getBlockSize(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getBlockSizeLong(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getFreeBytes(); // // @Deprecated // public int getFreeBlocks(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getFreeBlocksLong(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getTotalBytes(); // } // Path: app/src/main/java/com/google/android/diskusage/datasource/fast/DefaultDataSource.java import com.google.android.diskusage.datasource.AppStatsCallback; import com.google.android.diskusage.datasource.DataSource; import com.google.android.diskusage.datasource.LegacyFile; import com.google.android.diskusage.datasource.PkgInfo; import com.google.android.diskusage.datasource.PortableFile; import com.google.android.diskusage.datasource.StatFsSource; import android.annotation.TargetApi; import android.content.Context; import android.content.pm.IPackageStatsObserver; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageStats; import android.os.Build; import android.os.Environment; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; @Override public InputStream createNativeScanner( Context context, String path, boolean rootRequired) throws IOException, InterruptedException { return new NativeScannerStream.Factory(context).create(path, rootRequired); } @Override public boolean isDeviceRooted() { String pathEnv = System.getenv("PATH"); if (pathEnv != null) { String[] searchPaths = pathEnv.split(":"); for (String path : searchPaths) { if (path.length() == 0) { continue; } String suPath = path + "/su"; File suFile = new File(suPath); if (suFile.exists() && !suFile.isDirectory()) { return true; } } } return new File("/system/bin/su").isFile() || new File("/system/xbin/su").isFile(); } @Override
public LegacyFile createLegacyScanFile(String root) {
IvanVolosyuk/diskusage
app/src/main/java/com/google/android/diskusage/datasource/fast/DefaultDataSource.java
// Path: app/src/main/java/com/google/android/diskusage/datasource/AppStatsCallback.java // public interface AppStatsCallback { // void onGetStatsCompleted(AppStats stats, boolean succeeded); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/DataSource.java // public abstract class DataSource { // private static DataSource currentDataSource = new DefaultDataSource(); // // public static DataSource get() { // return currentDataSource; // } // // public static void override(DataSource dataSource) { // LoadableActivity.resetStoredStates(); // currentDataSource = dataSource; // } // // public abstract int getAndroidVersion(); // // public abstract List<PkgInfo> getInstalledPackages(PackageManager pm); // // public abstract StatFsSource statFs(String mountPoint); // // @TargetApi(Build.VERSION_CODES.FROYO) // public abstract PortableFile getExternalFilesDir(Context context); // @TargetApi(Build.VERSION_CODES.KITKAT) // public abstract PortableFile[] getExternalFilesDirs(Context context); // // public abstract PortableFile getExternalStorageDirectory(); // // public abstract InputStream createNativeScanner( // Context context, String path, // boolean rootRequired) throws IOException, InterruptedException; // // public abstract boolean isDeviceRooted(); // // public abstract LegacyFile createLegacyScanFile(String root); // // public final BufferedReader getProcReader() throws IOException { // return new BufferedReader(new InputStreamReader(getProc())); // } // // public abstract InputStream getProc() throws IOException; // // public abstract void getPackageSizeInfo( // PkgInfo pkgInfo, // Method getPackageSizeInfo, // PackageManager pm, // AppStatsCallback callback) throws Exception; // // public abstract PortableFile getParentFile(PortableFile file); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/LegacyFile.java // public interface LegacyFile { // String getName(); // String getCannonicalPath() throws IOException; // // boolean isLink(); // boolean isFile(); // long length(); // // LegacyFile[] listFiles(); // String[] list(); // // LegacyFile getChild(String string); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/PkgInfo.java // public interface PkgInfo { // String getPackageName(); // AppInfo getApplicationInfo(); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/PortableFile.java // public interface PortableFile { // @TargetApi(Build.VERSION_CODES.LOLLIPOP) // boolean isExternalStorageEmulated(); // @TargetApi(Build.VERSION_CODES.LOLLIPOP) // boolean isExternalStorageRemovable(); // // /** Retries with getAbsolutePath() on IOException */ // String getCanonicalPath(); // String getAbsolutePath(); // // @TargetApi(Build.VERSION_CODES.GINGERBREAD) // long getTotalSpace(); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/StatFsSource.java // public interface StatFsSource { // // @Deprecated // int getAvailableBlocks(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getAvailableBlocksLong(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getAvailableBytes(); // // @Deprecated // public int getBlockCount(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getBlockCountLong(); // // @Deprecated // public int getBlockSize(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getBlockSizeLong(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getFreeBytes(); // // @Deprecated // public int getFreeBlocks(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getFreeBlocksLong(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getTotalBytes(); // }
import com.google.android.diskusage.datasource.AppStatsCallback; import com.google.android.diskusage.datasource.DataSource; import com.google.android.diskusage.datasource.LegacyFile; import com.google.android.diskusage.datasource.PkgInfo; import com.google.android.diskusage.datasource.PortableFile; import com.google.android.diskusage.datasource.StatFsSource; import android.annotation.TargetApi; import android.content.Context; import android.content.pm.IPackageStatsObserver; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageStats; import android.os.Build; import android.os.Environment; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List;
public boolean isDeviceRooted() { String pathEnv = System.getenv("PATH"); if (pathEnv != null) { String[] searchPaths = pathEnv.split(":"); for (String path : searchPaths) { if (path.length() == 0) { continue; } String suPath = path + "/su"; File suFile = new File(suPath); if (suFile.exists() && !suFile.isDirectory()) { return true; } } } return new File("/system/bin/su").isFile() || new File("/system/xbin/su").isFile(); } @Override public LegacyFile createLegacyScanFile(String root) { return LegacyFileImpl.createRoot(root); } @Override public void getPackageSizeInfo( PkgInfo pkgInfo, Method getPackageSizeInfo, PackageManager pm,
// Path: app/src/main/java/com/google/android/diskusage/datasource/AppStatsCallback.java // public interface AppStatsCallback { // void onGetStatsCompleted(AppStats stats, boolean succeeded); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/DataSource.java // public abstract class DataSource { // private static DataSource currentDataSource = new DefaultDataSource(); // // public static DataSource get() { // return currentDataSource; // } // // public static void override(DataSource dataSource) { // LoadableActivity.resetStoredStates(); // currentDataSource = dataSource; // } // // public abstract int getAndroidVersion(); // // public abstract List<PkgInfo> getInstalledPackages(PackageManager pm); // // public abstract StatFsSource statFs(String mountPoint); // // @TargetApi(Build.VERSION_CODES.FROYO) // public abstract PortableFile getExternalFilesDir(Context context); // @TargetApi(Build.VERSION_CODES.KITKAT) // public abstract PortableFile[] getExternalFilesDirs(Context context); // // public abstract PortableFile getExternalStorageDirectory(); // // public abstract InputStream createNativeScanner( // Context context, String path, // boolean rootRequired) throws IOException, InterruptedException; // // public abstract boolean isDeviceRooted(); // // public abstract LegacyFile createLegacyScanFile(String root); // // public final BufferedReader getProcReader() throws IOException { // return new BufferedReader(new InputStreamReader(getProc())); // } // // public abstract InputStream getProc() throws IOException; // // public abstract void getPackageSizeInfo( // PkgInfo pkgInfo, // Method getPackageSizeInfo, // PackageManager pm, // AppStatsCallback callback) throws Exception; // // public abstract PortableFile getParentFile(PortableFile file); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/LegacyFile.java // public interface LegacyFile { // String getName(); // String getCannonicalPath() throws IOException; // // boolean isLink(); // boolean isFile(); // long length(); // // LegacyFile[] listFiles(); // String[] list(); // // LegacyFile getChild(String string); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/PkgInfo.java // public interface PkgInfo { // String getPackageName(); // AppInfo getApplicationInfo(); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/PortableFile.java // public interface PortableFile { // @TargetApi(Build.VERSION_CODES.LOLLIPOP) // boolean isExternalStorageEmulated(); // @TargetApi(Build.VERSION_CODES.LOLLIPOP) // boolean isExternalStorageRemovable(); // // /** Retries with getAbsolutePath() on IOException */ // String getCanonicalPath(); // String getAbsolutePath(); // // @TargetApi(Build.VERSION_CODES.GINGERBREAD) // long getTotalSpace(); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/StatFsSource.java // public interface StatFsSource { // // @Deprecated // int getAvailableBlocks(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getAvailableBlocksLong(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getAvailableBytes(); // // @Deprecated // public int getBlockCount(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getBlockCountLong(); // // @Deprecated // public int getBlockSize(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getBlockSizeLong(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getFreeBytes(); // // @Deprecated // public int getFreeBlocks(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getFreeBlocksLong(); // // @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) // public long getTotalBytes(); // } // Path: app/src/main/java/com/google/android/diskusage/datasource/fast/DefaultDataSource.java import com.google.android.diskusage.datasource.AppStatsCallback; import com.google.android.diskusage.datasource.DataSource; import com.google.android.diskusage.datasource.LegacyFile; import com.google.android.diskusage.datasource.PkgInfo; import com.google.android.diskusage.datasource.PortableFile; import com.google.android.diskusage.datasource.StatFsSource; import android.annotation.TargetApi; import android.content.Context; import android.content.pm.IPackageStatsObserver; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageStats; import android.os.Build; import android.os.Environment; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; public boolean isDeviceRooted() { String pathEnv = System.getenv("PATH"); if (pathEnv != null) { String[] searchPaths = pathEnv.split(":"); for (String path : searchPaths) { if (path.length() == 0) { continue; } String suPath = path + "/su"; File suFile = new File(suPath); if (suFile.exists() && !suFile.isDirectory()) { return true; } } } return new File("/system/bin/su").isFile() || new File("/system/xbin/su").isFile(); } @Override public LegacyFile createLegacyScanFile(String root) { return LegacyFileImpl.createRoot(root); } @Override public void getPackageSizeInfo( PkgInfo pkgInfo, Method getPackageSizeInfo, PackageManager pm,
final AppStatsCallback callback) throws Exception {
IvanVolosyuk/diskusage
app/src/main/java/com/google/android/diskusage/datasource/debug/PortableResult.java
// Path: app/src/main/java/com/google/android/diskusage/proto/PortableResultProto.java // @SuppressWarnings("hiding") // public final class PortableResultProto extends // com.google.protobuf.nano.MessageNano { // // private static volatile PortableResultProto[] _emptyArray; // public static PortableResultProto[] emptyArray() { // // Lazily initializes the empty array // if (_emptyArray == null) { // synchronized ( // com.google.protobuf.nano.InternalNano.LAZY_INIT_LOCK) { // if (_emptyArray == null) { // _emptyArray = new PortableResultProto[0]; // } // } // } // return _emptyArray; // } // // // optional .PortableExceptionProto exception = 1; // public com.google.android.diskusage.proto.PortableExceptionProto exception; // // // optional bool evaluated = 2; // public boolean evaluated; // // public PortableResultProto() { // clear(); // } // // public PortableResultProto clear() { // exception = null; // evaluated = false; // cachedSize = -1; // return this; // } // // @Override // public void writeTo(com.google.protobuf.nano.CodedOutputByteBufferNano output) // throws java.io.IOException { // if (this.exception != null) { // output.writeMessage(1, this.exception); // } // if (this.evaluated != false) { // output.writeBool(2, this.evaluated); // } // super.writeTo(output); // } // // @Override // protected int computeSerializedSize() { // int size = super.computeSerializedSize(); // if (this.exception != null) { // size += com.google.protobuf.nano.CodedOutputByteBufferNano // .computeMessageSize(1, this.exception); // } // if (this.evaluated != false) { // size += com.google.protobuf.nano.CodedOutputByteBufferNano // .computeBoolSize(2, this.evaluated); // } // return size; // } // // @Override // public PortableResultProto mergeFrom( // com.google.protobuf.nano.CodedInputByteBufferNano input) // throws java.io.IOException { // while (true) { // int tag = input.readTag(); // switch (tag) { // case 0: // return this; // default: { // if (!com.google.protobuf.nano.WireFormatNano.parseUnknownField(input, tag)) { // return this; // } // break; // } // case 10: { // if (this.exception == null) { // this.exception = new com.google.android.diskusage.proto.PortableExceptionProto(); // } // input.readMessage(this.exception); // break; // } // case 16: { // this.evaluated = input.readBool(); // break; // } // } // } // } // // public static PortableResultProto parseFrom(byte[] data) // throws com.google.protobuf.nano.InvalidProtocolBufferNanoException { // return com.google.protobuf.nano.MessageNano.mergeFrom(new PortableResultProto(), data); // } // // public static PortableResultProto parseFrom( // com.google.protobuf.nano.CodedInputByteBufferNano input) // throws java.io.IOException { // return new PortableResultProto().mergeFrom(input); // } // }
import com.google.android.diskusage.proto.PortableResultProto;
package com.google.android.diskusage.datasource.debug; public abstract class PortableResult { public abstract void run() throws Exception;
// Path: app/src/main/java/com/google/android/diskusage/proto/PortableResultProto.java // @SuppressWarnings("hiding") // public final class PortableResultProto extends // com.google.protobuf.nano.MessageNano { // // private static volatile PortableResultProto[] _emptyArray; // public static PortableResultProto[] emptyArray() { // // Lazily initializes the empty array // if (_emptyArray == null) { // synchronized ( // com.google.protobuf.nano.InternalNano.LAZY_INIT_LOCK) { // if (_emptyArray == null) { // _emptyArray = new PortableResultProto[0]; // } // } // } // return _emptyArray; // } // // // optional .PortableExceptionProto exception = 1; // public com.google.android.diskusage.proto.PortableExceptionProto exception; // // // optional bool evaluated = 2; // public boolean evaluated; // // public PortableResultProto() { // clear(); // } // // public PortableResultProto clear() { // exception = null; // evaluated = false; // cachedSize = -1; // return this; // } // // @Override // public void writeTo(com.google.protobuf.nano.CodedOutputByteBufferNano output) // throws java.io.IOException { // if (this.exception != null) { // output.writeMessage(1, this.exception); // } // if (this.evaluated != false) { // output.writeBool(2, this.evaluated); // } // super.writeTo(output); // } // // @Override // protected int computeSerializedSize() { // int size = super.computeSerializedSize(); // if (this.exception != null) { // size += com.google.protobuf.nano.CodedOutputByteBufferNano // .computeMessageSize(1, this.exception); // } // if (this.evaluated != false) { // size += com.google.protobuf.nano.CodedOutputByteBufferNano // .computeBoolSize(2, this.evaluated); // } // return size; // } // // @Override // public PortableResultProto mergeFrom( // com.google.protobuf.nano.CodedInputByteBufferNano input) // throws java.io.IOException { // while (true) { // int tag = input.readTag(); // switch (tag) { // case 0: // return this; // default: { // if (!com.google.protobuf.nano.WireFormatNano.parseUnknownField(input, tag)) { // return this; // } // break; // } // case 10: { // if (this.exception == null) { // this.exception = new com.google.android.diskusage.proto.PortableExceptionProto(); // } // input.readMessage(this.exception); // break; // } // case 16: { // this.evaluated = input.readBool(); // break; // } // } // } // } // // public static PortableResultProto parseFrom(byte[] data) // throws com.google.protobuf.nano.InvalidProtocolBufferNanoException { // return com.google.protobuf.nano.MessageNano.mergeFrom(new PortableResultProto(), data); // } // // public static PortableResultProto parseFrom( // com.google.protobuf.nano.CodedInputByteBufferNano input) // throws java.io.IOException { // return new PortableResultProto().mergeFrom(input); // } // } // Path: app/src/main/java/com/google/android/diskusage/datasource/debug/PortableResult.java import com.google.android.diskusage.proto.PortableResultProto; package com.google.android.diskusage.datasource.debug; public abstract class PortableResult { public abstract void run() throws Exception;
public static PortableResultProto eval(PortableResult r) {
IvanVolosyuk/diskusage
app/src/main/java/com/google/android/diskusage/RendererManager.java
// Path: app/src/main/java/com/google/android/diskusage/datasource/DataSource.java // public abstract class DataSource { // private static DataSource currentDataSource = new DefaultDataSource(); // // public static DataSource get() { // return currentDataSource; // } // // public static void override(DataSource dataSource) { // LoadableActivity.resetStoredStates(); // currentDataSource = dataSource; // } // // public abstract int getAndroidVersion(); // // public abstract List<PkgInfo> getInstalledPackages(PackageManager pm); // // public abstract StatFsSource statFs(String mountPoint); // // @TargetApi(Build.VERSION_CODES.FROYO) // public abstract PortableFile getExternalFilesDir(Context context); // @TargetApi(Build.VERSION_CODES.KITKAT) // public abstract PortableFile[] getExternalFilesDirs(Context context); // // public abstract PortableFile getExternalStorageDirectory(); // // public abstract InputStream createNativeScanner( // Context context, String path, // boolean rootRequired) throws IOException, InterruptedException; // // public abstract boolean isDeviceRooted(); // // public abstract LegacyFile createLegacyScanFile(String root); // // public final BufferedReader getProcReader() throws IOException { // return new BufferedReader(new InputStreamReader(getProc())); // } // // public abstract InputStream getProc() throws IOException; // // public abstract void getPackageSizeInfo( // PkgInfo pkgInfo, // Method getPackageSizeInfo, // PackageManager pm, // AppStatsCallback callback) throws Exception; // // public abstract PortableFile getParentFile(PortableFile file); // }
import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.content.DialogInterface.OnCancelListener; import android.content.DialogInterface.OnClickListener; import android.os.Build; import android.view.View; import com.google.android.diskusage.datasource.DataSource; import com.google.android.diskusage.entity.FileSystemSuperRoot; import com.google.android.diskusage.opengl.FileSystemViewGPU;
package com.google.android.diskusage; public class RendererManager { private static final String HW_RENDERER = "hw_renderer"; private final DiskUsage diskusage; private boolean hwRenderer; private boolean rendererChanged = false; private SharedPreferences getPrefs() { return diskusage.getSharedPreferences("settings", Context.MODE_PRIVATE); } public RendererManager(DiskUsage diskusage) { this.diskusage = diskusage; } public boolean hardwareRendererByDefault() {
// Path: app/src/main/java/com/google/android/diskusage/datasource/DataSource.java // public abstract class DataSource { // private static DataSource currentDataSource = new DefaultDataSource(); // // public static DataSource get() { // return currentDataSource; // } // // public static void override(DataSource dataSource) { // LoadableActivity.resetStoredStates(); // currentDataSource = dataSource; // } // // public abstract int getAndroidVersion(); // // public abstract List<PkgInfo> getInstalledPackages(PackageManager pm); // // public abstract StatFsSource statFs(String mountPoint); // // @TargetApi(Build.VERSION_CODES.FROYO) // public abstract PortableFile getExternalFilesDir(Context context); // @TargetApi(Build.VERSION_CODES.KITKAT) // public abstract PortableFile[] getExternalFilesDirs(Context context); // // public abstract PortableFile getExternalStorageDirectory(); // // public abstract InputStream createNativeScanner( // Context context, String path, // boolean rootRequired) throws IOException, InterruptedException; // // public abstract boolean isDeviceRooted(); // // public abstract LegacyFile createLegacyScanFile(String root); // // public final BufferedReader getProcReader() throws IOException { // return new BufferedReader(new InputStreamReader(getProc())); // } // // public abstract InputStream getProc() throws IOException; // // public abstract void getPackageSizeInfo( // PkgInfo pkgInfo, // Method getPackageSizeInfo, // PackageManager pm, // AppStatsCallback callback) throws Exception; // // public abstract PortableFile getParentFile(PortableFile file); // } // Path: app/src/main/java/com/google/android/diskusage/RendererManager.java import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.content.DialogInterface.OnCancelListener; import android.content.DialogInterface.OnClickListener; import android.os.Build; import android.view.View; import com.google.android.diskusage.datasource.DataSource; import com.google.android.diskusage.entity.FileSystemSuperRoot; import com.google.android.diskusage.opengl.FileSystemViewGPU; package com.google.android.diskusage; public class RendererManager { private static final String HW_RENDERER = "hw_renderer"; private final DiskUsage diskusage; private boolean hwRenderer; private boolean rendererChanged = false; private SharedPreferences getPrefs() { return diskusage.getSharedPreferences("settings", Context.MODE_PRIVATE); } public RendererManager(DiskUsage diskusage) { this.diskusage = diskusage; } public boolean hardwareRendererByDefault() {
final int sdkVersion = DataSource.get().getAndroidVersion();
IvanVolosyuk/diskusage
app/src/main/java/com/google/android/diskusage/datasource/fast/PkgInfoImpl.java
// Path: app/src/main/java/com/google/android/diskusage/datasource/AppInfo.java // public interface AppInfo { // int getFlags(); // String getDataDir(); // boolean isEnabled(); // String getName(); // String getPackageName(); // String getPublicSourceDir(); // String getSourceDir(); // @TargetApi(Build.VERSION_CODES.LOLLIPOP) // String[] getSplitSourceDirs(); // public String getApplicationLabel(); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/PkgInfo.java // public interface PkgInfo { // String getPackageName(); // AppInfo getApplicationInfo(); // }
import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import com.google.android.diskusage.datasource.AppInfo; import com.google.android.diskusage.datasource.PkgInfo;
package com.google.android.diskusage.datasource.fast; public class PkgInfoImpl implements PkgInfo { private final PackageInfo info; private final PackageManager pm; public PkgInfoImpl(PackageInfo info, PackageManager pm) { this.info = info; this.pm = pm; } @Override public String getPackageName() { return info.packageName; } @Override
// Path: app/src/main/java/com/google/android/diskusage/datasource/AppInfo.java // public interface AppInfo { // int getFlags(); // String getDataDir(); // boolean isEnabled(); // String getName(); // String getPackageName(); // String getPublicSourceDir(); // String getSourceDir(); // @TargetApi(Build.VERSION_CODES.LOLLIPOP) // String[] getSplitSourceDirs(); // public String getApplicationLabel(); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/PkgInfo.java // public interface PkgInfo { // String getPackageName(); // AppInfo getApplicationInfo(); // } // Path: app/src/main/java/com/google/android/diskusage/datasource/fast/PkgInfoImpl.java import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import com.google.android.diskusage.datasource.AppInfo; import com.google.android.diskusage.datasource.PkgInfo; package com.google.android.diskusage.datasource.fast; public class PkgInfoImpl implements PkgInfo { private final PackageInfo info; private final PackageManager pm; public PkgInfoImpl(PackageInfo info, PackageManager pm) { this.info = info; this.pm = pm; } @Override public String getPackageName() { return info.packageName; } @Override
public AppInfo getApplicationInfo() {
IvanVolosyuk/diskusage
app/src/main/java/com/google/android/diskusage/entity/FileSystemEntry.java
// Path: app/src/main/java/com/google/android/diskusage/Cursor.java // public class Cursor { // FileSystemEntry root; // public FileSystemEntry position; // public long top; // public int depth; // // Cursor(FileSystemState state, // FileSystemEntry root) { // this.root = root; // // if (root.children == null || root.children.length == 0) { // throw new RuntimeException("no place for position"); // } // position = root.children[0]; // depth = 0; // top = 0; // updateTitle(state); // } // // public void updateTitle(FileSystemState state) { // state.mainThreadAction.updateTitle(position); // } // // // void down(FileSystemState view) { // FileSystemEntry newCursor = position.getNext(); // if (newCursor == position) return; // view.invalidate(this); // top += position.getSizeForRendering(); // position = newCursor; // view.invalidate(this); // updateTitle(view); // } // // void up(FileSystemState view) { // FileSystemEntry newCursor = position.getPrev(); // if (newCursor == position) return; // view.invalidate(this); // top -= newCursor.getSizeForRendering(); // position = newCursor; // view.invalidate(this); // updateTitle(view); // } // // void right(FileSystemState state) { // if (position.children == null) return; // if (position.children.length == 0) return; // state.invalidate(this); // position = position.children[0]; // depth++; // // Log.d("Sample", "position depth = " + depth); // state.invalidate(this); // updateTitle(state); // } // // boolean left(FileSystemState state) { // if (position.parent == root) return false; // state.invalidate(this); // position = position.parent; // top = root.getOffset(position); // depth--; // // Log.d("Sample", "position depth = " + depth); // state.invalidate(this); // updateTitle(state); // return true; // } // // void set(FileSystemState state, FileSystemEntry newpos) { // if (newpos == root) throw new RuntimeException("will break zoomOut()"); // state.invalidate(this); // position = newpos; // depth = root.depth(position) - 1; // // Log.d("Sample", "position depth = " + depth); // top = root.getOffset(position); // state.invalidate(this); // updateTitle(state); // } // // void refresh(FileSystemState view) { // set(view, position); // } // } // // Path: app/src/main/java/com/google/android/diskusage/opengl/DrawingCache.java // public class DrawingCache { // private FileSystemEntry entry; // private String sizeString; // public RenderingThread.TextPixels textPixels; // public RenderingThread.TextPixels sizePixels; // // public DrawingCache(FileSystemEntry entry) { // this.entry = entry; // } // // public String getSizeString() { // if (sizeString != null) { // return sizeString; // } // String sizeString = entry.sizeString(); // this.sizeString = sizeString; // return sizeString; // } // // public void resetSizeString() { // sizeString = null; // sizePixels = null; // } // // public void drawText(RenderingThread rt, float x0, float y0, int elementWidth) { // if (textPixels == null) { // textPixels = new TextPixels(entry.name); // } // textPixels.draw(rt, x0, y0, elementWidth); // } // // public void drawSize(RenderingThread rt, float x0, float y0, int elementWidth) { // if (sizePixels == null) { // sizePixels = new TextPixels(getSizeString()); // } // sizePixels.draw(rt, x0, y0, elementWidth); // } // }
import android.graphics.Rect; import android.util.Log; import com.google.android.diskusage.Cursor; import com.google.android.diskusage.R; import com.google.android.diskusage.opengl.DrawingCache; import com.google.android.diskusage.opengl.RenderingThread; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.Map; import java.util.TreeMap; import java.util.Map.Entry; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint;
pos = windowHeight0 - fontSize0; } else { pos = top + fontSize0; } } float pos1 = pos - descent; float pos2 = pos - ascent; DrawingCache cache = c.getDrawingCache(); String sizeString = cache.getSizeString(); int cliplen = fg2.breakText(c.name, true, elementWidth - 4, null); String clippedName = c.name.substring(0, cliplen); Paint paint = c.children == null ? textPaintFile : textPaintFolder; canvas.drawText(clippedName, xoffset + 2, pos1, paint); canvas.drawText(sizeString, xoffset + 2, pos2, paint); } else if (bottom - top > fontSize0) { int cliplen = fg2.breakText(c.name, true, elementWidth - 4, null); String clippedName = c.name.substring(0, cliplen); Paint paint = c.children == null ? textPaintFile : textPaintFolder; canvas.drawText(clippedName, xoffset + 2, (top + bottom - ascent - descent) / 2, paint); } } child_clipTop -= csize; child_clipBottom -= csize; yoffset = bottom; } } public final void paintGPU(RenderingThread rt,
// Path: app/src/main/java/com/google/android/diskusage/Cursor.java // public class Cursor { // FileSystemEntry root; // public FileSystemEntry position; // public long top; // public int depth; // // Cursor(FileSystemState state, // FileSystemEntry root) { // this.root = root; // // if (root.children == null || root.children.length == 0) { // throw new RuntimeException("no place for position"); // } // position = root.children[0]; // depth = 0; // top = 0; // updateTitle(state); // } // // public void updateTitle(FileSystemState state) { // state.mainThreadAction.updateTitle(position); // } // // // void down(FileSystemState view) { // FileSystemEntry newCursor = position.getNext(); // if (newCursor == position) return; // view.invalidate(this); // top += position.getSizeForRendering(); // position = newCursor; // view.invalidate(this); // updateTitle(view); // } // // void up(FileSystemState view) { // FileSystemEntry newCursor = position.getPrev(); // if (newCursor == position) return; // view.invalidate(this); // top -= newCursor.getSizeForRendering(); // position = newCursor; // view.invalidate(this); // updateTitle(view); // } // // void right(FileSystemState state) { // if (position.children == null) return; // if (position.children.length == 0) return; // state.invalidate(this); // position = position.children[0]; // depth++; // // Log.d("Sample", "position depth = " + depth); // state.invalidate(this); // updateTitle(state); // } // // boolean left(FileSystemState state) { // if (position.parent == root) return false; // state.invalidate(this); // position = position.parent; // top = root.getOffset(position); // depth--; // // Log.d("Sample", "position depth = " + depth); // state.invalidate(this); // updateTitle(state); // return true; // } // // void set(FileSystemState state, FileSystemEntry newpos) { // if (newpos == root) throw new RuntimeException("will break zoomOut()"); // state.invalidate(this); // position = newpos; // depth = root.depth(position) - 1; // // Log.d("Sample", "position depth = " + depth); // top = root.getOffset(position); // state.invalidate(this); // updateTitle(state); // } // // void refresh(FileSystemState view) { // set(view, position); // } // } // // Path: app/src/main/java/com/google/android/diskusage/opengl/DrawingCache.java // public class DrawingCache { // private FileSystemEntry entry; // private String sizeString; // public RenderingThread.TextPixels textPixels; // public RenderingThread.TextPixels sizePixels; // // public DrawingCache(FileSystemEntry entry) { // this.entry = entry; // } // // public String getSizeString() { // if (sizeString != null) { // return sizeString; // } // String sizeString = entry.sizeString(); // this.sizeString = sizeString; // return sizeString; // } // // public void resetSizeString() { // sizeString = null; // sizePixels = null; // } // // public void drawText(RenderingThread rt, float x0, float y0, int elementWidth) { // if (textPixels == null) { // textPixels = new TextPixels(entry.name); // } // textPixels.draw(rt, x0, y0, elementWidth); // } // // public void drawSize(RenderingThread rt, float x0, float y0, int elementWidth) { // if (sizePixels == null) { // sizePixels = new TextPixels(getSizeString()); // } // sizePixels.draw(rt, x0, y0, elementWidth); // } // } // Path: app/src/main/java/com/google/android/diskusage/entity/FileSystemEntry.java import android.graphics.Rect; import android.util.Log; import com.google.android.diskusage.Cursor; import com.google.android.diskusage.R; import com.google.android.diskusage.opengl.DrawingCache; import com.google.android.diskusage.opengl.RenderingThread; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.Map; import java.util.TreeMap; import java.util.Map.Entry; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; pos = windowHeight0 - fontSize0; } else { pos = top + fontSize0; } } float pos1 = pos - descent; float pos2 = pos - ascent; DrawingCache cache = c.getDrawingCache(); String sizeString = cache.getSizeString(); int cliplen = fg2.breakText(c.name, true, elementWidth - 4, null); String clippedName = c.name.substring(0, cliplen); Paint paint = c.children == null ? textPaintFile : textPaintFolder; canvas.drawText(clippedName, xoffset + 2, pos1, paint); canvas.drawText(sizeString, xoffset + 2, pos2, paint); } else if (bottom - top > fontSize0) { int cliplen = fg2.breakText(c.name, true, elementWidth - 4, null); String clippedName = c.name.substring(0, cliplen); Paint paint = c.children == null ? textPaintFile : textPaintFolder; canvas.drawText(clippedName, xoffset + 2, (top + bottom - ascent - descent) / 2, paint); } } child_clipTop -= csize; child_clipBottom -= csize; yoffset = bottom; } } public final void paintGPU(RenderingThread rt,
Rect bounds, Cursor cursor, long viewTop,
IvanVolosyuk/diskusage
app/src/main/java/com/google/android/diskusage/datasource/debug/DebugDataSourceBridgeImpl.java
// Path: app/src/main/java/com/google/android/diskusage/datasource/DataSource.java // public abstract class DataSource { // private static DataSource currentDataSource = new DefaultDataSource(); // // public static DataSource get() { // return currentDataSource; // } // // public static void override(DataSource dataSource) { // LoadableActivity.resetStoredStates(); // currentDataSource = dataSource; // } // // public abstract int getAndroidVersion(); // // public abstract List<PkgInfo> getInstalledPackages(PackageManager pm); // // public abstract StatFsSource statFs(String mountPoint); // // @TargetApi(Build.VERSION_CODES.FROYO) // public abstract PortableFile getExternalFilesDir(Context context); // @TargetApi(Build.VERSION_CODES.KITKAT) // public abstract PortableFile[] getExternalFilesDirs(Context context); // // public abstract PortableFile getExternalStorageDirectory(); // // public abstract InputStream createNativeScanner( // Context context, String path, // boolean rootRequired) throws IOException, InterruptedException; // // public abstract boolean isDeviceRooted(); // // public abstract LegacyFile createLegacyScanFile(String root); // // public final BufferedReader getProcReader() throws IOException { // return new BufferedReader(new InputStreamReader(getProc())); // } // // public abstract InputStream getProc() throws IOException; // // public abstract void getPackageSizeInfo( // PkgInfo pkgInfo, // Method getPackageSizeInfo, // PackageManager pm, // AppStatsCallback callback) throws Exception; // // public abstract PortableFile getParentFile(PortableFile file); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/DebugDataSourceBridge.java // public interface DebugDataSourceBridge { // DataSource initNewDump(Context context) throws IOException; // DataSource loadDefaultDump() throws IOException; // void saveDumpAndSendReport(DataSource debugDataSource, Context context) throws IOException; // boolean dumpExist(); // }
import java.io.IOException; import android.content.Context; import com.google.android.diskusage.datasource.DataSource; import com.google.android.diskusage.datasource.DebugDataSourceBridge;
package com.google.android.diskusage.datasource.debug; public class DebugDataSourceBridgeImpl implements DebugDataSourceBridge { public DebugDataSourceBridgeImpl() { } @Override
// Path: app/src/main/java/com/google/android/diskusage/datasource/DataSource.java // public abstract class DataSource { // private static DataSource currentDataSource = new DefaultDataSource(); // // public static DataSource get() { // return currentDataSource; // } // // public static void override(DataSource dataSource) { // LoadableActivity.resetStoredStates(); // currentDataSource = dataSource; // } // // public abstract int getAndroidVersion(); // // public abstract List<PkgInfo> getInstalledPackages(PackageManager pm); // // public abstract StatFsSource statFs(String mountPoint); // // @TargetApi(Build.VERSION_CODES.FROYO) // public abstract PortableFile getExternalFilesDir(Context context); // @TargetApi(Build.VERSION_CODES.KITKAT) // public abstract PortableFile[] getExternalFilesDirs(Context context); // // public abstract PortableFile getExternalStorageDirectory(); // // public abstract InputStream createNativeScanner( // Context context, String path, // boolean rootRequired) throws IOException, InterruptedException; // // public abstract boolean isDeviceRooted(); // // public abstract LegacyFile createLegacyScanFile(String root); // // public final BufferedReader getProcReader() throws IOException { // return new BufferedReader(new InputStreamReader(getProc())); // } // // public abstract InputStream getProc() throws IOException; // // public abstract void getPackageSizeInfo( // PkgInfo pkgInfo, // Method getPackageSizeInfo, // PackageManager pm, // AppStatsCallback callback) throws Exception; // // public abstract PortableFile getParentFile(PortableFile file); // } // // Path: app/src/main/java/com/google/android/diskusage/datasource/DebugDataSourceBridge.java // public interface DebugDataSourceBridge { // DataSource initNewDump(Context context) throws IOException; // DataSource loadDefaultDump() throws IOException; // void saveDumpAndSendReport(DataSource debugDataSource, Context context) throws IOException; // boolean dumpExist(); // } // Path: app/src/main/java/com/google/android/diskusage/datasource/debug/DebugDataSourceBridgeImpl.java import java.io.IOException; import android.content.Context; import com.google.android.diskusage.datasource.DataSource; import com.google.android.diskusage.datasource.DebugDataSourceBridge; package com.google.android.diskusage.datasource.debug; public class DebugDataSourceBridgeImpl implements DebugDataSourceBridge { public DebugDataSourceBridgeImpl() { } @Override
public DataSource initNewDump(Context context) throws IOException {
SmileWide/main
src/main/java/smile/wide/AttributeValueHistogramMapper.java
// Path: src/main/java/smile/wide/data/DataSetReader.java // public interface DataSetReader<K,V> { // // // ========================================== // // this part about configuring the reader // // /** // * // * @param filter - a string like 1,2,4-5, all - weka-style // * // * 1-based index of the column in the un-filtered dataset // * // */ // void setFilter(String filter); // // /** // * Which column represents the unique instance ID. // * This is required, because the map may require // * the instance ID for output to reduce. // * // * 1-based index of the column in the un-filtered dataset // * So if filter is 1,3,5 and instanceID = 2, the second // * column is used, and not part of the data presented to the // * Bayes network. // */ // void setInstanceIDColumn(int instanceIDcolumn); // // // ========================================== // // this part about reading from a text file // // /** // * open the file to read from. // * close previous file if open // * // * @return file successfully opened // */ // boolean setFile(String fileName); // // /** // * set file pointer back to start // * // * @return file successfully rewound // */ // boolean rewind(); // // /** // * // * @return the next record as an instance // * or null if end of file // * // */ // Instance<K, V> nextRecord(); // // // ========================================== // // this part about parsing lines one by one // // Instance<K, V> parseLine(String value); // // // ========================================== // // this part about interpreting the values // // /** // * Interpret a raw string value as a BN outcome. // * Must guarantee that output is a valid SMILE BN outcome identifier, // * but need not specifically check that it is valid for a particular network. // * // * @param value // * @return A Bayesian network outcome valid for the attribute. // */ // public abstract String interpret(String value, String forAttribute); // // /** // * Does the given string represents a missing value for the given attribute? // * // * @param value // * @param forAtribute // * @return True iff the given string represent a missing value for the given attribute. // */ // public abstract boolean isMissingValue(String value, String forAtribute); // // } // // Path: src/main/java/smile/wide/data/Instance.java // public class Instance<ID,Value> { // // private ID _id; // private Value[] _val; // // public Instance(ID id, Value[] v){ // this._id = id; // this._val = v; // } // // public ID getID() // { // return _id; // } // // public Value[] getValue() // { // return _val; // } // // public void setID(ID id) // { // this._id = id; // } // // public void setValue(Value[] v) // { // this._val = v; // } // // }
import smile.wide.data.Instance; import static org.junit.Assert.*; import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.MapWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; import org.apache.log4j.Level; import org.apache.log4j.Logger; import smile.wide.data.DataSetReader;
/* Licensed to the DARPA XDATA project. DARPA XDATA 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 smile.wide; public class AttributeValueHistogramMapper extends Mapper<LongWritable, Text, Text, MapWritable > { private static final Logger s_logger; static { s_logger = Logger.getLogger(PerInstanceInferenceMapper.class); s_logger.setLevel(Level.INFO); } // ============================================================== // Members // configuration and initialization private Configuration conf_ = null; private String fileReaderClass_ = null; // what class to use to read the file private String fileReaderFilter_ = null; // a filter - which columns to use private String[] columnNames_ = null; private boolean initializing_ = true; // helpers
// Path: src/main/java/smile/wide/data/DataSetReader.java // public interface DataSetReader<K,V> { // // // ========================================== // // this part about configuring the reader // // /** // * // * @param filter - a string like 1,2,4-5, all - weka-style // * // * 1-based index of the column in the un-filtered dataset // * // */ // void setFilter(String filter); // // /** // * Which column represents the unique instance ID. // * This is required, because the map may require // * the instance ID for output to reduce. // * // * 1-based index of the column in the un-filtered dataset // * So if filter is 1,3,5 and instanceID = 2, the second // * column is used, and not part of the data presented to the // * Bayes network. // */ // void setInstanceIDColumn(int instanceIDcolumn); // // // ========================================== // // this part about reading from a text file // // /** // * open the file to read from. // * close previous file if open // * // * @return file successfully opened // */ // boolean setFile(String fileName); // // /** // * set file pointer back to start // * // * @return file successfully rewound // */ // boolean rewind(); // // /** // * // * @return the next record as an instance // * or null if end of file // * // */ // Instance<K, V> nextRecord(); // // // ========================================== // // this part about parsing lines one by one // // Instance<K, V> parseLine(String value); // // // ========================================== // // this part about interpreting the values // // /** // * Interpret a raw string value as a BN outcome. // * Must guarantee that output is a valid SMILE BN outcome identifier, // * but need not specifically check that it is valid for a particular network. // * // * @param value // * @return A Bayesian network outcome valid for the attribute. // */ // public abstract String interpret(String value, String forAttribute); // // /** // * Does the given string represents a missing value for the given attribute? // * // * @param value // * @param forAtribute // * @return True iff the given string represent a missing value for the given attribute. // */ // public abstract boolean isMissingValue(String value, String forAtribute); // // } // // Path: src/main/java/smile/wide/data/Instance.java // public class Instance<ID,Value> { // // private ID _id; // private Value[] _val; // // public Instance(ID id, Value[] v){ // this._id = id; // this._val = v; // } // // public ID getID() // { // return _id; // } // // public Value[] getValue() // { // return _val; // } // // public void setID(ID id) // { // this._id = id; // } // // public void setValue(Value[] v) // { // this._val = v; // } // // } // Path: src/main/java/smile/wide/AttributeValueHistogramMapper.java import smile.wide.data.Instance; import static org.junit.Assert.*; import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.MapWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; import org.apache.log4j.Level; import org.apache.log4j.Logger; import smile.wide.data.DataSetReader; /* Licensed to the DARPA XDATA project. DARPA XDATA 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 smile.wide; public class AttributeValueHistogramMapper extends Mapper<LongWritable, Text, Text, MapWritable > { private static final Logger s_logger; static { s_logger = Logger.getLogger(PerInstanceInferenceMapper.class); s_logger.setLevel(Level.INFO); } // ============================================================== // Members // configuration and initialization private Configuration conf_ = null; private String fileReaderClass_ = null; // what class to use to read the file private String fileReaderFilter_ = null; // a filter - which columns to use private String[] columnNames_ = null; private boolean initializing_ = true; // helpers
private DataSetReader<Integer,String> reader_;
SmileWide/main
src/main/java/smile/wide/AttributeValueHistogramMapper.java
// Path: src/main/java/smile/wide/data/DataSetReader.java // public interface DataSetReader<K,V> { // // // ========================================== // // this part about configuring the reader // // /** // * // * @param filter - a string like 1,2,4-5, all - weka-style // * // * 1-based index of the column in the un-filtered dataset // * // */ // void setFilter(String filter); // // /** // * Which column represents the unique instance ID. // * This is required, because the map may require // * the instance ID for output to reduce. // * // * 1-based index of the column in the un-filtered dataset // * So if filter is 1,3,5 and instanceID = 2, the second // * column is used, and not part of the data presented to the // * Bayes network. // */ // void setInstanceIDColumn(int instanceIDcolumn); // // // ========================================== // // this part about reading from a text file // // /** // * open the file to read from. // * close previous file if open // * // * @return file successfully opened // */ // boolean setFile(String fileName); // // /** // * set file pointer back to start // * // * @return file successfully rewound // */ // boolean rewind(); // // /** // * // * @return the next record as an instance // * or null if end of file // * // */ // Instance<K, V> nextRecord(); // // // ========================================== // // this part about parsing lines one by one // // Instance<K, V> parseLine(String value); // // // ========================================== // // this part about interpreting the values // // /** // * Interpret a raw string value as a BN outcome. // * Must guarantee that output is a valid SMILE BN outcome identifier, // * but need not specifically check that it is valid for a particular network. // * // * @param value // * @return A Bayesian network outcome valid for the attribute. // */ // public abstract String interpret(String value, String forAttribute); // // /** // * Does the given string represents a missing value for the given attribute? // * // * @param value // * @param forAtribute // * @return True iff the given string represent a missing value for the given attribute. // */ // public abstract boolean isMissingValue(String value, String forAtribute); // // } // // Path: src/main/java/smile/wide/data/Instance.java // public class Instance<ID,Value> { // // private ID _id; // private Value[] _val; // // public Instance(ID id, Value[] v){ // this._id = id; // this._val = v; // } // // public ID getID() // { // return _id; // } // // public Value[] getValue() // { // return _val; // } // // public void setID(ID id) // { // this._id = id; // } // // public void setValue(Value[] v) // { // this._val = v; // } // // }
import smile.wide.data.Instance; import static org.junit.Assert.*; import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.MapWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; import org.apache.log4j.Level; import org.apache.log4j.Logger; import smile.wide.data.DataSetReader;
assertEquals(columnNames_.length, fileReaderFilter_.split(",").length); try { Object r = Class.forName(fileReaderClass_).newInstance(); reader_ = (DataSetReader<Integer,String>) r; } catch (InstantiationException e) { s_logger.error("Instantiation exception for DataSetReader " + fileReaderClass_); e.printStackTrace(); System.exit(1); } catch (IllegalAccessException e) { s_logger.error("IllegalAccess exception for DataSetReader " + fileReaderClass_); e.printStackTrace(); System.exit(1); } catch (ClassNotFoundException e) { s_logger.error("ClassDefNotFoundException for DataSetReader " + fileReaderClass_); e.printStackTrace(); System.exit(1); } catch (ClassCastException e) { s_logger.error("ClassCastException for DataSetReader " + fileReaderClass_); e.printStackTrace(); System.exit(1); } reader_.setFilter(fileReaderFilter_); reader_.setInstanceIDColumn(1); // doesn't matter, won't use initializing_ = false; } // we're initialized
// Path: src/main/java/smile/wide/data/DataSetReader.java // public interface DataSetReader<K,V> { // // // ========================================== // // this part about configuring the reader // // /** // * // * @param filter - a string like 1,2,4-5, all - weka-style // * // * 1-based index of the column in the un-filtered dataset // * // */ // void setFilter(String filter); // // /** // * Which column represents the unique instance ID. // * This is required, because the map may require // * the instance ID for output to reduce. // * // * 1-based index of the column in the un-filtered dataset // * So if filter is 1,3,5 and instanceID = 2, the second // * column is used, and not part of the data presented to the // * Bayes network. // */ // void setInstanceIDColumn(int instanceIDcolumn); // // // ========================================== // // this part about reading from a text file // // /** // * open the file to read from. // * close previous file if open // * // * @return file successfully opened // */ // boolean setFile(String fileName); // // /** // * set file pointer back to start // * // * @return file successfully rewound // */ // boolean rewind(); // // /** // * // * @return the next record as an instance // * or null if end of file // * // */ // Instance<K, V> nextRecord(); // // // ========================================== // // this part about parsing lines one by one // // Instance<K, V> parseLine(String value); // // // ========================================== // // this part about interpreting the values // // /** // * Interpret a raw string value as a BN outcome. // * Must guarantee that output is a valid SMILE BN outcome identifier, // * but need not specifically check that it is valid for a particular network. // * // * @param value // * @return A Bayesian network outcome valid for the attribute. // */ // public abstract String interpret(String value, String forAttribute); // // /** // * Does the given string represents a missing value for the given attribute? // * // * @param value // * @param forAtribute // * @return True iff the given string represent a missing value for the given attribute. // */ // public abstract boolean isMissingValue(String value, String forAtribute); // // } // // Path: src/main/java/smile/wide/data/Instance.java // public class Instance<ID,Value> { // // private ID _id; // private Value[] _val; // // public Instance(ID id, Value[] v){ // this._id = id; // this._val = v; // } // // public ID getID() // { // return _id; // } // // public Value[] getValue() // { // return _val; // } // // public void setID(ID id) // { // this._id = id; // } // // public void setValue(Value[] v) // { // this._val = v; // } // // } // Path: src/main/java/smile/wide/AttributeValueHistogramMapper.java import smile.wide.data.Instance; import static org.junit.Assert.*; import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.MapWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; import org.apache.log4j.Level; import org.apache.log4j.Logger; import smile.wide.data.DataSetReader; assertEquals(columnNames_.length, fileReaderFilter_.split(",").length); try { Object r = Class.forName(fileReaderClass_).newInstance(); reader_ = (DataSetReader<Integer,String>) r; } catch (InstantiationException e) { s_logger.error("Instantiation exception for DataSetReader " + fileReaderClass_); e.printStackTrace(); System.exit(1); } catch (IllegalAccessException e) { s_logger.error("IllegalAccess exception for DataSetReader " + fileReaderClass_); e.printStackTrace(); System.exit(1); } catch (ClassNotFoundException e) { s_logger.error("ClassDefNotFoundException for DataSetReader " + fileReaderClass_); e.printStackTrace(); System.exit(1); } catch (ClassCastException e) { s_logger.error("ClassCastException for DataSetReader " + fileReaderClass_); e.printStackTrace(); System.exit(1); } reader_.setFilter(fileReaderFilter_); reader_.setInstanceIDColumn(1); // doesn't matter, won't use initializing_ = false; } // we're initialized
Instance<Integer,String> inst = reader_.parseLine(value.toString());
SmileWide/main
src/main/java/smile/wide/PerInstanceInferenceMapper.java
// Path: src/main/java/smile/wide/data/DataSetReader.java // public interface DataSetReader<K,V> { // // // ========================================== // // this part about configuring the reader // // /** // * // * @param filter - a string like 1,2,4-5, all - weka-style // * // * 1-based index of the column in the un-filtered dataset // * // */ // void setFilter(String filter); // // /** // * Which column represents the unique instance ID. // * This is required, because the map may require // * the instance ID for output to reduce. // * // * 1-based index of the column in the un-filtered dataset // * So if filter is 1,3,5 and instanceID = 2, the second // * column is used, and not part of the data presented to the // * Bayes network. // */ // void setInstanceIDColumn(int instanceIDcolumn); // // // ========================================== // // this part about reading from a text file // // /** // * open the file to read from. // * close previous file if open // * // * @return file successfully opened // */ // boolean setFile(String fileName); // // /** // * set file pointer back to start // * // * @return file successfully rewound // */ // boolean rewind(); // // /** // * // * @return the next record as an instance // * or null if end of file // * // */ // Instance<K, V> nextRecord(); // // // ========================================== // // this part about parsing lines one by one // // Instance<K, V> parseLine(String value); // // // ========================================== // // this part about interpreting the values // // /** // * Interpret a raw string value as a BN outcome. // * Must guarantee that output is a valid SMILE BN outcome identifier, // * but need not specifically check that it is valid for a particular network. // * // * @param value // * @return A Bayesian network outcome valid for the attribute. // */ // public abstract String interpret(String value, String forAttribute); // // /** // * Does the given string represents a missing value for the given attribute? // * // * @param value // * @param forAtribute // * @return True iff the given string represent a missing value for the given attribute. // */ // public abstract boolean isMissingValue(String value, String forAtribute); // // } // // Path: src/main/java/smile/wide/data/Instance.java // public class Instance<ID,Value> { // // private ID _id; // private Value[] _val; // // public Instance(ID id, Value[] v){ // this._id = id; // this._val = v; // } // // public ID getID() // { // return _id; // } // // public Value[] getValue() // { // return _val; // } // // public void setID(ID id) // { // this._id = id; // } // // public void setValue(Value[] v) // { // this._val = v; // } // // }
import smile.wide.data.DataSetReader; import smile.wide.data.Instance; import smile.wide.hadoop.io.DoubleArrayWritable; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.DoubleWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; import org.apache.log4j.Level; import org.apache.log4j.Logger; import smile.Network;
/* Licensed to the DARPA XDATA project. DARPA XDATA 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 smile.wide; /** * <p> * Extends Hadoop's Mapper class: * </p><p> * Mapper&lt;LongWritable, Text, LongWritable, DoubleArrayWritable> * </p><ul> * <li>LongWritable: text offset</li> * <li>Text: the line to parse</li> * <li>LongWritable: the instance ID</li> * <li>DoubleArrayWritable: the posterior</li> * </ul> * @author tomas.singliar@boeing.com */ public class PerInstanceInferenceMapper extends Mapper<LongWritable, Text, LongWritable, DoubleArrayWritable> { private static final Logger s_logger; static { s_logger = Logger.getLogger(PerInstanceInferenceMapper.class); s_logger.setLevel(Level.INFO); } //=================================================================== // Instance members private Configuration conf_ = null; private String networkFile_ = null; private String fileReaderClass_ = null; // what class to use to read the file private String fileReaderFilter_ = null; // a filter - which columns to use private int instanceIDcolumn_ = -1; // which one of them is the instance ID private String queryVariable_ = null; private String[] dataVariables_ = null; private Network theNet_ = null;
// Path: src/main/java/smile/wide/data/DataSetReader.java // public interface DataSetReader<K,V> { // // // ========================================== // // this part about configuring the reader // // /** // * // * @param filter - a string like 1,2,4-5, all - weka-style // * // * 1-based index of the column in the un-filtered dataset // * // */ // void setFilter(String filter); // // /** // * Which column represents the unique instance ID. // * This is required, because the map may require // * the instance ID for output to reduce. // * // * 1-based index of the column in the un-filtered dataset // * So if filter is 1,3,5 and instanceID = 2, the second // * column is used, and not part of the data presented to the // * Bayes network. // */ // void setInstanceIDColumn(int instanceIDcolumn); // // // ========================================== // // this part about reading from a text file // // /** // * open the file to read from. // * close previous file if open // * // * @return file successfully opened // */ // boolean setFile(String fileName); // // /** // * set file pointer back to start // * // * @return file successfully rewound // */ // boolean rewind(); // // /** // * // * @return the next record as an instance // * or null if end of file // * // */ // Instance<K, V> nextRecord(); // // // ========================================== // // this part about parsing lines one by one // // Instance<K, V> parseLine(String value); // // // ========================================== // // this part about interpreting the values // // /** // * Interpret a raw string value as a BN outcome. // * Must guarantee that output is a valid SMILE BN outcome identifier, // * but need not specifically check that it is valid for a particular network. // * // * @param value // * @return A Bayesian network outcome valid for the attribute. // */ // public abstract String interpret(String value, String forAttribute); // // /** // * Does the given string represents a missing value for the given attribute? // * // * @param value // * @param forAtribute // * @return True iff the given string represent a missing value for the given attribute. // */ // public abstract boolean isMissingValue(String value, String forAtribute); // // } // // Path: src/main/java/smile/wide/data/Instance.java // public class Instance<ID,Value> { // // private ID _id; // private Value[] _val; // // public Instance(ID id, Value[] v){ // this._id = id; // this._val = v; // } // // public ID getID() // { // return _id; // } // // public Value[] getValue() // { // return _val; // } // // public void setID(ID id) // { // this._id = id; // } // // public void setValue(Value[] v) // { // this._val = v; // } // // } // Path: src/main/java/smile/wide/PerInstanceInferenceMapper.java import smile.wide.data.DataSetReader; import smile.wide.data.Instance; import smile.wide.hadoop.io.DoubleArrayWritable; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.DoubleWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; import org.apache.log4j.Level; import org.apache.log4j.Logger; import smile.Network; /* Licensed to the DARPA XDATA project. DARPA XDATA 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 smile.wide; /** * <p> * Extends Hadoop's Mapper class: * </p><p> * Mapper&lt;LongWritable, Text, LongWritable, DoubleArrayWritable> * </p><ul> * <li>LongWritable: text offset</li> * <li>Text: the line to parse</li> * <li>LongWritable: the instance ID</li> * <li>DoubleArrayWritable: the posterior</li> * </ul> * @author tomas.singliar@boeing.com */ public class PerInstanceInferenceMapper extends Mapper<LongWritable, Text, LongWritable, DoubleArrayWritable> { private static final Logger s_logger; static { s_logger = Logger.getLogger(PerInstanceInferenceMapper.class); s_logger.setLevel(Level.INFO); } //=================================================================== // Instance members private Configuration conf_ = null; private String networkFile_ = null; private String fileReaderClass_ = null; // what class to use to read the file private String fileReaderFilter_ = null; // a filter - which columns to use private int instanceIDcolumn_ = -1; // which one of them is the instance ID private String queryVariable_ = null; private String[] dataVariables_ = null; private Network theNet_ = null;
private DataSetReader<Long,String> reader_;
SmileWide/main
src/main/java/smile/wide/PerInstanceInferenceMapper.java
// Path: src/main/java/smile/wide/data/DataSetReader.java // public interface DataSetReader<K,V> { // // // ========================================== // // this part about configuring the reader // // /** // * // * @param filter - a string like 1,2,4-5, all - weka-style // * // * 1-based index of the column in the un-filtered dataset // * // */ // void setFilter(String filter); // // /** // * Which column represents the unique instance ID. // * This is required, because the map may require // * the instance ID for output to reduce. // * // * 1-based index of the column in the un-filtered dataset // * So if filter is 1,3,5 and instanceID = 2, the second // * column is used, and not part of the data presented to the // * Bayes network. // */ // void setInstanceIDColumn(int instanceIDcolumn); // // // ========================================== // // this part about reading from a text file // // /** // * open the file to read from. // * close previous file if open // * // * @return file successfully opened // */ // boolean setFile(String fileName); // // /** // * set file pointer back to start // * // * @return file successfully rewound // */ // boolean rewind(); // // /** // * // * @return the next record as an instance // * or null if end of file // * // */ // Instance<K, V> nextRecord(); // // // ========================================== // // this part about parsing lines one by one // // Instance<K, V> parseLine(String value); // // // ========================================== // // this part about interpreting the values // // /** // * Interpret a raw string value as a BN outcome. // * Must guarantee that output is a valid SMILE BN outcome identifier, // * but need not specifically check that it is valid for a particular network. // * // * @param value // * @return A Bayesian network outcome valid for the attribute. // */ // public abstract String interpret(String value, String forAttribute); // // /** // * Does the given string represents a missing value for the given attribute? // * // * @param value // * @param forAtribute // * @return True iff the given string represent a missing value for the given attribute. // */ // public abstract boolean isMissingValue(String value, String forAtribute); // // } // // Path: src/main/java/smile/wide/data/Instance.java // public class Instance<ID,Value> { // // private ID _id; // private Value[] _val; // // public Instance(ID id, Value[] v){ // this._id = id; // this._val = v; // } // // public ID getID() // { // return _id; // } // // public Value[] getValue() // { // return _val; // } // // public void setID(ID id) // { // this._id = id; // } // // public void setValue(Value[] v) // { // this._val = v; // } // // }
import smile.wide.data.DataSetReader; import smile.wide.data.Instance; import smile.wide.hadoop.io.DoubleArrayWritable; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.DoubleWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; import org.apache.log4j.Level; import org.apache.log4j.Logger; import smile.Network;
// initialize the file reader try { Object r = Class.forName(fileReaderClass_).newInstance(); reader_ = (DataSetReader<Long,String>) r; } catch (InstantiationException e) { s_logger.error("Instantiation exception for DataSetReader " + fileReaderClass_); e.printStackTrace(); System.exit(1); } catch (IllegalAccessException e) { s_logger.error("IllegalAccess exception for DataSetReader " + fileReaderClass_); e.printStackTrace(); System.exit(1); } catch (ClassNotFoundException e) { s_logger.error("ClassDefNotFoundException for DataSetReader " + fileReaderClass_); e.printStackTrace(); System.exit(1); } catch (ClassCastException e) { s_logger.error("ClassCastException for DataSetReader " + fileReaderClass_); e.printStackTrace(); System.exit(1); } reader_.setFilter(fileReaderFilter_); reader_.setInstanceIDColumn(instanceIDcolumn_); initializing_ = false; } // here starts the part where we are already initialized and going line-by-line
// Path: src/main/java/smile/wide/data/DataSetReader.java // public interface DataSetReader<K,V> { // // // ========================================== // // this part about configuring the reader // // /** // * // * @param filter - a string like 1,2,4-5, all - weka-style // * // * 1-based index of the column in the un-filtered dataset // * // */ // void setFilter(String filter); // // /** // * Which column represents the unique instance ID. // * This is required, because the map may require // * the instance ID for output to reduce. // * // * 1-based index of the column in the un-filtered dataset // * So if filter is 1,3,5 and instanceID = 2, the second // * column is used, and not part of the data presented to the // * Bayes network. // */ // void setInstanceIDColumn(int instanceIDcolumn); // // // ========================================== // // this part about reading from a text file // // /** // * open the file to read from. // * close previous file if open // * // * @return file successfully opened // */ // boolean setFile(String fileName); // // /** // * set file pointer back to start // * // * @return file successfully rewound // */ // boolean rewind(); // // /** // * // * @return the next record as an instance // * or null if end of file // * // */ // Instance<K, V> nextRecord(); // // // ========================================== // // this part about parsing lines one by one // // Instance<K, V> parseLine(String value); // // // ========================================== // // this part about interpreting the values // // /** // * Interpret a raw string value as a BN outcome. // * Must guarantee that output is a valid SMILE BN outcome identifier, // * but need not specifically check that it is valid for a particular network. // * // * @param value // * @return A Bayesian network outcome valid for the attribute. // */ // public abstract String interpret(String value, String forAttribute); // // /** // * Does the given string represents a missing value for the given attribute? // * // * @param value // * @param forAtribute // * @return True iff the given string represent a missing value for the given attribute. // */ // public abstract boolean isMissingValue(String value, String forAtribute); // // } // // Path: src/main/java/smile/wide/data/Instance.java // public class Instance<ID,Value> { // // private ID _id; // private Value[] _val; // // public Instance(ID id, Value[] v){ // this._id = id; // this._val = v; // } // // public ID getID() // { // return _id; // } // // public Value[] getValue() // { // return _val; // } // // public void setID(ID id) // { // this._id = id; // } // // public void setValue(Value[] v) // { // this._val = v; // } // // } // Path: src/main/java/smile/wide/PerInstanceInferenceMapper.java import smile.wide.data.DataSetReader; import smile.wide.data.Instance; import smile.wide.hadoop.io.DoubleArrayWritable; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.DoubleWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; import org.apache.log4j.Level; import org.apache.log4j.Logger; import smile.Network; // initialize the file reader try { Object r = Class.forName(fileReaderClass_).newInstance(); reader_ = (DataSetReader<Long,String>) r; } catch (InstantiationException e) { s_logger.error("Instantiation exception for DataSetReader " + fileReaderClass_); e.printStackTrace(); System.exit(1); } catch (IllegalAccessException e) { s_logger.error("IllegalAccess exception for DataSetReader " + fileReaderClass_); e.printStackTrace(); System.exit(1); } catch (ClassNotFoundException e) { s_logger.error("ClassDefNotFoundException for DataSetReader " + fileReaderClass_); e.printStackTrace(); System.exit(1); } catch (ClassCastException e) { s_logger.error("ClassCastException for DataSetReader " + fileReaderClass_); e.printStackTrace(); System.exit(1); } reader_.setFilter(fileReaderFilter_); reader_.setInstanceIDColumn(instanceIDcolumn_); initializing_ = false; } // here starts the part where we are already initialized and going line-by-line
Instance<Long,String> inst = reader_.parseLine(value.toString());
SmileWide/main
src/main/java/smile/wide/obsolete/GenieFileReader.java
// Path: src/main/java/smile/wide/data/Instance.java // public class Instance<ID,Value> { // // private ID _id; // private Value[] _val; // // public Instance(ID id, Value[] v){ // this._id = id; // this._val = v; // } // // public ID getID() // { // return _id; // } // // public Value[] getValue() // { // return _val; // } // // public void setID(ID id) // { // this._id = id; // } // // public void setValue(Value[] v) // { // this._val = v; // } // // }
import smile.Network; import smile.wide.data.Instance; import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; import java.util.List;
/* Licensed to the DARPA XDATA project. DARPA XDATA 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 smile.wide.obsolete; @Deprecated public class GenieFileReader { /** * Reads in the file produced by Genie - pretty straightforward * comma/tab-separated format. Expects the first column to be the unique ID * and checks uniqueness. Can generate the unique ID if told so. Outputs for * each row its unique ID and the attribute value indices (wants to access * the network to translate strings to indices per the network definition * * @param net- the Bayesian network * @param file - the file from which to read data * @param makeIDs * - whether to make unique instance IDs true - assumes the first * entry on a line is a data value, not an ID false - assumes the * first entry is an ID * @param separator: ",", "\t", or other separator character * @return * */
// Path: src/main/java/smile/wide/data/Instance.java // public class Instance<ID,Value> { // // private ID _id; // private Value[] _val; // // public Instance(ID id, Value[] v){ // this._id = id; // this._val = v; // } // // public ID getID() // { // return _id; // } // // public Value[] getValue() // { // return _val; // } // // public void setID(ID id) // { // this._id = id; // } // // public void setValue(Value[] v) // { // this._val = v; // } // // } // Path: src/main/java/smile/wide/obsolete/GenieFileReader.java import smile.Network; import smile.wide.data.Instance; import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; import java.util.List; /* Licensed to the DARPA XDATA project. DARPA XDATA 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 smile.wide.obsolete; @Deprecated public class GenieFileReader { /** * Reads in the file produced by Genie - pretty straightforward * comma/tab-separated format. Expects the first column to be the unique ID * and checks uniqueness. Can generate the unique ID if told so. Outputs for * each row its unique ID and the attribute value indices (wants to access * the network to translate strings to indices per the network definition * * @param net- the Bayesian network * @param file - the file from which to read data * @param makeIDs * - whether to make unique instance IDs true - assumes the first * entry on a line is a data value, not an ID false - assumes the * first entry is an ID * @param separator: ",", "\t", or other separator character * @return * */
public List<Instance<Integer, Integer>> readFile(Network net, String fileName, boolean makeIDs, String separator)
Esri/spatial-framework-for-hadoop
hive/src/main/java/com/esri/hadoop/hive/ST_AsText.java
// Path: hive/src/main/java/com/esri/hadoop/hive/GeometryUtils.java // public enum OGCType { // UNKNOWN(0), // ST_POINT(1), // ST_LINESTRING(2), // ST_POLYGON(3), // ST_MULTIPOINT(4), // ST_MULTILINESTRING(5), // ST_MULTIPOLYGON(6); // // private final int index; // // OGCType(int index){ // this.index = index; // } // // public int getIndex(){ // return this.index; // } // }
import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.hive.ql.exec.Description; import org.apache.hadoop.io.BytesWritable; import org.apache.hadoop.io.Text; import com.esri.core.geometry.GeometryEngine; import com.esri.core.geometry.WktExportFlags; import com.esri.hadoop.hive.GeometryUtils.OGCType; import com.esri.core.geometry.ogc.OGCGeometry;
package com.esri.hadoop.hive; @Description( name = "ST_AsText", value = "_FUNC_(ST_Geometry) - return Well-Known Text (WKT) representation of ST_Geometry\n", extended = "Example:\n" + " SELECT _FUNC_(ST_Point(1, 2)) FROM onerow; -- POINT (1 2)\n" ) //@HivePdkUnitTests( // cases = { // @HivePdkUnitTest( // query = "SELECT ST_AsText(ST_Point(1, 2)), ST_AsText(ST_MultiPoint(1, 2, 3, 4)) FROM onerow", // result = "POINT (1 2) MULTIPOINT ((1 2), (3 4))" // ), // @HivePdkUnitTest( // query = "SELECT ST_AsText(ST_LineString(1, 1, 2, 2, 3, 3)) FROM onerow", // result = "LINESTRING (1 1, 2 2, 3 3)" // ), // @HivePdkUnitTest( // query = "SELECT ST_AsText(ST_Polygon(1, 1, 1, 4, 4, 4, 4, 1)), ST_AsText(ST_Polygon(1, 1, 4, 1, 4, 4, 1, 4)) FROM onerow", // result = "POLYGON ((4 1, 4 4, 1 4, 1 1, 4 1)) NULL" // ), // @HivePdkUnitTest( // query = "SELECT ST_AsText(ST_MultiPolygon(array(1, 1, 1, 4, 4, 4, 4, 1), array(11, 11, 11, 14, 14, 14, 14, 11))) FROM onerow", // result = "MULTIPOLYGON (((4 1, 4 4, 1 4, 1 1, 4 1)), ((14 11, 14 14, 11 14, 11 11, 14 11)))" // ) // } // ) public class ST_AsText extends ST_Geometry { static final Log LOG = LogFactory.getLog(ST_AsText.class.getName()); public Text evaluate(BytesWritable geomref){ if (geomref == null || geomref.getLength() == 0){ LogUtils.Log_ArgumentsNull(LOG); return null; } OGCGeometry ogcGeometry = GeometryUtils.geometryFromEsriShape(geomref); if (ogcGeometry == null){ LogUtils.Log_ArgumentsNull(LOG); return null; } int wktExportFlag = getWktExportFlag(GeometryUtils.getType(geomref)); try { // mind: GeometryType with ST_AsText(ST_GeomFromText('MultiLineString((0 80, 0.03 80.04))')) // return new Text(ogcGeometry.asText()); return new Text(GeometryEngine.geometryToWkt(ogcGeometry.getEsriGeometry(), wktExportFlag)); } catch (Exception e){ LOG.error(e.getMessage()); return null; } }
// Path: hive/src/main/java/com/esri/hadoop/hive/GeometryUtils.java // public enum OGCType { // UNKNOWN(0), // ST_POINT(1), // ST_LINESTRING(2), // ST_POLYGON(3), // ST_MULTIPOINT(4), // ST_MULTILINESTRING(5), // ST_MULTIPOLYGON(6); // // private final int index; // // OGCType(int index){ // this.index = index; // } // // public int getIndex(){ // return this.index; // } // } // Path: hive/src/main/java/com/esri/hadoop/hive/ST_AsText.java import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.hive.ql.exec.Description; import org.apache.hadoop.io.BytesWritable; import org.apache.hadoop.io.Text; import com.esri.core.geometry.GeometryEngine; import com.esri.core.geometry.WktExportFlags; import com.esri.hadoop.hive.GeometryUtils.OGCType; import com.esri.core.geometry.ogc.OGCGeometry; package com.esri.hadoop.hive; @Description( name = "ST_AsText", value = "_FUNC_(ST_Geometry) - return Well-Known Text (WKT) representation of ST_Geometry\n", extended = "Example:\n" + " SELECT _FUNC_(ST_Point(1, 2)) FROM onerow; -- POINT (1 2)\n" ) //@HivePdkUnitTests( // cases = { // @HivePdkUnitTest( // query = "SELECT ST_AsText(ST_Point(1, 2)), ST_AsText(ST_MultiPoint(1, 2, 3, 4)) FROM onerow", // result = "POINT (1 2) MULTIPOINT ((1 2), (3 4))" // ), // @HivePdkUnitTest( // query = "SELECT ST_AsText(ST_LineString(1, 1, 2, 2, 3, 3)) FROM onerow", // result = "LINESTRING (1 1, 2 2, 3 3)" // ), // @HivePdkUnitTest( // query = "SELECT ST_AsText(ST_Polygon(1, 1, 1, 4, 4, 4, 4, 1)), ST_AsText(ST_Polygon(1, 1, 4, 1, 4, 4, 1, 4)) FROM onerow", // result = "POLYGON ((4 1, 4 4, 1 4, 1 1, 4 1)) NULL" // ), // @HivePdkUnitTest( // query = "SELECT ST_AsText(ST_MultiPolygon(array(1, 1, 1, 4, 4, 4, 4, 1), array(11, 11, 11, 14, 14, 14, 14, 11))) FROM onerow", // result = "MULTIPOLYGON (((4 1, 4 4, 1 4, 1 1, 4 1)), ((14 11, 14 14, 11 14, 11 11, 14 11)))" // ) // } // ) public class ST_AsText extends ST_Geometry { static final Log LOG = LogFactory.getLog(ST_AsText.class.getName()); public Text evaluate(BytesWritable geomref){ if (geomref == null || geomref.getLength() == 0){ LogUtils.Log_ArgumentsNull(LOG); return null; } OGCGeometry ogcGeometry = GeometryUtils.geometryFromEsriShape(geomref); if (ogcGeometry == null){ LogUtils.Log_ArgumentsNull(LOG); return null; } int wktExportFlag = getWktExportFlag(GeometryUtils.getType(geomref)); try { // mind: GeometryType with ST_AsText(ST_GeomFromText('MultiLineString((0 80, 0.03 80.04))')) // return new Text(ogcGeometry.asText()); return new Text(GeometryEngine.geometryToWkt(ogcGeometry.getEsriGeometry(), wktExportFlag)); } catch (Exception e){ LOG.error(e.getMessage()); return null; } }
private int getWktExportFlag(OGCType type){
Esri/spatial-framework-for-hadoop
hive/src/main/java/com/esri/hadoop/hive/ST_ConvexHull.java
// Path: hive/src/main/java/com/esri/hadoop/hive/GeometryUtils.java // public enum OGCType { // UNKNOWN(0), // ST_POINT(1), // ST_LINESTRING(2), // ST_POLYGON(3), // ST_MULTIPOINT(4), // ST_MULTILINESTRING(5), // ST_MULTIPOLYGON(6); // // private final int index; // // OGCType(int index){ // this.index = index; // } // // public int getIndex(){ // return this.index; // } // }
import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.hive.ql.exec.Description; import org.apache.hadoop.io.BytesWritable; import com.esri.core.geometry.Geometry; import com.esri.core.geometry.GeometryEngine; import com.esri.hadoop.hive.GeometryUtils.OGCType; import com.esri.core.geometry.ogc.OGCGeometry;
} } // now build geometry array to pass to GeometryEngine.union Geometry [] geomsToProcess = new Geometry[geomrefs.length]; for (int i=0;i<geomrefs.length;i++){ //HiveGeometry hiveGeometry = GeometryUtils.geometryFromEsriShape(geomrefs[i]); OGCGeometry ogcGeometry = GeometryUtils.geometryFromEsriShape(geomrefs[i]); if (ogcGeometry == null){ LogUtils.Log_ArgumentsNull(LOG); return null; } geomsToProcess[i] = ogcGeometry.getEsriGeometry(); } try { Geometry [] geomResult = GeometryEngine.convexHull(geomsToProcess, true); if (geomResult.length != 1){ return null; } Geometry merged = geomResult[0]; // we have to infer the type of the differenced geometry because we don't know // if it's going to end up as a single or multi-part geometry
// Path: hive/src/main/java/com/esri/hadoop/hive/GeometryUtils.java // public enum OGCType { // UNKNOWN(0), // ST_POINT(1), // ST_LINESTRING(2), // ST_POLYGON(3), // ST_MULTIPOINT(4), // ST_MULTILINESTRING(5), // ST_MULTIPOLYGON(6); // // private final int index; // // OGCType(int index){ // this.index = index; // } // // public int getIndex(){ // return this.index; // } // } // Path: hive/src/main/java/com/esri/hadoop/hive/ST_ConvexHull.java import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.hive.ql.exec.Description; import org.apache.hadoop.io.BytesWritable; import com.esri.core.geometry.Geometry; import com.esri.core.geometry.GeometryEngine; import com.esri.hadoop.hive.GeometryUtils.OGCType; import com.esri.core.geometry.ogc.OGCGeometry; } } // now build geometry array to pass to GeometryEngine.union Geometry [] geomsToProcess = new Geometry[geomrefs.length]; for (int i=0;i<geomrefs.length;i++){ //HiveGeometry hiveGeometry = GeometryUtils.geometryFromEsriShape(geomrefs[i]); OGCGeometry ogcGeometry = GeometryUtils.geometryFromEsriShape(geomrefs[i]); if (ogcGeometry == null){ LogUtils.Log_ArgumentsNull(LOG); return null; } geomsToProcess[i] = ogcGeometry.getEsriGeometry(); } try { Geometry [] geomResult = GeometryEngine.convexHull(geomsToProcess, true); if (geomResult.length != 1){ return null; } Geometry merged = geomResult[0]; // we have to infer the type of the differenced geometry because we don't know // if it's going to end up as a single or multi-part geometry
OGCType inferredType = GeometryUtils.getInferredOGCType(merged);
Esri/spatial-framework-for-hadoop
json/src/main/java/com/esri/json/EsriJsonFactory.java
// Path: json/src/main/java/com/esri/json/deserializer/GeometryJsonDeserializer.java // public class GeometryJsonDeserializer extends JsonDeserializer<Geometry> { // // public GeometryJsonDeserializer(){} // // @Override // public Geometry deserialize(JsonParser arg0, DeserializationContext arg1) // throws IOException, JsonProcessingException { // return GeometryEngine.jsonToGeometry(arg0).getGeometry(); // } // } // // Path: json/src/main/java/com/esri/json/deserializer/GeometryTypeJsonDeserializer.java // public class GeometryTypeJsonDeserializer extends JsonDeserializer<Geometry.Type> { // // public GeometryTypeJsonDeserializer(){} // // @Override // public Geometry.Type deserialize(JsonParser parser, DeserializationContext arg1) // throws IOException, JsonProcessingException { // // String type_text = parser.getText(); // // // geometry type enumerations coming from the JSON are prepended with "esriGeometry" (i.e. esriGeometryPolygon) // // while the geometry-java-api uses the form Geometry.Type.Polygon // if (type_text.startsWith("esriGeometry")) // { // // cut out esriGeometry to match Geometry.Type enumeration values // type_text = type_text.substring(12); // // try { // return Enum.valueOf(Geometry.Type.class, type_text); // } catch (Exception e){ // // parsing failed, fall through to unknown geometry type // } // } // // // return Geometry.Type.Unknown; // } // } // // Path: json/src/main/java/com/esri/json/deserializer/SpatialReferenceJsonDeserializer.java // public class SpatialReferenceJsonDeserializer extends JsonDeserializer<SpatialReference> { // // public SpatialReferenceJsonDeserializer(){} // // @Override // public SpatialReference deserialize(JsonParser parser, DeserializationContext arg1) // throws IOException, JsonProcessingException { // try { // return SpatialReference.fromJson(parser); // } catch (Exception e) { // return null; // } // } // } // // Path: json/src/main/java/com/esri/json/serializer/GeometryJsonSerializer.java // public class GeometryJsonSerializer extends JsonSerializer<Geometry> { // // @Override // public void serialize(Geometry geometry, JsonGenerator jsonGenerator, // SerializerProvider arg2) throws IOException, // JsonProcessingException { // // jsonGenerator.writeRawValue(GeometryEngine.geometryToJson(null, geometry)); // } // } // // Path: json/src/main/java/com/esri/json/serializer/GeometryTypeJsonSerializer.java // public class GeometryTypeJsonSerializer extends JsonSerializer<Geometry.Type>{ // // @Override // public void serialize(Type geometryType, JsonGenerator jsonGenerator, SerializerProvider arg2) // throws IOException, JsonProcessingException { // jsonGenerator.writeString("esriGeometry" + geometryType); // } // } // // Path: json/src/main/java/com/esri/json/serializer/SpatialReferenceJsonSerializer.java // public class SpatialReferenceJsonSerializer extends JsonSerializer<SpatialReference>{ // // @Override // public void serialize(SpatialReference spatialReference, JsonGenerator jsonGenerator, // SerializerProvider arg2) throws IOException, // JsonProcessingException { // // int wkid = spatialReference.getID(); // // jsonGenerator.writeStartObject(); // jsonGenerator.writeObjectField("wkid", wkid); // jsonGenerator.writeEndObject(); // } // // }
import java.io.IOException; import java.io.InputStream; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.Version; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; import com.esri.core.geometry.Geometry; import com.esri.core.geometry.SpatialReference; import com.esri.json.deserializer.GeometryJsonDeserializer; import com.esri.json.deserializer.GeometryTypeJsonDeserializer; import com.esri.json.deserializer.SpatialReferenceJsonDeserializer; import com.esri.json.serializer.GeometryJsonSerializer; import com.esri.json.serializer.GeometryTypeJsonSerializer; import com.esri.json.serializer.SpatialReferenceJsonSerializer;
package com.esri.json; public class EsriJsonFactory { private static final ObjectMapper jsonObjectMapper; private static final JsonFactory jsonFactory = new JsonFactory(); static { jsonObjectMapper = new ObjectMapper(); SimpleModule module = new SimpleModule("EsriJsonModule", new Version(1, 0, 0, null)); // add deserializers and serializers for types that can't be mapped field for field from the JSON
// Path: json/src/main/java/com/esri/json/deserializer/GeometryJsonDeserializer.java // public class GeometryJsonDeserializer extends JsonDeserializer<Geometry> { // // public GeometryJsonDeserializer(){} // // @Override // public Geometry deserialize(JsonParser arg0, DeserializationContext arg1) // throws IOException, JsonProcessingException { // return GeometryEngine.jsonToGeometry(arg0).getGeometry(); // } // } // // Path: json/src/main/java/com/esri/json/deserializer/GeometryTypeJsonDeserializer.java // public class GeometryTypeJsonDeserializer extends JsonDeserializer<Geometry.Type> { // // public GeometryTypeJsonDeserializer(){} // // @Override // public Geometry.Type deserialize(JsonParser parser, DeserializationContext arg1) // throws IOException, JsonProcessingException { // // String type_text = parser.getText(); // // // geometry type enumerations coming from the JSON are prepended with "esriGeometry" (i.e. esriGeometryPolygon) // // while the geometry-java-api uses the form Geometry.Type.Polygon // if (type_text.startsWith("esriGeometry")) // { // // cut out esriGeometry to match Geometry.Type enumeration values // type_text = type_text.substring(12); // // try { // return Enum.valueOf(Geometry.Type.class, type_text); // } catch (Exception e){ // // parsing failed, fall through to unknown geometry type // } // } // // // return Geometry.Type.Unknown; // } // } // // Path: json/src/main/java/com/esri/json/deserializer/SpatialReferenceJsonDeserializer.java // public class SpatialReferenceJsonDeserializer extends JsonDeserializer<SpatialReference> { // // public SpatialReferenceJsonDeserializer(){} // // @Override // public SpatialReference deserialize(JsonParser parser, DeserializationContext arg1) // throws IOException, JsonProcessingException { // try { // return SpatialReference.fromJson(parser); // } catch (Exception e) { // return null; // } // } // } // // Path: json/src/main/java/com/esri/json/serializer/GeometryJsonSerializer.java // public class GeometryJsonSerializer extends JsonSerializer<Geometry> { // // @Override // public void serialize(Geometry geometry, JsonGenerator jsonGenerator, // SerializerProvider arg2) throws IOException, // JsonProcessingException { // // jsonGenerator.writeRawValue(GeometryEngine.geometryToJson(null, geometry)); // } // } // // Path: json/src/main/java/com/esri/json/serializer/GeometryTypeJsonSerializer.java // public class GeometryTypeJsonSerializer extends JsonSerializer<Geometry.Type>{ // // @Override // public void serialize(Type geometryType, JsonGenerator jsonGenerator, SerializerProvider arg2) // throws IOException, JsonProcessingException { // jsonGenerator.writeString("esriGeometry" + geometryType); // } // } // // Path: json/src/main/java/com/esri/json/serializer/SpatialReferenceJsonSerializer.java // public class SpatialReferenceJsonSerializer extends JsonSerializer<SpatialReference>{ // // @Override // public void serialize(SpatialReference spatialReference, JsonGenerator jsonGenerator, // SerializerProvider arg2) throws IOException, // JsonProcessingException { // // int wkid = spatialReference.getID(); // // jsonGenerator.writeStartObject(); // jsonGenerator.writeObjectField("wkid", wkid); // jsonGenerator.writeEndObject(); // } // // } // Path: json/src/main/java/com/esri/json/EsriJsonFactory.java import java.io.IOException; import java.io.InputStream; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.Version; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; import com.esri.core.geometry.Geometry; import com.esri.core.geometry.SpatialReference; import com.esri.json.deserializer.GeometryJsonDeserializer; import com.esri.json.deserializer.GeometryTypeJsonDeserializer; import com.esri.json.deserializer.SpatialReferenceJsonDeserializer; import com.esri.json.serializer.GeometryJsonSerializer; import com.esri.json.serializer.GeometryTypeJsonSerializer; import com.esri.json.serializer.SpatialReferenceJsonSerializer; package com.esri.json; public class EsriJsonFactory { private static final ObjectMapper jsonObjectMapper; private static final JsonFactory jsonFactory = new JsonFactory(); static { jsonObjectMapper = new ObjectMapper(); SimpleModule module = new SimpleModule("EsriJsonModule", new Version(1, 0, 0, null)); // add deserializers and serializers for types that can't be mapped field for field from the JSON
module.addDeserializer(Geometry.class, new GeometryJsonDeserializer());
Esri/spatial-framework-for-hadoop
json/src/main/java/com/esri/json/EsriJsonFactory.java
// Path: json/src/main/java/com/esri/json/deserializer/GeometryJsonDeserializer.java // public class GeometryJsonDeserializer extends JsonDeserializer<Geometry> { // // public GeometryJsonDeserializer(){} // // @Override // public Geometry deserialize(JsonParser arg0, DeserializationContext arg1) // throws IOException, JsonProcessingException { // return GeometryEngine.jsonToGeometry(arg0).getGeometry(); // } // } // // Path: json/src/main/java/com/esri/json/deserializer/GeometryTypeJsonDeserializer.java // public class GeometryTypeJsonDeserializer extends JsonDeserializer<Geometry.Type> { // // public GeometryTypeJsonDeserializer(){} // // @Override // public Geometry.Type deserialize(JsonParser parser, DeserializationContext arg1) // throws IOException, JsonProcessingException { // // String type_text = parser.getText(); // // // geometry type enumerations coming from the JSON are prepended with "esriGeometry" (i.e. esriGeometryPolygon) // // while the geometry-java-api uses the form Geometry.Type.Polygon // if (type_text.startsWith("esriGeometry")) // { // // cut out esriGeometry to match Geometry.Type enumeration values // type_text = type_text.substring(12); // // try { // return Enum.valueOf(Geometry.Type.class, type_text); // } catch (Exception e){ // // parsing failed, fall through to unknown geometry type // } // } // // // return Geometry.Type.Unknown; // } // } // // Path: json/src/main/java/com/esri/json/deserializer/SpatialReferenceJsonDeserializer.java // public class SpatialReferenceJsonDeserializer extends JsonDeserializer<SpatialReference> { // // public SpatialReferenceJsonDeserializer(){} // // @Override // public SpatialReference deserialize(JsonParser parser, DeserializationContext arg1) // throws IOException, JsonProcessingException { // try { // return SpatialReference.fromJson(parser); // } catch (Exception e) { // return null; // } // } // } // // Path: json/src/main/java/com/esri/json/serializer/GeometryJsonSerializer.java // public class GeometryJsonSerializer extends JsonSerializer<Geometry> { // // @Override // public void serialize(Geometry geometry, JsonGenerator jsonGenerator, // SerializerProvider arg2) throws IOException, // JsonProcessingException { // // jsonGenerator.writeRawValue(GeometryEngine.geometryToJson(null, geometry)); // } // } // // Path: json/src/main/java/com/esri/json/serializer/GeometryTypeJsonSerializer.java // public class GeometryTypeJsonSerializer extends JsonSerializer<Geometry.Type>{ // // @Override // public void serialize(Type geometryType, JsonGenerator jsonGenerator, SerializerProvider arg2) // throws IOException, JsonProcessingException { // jsonGenerator.writeString("esriGeometry" + geometryType); // } // } // // Path: json/src/main/java/com/esri/json/serializer/SpatialReferenceJsonSerializer.java // public class SpatialReferenceJsonSerializer extends JsonSerializer<SpatialReference>{ // // @Override // public void serialize(SpatialReference spatialReference, JsonGenerator jsonGenerator, // SerializerProvider arg2) throws IOException, // JsonProcessingException { // // int wkid = spatialReference.getID(); // // jsonGenerator.writeStartObject(); // jsonGenerator.writeObjectField("wkid", wkid); // jsonGenerator.writeEndObject(); // } // // }
import java.io.IOException; import java.io.InputStream; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.Version; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; import com.esri.core.geometry.Geometry; import com.esri.core.geometry.SpatialReference; import com.esri.json.deserializer.GeometryJsonDeserializer; import com.esri.json.deserializer.GeometryTypeJsonDeserializer; import com.esri.json.deserializer.SpatialReferenceJsonDeserializer; import com.esri.json.serializer.GeometryJsonSerializer; import com.esri.json.serializer.GeometryTypeJsonSerializer; import com.esri.json.serializer.SpatialReferenceJsonSerializer;
package com.esri.json; public class EsriJsonFactory { private static final ObjectMapper jsonObjectMapper; private static final JsonFactory jsonFactory = new JsonFactory(); static { jsonObjectMapper = new ObjectMapper(); SimpleModule module = new SimpleModule("EsriJsonModule", new Version(1, 0, 0, null)); // add deserializers and serializers for types that can't be mapped field for field from the JSON module.addDeserializer(Geometry.class, new GeometryJsonDeserializer());
// Path: json/src/main/java/com/esri/json/deserializer/GeometryJsonDeserializer.java // public class GeometryJsonDeserializer extends JsonDeserializer<Geometry> { // // public GeometryJsonDeserializer(){} // // @Override // public Geometry deserialize(JsonParser arg0, DeserializationContext arg1) // throws IOException, JsonProcessingException { // return GeometryEngine.jsonToGeometry(arg0).getGeometry(); // } // } // // Path: json/src/main/java/com/esri/json/deserializer/GeometryTypeJsonDeserializer.java // public class GeometryTypeJsonDeserializer extends JsonDeserializer<Geometry.Type> { // // public GeometryTypeJsonDeserializer(){} // // @Override // public Geometry.Type deserialize(JsonParser parser, DeserializationContext arg1) // throws IOException, JsonProcessingException { // // String type_text = parser.getText(); // // // geometry type enumerations coming from the JSON are prepended with "esriGeometry" (i.e. esriGeometryPolygon) // // while the geometry-java-api uses the form Geometry.Type.Polygon // if (type_text.startsWith("esriGeometry")) // { // // cut out esriGeometry to match Geometry.Type enumeration values // type_text = type_text.substring(12); // // try { // return Enum.valueOf(Geometry.Type.class, type_text); // } catch (Exception e){ // // parsing failed, fall through to unknown geometry type // } // } // // // return Geometry.Type.Unknown; // } // } // // Path: json/src/main/java/com/esri/json/deserializer/SpatialReferenceJsonDeserializer.java // public class SpatialReferenceJsonDeserializer extends JsonDeserializer<SpatialReference> { // // public SpatialReferenceJsonDeserializer(){} // // @Override // public SpatialReference deserialize(JsonParser parser, DeserializationContext arg1) // throws IOException, JsonProcessingException { // try { // return SpatialReference.fromJson(parser); // } catch (Exception e) { // return null; // } // } // } // // Path: json/src/main/java/com/esri/json/serializer/GeometryJsonSerializer.java // public class GeometryJsonSerializer extends JsonSerializer<Geometry> { // // @Override // public void serialize(Geometry geometry, JsonGenerator jsonGenerator, // SerializerProvider arg2) throws IOException, // JsonProcessingException { // // jsonGenerator.writeRawValue(GeometryEngine.geometryToJson(null, geometry)); // } // } // // Path: json/src/main/java/com/esri/json/serializer/GeometryTypeJsonSerializer.java // public class GeometryTypeJsonSerializer extends JsonSerializer<Geometry.Type>{ // // @Override // public void serialize(Type geometryType, JsonGenerator jsonGenerator, SerializerProvider arg2) // throws IOException, JsonProcessingException { // jsonGenerator.writeString("esriGeometry" + geometryType); // } // } // // Path: json/src/main/java/com/esri/json/serializer/SpatialReferenceJsonSerializer.java // public class SpatialReferenceJsonSerializer extends JsonSerializer<SpatialReference>{ // // @Override // public void serialize(SpatialReference spatialReference, JsonGenerator jsonGenerator, // SerializerProvider arg2) throws IOException, // JsonProcessingException { // // int wkid = spatialReference.getID(); // // jsonGenerator.writeStartObject(); // jsonGenerator.writeObjectField("wkid", wkid); // jsonGenerator.writeEndObject(); // } // // } // Path: json/src/main/java/com/esri/json/EsriJsonFactory.java import java.io.IOException; import java.io.InputStream; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.Version; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; import com.esri.core.geometry.Geometry; import com.esri.core.geometry.SpatialReference; import com.esri.json.deserializer.GeometryJsonDeserializer; import com.esri.json.deserializer.GeometryTypeJsonDeserializer; import com.esri.json.deserializer.SpatialReferenceJsonDeserializer; import com.esri.json.serializer.GeometryJsonSerializer; import com.esri.json.serializer.GeometryTypeJsonSerializer; import com.esri.json.serializer.SpatialReferenceJsonSerializer; package com.esri.json; public class EsriJsonFactory { private static final ObjectMapper jsonObjectMapper; private static final JsonFactory jsonFactory = new JsonFactory(); static { jsonObjectMapper = new ObjectMapper(); SimpleModule module = new SimpleModule("EsriJsonModule", new Version(1, 0, 0, null)); // add deserializers and serializers for types that can't be mapped field for field from the JSON module.addDeserializer(Geometry.class, new GeometryJsonDeserializer());
module.addDeserializer(SpatialReference.class, new SpatialReferenceJsonDeserializer());
Esri/spatial-framework-for-hadoop
json/src/main/java/com/esri/json/EsriJsonFactory.java
// Path: json/src/main/java/com/esri/json/deserializer/GeometryJsonDeserializer.java // public class GeometryJsonDeserializer extends JsonDeserializer<Geometry> { // // public GeometryJsonDeserializer(){} // // @Override // public Geometry deserialize(JsonParser arg0, DeserializationContext arg1) // throws IOException, JsonProcessingException { // return GeometryEngine.jsonToGeometry(arg0).getGeometry(); // } // } // // Path: json/src/main/java/com/esri/json/deserializer/GeometryTypeJsonDeserializer.java // public class GeometryTypeJsonDeserializer extends JsonDeserializer<Geometry.Type> { // // public GeometryTypeJsonDeserializer(){} // // @Override // public Geometry.Type deserialize(JsonParser parser, DeserializationContext arg1) // throws IOException, JsonProcessingException { // // String type_text = parser.getText(); // // // geometry type enumerations coming from the JSON are prepended with "esriGeometry" (i.e. esriGeometryPolygon) // // while the geometry-java-api uses the form Geometry.Type.Polygon // if (type_text.startsWith("esriGeometry")) // { // // cut out esriGeometry to match Geometry.Type enumeration values // type_text = type_text.substring(12); // // try { // return Enum.valueOf(Geometry.Type.class, type_text); // } catch (Exception e){ // // parsing failed, fall through to unknown geometry type // } // } // // // return Geometry.Type.Unknown; // } // } // // Path: json/src/main/java/com/esri/json/deserializer/SpatialReferenceJsonDeserializer.java // public class SpatialReferenceJsonDeserializer extends JsonDeserializer<SpatialReference> { // // public SpatialReferenceJsonDeserializer(){} // // @Override // public SpatialReference deserialize(JsonParser parser, DeserializationContext arg1) // throws IOException, JsonProcessingException { // try { // return SpatialReference.fromJson(parser); // } catch (Exception e) { // return null; // } // } // } // // Path: json/src/main/java/com/esri/json/serializer/GeometryJsonSerializer.java // public class GeometryJsonSerializer extends JsonSerializer<Geometry> { // // @Override // public void serialize(Geometry geometry, JsonGenerator jsonGenerator, // SerializerProvider arg2) throws IOException, // JsonProcessingException { // // jsonGenerator.writeRawValue(GeometryEngine.geometryToJson(null, geometry)); // } // } // // Path: json/src/main/java/com/esri/json/serializer/GeometryTypeJsonSerializer.java // public class GeometryTypeJsonSerializer extends JsonSerializer<Geometry.Type>{ // // @Override // public void serialize(Type geometryType, JsonGenerator jsonGenerator, SerializerProvider arg2) // throws IOException, JsonProcessingException { // jsonGenerator.writeString("esriGeometry" + geometryType); // } // } // // Path: json/src/main/java/com/esri/json/serializer/SpatialReferenceJsonSerializer.java // public class SpatialReferenceJsonSerializer extends JsonSerializer<SpatialReference>{ // // @Override // public void serialize(SpatialReference spatialReference, JsonGenerator jsonGenerator, // SerializerProvider arg2) throws IOException, // JsonProcessingException { // // int wkid = spatialReference.getID(); // // jsonGenerator.writeStartObject(); // jsonGenerator.writeObjectField("wkid", wkid); // jsonGenerator.writeEndObject(); // } // // }
import java.io.IOException; import java.io.InputStream; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.Version; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; import com.esri.core.geometry.Geometry; import com.esri.core.geometry.SpatialReference; import com.esri.json.deserializer.GeometryJsonDeserializer; import com.esri.json.deserializer.GeometryTypeJsonDeserializer; import com.esri.json.deserializer.SpatialReferenceJsonDeserializer; import com.esri.json.serializer.GeometryJsonSerializer; import com.esri.json.serializer.GeometryTypeJsonSerializer; import com.esri.json.serializer.SpatialReferenceJsonSerializer;
package com.esri.json; public class EsriJsonFactory { private static final ObjectMapper jsonObjectMapper; private static final JsonFactory jsonFactory = new JsonFactory(); static { jsonObjectMapper = new ObjectMapper(); SimpleModule module = new SimpleModule("EsriJsonModule", new Version(1, 0, 0, null)); // add deserializers and serializers for types that can't be mapped field for field from the JSON module.addDeserializer(Geometry.class, new GeometryJsonDeserializer()); module.addDeserializer(SpatialReference.class, new SpatialReferenceJsonDeserializer());
// Path: json/src/main/java/com/esri/json/deserializer/GeometryJsonDeserializer.java // public class GeometryJsonDeserializer extends JsonDeserializer<Geometry> { // // public GeometryJsonDeserializer(){} // // @Override // public Geometry deserialize(JsonParser arg0, DeserializationContext arg1) // throws IOException, JsonProcessingException { // return GeometryEngine.jsonToGeometry(arg0).getGeometry(); // } // } // // Path: json/src/main/java/com/esri/json/deserializer/GeometryTypeJsonDeserializer.java // public class GeometryTypeJsonDeserializer extends JsonDeserializer<Geometry.Type> { // // public GeometryTypeJsonDeserializer(){} // // @Override // public Geometry.Type deserialize(JsonParser parser, DeserializationContext arg1) // throws IOException, JsonProcessingException { // // String type_text = parser.getText(); // // // geometry type enumerations coming from the JSON are prepended with "esriGeometry" (i.e. esriGeometryPolygon) // // while the geometry-java-api uses the form Geometry.Type.Polygon // if (type_text.startsWith("esriGeometry")) // { // // cut out esriGeometry to match Geometry.Type enumeration values // type_text = type_text.substring(12); // // try { // return Enum.valueOf(Geometry.Type.class, type_text); // } catch (Exception e){ // // parsing failed, fall through to unknown geometry type // } // } // // // return Geometry.Type.Unknown; // } // } // // Path: json/src/main/java/com/esri/json/deserializer/SpatialReferenceJsonDeserializer.java // public class SpatialReferenceJsonDeserializer extends JsonDeserializer<SpatialReference> { // // public SpatialReferenceJsonDeserializer(){} // // @Override // public SpatialReference deserialize(JsonParser parser, DeserializationContext arg1) // throws IOException, JsonProcessingException { // try { // return SpatialReference.fromJson(parser); // } catch (Exception e) { // return null; // } // } // } // // Path: json/src/main/java/com/esri/json/serializer/GeometryJsonSerializer.java // public class GeometryJsonSerializer extends JsonSerializer<Geometry> { // // @Override // public void serialize(Geometry geometry, JsonGenerator jsonGenerator, // SerializerProvider arg2) throws IOException, // JsonProcessingException { // // jsonGenerator.writeRawValue(GeometryEngine.geometryToJson(null, geometry)); // } // } // // Path: json/src/main/java/com/esri/json/serializer/GeometryTypeJsonSerializer.java // public class GeometryTypeJsonSerializer extends JsonSerializer<Geometry.Type>{ // // @Override // public void serialize(Type geometryType, JsonGenerator jsonGenerator, SerializerProvider arg2) // throws IOException, JsonProcessingException { // jsonGenerator.writeString("esriGeometry" + geometryType); // } // } // // Path: json/src/main/java/com/esri/json/serializer/SpatialReferenceJsonSerializer.java // public class SpatialReferenceJsonSerializer extends JsonSerializer<SpatialReference>{ // // @Override // public void serialize(SpatialReference spatialReference, JsonGenerator jsonGenerator, // SerializerProvider arg2) throws IOException, // JsonProcessingException { // // int wkid = spatialReference.getID(); // // jsonGenerator.writeStartObject(); // jsonGenerator.writeObjectField("wkid", wkid); // jsonGenerator.writeEndObject(); // } // // } // Path: json/src/main/java/com/esri/json/EsriJsonFactory.java import java.io.IOException; import java.io.InputStream; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.Version; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; import com.esri.core.geometry.Geometry; import com.esri.core.geometry.SpatialReference; import com.esri.json.deserializer.GeometryJsonDeserializer; import com.esri.json.deserializer.GeometryTypeJsonDeserializer; import com.esri.json.deserializer.SpatialReferenceJsonDeserializer; import com.esri.json.serializer.GeometryJsonSerializer; import com.esri.json.serializer.GeometryTypeJsonSerializer; import com.esri.json.serializer.SpatialReferenceJsonSerializer; package com.esri.json; public class EsriJsonFactory { private static final ObjectMapper jsonObjectMapper; private static final JsonFactory jsonFactory = new JsonFactory(); static { jsonObjectMapper = new ObjectMapper(); SimpleModule module = new SimpleModule("EsriJsonModule", new Version(1, 0, 0, null)); // add deserializers and serializers for types that can't be mapped field for field from the JSON module.addDeserializer(Geometry.class, new GeometryJsonDeserializer()); module.addDeserializer(SpatialReference.class, new SpatialReferenceJsonDeserializer());
module.addDeserializer(Geometry.Type.class, new GeometryTypeJsonDeserializer());
Esri/spatial-framework-for-hadoop
json/src/main/java/com/esri/json/EsriJsonFactory.java
// Path: json/src/main/java/com/esri/json/deserializer/GeometryJsonDeserializer.java // public class GeometryJsonDeserializer extends JsonDeserializer<Geometry> { // // public GeometryJsonDeserializer(){} // // @Override // public Geometry deserialize(JsonParser arg0, DeserializationContext arg1) // throws IOException, JsonProcessingException { // return GeometryEngine.jsonToGeometry(arg0).getGeometry(); // } // } // // Path: json/src/main/java/com/esri/json/deserializer/GeometryTypeJsonDeserializer.java // public class GeometryTypeJsonDeserializer extends JsonDeserializer<Geometry.Type> { // // public GeometryTypeJsonDeserializer(){} // // @Override // public Geometry.Type deserialize(JsonParser parser, DeserializationContext arg1) // throws IOException, JsonProcessingException { // // String type_text = parser.getText(); // // // geometry type enumerations coming from the JSON are prepended with "esriGeometry" (i.e. esriGeometryPolygon) // // while the geometry-java-api uses the form Geometry.Type.Polygon // if (type_text.startsWith("esriGeometry")) // { // // cut out esriGeometry to match Geometry.Type enumeration values // type_text = type_text.substring(12); // // try { // return Enum.valueOf(Geometry.Type.class, type_text); // } catch (Exception e){ // // parsing failed, fall through to unknown geometry type // } // } // // // return Geometry.Type.Unknown; // } // } // // Path: json/src/main/java/com/esri/json/deserializer/SpatialReferenceJsonDeserializer.java // public class SpatialReferenceJsonDeserializer extends JsonDeserializer<SpatialReference> { // // public SpatialReferenceJsonDeserializer(){} // // @Override // public SpatialReference deserialize(JsonParser parser, DeserializationContext arg1) // throws IOException, JsonProcessingException { // try { // return SpatialReference.fromJson(parser); // } catch (Exception e) { // return null; // } // } // } // // Path: json/src/main/java/com/esri/json/serializer/GeometryJsonSerializer.java // public class GeometryJsonSerializer extends JsonSerializer<Geometry> { // // @Override // public void serialize(Geometry geometry, JsonGenerator jsonGenerator, // SerializerProvider arg2) throws IOException, // JsonProcessingException { // // jsonGenerator.writeRawValue(GeometryEngine.geometryToJson(null, geometry)); // } // } // // Path: json/src/main/java/com/esri/json/serializer/GeometryTypeJsonSerializer.java // public class GeometryTypeJsonSerializer extends JsonSerializer<Geometry.Type>{ // // @Override // public void serialize(Type geometryType, JsonGenerator jsonGenerator, SerializerProvider arg2) // throws IOException, JsonProcessingException { // jsonGenerator.writeString("esriGeometry" + geometryType); // } // } // // Path: json/src/main/java/com/esri/json/serializer/SpatialReferenceJsonSerializer.java // public class SpatialReferenceJsonSerializer extends JsonSerializer<SpatialReference>{ // // @Override // public void serialize(SpatialReference spatialReference, JsonGenerator jsonGenerator, // SerializerProvider arg2) throws IOException, // JsonProcessingException { // // int wkid = spatialReference.getID(); // // jsonGenerator.writeStartObject(); // jsonGenerator.writeObjectField("wkid", wkid); // jsonGenerator.writeEndObject(); // } // // }
import java.io.IOException; import java.io.InputStream; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.Version; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; import com.esri.core.geometry.Geometry; import com.esri.core.geometry.SpatialReference; import com.esri.json.deserializer.GeometryJsonDeserializer; import com.esri.json.deserializer.GeometryTypeJsonDeserializer; import com.esri.json.deserializer.SpatialReferenceJsonDeserializer; import com.esri.json.serializer.GeometryJsonSerializer; import com.esri.json.serializer.GeometryTypeJsonSerializer; import com.esri.json.serializer.SpatialReferenceJsonSerializer;
package com.esri.json; public class EsriJsonFactory { private static final ObjectMapper jsonObjectMapper; private static final JsonFactory jsonFactory = new JsonFactory(); static { jsonObjectMapper = new ObjectMapper(); SimpleModule module = new SimpleModule("EsriJsonModule", new Version(1, 0, 0, null)); // add deserializers and serializers for types that can't be mapped field for field from the JSON module.addDeserializer(Geometry.class, new GeometryJsonDeserializer()); module.addDeserializer(SpatialReference.class, new SpatialReferenceJsonDeserializer()); module.addDeserializer(Geometry.Type.class, new GeometryTypeJsonDeserializer());
// Path: json/src/main/java/com/esri/json/deserializer/GeometryJsonDeserializer.java // public class GeometryJsonDeserializer extends JsonDeserializer<Geometry> { // // public GeometryJsonDeserializer(){} // // @Override // public Geometry deserialize(JsonParser arg0, DeserializationContext arg1) // throws IOException, JsonProcessingException { // return GeometryEngine.jsonToGeometry(arg0).getGeometry(); // } // } // // Path: json/src/main/java/com/esri/json/deserializer/GeometryTypeJsonDeserializer.java // public class GeometryTypeJsonDeserializer extends JsonDeserializer<Geometry.Type> { // // public GeometryTypeJsonDeserializer(){} // // @Override // public Geometry.Type deserialize(JsonParser parser, DeserializationContext arg1) // throws IOException, JsonProcessingException { // // String type_text = parser.getText(); // // // geometry type enumerations coming from the JSON are prepended with "esriGeometry" (i.e. esriGeometryPolygon) // // while the geometry-java-api uses the form Geometry.Type.Polygon // if (type_text.startsWith("esriGeometry")) // { // // cut out esriGeometry to match Geometry.Type enumeration values // type_text = type_text.substring(12); // // try { // return Enum.valueOf(Geometry.Type.class, type_text); // } catch (Exception e){ // // parsing failed, fall through to unknown geometry type // } // } // // // return Geometry.Type.Unknown; // } // } // // Path: json/src/main/java/com/esri/json/deserializer/SpatialReferenceJsonDeserializer.java // public class SpatialReferenceJsonDeserializer extends JsonDeserializer<SpatialReference> { // // public SpatialReferenceJsonDeserializer(){} // // @Override // public SpatialReference deserialize(JsonParser parser, DeserializationContext arg1) // throws IOException, JsonProcessingException { // try { // return SpatialReference.fromJson(parser); // } catch (Exception e) { // return null; // } // } // } // // Path: json/src/main/java/com/esri/json/serializer/GeometryJsonSerializer.java // public class GeometryJsonSerializer extends JsonSerializer<Geometry> { // // @Override // public void serialize(Geometry geometry, JsonGenerator jsonGenerator, // SerializerProvider arg2) throws IOException, // JsonProcessingException { // // jsonGenerator.writeRawValue(GeometryEngine.geometryToJson(null, geometry)); // } // } // // Path: json/src/main/java/com/esri/json/serializer/GeometryTypeJsonSerializer.java // public class GeometryTypeJsonSerializer extends JsonSerializer<Geometry.Type>{ // // @Override // public void serialize(Type geometryType, JsonGenerator jsonGenerator, SerializerProvider arg2) // throws IOException, JsonProcessingException { // jsonGenerator.writeString("esriGeometry" + geometryType); // } // } // // Path: json/src/main/java/com/esri/json/serializer/SpatialReferenceJsonSerializer.java // public class SpatialReferenceJsonSerializer extends JsonSerializer<SpatialReference>{ // // @Override // public void serialize(SpatialReference spatialReference, JsonGenerator jsonGenerator, // SerializerProvider arg2) throws IOException, // JsonProcessingException { // // int wkid = spatialReference.getID(); // // jsonGenerator.writeStartObject(); // jsonGenerator.writeObjectField("wkid", wkid); // jsonGenerator.writeEndObject(); // } // // } // Path: json/src/main/java/com/esri/json/EsriJsonFactory.java import java.io.IOException; import java.io.InputStream; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.Version; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; import com.esri.core.geometry.Geometry; import com.esri.core.geometry.SpatialReference; import com.esri.json.deserializer.GeometryJsonDeserializer; import com.esri.json.deserializer.GeometryTypeJsonDeserializer; import com.esri.json.deserializer.SpatialReferenceJsonDeserializer; import com.esri.json.serializer.GeometryJsonSerializer; import com.esri.json.serializer.GeometryTypeJsonSerializer; import com.esri.json.serializer.SpatialReferenceJsonSerializer; package com.esri.json; public class EsriJsonFactory { private static final ObjectMapper jsonObjectMapper; private static final JsonFactory jsonFactory = new JsonFactory(); static { jsonObjectMapper = new ObjectMapper(); SimpleModule module = new SimpleModule("EsriJsonModule", new Version(1, 0, 0, null)); // add deserializers and serializers for types that can't be mapped field for field from the JSON module.addDeserializer(Geometry.class, new GeometryJsonDeserializer()); module.addDeserializer(SpatialReference.class, new SpatialReferenceJsonDeserializer()); module.addDeserializer(Geometry.Type.class, new GeometryTypeJsonDeserializer());
module.addSerializer(Geometry.class, new GeometryJsonSerializer());
Esri/spatial-framework-for-hadoop
json/src/main/java/com/esri/json/EsriJsonFactory.java
// Path: json/src/main/java/com/esri/json/deserializer/GeometryJsonDeserializer.java // public class GeometryJsonDeserializer extends JsonDeserializer<Geometry> { // // public GeometryJsonDeserializer(){} // // @Override // public Geometry deserialize(JsonParser arg0, DeserializationContext arg1) // throws IOException, JsonProcessingException { // return GeometryEngine.jsonToGeometry(arg0).getGeometry(); // } // } // // Path: json/src/main/java/com/esri/json/deserializer/GeometryTypeJsonDeserializer.java // public class GeometryTypeJsonDeserializer extends JsonDeserializer<Geometry.Type> { // // public GeometryTypeJsonDeserializer(){} // // @Override // public Geometry.Type deserialize(JsonParser parser, DeserializationContext arg1) // throws IOException, JsonProcessingException { // // String type_text = parser.getText(); // // // geometry type enumerations coming from the JSON are prepended with "esriGeometry" (i.e. esriGeometryPolygon) // // while the geometry-java-api uses the form Geometry.Type.Polygon // if (type_text.startsWith("esriGeometry")) // { // // cut out esriGeometry to match Geometry.Type enumeration values // type_text = type_text.substring(12); // // try { // return Enum.valueOf(Geometry.Type.class, type_text); // } catch (Exception e){ // // parsing failed, fall through to unknown geometry type // } // } // // // return Geometry.Type.Unknown; // } // } // // Path: json/src/main/java/com/esri/json/deserializer/SpatialReferenceJsonDeserializer.java // public class SpatialReferenceJsonDeserializer extends JsonDeserializer<SpatialReference> { // // public SpatialReferenceJsonDeserializer(){} // // @Override // public SpatialReference deserialize(JsonParser parser, DeserializationContext arg1) // throws IOException, JsonProcessingException { // try { // return SpatialReference.fromJson(parser); // } catch (Exception e) { // return null; // } // } // } // // Path: json/src/main/java/com/esri/json/serializer/GeometryJsonSerializer.java // public class GeometryJsonSerializer extends JsonSerializer<Geometry> { // // @Override // public void serialize(Geometry geometry, JsonGenerator jsonGenerator, // SerializerProvider arg2) throws IOException, // JsonProcessingException { // // jsonGenerator.writeRawValue(GeometryEngine.geometryToJson(null, geometry)); // } // } // // Path: json/src/main/java/com/esri/json/serializer/GeometryTypeJsonSerializer.java // public class GeometryTypeJsonSerializer extends JsonSerializer<Geometry.Type>{ // // @Override // public void serialize(Type geometryType, JsonGenerator jsonGenerator, SerializerProvider arg2) // throws IOException, JsonProcessingException { // jsonGenerator.writeString("esriGeometry" + geometryType); // } // } // // Path: json/src/main/java/com/esri/json/serializer/SpatialReferenceJsonSerializer.java // public class SpatialReferenceJsonSerializer extends JsonSerializer<SpatialReference>{ // // @Override // public void serialize(SpatialReference spatialReference, JsonGenerator jsonGenerator, // SerializerProvider arg2) throws IOException, // JsonProcessingException { // // int wkid = spatialReference.getID(); // // jsonGenerator.writeStartObject(); // jsonGenerator.writeObjectField("wkid", wkid); // jsonGenerator.writeEndObject(); // } // // }
import java.io.IOException; import java.io.InputStream; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.Version; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; import com.esri.core.geometry.Geometry; import com.esri.core.geometry.SpatialReference; import com.esri.json.deserializer.GeometryJsonDeserializer; import com.esri.json.deserializer.GeometryTypeJsonDeserializer; import com.esri.json.deserializer.SpatialReferenceJsonDeserializer; import com.esri.json.serializer.GeometryJsonSerializer; import com.esri.json.serializer.GeometryTypeJsonSerializer; import com.esri.json.serializer.SpatialReferenceJsonSerializer;
package com.esri.json; public class EsriJsonFactory { private static final ObjectMapper jsonObjectMapper; private static final JsonFactory jsonFactory = new JsonFactory(); static { jsonObjectMapper = new ObjectMapper(); SimpleModule module = new SimpleModule("EsriJsonModule", new Version(1, 0, 0, null)); // add deserializers and serializers for types that can't be mapped field for field from the JSON module.addDeserializer(Geometry.class, new GeometryJsonDeserializer()); module.addDeserializer(SpatialReference.class, new SpatialReferenceJsonDeserializer()); module.addDeserializer(Geometry.Type.class, new GeometryTypeJsonDeserializer()); module.addSerializer(Geometry.class, new GeometryJsonSerializer());
// Path: json/src/main/java/com/esri/json/deserializer/GeometryJsonDeserializer.java // public class GeometryJsonDeserializer extends JsonDeserializer<Geometry> { // // public GeometryJsonDeserializer(){} // // @Override // public Geometry deserialize(JsonParser arg0, DeserializationContext arg1) // throws IOException, JsonProcessingException { // return GeometryEngine.jsonToGeometry(arg0).getGeometry(); // } // } // // Path: json/src/main/java/com/esri/json/deserializer/GeometryTypeJsonDeserializer.java // public class GeometryTypeJsonDeserializer extends JsonDeserializer<Geometry.Type> { // // public GeometryTypeJsonDeserializer(){} // // @Override // public Geometry.Type deserialize(JsonParser parser, DeserializationContext arg1) // throws IOException, JsonProcessingException { // // String type_text = parser.getText(); // // // geometry type enumerations coming from the JSON are prepended with "esriGeometry" (i.e. esriGeometryPolygon) // // while the geometry-java-api uses the form Geometry.Type.Polygon // if (type_text.startsWith("esriGeometry")) // { // // cut out esriGeometry to match Geometry.Type enumeration values // type_text = type_text.substring(12); // // try { // return Enum.valueOf(Geometry.Type.class, type_text); // } catch (Exception e){ // // parsing failed, fall through to unknown geometry type // } // } // // // return Geometry.Type.Unknown; // } // } // // Path: json/src/main/java/com/esri/json/deserializer/SpatialReferenceJsonDeserializer.java // public class SpatialReferenceJsonDeserializer extends JsonDeserializer<SpatialReference> { // // public SpatialReferenceJsonDeserializer(){} // // @Override // public SpatialReference deserialize(JsonParser parser, DeserializationContext arg1) // throws IOException, JsonProcessingException { // try { // return SpatialReference.fromJson(parser); // } catch (Exception e) { // return null; // } // } // } // // Path: json/src/main/java/com/esri/json/serializer/GeometryJsonSerializer.java // public class GeometryJsonSerializer extends JsonSerializer<Geometry> { // // @Override // public void serialize(Geometry geometry, JsonGenerator jsonGenerator, // SerializerProvider arg2) throws IOException, // JsonProcessingException { // // jsonGenerator.writeRawValue(GeometryEngine.geometryToJson(null, geometry)); // } // } // // Path: json/src/main/java/com/esri/json/serializer/GeometryTypeJsonSerializer.java // public class GeometryTypeJsonSerializer extends JsonSerializer<Geometry.Type>{ // // @Override // public void serialize(Type geometryType, JsonGenerator jsonGenerator, SerializerProvider arg2) // throws IOException, JsonProcessingException { // jsonGenerator.writeString("esriGeometry" + geometryType); // } // } // // Path: json/src/main/java/com/esri/json/serializer/SpatialReferenceJsonSerializer.java // public class SpatialReferenceJsonSerializer extends JsonSerializer<SpatialReference>{ // // @Override // public void serialize(SpatialReference spatialReference, JsonGenerator jsonGenerator, // SerializerProvider arg2) throws IOException, // JsonProcessingException { // // int wkid = spatialReference.getID(); // // jsonGenerator.writeStartObject(); // jsonGenerator.writeObjectField("wkid", wkid); // jsonGenerator.writeEndObject(); // } // // } // Path: json/src/main/java/com/esri/json/EsriJsonFactory.java import java.io.IOException; import java.io.InputStream; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.Version; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; import com.esri.core.geometry.Geometry; import com.esri.core.geometry.SpatialReference; import com.esri.json.deserializer.GeometryJsonDeserializer; import com.esri.json.deserializer.GeometryTypeJsonDeserializer; import com.esri.json.deserializer.SpatialReferenceJsonDeserializer; import com.esri.json.serializer.GeometryJsonSerializer; import com.esri.json.serializer.GeometryTypeJsonSerializer; import com.esri.json.serializer.SpatialReferenceJsonSerializer; package com.esri.json; public class EsriJsonFactory { private static final ObjectMapper jsonObjectMapper; private static final JsonFactory jsonFactory = new JsonFactory(); static { jsonObjectMapper = new ObjectMapper(); SimpleModule module = new SimpleModule("EsriJsonModule", new Version(1, 0, 0, null)); // add deserializers and serializers for types that can't be mapped field for field from the JSON module.addDeserializer(Geometry.class, new GeometryJsonDeserializer()); module.addDeserializer(SpatialReference.class, new SpatialReferenceJsonDeserializer()); module.addDeserializer(Geometry.Type.class, new GeometryTypeJsonDeserializer()); module.addSerializer(Geometry.class, new GeometryJsonSerializer());
module.addSerializer(Geometry.Type.class, new GeometryTypeJsonSerializer());
Esri/spatial-framework-for-hadoop
json/src/main/java/com/esri/json/EsriJsonFactory.java
// Path: json/src/main/java/com/esri/json/deserializer/GeometryJsonDeserializer.java // public class GeometryJsonDeserializer extends JsonDeserializer<Geometry> { // // public GeometryJsonDeserializer(){} // // @Override // public Geometry deserialize(JsonParser arg0, DeserializationContext arg1) // throws IOException, JsonProcessingException { // return GeometryEngine.jsonToGeometry(arg0).getGeometry(); // } // } // // Path: json/src/main/java/com/esri/json/deserializer/GeometryTypeJsonDeserializer.java // public class GeometryTypeJsonDeserializer extends JsonDeserializer<Geometry.Type> { // // public GeometryTypeJsonDeserializer(){} // // @Override // public Geometry.Type deserialize(JsonParser parser, DeserializationContext arg1) // throws IOException, JsonProcessingException { // // String type_text = parser.getText(); // // // geometry type enumerations coming from the JSON are prepended with "esriGeometry" (i.e. esriGeometryPolygon) // // while the geometry-java-api uses the form Geometry.Type.Polygon // if (type_text.startsWith("esriGeometry")) // { // // cut out esriGeometry to match Geometry.Type enumeration values // type_text = type_text.substring(12); // // try { // return Enum.valueOf(Geometry.Type.class, type_text); // } catch (Exception e){ // // parsing failed, fall through to unknown geometry type // } // } // // // return Geometry.Type.Unknown; // } // } // // Path: json/src/main/java/com/esri/json/deserializer/SpatialReferenceJsonDeserializer.java // public class SpatialReferenceJsonDeserializer extends JsonDeserializer<SpatialReference> { // // public SpatialReferenceJsonDeserializer(){} // // @Override // public SpatialReference deserialize(JsonParser parser, DeserializationContext arg1) // throws IOException, JsonProcessingException { // try { // return SpatialReference.fromJson(parser); // } catch (Exception e) { // return null; // } // } // } // // Path: json/src/main/java/com/esri/json/serializer/GeometryJsonSerializer.java // public class GeometryJsonSerializer extends JsonSerializer<Geometry> { // // @Override // public void serialize(Geometry geometry, JsonGenerator jsonGenerator, // SerializerProvider arg2) throws IOException, // JsonProcessingException { // // jsonGenerator.writeRawValue(GeometryEngine.geometryToJson(null, geometry)); // } // } // // Path: json/src/main/java/com/esri/json/serializer/GeometryTypeJsonSerializer.java // public class GeometryTypeJsonSerializer extends JsonSerializer<Geometry.Type>{ // // @Override // public void serialize(Type geometryType, JsonGenerator jsonGenerator, SerializerProvider arg2) // throws IOException, JsonProcessingException { // jsonGenerator.writeString("esriGeometry" + geometryType); // } // } // // Path: json/src/main/java/com/esri/json/serializer/SpatialReferenceJsonSerializer.java // public class SpatialReferenceJsonSerializer extends JsonSerializer<SpatialReference>{ // // @Override // public void serialize(SpatialReference spatialReference, JsonGenerator jsonGenerator, // SerializerProvider arg2) throws IOException, // JsonProcessingException { // // int wkid = spatialReference.getID(); // // jsonGenerator.writeStartObject(); // jsonGenerator.writeObjectField("wkid", wkid); // jsonGenerator.writeEndObject(); // } // // }
import java.io.IOException; import java.io.InputStream; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.Version; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; import com.esri.core.geometry.Geometry; import com.esri.core.geometry.SpatialReference; import com.esri.json.deserializer.GeometryJsonDeserializer; import com.esri.json.deserializer.GeometryTypeJsonDeserializer; import com.esri.json.deserializer.SpatialReferenceJsonDeserializer; import com.esri.json.serializer.GeometryJsonSerializer; import com.esri.json.serializer.GeometryTypeJsonSerializer; import com.esri.json.serializer.SpatialReferenceJsonSerializer;
package com.esri.json; public class EsriJsonFactory { private static final ObjectMapper jsonObjectMapper; private static final JsonFactory jsonFactory = new JsonFactory(); static { jsonObjectMapper = new ObjectMapper(); SimpleModule module = new SimpleModule("EsriJsonModule", new Version(1, 0, 0, null)); // add deserializers and serializers for types that can't be mapped field for field from the JSON module.addDeserializer(Geometry.class, new GeometryJsonDeserializer()); module.addDeserializer(SpatialReference.class, new SpatialReferenceJsonDeserializer()); module.addDeserializer(Geometry.Type.class, new GeometryTypeJsonDeserializer()); module.addSerializer(Geometry.class, new GeometryJsonSerializer()); module.addSerializer(Geometry.Type.class, new GeometryTypeJsonSerializer());
// Path: json/src/main/java/com/esri/json/deserializer/GeometryJsonDeserializer.java // public class GeometryJsonDeserializer extends JsonDeserializer<Geometry> { // // public GeometryJsonDeserializer(){} // // @Override // public Geometry deserialize(JsonParser arg0, DeserializationContext arg1) // throws IOException, JsonProcessingException { // return GeometryEngine.jsonToGeometry(arg0).getGeometry(); // } // } // // Path: json/src/main/java/com/esri/json/deserializer/GeometryTypeJsonDeserializer.java // public class GeometryTypeJsonDeserializer extends JsonDeserializer<Geometry.Type> { // // public GeometryTypeJsonDeserializer(){} // // @Override // public Geometry.Type deserialize(JsonParser parser, DeserializationContext arg1) // throws IOException, JsonProcessingException { // // String type_text = parser.getText(); // // // geometry type enumerations coming from the JSON are prepended with "esriGeometry" (i.e. esriGeometryPolygon) // // while the geometry-java-api uses the form Geometry.Type.Polygon // if (type_text.startsWith("esriGeometry")) // { // // cut out esriGeometry to match Geometry.Type enumeration values // type_text = type_text.substring(12); // // try { // return Enum.valueOf(Geometry.Type.class, type_text); // } catch (Exception e){ // // parsing failed, fall through to unknown geometry type // } // } // // // return Geometry.Type.Unknown; // } // } // // Path: json/src/main/java/com/esri/json/deserializer/SpatialReferenceJsonDeserializer.java // public class SpatialReferenceJsonDeserializer extends JsonDeserializer<SpatialReference> { // // public SpatialReferenceJsonDeserializer(){} // // @Override // public SpatialReference deserialize(JsonParser parser, DeserializationContext arg1) // throws IOException, JsonProcessingException { // try { // return SpatialReference.fromJson(parser); // } catch (Exception e) { // return null; // } // } // } // // Path: json/src/main/java/com/esri/json/serializer/GeometryJsonSerializer.java // public class GeometryJsonSerializer extends JsonSerializer<Geometry> { // // @Override // public void serialize(Geometry geometry, JsonGenerator jsonGenerator, // SerializerProvider arg2) throws IOException, // JsonProcessingException { // // jsonGenerator.writeRawValue(GeometryEngine.geometryToJson(null, geometry)); // } // } // // Path: json/src/main/java/com/esri/json/serializer/GeometryTypeJsonSerializer.java // public class GeometryTypeJsonSerializer extends JsonSerializer<Geometry.Type>{ // // @Override // public void serialize(Type geometryType, JsonGenerator jsonGenerator, SerializerProvider arg2) // throws IOException, JsonProcessingException { // jsonGenerator.writeString("esriGeometry" + geometryType); // } // } // // Path: json/src/main/java/com/esri/json/serializer/SpatialReferenceJsonSerializer.java // public class SpatialReferenceJsonSerializer extends JsonSerializer<SpatialReference>{ // // @Override // public void serialize(SpatialReference spatialReference, JsonGenerator jsonGenerator, // SerializerProvider arg2) throws IOException, // JsonProcessingException { // // int wkid = spatialReference.getID(); // // jsonGenerator.writeStartObject(); // jsonGenerator.writeObjectField("wkid", wkid); // jsonGenerator.writeEndObject(); // } // // } // Path: json/src/main/java/com/esri/json/EsriJsonFactory.java import java.io.IOException; import java.io.InputStream; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.Version; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; import com.esri.core.geometry.Geometry; import com.esri.core.geometry.SpatialReference; import com.esri.json.deserializer.GeometryJsonDeserializer; import com.esri.json.deserializer.GeometryTypeJsonDeserializer; import com.esri.json.deserializer.SpatialReferenceJsonDeserializer; import com.esri.json.serializer.GeometryJsonSerializer; import com.esri.json.serializer.GeometryTypeJsonSerializer; import com.esri.json.serializer.SpatialReferenceJsonSerializer; package com.esri.json; public class EsriJsonFactory { private static final ObjectMapper jsonObjectMapper; private static final JsonFactory jsonFactory = new JsonFactory(); static { jsonObjectMapper = new ObjectMapper(); SimpleModule module = new SimpleModule("EsriJsonModule", new Version(1, 0, 0, null)); // add deserializers and serializers for types that can't be mapped field for field from the JSON module.addDeserializer(Geometry.class, new GeometryJsonDeserializer()); module.addDeserializer(SpatialReference.class, new SpatialReferenceJsonDeserializer()); module.addDeserializer(Geometry.Type.class, new GeometryTypeJsonDeserializer()); module.addSerializer(Geometry.class, new GeometryJsonSerializer()); module.addSerializer(Geometry.Type.class, new GeometryTypeJsonSerializer());
module.addSerializer(SpatialReference.class, new SpatialReferenceJsonSerializer());
Esri/spatial-framework-for-hadoop
hive/src/main/java/com/esri/hadoop/hive/ST_GeomFromShape.java
// Path: hive/src/main/java/com/esri/hadoop/hive/GeometryUtils.java // public enum OGCType { // UNKNOWN(0), // ST_POINT(1), // ST_LINESTRING(2), // ST_POLYGON(3), // ST_MULTIPOINT(4), // ST_MULTILINESTRING(5), // ST_MULTIPOLYGON(6); // // private final int index; // // OGCType(int index){ // this.index = index; // } // // public int getIndex(){ // return this.index; // } // }
import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.hive.ql.exec.Description; import org.apache.hadoop.hive.ql.exec.UDFArgumentException; import org.apache.hadoop.io.BytesWritable; import com.esri.core.geometry.Geometry; import com.esri.core.geometry.GeometryEngine; import com.esri.core.geometry.SpatialReference; import com.esri.hadoop.hive.GeometryUtils.OGCType;
package com.esri.hadoop.hive; @Description( name = "ST_GeomFromShape", value = "_FUNC_(shape) - construct ST_Geometry from Esri shape representation of geometry\n", extended = "Example:\n" + " SELECT _FUNC_(ST_AsShape(ST_Point(1, 2))); -- constructs ST_Point\n" ) public class ST_GeomFromShape extends ST_Geometry { static final Log LOG = LogFactory.getLog(ST_GeomFromShape.class.getName()); public BytesWritable evaluate(BytesWritable shape) throws UDFArgumentException { return evaluate(shape, 0); } public BytesWritable evaluate(BytesWritable shape, int wkid) throws UDFArgumentException { try { Geometry geometry = GeometryEngine.geometryFromEsriShape(shape.getBytes(), Geometry.Type.Unknown); switch (geometry.getType()) { case Point:
// Path: hive/src/main/java/com/esri/hadoop/hive/GeometryUtils.java // public enum OGCType { // UNKNOWN(0), // ST_POINT(1), // ST_LINESTRING(2), // ST_POLYGON(3), // ST_MULTIPOINT(4), // ST_MULTILINESTRING(5), // ST_MULTIPOLYGON(6); // // private final int index; // // OGCType(int index){ // this.index = index; // } // // public int getIndex(){ // return this.index; // } // } // Path: hive/src/main/java/com/esri/hadoop/hive/ST_GeomFromShape.java import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.hive.ql.exec.Description; import org.apache.hadoop.hive.ql.exec.UDFArgumentException; import org.apache.hadoop.io.BytesWritable; import com.esri.core.geometry.Geometry; import com.esri.core.geometry.GeometryEngine; import com.esri.core.geometry.SpatialReference; import com.esri.hadoop.hive.GeometryUtils.OGCType; package com.esri.hadoop.hive; @Description( name = "ST_GeomFromShape", value = "_FUNC_(shape) - construct ST_Geometry from Esri shape representation of geometry\n", extended = "Example:\n" + " SELECT _FUNC_(ST_AsShape(ST_Point(1, 2))); -- constructs ST_Point\n" ) public class ST_GeomFromShape extends ST_Geometry { static final Log LOG = LogFactory.getLog(ST_GeomFromShape.class.getName()); public BytesWritable evaluate(BytesWritable shape) throws UDFArgumentException { return evaluate(shape, 0); } public BytesWritable evaluate(BytesWritable shape, int wkid) throws UDFArgumentException { try { Geometry geometry = GeometryEngine.geometryFromEsriShape(shape.getBytes(), Geometry.Type.Unknown); switch (geometry.getType()) { case Point:
return GeometryUtils.geometryToEsriShapeBytesWritable(geometry, wkid, OGCType.ST_POINT);
Esri/spatial-framework-for-hadoop
hive/src/main/java/com/esri/hadoop/hive/ST_Union.java
// Path: hive/src/main/java/com/esri/hadoop/hive/GeometryUtils.java // public enum OGCType { // UNKNOWN(0), // ST_POINT(1), // ST_LINESTRING(2), // ST_POLYGON(3), // ST_MULTIPOINT(4), // ST_MULTILINESTRING(5), // ST_MULTIPOLYGON(6); // // private final int index; // // OGCType(int index){ // this.index = index; // } // // public int getIndex(){ // return this.index; // } // }
import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.hive.ql.exec.Description; import org.apache.hadoop.io.BytesWritable; import com.esri.core.geometry.Geometry; import com.esri.core.geometry.GeometryEngine; import com.esri.core.geometry.SpatialReference; import com.esri.hadoop.hive.GeometryUtils.OGCType; import com.esri.core.geometry.ogc.OGCGeometry;
} else if (firstWKID != GeometryUtils.getWKID(geomref)){ LogUtils.Log_SRIDMismatch(LOG, geomrefs[0], geomref); return null; } } // now build geometry array to pass to GeometryEngine.union Geometry [] geomsToUnion = new Geometry[geomrefs.length]; for (int i=0;i<geomrefs.length;i++){ //HiveGeometry hiveGeometry = GeometryUtils.geometryFromEsriShape(geomrefs[i]); OGCGeometry ogcGeometry = GeometryUtils.geometryFromEsriShape(geomrefs[i]); // if (i==0){ // get from ogcGeometry rather than re-create above? // spatialRef = hiveGeometry.spatialReference; // } if (ogcGeometry == null){ LogUtils.Log_ArgumentsNull(LOG); return null; } geomsToUnion[i] = ogcGeometry.getEsriGeometry(); } try { Geometry unioned = GeometryEngine.union(geomsToUnion, spatialRef); // we have to infer the type of the differenced geometry because we don't know // if it's going to end up as a single or multi-part geometry
// Path: hive/src/main/java/com/esri/hadoop/hive/GeometryUtils.java // public enum OGCType { // UNKNOWN(0), // ST_POINT(1), // ST_LINESTRING(2), // ST_POLYGON(3), // ST_MULTIPOINT(4), // ST_MULTILINESTRING(5), // ST_MULTIPOLYGON(6); // // private final int index; // // OGCType(int index){ // this.index = index; // } // // public int getIndex(){ // return this.index; // } // } // Path: hive/src/main/java/com/esri/hadoop/hive/ST_Union.java import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.hive.ql.exec.Description; import org.apache.hadoop.io.BytesWritable; import com.esri.core.geometry.Geometry; import com.esri.core.geometry.GeometryEngine; import com.esri.core.geometry.SpatialReference; import com.esri.hadoop.hive.GeometryUtils.OGCType; import com.esri.core.geometry.ogc.OGCGeometry; } else if (firstWKID != GeometryUtils.getWKID(geomref)){ LogUtils.Log_SRIDMismatch(LOG, geomrefs[0], geomref); return null; } } // now build geometry array to pass to GeometryEngine.union Geometry [] geomsToUnion = new Geometry[geomrefs.length]; for (int i=0;i<geomrefs.length;i++){ //HiveGeometry hiveGeometry = GeometryUtils.geometryFromEsriShape(geomrefs[i]); OGCGeometry ogcGeometry = GeometryUtils.geometryFromEsriShape(geomrefs[i]); // if (i==0){ // get from ogcGeometry rather than re-create above? // spatialRef = hiveGeometry.spatialReference; // } if (ogcGeometry == null){ LogUtils.Log_ArgumentsNull(LOG); return null; } geomsToUnion[i] = ogcGeometry.getEsriGeometry(); } try { Geometry unioned = GeometryEngine.union(geomsToUnion, spatialRef); // we have to infer the type of the differenced geometry because we don't know // if it's going to end up as a single or multi-part geometry
OGCType inferredType = GeometryUtils.getInferredOGCType(unioned);
Esri/spatial-framework-for-hadoop
hive/src/main/java/com/esri/hadoop/hive/ST_BinEnvelope.java
// Path: hive/src/main/java/com/esri/hadoop/hive/GeometryUtils.java // public enum OGCType { // UNKNOWN(0), // ST_POINT(1), // ST_LINESTRING(2), // ST_POLYGON(3), // ST_MULTIPOINT(4), // ST_MULTILINESTRING(5), // ST_MULTIPOLYGON(6); // // private final int index; // // OGCType(int index){ // this.index = index; // } // // public int getIndex(){ // return this.index; // } // }
import java.util.EnumSet; import org.apache.hadoop.hive.ql.exec.Description; import org.apache.hadoop.hive.ql.exec.UDFArgumentException; import org.apache.hadoop.hive.ql.metadata.HiveException; import org.apache.hadoop.hive.ql.udf.generic.GenericUDF; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector.Category; import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector.PrimitiveCategory; import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorUtils; import com.esri.core.geometry.Envelope; import com.esri.core.geometry.ogc.OGCPoint; import com.esri.hadoop.hive.GeometryUtils.OGCType;
public Object evaluate(DeferredObject[] args) throws HiveException { double binSize = PrimitiveObjectInspectorUtils.getDouble(args[0].get(), oiBinSize); if (!binSizeIsConstant || bins == null) { bins = new BinUtils(binSize); } Envelope env = new Envelope(); if (oiBinId != null) { // argument 1 is a number, attempt to get the envelope with bin ID if (args[1].get() == null) { // null bin ID argument usually means the source point was null or failed to parse return null; } long binId = PrimitiveObjectInspectorUtils.getLong(args[1].get(), oiBinId); bins.queryEnvelope(binId, env); } else { // argument 1 is a geometry, attempt to get the envelope with a point OGCPoint point = binPoint.getPoint(args); if (point == null) { return null; } bins.queryEnvelope(point.X(), point.Y(), env); }
// Path: hive/src/main/java/com/esri/hadoop/hive/GeometryUtils.java // public enum OGCType { // UNKNOWN(0), // ST_POINT(1), // ST_LINESTRING(2), // ST_POLYGON(3), // ST_MULTIPOINT(4), // ST_MULTILINESTRING(5), // ST_MULTIPOLYGON(6); // // private final int index; // // OGCType(int index){ // this.index = index; // } // // public int getIndex(){ // return this.index; // } // } // Path: hive/src/main/java/com/esri/hadoop/hive/ST_BinEnvelope.java import java.util.EnumSet; import org.apache.hadoop.hive.ql.exec.Description; import org.apache.hadoop.hive.ql.exec.UDFArgumentException; import org.apache.hadoop.hive.ql.metadata.HiveException; import org.apache.hadoop.hive.ql.udf.generic.GenericUDF; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector.Category; import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector.PrimitiveCategory; import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorUtils; import com.esri.core.geometry.Envelope; import com.esri.core.geometry.ogc.OGCPoint; import com.esri.hadoop.hive.GeometryUtils.OGCType; public Object evaluate(DeferredObject[] args) throws HiveException { double binSize = PrimitiveObjectInspectorUtils.getDouble(args[0].get(), oiBinSize); if (!binSizeIsConstant || bins == null) { bins = new BinUtils(binSize); } Envelope env = new Envelope(); if (oiBinId != null) { // argument 1 is a number, attempt to get the envelope with bin ID if (args[1].get() == null) { // null bin ID argument usually means the source point was null or failed to parse return null; } long binId = PrimitiveObjectInspectorUtils.getLong(args[1].get(), oiBinId); bins.queryEnvelope(binId, env); } else { // argument 1 is a geometry, attempt to get the envelope with a point OGCPoint point = binPoint.getPoint(args); if (point == null) { return null; } bins.queryEnvelope(point.X(), point.Y(), env); }
return GeometryUtils.geometryToEsriShapeBytesWritable(env, 0, OGCType.ST_POLYGON);
Esri/spatial-framework-for-hadoop
hive/src/main/java/com/esri/hadoop/hive/LogUtils.java
// Path: hive/src/main/java/com/esri/hadoop/hive/GeometryUtils.java // public enum OGCType { // UNKNOWN(0), // ST_POINT(1), // ST_LINESTRING(2), // ST_POLYGON(3), // ST_MULTIPOINT(4), // ST_MULTILINESTRING(5), // ST_MULTIPOLYGON(6); // // private final int index; // // OGCType(int index){ // this.index = index; // } // // public int getIndex(){ // return this.index; // } // }
import org.apache.commons.logging.Log; import org.apache.hadoop.io.BytesWritable; import com.esri.hadoop.hive.GeometryUtils.OGCType;
/** * Log when comparing geometries in different spatial references * * @param logger * @param geomref1 * @param geomref2 */ public static void Log_SRIDMismatch(Log logger, BytesWritable geomref1, BytesWritable geomref2){ logger.error(String.format(messages[MSG_SRID_MISMATCH], GeometryUtils.getWKID(geomref1), GeometryUtils.getWKID(geomref2))); } public static void Log_SRIDMismatch(Log logger, BytesWritable geomref1, int wkid2){ logger.error(String.format(messages[MSG_SRID_MISMATCH], GeometryUtils.getWKID(geomref1), wkid2)); } /** * Log when arguments passed to evaluate are null * @param logger */ public static void Log_ArgumentsNull(Log logger){ logger.error(messages[MSG_ARGUMENTS_NULL]); } public static void Log_VariableArgumentLengthXY(Log logger){ logger.error(messages[MSG_ARGUMENT_LENGTH_XY]); } public static void Log_VariableArgumentLengthXY(Log logger, int array_argument_index){ logger.error(String.format(messages[MSG_MULTI_ARGUMENT_LENGTH_XY], array_argument_index)); }
// Path: hive/src/main/java/com/esri/hadoop/hive/GeometryUtils.java // public enum OGCType { // UNKNOWN(0), // ST_POINT(1), // ST_LINESTRING(2), // ST_POLYGON(3), // ST_MULTIPOINT(4), // ST_MULTILINESTRING(5), // ST_MULTIPOLYGON(6); // // private final int index; // // OGCType(int index){ // this.index = index; // } // // public int getIndex(){ // return this.index; // } // } // Path: hive/src/main/java/com/esri/hadoop/hive/LogUtils.java import org.apache.commons.logging.Log; import org.apache.hadoop.io.BytesWritable; import com.esri.hadoop.hive.GeometryUtils.OGCType; /** * Log when comparing geometries in different spatial references * * @param logger * @param geomref1 * @param geomref2 */ public static void Log_SRIDMismatch(Log logger, BytesWritable geomref1, BytesWritable geomref2){ logger.error(String.format(messages[MSG_SRID_MISMATCH], GeometryUtils.getWKID(geomref1), GeometryUtils.getWKID(geomref2))); } public static void Log_SRIDMismatch(Log logger, BytesWritable geomref1, int wkid2){ logger.error(String.format(messages[MSG_SRID_MISMATCH], GeometryUtils.getWKID(geomref1), wkid2)); } /** * Log when arguments passed to evaluate are null * @param logger */ public static void Log_ArgumentsNull(Log logger){ logger.error(messages[MSG_ARGUMENTS_NULL]); } public static void Log_VariableArgumentLengthXY(Log logger){ logger.error(messages[MSG_ARGUMENT_LENGTH_XY]); } public static void Log_VariableArgumentLengthXY(Log logger, int array_argument_index){ logger.error(String.format(messages[MSG_MULTI_ARGUMENT_LENGTH_XY], array_argument_index)); }
public static void Log_InvalidType(Log logger, OGCType expecting, OGCType actual){
difi/datahotel
src/test/java/no/difi/datahotel/util/formater/JSONPFormaterTest.java
// Path: src/test/java/no/difi/datahotel/BaseTest.java // public class BaseTest { // // @BeforeClass // public static void beforeClass() throws Exception { // System.setProperty("datahotel.home", new File(ChunkBeanTest.class.getResource("/").toURI()).toString() + File.separator + "datahotel"); // } // } // // Path: src/main/java/no/difi/datahotel/util/RequestContext.java // public class RequestContext { // // private int page = 1; // private String query = null; // private Map<String, String> lookup = new HashMap<String, String>(); // private String callback; // // public RequestContext() { // // } // // public RequestContext(UriInfo uriInfo) { // this(uriInfo, null); // } // // public RequestContext(UriInfo uriInfo, List<FieldLight> fields) { // MultivaluedMap<String, String> parameters = uriInfo.getQueryParameters(); // // if (fields != null) // for (FieldLight f : fields) // if (f.getGroupable()) // if (parameters.containsKey(f.getShortName())) // if (!"".equals(parameters.getFirst(f.getShortName()))) // lookup.put(f.getShortName(), parameters.getFirst(f.getShortName())); // // if (parameters.containsKey("query")) // if (!"".equals(parameters.getFirst("query"))) // query = parameters.getFirst("query"); // // if (parameters.containsKey("callback")) // if (!"".equals(parameters.getFirst("callback"))) // callback = parameters.getFirst("callback"); // // if (parameters.containsKey("page")) // if (!"".equals(parameters.getFirst("page"))) // page = Integer.parseInt(parameters.getFirst("page")); // } // // public int getPage() { // return page; // } // // public String getQuery() { // return query; // } // // public Map<String, String> getLookup() { // return lookup; // } // // public String getCallback() { // return callback; // } // // @Deprecated // public void setCallback(String callback) { // this.callback = callback; // } // // public boolean isSearch() { // return query != null || lookup.size() > 0; // } // } // // Path: src/main/java/no/difi/datahotel/util/formater/JSONPFormater.java // public class JSONPFormater extends JSONFormater { // // @Override // public String format(Object object, RequestContext context) { // String callback = context.getCallback() == null ? "callback" : context.getCallback(); // return String.valueOf(callback) + "(" + super.format(object, context) + ");"; // } // }
import static org.junit.Assert.*; import org.junit.Test; import no.difi.datahotel.BaseTest; import no.difi.datahotel.util.RequestContext; import no.difi.datahotel.util.formater.JSONPFormater;
package no.difi.datahotel.util.formater; public class JSONPFormaterTest extends BaseTest { @Test public void testing() {
// Path: src/test/java/no/difi/datahotel/BaseTest.java // public class BaseTest { // // @BeforeClass // public static void beforeClass() throws Exception { // System.setProperty("datahotel.home", new File(ChunkBeanTest.class.getResource("/").toURI()).toString() + File.separator + "datahotel"); // } // } // // Path: src/main/java/no/difi/datahotel/util/RequestContext.java // public class RequestContext { // // private int page = 1; // private String query = null; // private Map<String, String> lookup = new HashMap<String, String>(); // private String callback; // // public RequestContext() { // // } // // public RequestContext(UriInfo uriInfo) { // this(uriInfo, null); // } // // public RequestContext(UriInfo uriInfo, List<FieldLight> fields) { // MultivaluedMap<String, String> parameters = uriInfo.getQueryParameters(); // // if (fields != null) // for (FieldLight f : fields) // if (f.getGroupable()) // if (parameters.containsKey(f.getShortName())) // if (!"".equals(parameters.getFirst(f.getShortName()))) // lookup.put(f.getShortName(), parameters.getFirst(f.getShortName())); // // if (parameters.containsKey("query")) // if (!"".equals(parameters.getFirst("query"))) // query = parameters.getFirst("query"); // // if (parameters.containsKey("callback")) // if (!"".equals(parameters.getFirst("callback"))) // callback = parameters.getFirst("callback"); // // if (parameters.containsKey("page")) // if (!"".equals(parameters.getFirst("page"))) // page = Integer.parseInt(parameters.getFirst("page")); // } // // public int getPage() { // return page; // } // // public String getQuery() { // return query; // } // // public Map<String, String> getLookup() { // return lookup; // } // // public String getCallback() { // return callback; // } // // @Deprecated // public void setCallback(String callback) { // this.callback = callback; // } // // public boolean isSearch() { // return query != null || lookup.size() > 0; // } // } // // Path: src/main/java/no/difi/datahotel/util/formater/JSONPFormater.java // public class JSONPFormater extends JSONFormater { // // @Override // public String format(Object object, RequestContext context) { // String callback = context.getCallback() == null ? "callback" : context.getCallback(); // return String.valueOf(callback) + "(" + super.format(object, context) + ");"; // } // } // Path: src/test/java/no/difi/datahotel/util/formater/JSONPFormaterTest.java import static org.junit.Assert.*; import org.junit.Test; import no.difi.datahotel.BaseTest; import no.difi.datahotel.util.RequestContext; import no.difi.datahotel.util.formater.JSONPFormater; package no.difi.datahotel.util.formater; public class JSONPFormaterTest extends BaseTest { @Test public void testing() {
RequestContext context = new RequestContext();
difi/datahotel
src/test/java/no/difi/datahotel/util/formater/JSONPFormaterTest.java
// Path: src/test/java/no/difi/datahotel/BaseTest.java // public class BaseTest { // // @BeforeClass // public static void beforeClass() throws Exception { // System.setProperty("datahotel.home", new File(ChunkBeanTest.class.getResource("/").toURI()).toString() + File.separator + "datahotel"); // } // } // // Path: src/main/java/no/difi/datahotel/util/RequestContext.java // public class RequestContext { // // private int page = 1; // private String query = null; // private Map<String, String> lookup = new HashMap<String, String>(); // private String callback; // // public RequestContext() { // // } // // public RequestContext(UriInfo uriInfo) { // this(uriInfo, null); // } // // public RequestContext(UriInfo uriInfo, List<FieldLight> fields) { // MultivaluedMap<String, String> parameters = uriInfo.getQueryParameters(); // // if (fields != null) // for (FieldLight f : fields) // if (f.getGroupable()) // if (parameters.containsKey(f.getShortName())) // if (!"".equals(parameters.getFirst(f.getShortName()))) // lookup.put(f.getShortName(), parameters.getFirst(f.getShortName())); // // if (parameters.containsKey("query")) // if (!"".equals(parameters.getFirst("query"))) // query = parameters.getFirst("query"); // // if (parameters.containsKey("callback")) // if (!"".equals(parameters.getFirst("callback"))) // callback = parameters.getFirst("callback"); // // if (parameters.containsKey("page")) // if (!"".equals(parameters.getFirst("page"))) // page = Integer.parseInt(parameters.getFirst("page")); // } // // public int getPage() { // return page; // } // // public String getQuery() { // return query; // } // // public Map<String, String> getLookup() { // return lookup; // } // // public String getCallback() { // return callback; // } // // @Deprecated // public void setCallback(String callback) { // this.callback = callback; // } // // public boolean isSearch() { // return query != null || lookup.size() > 0; // } // } // // Path: src/main/java/no/difi/datahotel/util/formater/JSONPFormater.java // public class JSONPFormater extends JSONFormater { // // @Override // public String format(Object object, RequestContext context) { // String callback = context.getCallback() == null ? "callback" : context.getCallback(); // return String.valueOf(callback) + "(" + super.format(object, context) + ");"; // } // }
import static org.junit.Assert.*; import org.junit.Test; import no.difi.datahotel.BaseTest; import no.difi.datahotel.util.RequestContext; import no.difi.datahotel.util.formater.JSONPFormater;
package no.difi.datahotel.util.formater; public class JSONPFormaterTest extends BaseTest { @Test public void testing() { RequestContext context = new RequestContext();
// Path: src/test/java/no/difi/datahotel/BaseTest.java // public class BaseTest { // // @BeforeClass // public static void beforeClass() throws Exception { // System.setProperty("datahotel.home", new File(ChunkBeanTest.class.getResource("/").toURI()).toString() + File.separator + "datahotel"); // } // } // // Path: src/main/java/no/difi/datahotel/util/RequestContext.java // public class RequestContext { // // private int page = 1; // private String query = null; // private Map<String, String> lookup = new HashMap<String, String>(); // private String callback; // // public RequestContext() { // // } // // public RequestContext(UriInfo uriInfo) { // this(uriInfo, null); // } // // public RequestContext(UriInfo uriInfo, List<FieldLight> fields) { // MultivaluedMap<String, String> parameters = uriInfo.getQueryParameters(); // // if (fields != null) // for (FieldLight f : fields) // if (f.getGroupable()) // if (parameters.containsKey(f.getShortName())) // if (!"".equals(parameters.getFirst(f.getShortName()))) // lookup.put(f.getShortName(), parameters.getFirst(f.getShortName())); // // if (parameters.containsKey("query")) // if (!"".equals(parameters.getFirst("query"))) // query = parameters.getFirst("query"); // // if (parameters.containsKey("callback")) // if (!"".equals(parameters.getFirst("callback"))) // callback = parameters.getFirst("callback"); // // if (parameters.containsKey("page")) // if (!"".equals(parameters.getFirst("page"))) // page = Integer.parseInt(parameters.getFirst("page")); // } // // public int getPage() { // return page; // } // // public String getQuery() { // return query; // } // // public Map<String, String> getLookup() { // return lookup; // } // // public String getCallback() { // return callback; // } // // @Deprecated // public void setCallback(String callback) { // this.callback = callback; // } // // public boolean isSearch() { // return query != null || lookup.size() > 0; // } // } // // Path: src/main/java/no/difi/datahotel/util/formater/JSONPFormater.java // public class JSONPFormater extends JSONFormater { // // @Override // public String format(Object object, RequestContext context) { // String callback = context.getCallback() == null ? "callback" : context.getCallback(); // return String.valueOf(callback) + "(" + super.format(object, context) + ");"; // } // } // Path: src/test/java/no/difi/datahotel/util/formater/JSONPFormaterTest.java import static org.junit.Assert.*; import org.junit.Test; import no.difi.datahotel.BaseTest; import no.difi.datahotel.util.RequestContext; import no.difi.datahotel.util.formater.JSONPFormater; package no.difi.datahotel.util.formater; public class JSONPFormaterTest extends BaseTest { @Test public void testing() { RequestContext context = new RequestContext();
JSONPFormater formater = new JSONPFormater();