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
dkpro/dkpro-c4corpus
dkpro-c4corpus-hadoop/src/test/java/de/tudarmstadt/ukp/dkpro/c4corpus/hadoop/utils/URIExtractorTest.java
// Path: dkpro-c4corpus-hadoop/src/main/java/de/tudarmstadt/ukp/dkpro/c4corpus/hadoop/io/WARCWritable.java // public class WARCWritable // implements Writable // { // // private WARCRecord record; // // /** // * Creates an empty writable (with a null record). // */ // public WARCWritable() // { // this.record = null; // } // // /** // * Creates a writable wrapper around a given WARCRecord. // * // * @param record existing record // */ // public WARCWritable(WARCRecord record) // { // this.record = record; // } // // /** // * Returns the record currently wrapped by this writable. // * // * @return current record // */ // public WARCRecord getRecord() // { // return record; // } // // /** // * Updates the record held within this writable wrapper. // * // * @param record the record to be set // */ // public void setRecord(WARCRecord record) // { // this.record = record; // } // // /** // * Appends the current record to a {@link DataOutput} stream. // */ // @Override // public void write(DataOutput out) // throws IOException // { // if (record != null) { // record.write(out); // } // } // // /** // * Parses a {@link WARCRecord} out of a {@link DataInput} stream, and makes it the // * writable's current record. // * // * @throws IOException if the input is malformed // */ // @Override // public void readFields(DataInput in) // throws IOException // { // record = new WARCRecord(in); // } // }
import de.tudarmstadt.ukp.dkpro.c4corpus.hadoop.io.WARCWritable; import de.tudarmstadt.ukp.dkpro.c4corpus.warc.io.WARCRecord; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Text; import org.easymock.EasyMock; import org.junit.Test; import java.io.IOException;
/* * Copyright 2016 * Ubiquitous Knowledge Processing (UKP) Lab * Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.tudarmstadt.ukp.dkpro.c4corpus.hadoop.utils; /** * @author Ivan Habernal */ public class URIExtractorTest { @Test public void testMapper() throws IOException, InterruptedException { final String expectedURI = "https://www.ukp.tu-darmstadt.de/ukp-home/";
// Path: dkpro-c4corpus-hadoop/src/main/java/de/tudarmstadt/ukp/dkpro/c4corpus/hadoop/io/WARCWritable.java // public class WARCWritable // implements Writable // { // // private WARCRecord record; // // /** // * Creates an empty writable (with a null record). // */ // public WARCWritable() // { // this.record = null; // } // // /** // * Creates a writable wrapper around a given WARCRecord. // * // * @param record existing record // */ // public WARCWritable(WARCRecord record) // { // this.record = record; // } // // /** // * Returns the record currently wrapped by this writable. // * // * @return current record // */ // public WARCRecord getRecord() // { // return record; // } // // /** // * Updates the record held within this writable wrapper. // * // * @param record the record to be set // */ // public void setRecord(WARCRecord record) // { // this.record = record; // } // // /** // * Appends the current record to a {@link DataOutput} stream. // */ // @Override // public void write(DataOutput out) // throws IOException // { // if (record != null) { // record.write(out); // } // } // // /** // * Parses a {@link WARCRecord} out of a {@link DataInput} stream, and makes it the // * writable's current record. // * // * @throws IOException if the input is malformed // */ // @Override // public void readFields(DataInput in) // throws IOException // { // record = new WARCRecord(in); // } // } // Path: dkpro-c4corpus-hadoop/src/test/java/de/tudarmstadt/ukp/dkpro/c4corpus/hadoop/utils/URIExtractorTest.java import de.tudarmstadt.ukp.dkpro.c4corpus.hadoop.io.WARCWritable; import de.tudarmstadt.ukp.dkpro.c4corpus.warc.io.WARCRecord; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Text; import org.easymock.EasyMock; import org.junit.Test; import java.io.IOException; /* * Copyright 2016 * Ubiquitous Knowledge Processing (UKP) Lab * Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.tudarmstadt.ukp.dkpro.c4corpus.hadoop.utils; /** * @author Ivan Habernal */ public class URIExtractorTest { @Test public void testMapper() throws IOException, InterruptedException { final String expectedURI = "https://www.ukp.tu-darmstadt.de/ukp-home/";
final WARCWritable warc = EasyMock.mock(WARCWritable.class);
dkpro/dkpro-c4corpus
dkpro-c4corpus-hadoop/src/main/java/de/tudarmstadt/ukp/dkpro/c4corpus/hadoop/full/Phase5MergeByLangLicJob.java
// Path: dkpro-c4corpus-hadoop/src/main/java/de/tudarmstadt/ukp/dkpro/c4corpus/hadoop/io/WARCWritable.java // public class WARCWritable // implements Writable // { // // private WARCRecord record; // // /** // * Creates an empty writable (with a null record). // */ // public WARCWritable() // { // this.record = null; // } // // /** // * Creates a writable wrapper around a given WARCRecord. // * // * @param record existing record // */ // public WARCWritable(WARCRecord record) // { // this.record = record; // } // // /** // * Returns the record currently wrapped by this writable. // * // * @return current record // */ // public WARCRecord getRecord() // { // return record; // } // // /** // * Updates the record held within this writable wrapper. // * // * @param record the record to be set // */ // public void setRecord(WARCRecord record) // { // this.record = record; // } // // /** // * Appends the current record to a {@link DataOutput} stream. // */ // @Override // public void write(DataOutput out) // throws IOException // { // if (record != null) { // record.write(out); // } // } // // /** // * Parses a {@link WARCRecord} out of a {@link DataInput} stream, and makes it the // * writable's current record. // * // * @throws IOException if the input is malformed // */ // @Override // public void readFields(DataInput in) // throws IOException // { // record = new WARCRecord(in); // } // }
import org.apache.hadoop.util.ToolRunner; import java.io.IOException; import de.tudarmstadt.ukp.dkpro.c4corpus.hadoop.ConfigurationHelper; import de.tudarmstadt.ukp.dkpro.c4corpus.hadoop.io.WARCWritable; import de.tudarmstadt.ukp.dkpro.c4corpus.warc.io.WARCRecord; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.output.MultipleOutputs; import org.apache.hadoop.util.Tool;
/* * Copyright 2016 * Ubiquitous Knowledge Processing (UKP) Lab * Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.tudarmstadt.ukp.dkpro.c4corpus.hadoop.full; /** * Reads all input warc.gz files and writes them into separated files based on language and * license * * @author Ivan Habernal */ public class Phase5MergeByLangLicJob extends Configured implements Tool { @Override public int run(String[] args) throws Exception { Job job = Job.getInstance(getConf()); // set from the command line ConfigurationHelper.configureJob(job, Phase5MergeByLangLicJob.class, SimpleMapper.class, WARCWriterReducerPhase5.class, args[0], args[1]); return job.waitForCompletion(true) ? 0 : 1; } public static void main(String[] args) throws Exception { ToolRunner.run(new Phase5MergeByLangLicJob(), args); } public static class SimpleMapper
// Path: dkpro-c4corpus-hadoop/src/main/java/de/tudarmstadt/ukp/dkpro/c4corpus/hadoop/io/WARCWritable.java // public class WARCWritable // implements Writable // { // // private WARCRecord record; // // /** // * Creates an empty writable (with a null record). // */ // public WARCWritable() // { // this.record = null; // } // // /** // * Creates a writable wrapper around a given WARCRecord. // * // * @param record existing record // */ // public WARCWritable(WARCRecord record) // { // this.record = record; // } // // /** // * Returns the record currently wrapped by this writable. // * // * @return current record // */ // public WARCRecord getRecord() // { // return record; // } // // /** // * Updates the record held within this writable wrapper. // * // * @param record the record to be set // */ // public void setRecord(WARCRecord record) // { // this.record = record; // } // // /** // * Appends the current record to a {@link DataOutput} stream. // */ // @Override // public void write(DataOutput out) // throws IOException // { // if (record != null) { // record.write(out); // } // } // // /** // * Parses a {@link WARCRecord} out of a {@link DataInput} stream, and makes it the // * writable's current record. // * // * @throws IOException if the input is malformed // */ // @Override // public void readFields(DataInput in) // throws IOException // { // record = new WARCRecord(in); // } // } // Path: dkpro-c4corpus-hadoop/src/main/java/de/tudarmstadt/ukp/dkpro/c4corpus/hadoop/full/Phase5MergeByLangLicJob.java import org.apache.hadoop.util.ToolRunner; import java.io.IOException; import de.tudarmstadt.ukp.dkpro.c4corpus.hadoop.ConfigurationHelper; import de.tudarmstadt.ukp.dkpro.c4corpus.hadoop.io.WARCWritable; import de.tudarmstadt.ukp.dkpro.c4corpus.warc.io.WARCRecord; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.output.MultipleOutputs; import org.apache.hadoop.util.Tool; /* * Copyright 2016 * Ubiquitous Knowledge Processing (UKP) Lab * Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.tudarmstadt.ukp.dkpro.c4corpus.hadoop.full; /** * Reads all input warc.gz files and writes them into separated files based on language and * license * * @author Ivan Habernal */ public class Phase5MergeByLangLicJob extends Configured implements Tool { @Override public int run(String[] args) throws Exception { Job job = Job.getInstance(getConf()); // set from the command line ConfigurationHelper.configureJob(job, Phase5MergeByLangLicJob.class, SimpleMapper.class, WARCWriterReducerPhase5.class, args[0], args[1]); return job.waitForCompletion(true) ? 0 : 1; } public static void main(String[] args) throws Exception { ToolRunner.run(new Phase5MergeByLangLicJob(), args); } public static class SimpleMapper
extends Mapper<LongWritable, WARCWritable, Text, WARCWritable>
marcandreuf/sunfounder-sensors-raspi-4j
src/main/java/org/mandfer/sunfunpi4j/Ex28_MercurySwitch.java
// Path: src/main/java/org/mandfer/sunfunpi4j/BaseSketch.java // protected static final Logger logger = LoggerFactory.getLogger("Sketch"); // // Path: src/main/java/org/mandfer/sunfunpi4j/BaseSketch.java // protected static void wiringPiSetup(){ // if (Gpio.wiringPiSetup() == -1) { // String msg = "==>> GPIO SETUP FAILED"; // logger.debug(msg); // throw new RuntimeException(msg); // } // }
import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalInput; import com.pi4j.io.gpio.PinPullResistance; import com.pi4j.io.gpio.RaspiPin; import com.pi4j.io.gpio.event.GpioPinDigitalStateChangeEvent; import com.pi4j.io.gpio.event.GpioPinListenerDigital; import static org.mandfer.sunfunpi4j.BaseSketch.logger; import static org.mandfer.sunfunpi4j.BaseSketch.wiringPiSetup;
/** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ public class Ex28_MercurySwitch extends BaseSketch { private GpioPinDigitalInput mercuryPin; /** * @param gpio controller */ public Ex28_MercurySwitch(GpioController gpio){ super(gpio); } public static void main(String[] args) throws InterruptedException { Ex28_MercurySwitch sketch = new Ex28_MercurySwitch(GpioFactory.getInstance()); sketch.run(args); } @Override protected void setup(String[] args) {
// Path: src/main/java/org/mandfer/sunfunpi4j/BaseSketch.java // protected static final Logger logger = LoggerFactory.getLogger("Sketch"); // // Path: src/main/java/org/mandfer/sunfunpi4j/BaseSketch.java // protected static void wiringPiSetup(){ // if (Gpio.wiringPiSetup() == -1) { // String msg = "==>> GPIO SETUP FAILED"; // logger.debug(msg); // throw new RuntimeException(msg); // } // } // Path: src/main/java/org/mandfer/sunfunpi4j/Ex28_MercurySwitch.java import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalInput; import com.pi4j.io.gpio.PinPullResistance; import com.pi4j.io.gpio.RaspiPin; import com.pi4j.io.gpio.event.GpioPinDigitalStateChangeEvent; import com.pi4j.io.gpio.event.GpioPinListenerDigital; import static org.mandfer.sunfunpi4j.BaseSketch.logger; import static org.mandfer.sunfunpi4j.BaseSketch.wiringPiSetup; /** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ public class Ex28_MercurySwitch extends BaseSketch { private GpioPinDigitalInput mercuryPin; /** * @param gpio controller */ public Ex28_MercurySwitch(GpioController gpio){ super(gpio); } public static void main(String[] args) throws InterruptedException { Ex28_MercurySwitch sketch = new Ex28_MercurySwitch(GpioFactory.getInstance()); sketch.run(args); } @Override protected void setup(String[] args) {
wiringPiSetup();
marcandreuf/sunfounder-sensors-raspi-4j
src/main/java/org/mandfer/sunfunpi4j/Ex28_MercurySwitch.java
// Path: src/main/java/org/mandfer/sunfunpi4j/BaseSketch.java // protected static final Logger logger = LoggerFactory.getLogger("Sketch"); // // Path: src/main/java/org/mandfer/sunfunpi4j/BaseSketch.java // protected static void wiringPiSetup(){ // if (Gpio.wiringPiSetup() == -1) { // String msg = "==>> GPIO SETUP FAILED"; // logger.debug(msg); // throw new RuntimeException(msg); // } // }
import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalInput; import com.pi4j.io.gpio.PinPullResistance; import com.pi4j.io.gpio.RaspiPin; import com.pi4j.io.gpio.event.GpioPinDigitalStateChangeEvent; import com.pi4j.io.gpio.event.GpioPinListenerDigital; import static org.mandfer.sunfunpi4j.BaseSketch.logger; import static org.mandfer.sunfunpi4j.BaseSketch.wiringPiSetup;
/** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ public class Ex28_MercurySwitch extends BaseSketch { private GpioPinDigitalInput mercuryPin; /** * @param gpio controller */ public Ex28_MercurySwitch(GpioController gpio){ super(gpio); } public static void main(String[] args) throws InterruptedException { Ex28_MercurySwitch sketch = new Ex28_MercurySwitch(GpioFactory.getInstance()); sketch.run(args); } @Override protected void setup(String[] args) { wiringPiSetup(); mercuryPin = gpio.provisionDigitalInputPin(RaspiPin.GPIO_00, PinPullResistance.PULL_DOWN); mercuryPin.addListener(new GpioPinListenerDigital() { @Override public void handleGpioPinDigitalStateChangeEvent(GpioPinDigitalStateChangeEvent event) { if(event.getState().isLow()){
// Path: src/main/java/org/mandfer/sunfunpi4j/BaseSketch.java // protected static final Logger logger = LoggerFactory.getLogger("Sketch"); // // Path: src/main/java/org/mandfer/sunfunpi4j/BaseSketch.java // protected static void wiringPiSetup(){ // if (Gpio.wiringPiSetup() == -1) { // String msg = "==>> GPIO SETUP FAILED"; // logger.debug(msg); // throw new RuntimeException(msg); // } // } // Path: src/main/java/org/mandfer/sunfunpi4j/Ex28_MercurySwitch.java import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalInput; import com.pi4j.io.gpio.PinPullResistance; import com.pi4j.io.gpio.RaspiPin; import com.pi4j.io.gpio.event.GpioPinDigitalStateChangeEvent; import com.pi4j.io.gpio.event.GpioPinListenerDigital; import static org.mandfer.sunfunpi4j.BaseSketch.logger; import static org.mandfer.sunfunpi4j.BaseSketch.wiringPiSetup; /** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ public class Ex28_MercurySwitch extends BaseSketch { private GpioPinDigitalInput mercuryPin; /** * @param gpio controller */ public Ex28_MercurySwitch(GpioController gpio){ super(gpio); } public static void main(String[] args) throws InterruptedException { Ex28_MercurySwitch sketch = new Ex28_MercurySwitch(GpioFactory.getInstance()); sketch.run(args); } @Override protected void setup(String[] args) { wiringPiSetup(); mercuryPin = gpio.provisionDigitalInputPin(RaspiPin.GPIO_00, PinPullResistance.PULL_DOWN); mercuryPin.addListener(new GpioPinListenerDigital() { @Override public void handleGpioPinDigitalStateChangeEvent(GpioPinDigitalStateChangeEvent event) { if(event.getState().isLow()){
logger.debug("Led on !");
marcandreuf/sunfounder-sensors-raspi-4j
src/test/java/org/mandfer/sunfunpi4j/Ex06_ShockSwitchTest.java
// Path: src/test/java/org/mandfer/categories/FastTest.java // public interface FastTest {} // // Path: src/test/java/org/mandfer/categories/SlowTest.java // public interface SlowTest {}
import org.mandfer.categories.SlowTest; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.pi4j.io.gpio.GpioPinDigitalInput; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.RaspiPin; import com.pi4j.wiringpi.Gpio; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.mandfer.categories.FastTest;
/** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ @RunWith(PowerMockRunner.class) @PrepareForTest(Gpio.class) public class Ex06_ShockSwitchTest extends BaseSketchTest{ private GpioPinDigitalInput mocked_shockPin; private GpioPinDigitalOutput mocked_ledPin; private Ex06_ShockSwitch sketch; @Before public void setUp(){ PowerMockito.mockStatic(Gpio.class); mocked_shockPin = mock(GpioPinDigitalInput.class); mocked_ledPin = mock(GpioPinDigitalOutput.class); sketch = new Ex06_ShockSwitch(mocked_gpioController); } @Test
// Path: src/test/java/org/mandfer/categories/FastTest.java // public interface FastTest {} // // Path: src/test/java/org/mandfer/categories/SlowTest.java // public interface SlowTest {} // Path: src/test/java/org/mandfer/sunfunpi4j/Ex06_ShockSwitchTest.java import org.mandfer.categories.SlowTest; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.pi4j.io.gpio.GpioPinDigitalInput; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.RaspiPin; import com.pi4j.wiringpi.Gpio; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.mandfer.categories.FastTest; /** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ @RunWith(PowerMockRunner.class) @PrepareForTest(Gpio.class) public class Ex06_ShockSwitchTest extends BaseSketchTest{ private GpioPinDigitalInput mocked_shockPin; private GpioPinDigitalOutput mocked_ledPin; private Ex06_ShockSwitch sketch; @Before public void setUp(){ PowerMockito.mockStatic(Gpio.class); mocked_shockPin = mock(GpioPinDigitalInput.class); mocked_ledPin = mock(GpioPinDigitalOutput.class); sketch = new Ex06_ShockSwitch(mocked_gpioController); } @Test
@Category(FastTest.class)
marcandreuf/sunfounder-sensors-raspi-4j
src/test/java/org/mandfer/sunfunpi4j/Ex06_ShockSwitchTest.java
// Path: src/test/java/org/mandfer/categories/FastTest.java // public interface FastTest {} // // Path: src/test/java/org/mandfer/categories/SlowTest.java // public interface SlowTest {}
import org.mandfer.categories.SlowTest; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.pi4j.io.gpio.GpioPinDigitalInput; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.RaspiPin; import com.pi4j.wiringpi.Gpio; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.mandfer.categories.FastTest;
/** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ @RunWith(PowerMockRunner.class) @PrepareForTest(Gpio.class) public class Ex06_ShockSwitchTest extends BaseSketchTest{ private GpioPinDigitalInput mocked_shockPin; private GpioPinDigitalOutput mocked_ledPin; private Ex06_ShockSwitch sketch; @Before public void setUp(){ PowerMockito.mockStatic(Gpio.class); mocked_shockPin = mock(GpioPinDigitalInput.class); mocked_ledPin = mock(GpioPinDigitalOutput.class); sketch = new Ex06_ShockSwitch(mocked_gpioController); } @Test @Category(FastTest.class) public void verifySetup(){ sketch.setup(NO_ARGS); PowerMockito.verifyStatic(); Gpio.wiringPiSetup(); verify(mocked_gpioController).provisionDigitalInputPin(RaspiPin.GPIO_00); verify(mocked_gpioController).provisionDigitalOutputPin(RaspiPin.GPIO_01); verifyNoMoreInteractions(mocked_gpioController); } @Test
// Path: src/test/java/org/mandfer/categories/FastTest.java // public interface FastTest {} // // Path: src/test/java/org/mandfer/categories/SlowTest.java // public interface SlowTest {} // Path: src/test/java/org/mandfer/sunfunpi4j/Ex06_ShockSwitchTest.java import org.mandfer.categories.SlowTest; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.pi4j.io.gpio.GpioPinDigitalInput; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.RaspiPin; import com.pi4j.wiringpi.Gpio; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.mandfer.categories.FastTest; /** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ @RunWith(PowerMockRunner.class) @PrepareForTest(Gpio.class) public class Ex06_ShockSwitchTest extends BaseSketchTest{ private GpioPinDigitalInput mocked_shockPin; private GpioPinDigitalOutput mocked_ledPin; private Ex06_ShockSwitch sketch; @Before public void setUp(){ PowerMockito.mockStatic(Gpio.class); mocked_shockPin = mock(GpioPinDigitalInput.class); mocked_ledPin = mock(GpioPinDigitalOutput.class); sketch = new Ex06_ShockSwitch(mocked_gpioController); } @Test @Category(FastTest.class) public void verifySetup(){ sketch.setup(NO_ARGS); PowerMockito.verifyStatic(); Gpio.wiringPiSetup(); verify(mocked_gpioController).provisionDigitalInputPin(RaspiPin.GPIO_00); verify(mocked_gpioController).provisionDigitalOutputPin(RaspiPin.GPIO_01); verifyNoMoreInteractions(mocked_gpioController); } @Test
@Category(SlowTest.class)
marcandreuf/sunfounder-sensors-raspi-4j
src/main/java/org/mandfer/sunfunpi4j/Ex13_Button.java
// Path: src/main/java/org/mandfer/sunfunpi4j/BaseSketch.java // protected static void wiringPiSetup(){ // if (Gpio.wiringPiSetup() == -1) { // String msg = "==>> GPIO SETUP FAILED"; // logger.debug(msg); // throw new RuntimeException(msg); // } // }
import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalInput; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.RaspiPin; import static org.mandfer.sunfunpi4j.BaseSketch.wiringPiSetup;
/** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ public class Ex13_Button extends BaseSketch { private GpioPinDigitalInput btnPin; private GpioPinDigitalOutput ledPin; /** * @param gpio controller */ public Ex13_Button(GpioController gpio){ super(gpio); } public static void main(String[] args) throws InterruptedException { Ex13_Button sketch = new Ex13_Button(GpioFactory.getInstance()); sketch.run(args); } @Override protected void setup(String[] args) {
// Path: src/main/java/org/mandfer/sunfunpi4j/BaseSketch.java // protected static void wiringPiSetup(){ // if (Gpio.wiringPiSetup() == -1) { // String msg = "==>> GPIO SETUP FAILED"; // logger.debug(msg); // throw new RuntimeException(msg); // } // } // Path: src/main/java/org/mandfer/sunfunpi4j/Ex13_Button.java import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalInput; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.RaspiPin; import static org.mandfer.sunfunpi4j.BaseSketch.wiringPiSetup; /** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ public class Ex13_Button extends BaseSketch { private GpioPinDigitalInput btnPin; private GpioPinDigitalOutput ledPin; /** * @param gpio controller */ public Ex13_Button(GpioController gpio){ super(gpio); } public static void main(String[] args) throws InterruptedException { Ex13_Button sketch = new Ex13_Button(GpioFactory.getInstance()); sketch.run(args); } @Override protected void setup(String[] args) {
wiringPiSetup();
marcandreuf/sunfounder-sensors-raspi-4j
src/main/java/org/mandfer/sunfunpi4j/Ex15_TiltSwitchListener.java
// Path: src/main/java/org/mandfer/sunfunpi4j/BaseSketch.java // protected static void wiringPiSetup(){ // if (Gpio.wiringPiSetup() == -1) { // String msg = "==>> GPIO SETUP FAILED"; // logger.debug(msg); // throw new RuntimeException(msg); // } // }
import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalInput; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.PinPullResistance; import com.pi4j.io.gpio.RaspiPin; import com.pi4j.io.gpio.event.GpioPinDigitalStateChangeEvent; import com.pi4j.io.gpio.event.GpioPinListenerDigital; import static org.mandfer.sunfunpi4j.BaseSketch.wiringPiSetup;
/** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ public class Ex15_TiltSwitchListener extends BaseSketch { private GpioPinDigitalInput tiltSwitch; private GpioPinDigitalOutput ledPin; /** * @param gpio controller */ public Ex15_TiltSwitchListener(GpioController gpio){ super(gpio); } public static void main(String[] args) throws InterruptedException { Ex15_TiltSwitchListener sketch = new Ex15_TiltSwitchListener(GpioFactory.getInstance()); sketch.run(args); } @Override protected void setup(String[] args) {
// Path: src/main/java/org/mandfer/sunfunpi4j/BaseSketch.java // protected static void wiringPiSetup(){ // if (Gpio.wiringPiSetup() == -1) { // String msg = "==>> GPIO SETUP FAILED"; // logger.debug(msg); // throw new RuntimeException(msg); // } // } // Path: src/main/java/org/mandfer/sunfunpi4j/Ex15_TiltSwitchListener.java import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalInput; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.PinPullResistance; import com.pi4j.io.gpio.RaspiPin; import com.pi4j.io.gpio.event.GpioPinDigitalStateChangeEvent; import com.pi4j.io.gpio.event.GpioPinListenerDigital; import static org.mandfer.sunfunpi4j.BaseSketch.wiringPiSetup; /** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ public class Ex15_TiltSwitchListener extends BaseSketch { private GpioPinDigitalInput tiltSwitch; private GpioPinDigitalOutput ledPin; /** * @param gpio controller */ public Ex15_TiltSwitchListener(GpioController gpio){ super(gpio); } public static void main(String[] args) throws InterruptedException { Ex15_TiltSwitchListener sketch = new Ex15_TiltSwitchListener(GpioFactory.getInstance()); sketch.run(args); } @Override protected void setup(String[] args) {
wiringPiSetup();
marcandreuf/sunfounder-sensors-raspi-4j
src/main/java/org/mandfer/sunfunpi4j/Ex10_MagicRing.java
// Path: src/main/java/org/mandfer/sunfunpi4j/BaseSketch.java // protected static void wiringPiSetup(){ // if (Gpio.wiringPiSetup() == -1) { // String msg = "==>> GPIO SETUP FAILED"; // logger.debug(msg); // throw new RuntimeException(msg); // } // }
import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalInput; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.RaspiPin; import static org.mandfer.sunfunpi4j.BaseSketch.wiringPiSetup;
/** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ public class Ex10_MagicRing extends BaseSketch { private GpioPinDigitalInput switchPin; private GpioPinDigitalOutput ledPin; /** * @param gpio controller */ public Ex10_MagicRing(GpioController gpio){ super(gpio); } public static void main(String[] args) throws InterruptedException { Ex10_MagicRing sketch = new Ex10_MagicRing(GpioFactory.getInstance()); sketch.run(args); } @Override protected void setup(String[] args) {
// Path: src/main/java/org/mandfer/sunfunpi4j/BaseSketch.java // protected static void wiringPiSetup(){ // if (Gpio.wiringPiSetup() == -1) { // String msg = "==>> GPIO SETUP FAILED"; // logger.debug(msg); // throw new RuntimeException(msg); // } // } // Path: src/main/java/org/mandfer/sunfunpi4j/Ex10_MagicRing.java import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalInput; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.RaspiPin; import static org.mandfer.sunfunpi4j.BaseSketch.wiringPiSetup; /** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ public class Ex10_MagicRing extends BaseSketch { private GpioPinDigitalInput switchPin; private GpioPinDigitalOutput ledPin; /** * @param gpio controller */ public Ex10_MagicRing(GpioController gpio){ super(gpio); } public static void main(String[] args) throws InterruptedException { Ex10_MagicRing sketch = new Ex10_MagicRing(GpioFactory.getInstance()); sketch.run(args); } @Override protected void setup(String[] args) {
wiringPiSetup();
marcandreuf/sunfounder-sensors-raspi-4j
src/main/java/org/mandfer/sunfunpi4j/Ex14_LightBreakListener.java
// Path: src/main/java/org/mandfer/sunfunpi4j/BaseSketch.java // protected static void wiringPiSetup(){ // if (Gpio.wiringPiSetup() == -1) { // String msg = "==>> GPIO SETUP FAILED"; // logger.debug(msg); // throw new RuntimeException(msg); // } // }
import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalInput; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.PinPullResistance; import com.pi4j.io.gpio.RaspiPin; import com.pi4j.io.gpio.event.GpioPinDigitalStateChangeEvent; import com.pi4j.io.gpio.event.GpioPinListenerDigital; import static org.mandfer.sunfunpi4j.BaseSketch.wiringPiSetup;
/** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ public class Ex14_LightBreakListener extends BaseSketch { private GpioPinDigitalInput lightBreakPin; private GpioPinDigitalOutput ledPin; /** * @param gpio controller */ public Ex14_LightBreakListener(GpioController gpio){ super(gpio); } public static void main(String[] args) throws InterruptedException { Ex14_LightBreakListener sketch = new Ex14_LightBreakListener(GpioFactory.getInstance()); sketch.run(args); } @Override protected void setup(String[] args) {
// Path: src/main/java/org/mandfer/sunfunpi4j/BaseSketch.java // protected static void wiringPiSetup(){ // if (Gpio.wiringPiSetup() == -1) { // String msg = "==>> GPIO SETUP FAILED"; // logger.debug(msg); // throw new RuntimeException(msg); // } // } // Path: src/main/java/org/mandfer/sunfunpi4j/Ex14_LightBreakListener.java import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalInput; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.PinPullResistance; import com.pi4j.io.gpio.RaspiPin; import com.pi4j.io.gpio.event.GpioPinDigitalStateChangeEvent; import com.pi4j.io.gpio.event.GpioPinListenerDigital; import static org.mandfer.sunfunpi4j.BaseSketch.wiringPiSetup; /** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ public class Ex14_LightBreakListener extends BaseSketch { private GpioPinDigitalInput lightBreakPin; private GpioPinDigitalOutput ledPin; /** * @param gpio controller */ public Ex14_LightBreakListener(GpioController gpio){ super(gpio); } public static void main(String[] args) throws InterruptedException { Ex14_LightBreakListener sketch = new Ex14_LightBreakListener(GpioFactory.getInstance()); sketch.run(args); } @Override protected void setup(String[] args) {
wiringPiSetup();
marcandreuf/sunfounder-sensors-raspi-4j
src/main/java/org/mandfer/sunfunpi4j/Ex21_Obstacle01.java
// Path: src/main/java/org/mandfer/sunfunpi4j/BaseSketch.java // protected static final Logger logger = LoggerFactory.getLogger("Sketch");
import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalInput; import com.pi4j.io.gpio.PinPullResistance; import com.pi4j.io.gpio.RaspiPin; import com.pi4j.io.gpio.event.GpioPinDigitalStateChangeEvent; import com.pi4j.io.gpio.event.GpioPinListenerDigital; import static org.mandfer.sunfunpi4j.BaseSketch.logger;
/** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ public class Ex21_Obstacle01 extends BaseSketch { private GpioPinDigitalInput obstaclePin; /** * @param gpio controller */ public Ex21_Obstacle01(GpioController gpio){ super(gpio); } public static void main(String[] args) throws InterruptedException { Ex21_Obstacle01 sketch = new Ex21_Obstacle01(GpioFactory.getInstance()); sketch.run(args); } @Override protected void setup(String[] args) { wiringPiSetup(); obstaclePin = gpio.provisionDigitalInputPin(RaspiPin.GPIO_00, PinPullResistance.PULL_DOWN); obstaclePin.addListener(new GpioPinListenerDigital() { @Override public void handleGpioPinDigitalStateChangeEvent(GpioPinDigitalStateChangeEvent event) { if(event.getState().isHigh()){
// Path: src/main/java/org/mandfer/sunfunpi4j/BaseSketch.java // protected static final Logger logger = LoggerFactory.getLogger("Sketch"); // Path: src/main/java/org/mandfer/sunfunpi4j/Ex21_Obstacle01.java import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalInput; import com.pi4j.io.gpio.PinPullResistance; import com.pi4j.io.gpio.RaspiPin; import com.pi4j.io.gpio.event.GpioPinDigitalStateChangeEvent; import com.pi4j.io.gpio.event.GpioPinListenerDigital; import static org.mandfer.sunfunpi4j.BaseSketch.logger; /** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ public class Ex21_Obstacle01 extends BaseSketch { private GpioPinDigitalInput obstaclePin; /** * @param gpio controller */ public Ex21_Obstacle01(GpioController gpio){ super(gpio); } public static void main(String[] args) throws InterruptedException { Ex21_Obstacle01 sketch = new Ex21_Obstacle01(GpioFactory.getInstance()); sketch.run(args); } @Override protected void setup(String[] args) { wiringPiSetup(); obstaclePin = gpio.provisionDigitalInputPin(RaspiPin.GPIO_00, PinPullResistance.PULL_DOWN); obstaclePin.addListener(new GpioPinListenerDigital() { @Override public void handleGpioPinDigitalStateChangeEvent(GpioPinDigitalStateChangeEvent event) { if(event.getState().isHigh()){
logger.debug("Detected Barrier !");
marcandreuf/sunfounder-sensors-raspi-4j
src/test/java/org/mandfer/sunfunpi4j/Ex07_KnockSensorTest.java
// Path: src/test/java/org/mandfer/categories/FastTest.java // public interface FastTest {}
import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.pi4j.io.gpio.RaspiPin; import com.pi4j.wiringpi.Gpio; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.mandfer.categories.FastTest; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions;
/** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ @RunWith(PowerMockRunner.class) @PrepareForTest(Gpio.class) public class Ex07_KnockSensorTest extends BaseSketchTest{ private Ex07_KnockSensor sketch; @Before public void setUp(){ PowerMockito.mockStatic(Gpio.class); sketch = new Ex07_KnockSensor(mocked_gpioController); } @Test
// Path: src/test/java/org/mandfer/categories/FastTest.java // public interface FastTest {} // Path: src/test/java/org/mandfer/sunfunpi4j/Ex07_KnockSensorTest.java import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.pi4j.io.gpio.RaspiPin; import com.pi4j.wiringpi.Gpio; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.mandfer.categories.FastTest; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; /** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ @RunWith(PowerMockRunner.class) @PrepareForTest(Gpio.class) public class Ex07_KnockSensorTest extends BaseSketchTest{ private Ex07_KnockSensor sketch; @Before public void setUp(){ PowerMockito.mockStatic(Gpio.class); sketch = new Ex07_KnockSensor(mocked_gpioController); } @Test
@Category(FastTest.class)
marcandreuf/sunfounder-sensors-raspi-4j
src/main/java/org/mandfer/sunfunpi4j/Ex29_IrRecv.java
// Path: src/main/java/org/mandfer/sunfunpi4j/BaseSketch.java // protected static void wiringPiSetup(){ // if (Gpio.wiringPiSetup() == -1) { // String msg = "==>> GPIO SETUP FAILED"; // logger.debug(msg); // throw new RuntimeException(msg); // } // }
import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.wiringpi.Gpio; import com.pi4j.wiringpi.GpioInterruptCallback; import static org.mandfer.sunfunpi4j.BaseSketch.wiringPiSetup;
/** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ public class Ex29_IrRecv extends BaseSketch { private int count; private final int isrPin = 0; /** * @param gpio controller */ public Ex29_IrRecv(GpioController gpio){ super(gpio); } public static void main(String[] args) throws InterruptedException { Ex29_IrRecv sketch = new Ex29_IrRecv(GpioFactory.getInstance()); sketch.run(args); } @Override protected void setup(String[] args) {
// Path: src/main/java/org/mandfer/sunfunpi4j/BaseSketch.java // protected static void wiringPiSetup(){ // if (Gpio.wiringPiSetup() == -1) { // String msg = "==>> GPIO SETUP FAILED"; // logger.debug(msg); // throw new RuntimeException(msg); // } // } // Path: src/main/java/org/mandfer/sunfunpi4j/Ex29_IrRecv.java import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.wiringpi.Gpio; import com.pi4j.wiringpi.GpioInterruptCallback; import static org.mandfer.sunfunpi4j.BaseSketch.wiringPiSetup; /** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ public class Ex29_IrRecv extends BaseSketch { private int count; private final int isrPin = 0; /** * @param gpio controller */ public Ex29_IrRecv(GpioController gpio){ super(gpio); } public static void main(String[] args) throws InterruptedException { Ex29_IrRecv sketch = new Ex29_IrRecv(GpioFactory.getInstance()); sketch.run(args); } @Override protected void setup(String[] args) {
wiringPiSetup();
marcandreuf/sunfounder-sensors-raspi-4j
src/test/java/org/mandfer/sunfunpi4j/Ex05_DoubleColorLedTest.java
// Path: src/test/java/org/mandfer/categories/FastTest.java // public interface FastTest {} // // Path: src/main/java/org/mandfer/sunfunpi4j/RGB_Base.java // public static final int LEDPINRED = 0; // // Path: src/main/java/org/mandfer/sunfunpi4j/RGB_Base.java // public static final int LEDPINYELLOW = 1;
import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.pi4j.wiringpi.Gpio; import com.pi4j.wiringpi.SoftPwm; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.mandfer.categories.FastTest; import static org.mandfer.sunfunpi4j.RGB_Base.LEDPINRED; import static org.mandfer.sunfunpi4j.RGB_Base.LEDPINYELLOW;
/** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ @RunWith(PowerMockRunner.class) @PrepareForTest({Gpio.class, SoftPwm.class}) public class Ex05_DoubleColorLedTest extends BaseSketchTest{ private Ex05_DoubleColorLed sketch; @Before public void setUp(){ PowerMockito.mockStatic(Gpio.class); PowerMockito.mockStatic(SoftPwm.class); sketch = new Ex05_DoubleColorLed(mocked_gpioController); } @Test
// Path: src/test/java/org/mandfer/categories/FastTest.java // public interface FastTest {} // // Path: src/main/java/org/mandfer/sunfunpi4j/RGB_Base.java // public static final int LEDPINRED = 0; // // Path: src/main/java/org/mandfer/sunfunpi4j/RGB_Base.java // public static final int LEDPINYELLOW = 1; // Path: src/test/java/org/mandfer/sunfunpi4j/Ex05_DoubleColorLedTest.java import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.pi4j.wiringpi.Gpio; import com.pi4j.wiringpi.SoftPwm; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.mandfer.categories.FastTest; import static org.mandfer.sunfunpi4j.RGB_Base.LEDPINRED; import static org.mandfer.sunfunpi4j.RGB_Base.LEDPINYELLOW; /** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ @RunWith(PowerMockRunner.class) @PrepareForTest({Gpio.class, SoftPwm.class}) public class Ex05_DoubleColorLedTest extends BaseSketchTest{ private Ex05_DoubleColorLed sketch; @Before public void setUp(){ PowerMockito.mockStatic(Gpio.class); PowerMockito.mockStatic(SoftPwm.class); sketch = new Ex05_DoubleColorLed(mocked_gpioController); } @Test
@Category(FastTest.class)
marcandreuf/sunfounder-sensors-raspi-4j
src/test/java/org/mandfer/sunfunpi4j/Ex05_DoubleColorLedTest.java
// Path: src/test/java/org/mandfer/categories/FastTest.java // public interface FastTest {} // // Path: src/main/java/org/mandfer/sunfunpi4j/RGB_Base.java // public static final int LEDPINRED = 0; // // Path: src/main/java/org/mandfer/sunfunpi4j/RGB_Base.java // public static final int LEDPINYELLOW = 1;
import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.pi4j.wiringpi.Gpio; import com.pi4j.wiringpi.SoftPwm; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.mandfer.categories.FastTest; import static org.mandfer.sunfunpi4j.RGB_Base.LEDPINRED; import static org.mandfer.sunfunpi4j.RGB_Base.LEDPINYELLOW;
/** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ @RunWith(PowerMockRunner.class) @PrepareForTest({Gpio.class, SoftPwm.class}) public class Ex05_DoubleColorLedTest extends BaseSketchTest{ private Ex05_DoubleColorLed sketch; @Before public void setUp(){ PowerMockito.mockStatic(Gpio.class); PowerMockito.mockStatic(SoftPwm.class); sketch = new Ex05_DoubleColorLed(mocked_gpioController); } @Test @Category(FastTest.class) public void verifySetup(){ sketch.setup(NO_ARGS); PowerMockito.verifyStatic(); Gpio.wiringPiSetup(); PowerMockito.verifyStatic();
// Path: src/test/java/org/mandfer/categories/FastTest.java // public interface FastTest {} // // Path: src/main/java/org/mandfer/sunfunpi4j/RGB_Base.java // public static final int LEDPINRED = 0; // // Path: src/main/java/org/mandfer/sunfunpi4j/RGB_Base.java // public static final int LEDPINYELLOW = 1; // Path: src/test/java/org/mandfer/sunfunpi4j/Ex05_DoubleColorLedTest.java import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.pi4j.wiringpi.Gpio; import com.pi4j.wiringpi.SoftPwm; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.mandfer.categories.FastTest; import static org.mandfer.sunfunpi4j.RGB_Base.LEDPINRED; import static org.mandfer.sunfunpi4j.RGB_Base.LEDPINYELLOW; /** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ @RunWith(PowerMockRunner.class) @PrepareForTest({Gpio.class, SoftPwm.class}) public class Ex05_DoubleColorLedTest extends BaseSketchTest{ private Ex05_DoubleColorLed sketch; @Before public void setUp(){ PowerMockito.mockStatic(Gpio.class); PowerMockito.mockStatic(SoftPwm.class); sketch = new Ex05_DoubleColorLed(mocked_gpioController); } @Test @Category(FastTest.class) public void verifySetup(){ sketch.setup(NO_ARGS); PowerMockito.verifyStatic(); Gpio.wiringPiSetup(); PowerMockito.verifyStatic();
SoftPwm.softPwmCreate(LEDPINRED, 0, 100);
marcandreuf/sunfounder-sensors-raspi-4j
src/test/java/org/mandfer/sunfunpi4j/Ex05_DoubleColorLedTest.java
// Path: src/test/java/org/mandfer/categories/FastTest.java // public interface FastTest {} // // Path: src/main/java/org/mandfer/sunfunpi4j/RGB_Base.java // public static final int LEDPINRED = 0; // // Path: src/main/java/org/mandfer/sunfunpi4j/RGB_Base.java // public static final int LEDPINYELLOW = 1;
import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.pi4j.wiringpi.Gpio; import com.pi4j.wiringpi.SoftPwm; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.mandfer.categories.FastTest; import static org.mandfer.sunfunpi4j.RGB_Base.LEDPINRED; import static org.mandfer.sunfunpi4j.RGB_Base.LEDPINYELLOW;
/** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ @RunWith(PowerMockRunner.class) @PrepareForTest({Gpio.class, SoftPwm.class}) public class Ex05_DoubleColorLedTest extends BaseSketchTest{ private Ex05_DoubleColorLed sketch; @Before public void setUp(){ PowerMockito.mockStatic(Gpio.class); PowerMockito.mockStatic(SoftPwm.class); sketch = new Ex05_DoubleColorLed(mocked_gpioController); } @Test @Category(FastTest.class) public void verifySetup(){ sketch.setup(NO_ARGS); PowerMockito.verifyStatic(); Gpio.wiringPiSetup(); PowerMockito.verifyStatic(); SoftPwm.softPwmCreate(LEDPINRED, 0, 100); PowerMockito.verifyStatic();
// Path: src/test/java/org/mandfer/categories/FastTest.java // public interface FastTest {} // // Path: src/main/java/org/mandfer/sunfunpi4j/RGB_Base.java // public static final int LEDPINRED = 0; // // Path: src/main/java/org/mandfer/sunfunpi4j/RGB_Base.java // public static final int LEDPINYELLOW = 1; // Path: src/test/java/org/mandfer/sunfunpi4j/Ex05_DoubleColorLedTest.java import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.pi4j.wiringpi.Gpio; import com.pi4j.wiringpi.SoftPwm; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.mandfer.categories.FastTest; import static org.mandfer.sunfunpi4j.RGB_Base.LEDPINRED; import static org.mandfer.sunfunpi4j.RGB_Base.LEDPINYELLOW; /** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ @RunWith(PowerMockRunner.class) @PrepareForTest({Gpio.class, SoftPwm.class}) public class Ex05_DoubleColorLedTest extends BaseSketchTest{ private Ex05_DoubleColorLed sketch; @Before public void setUp(){ PowerMockito.mockStatic(Gpio.class); PowerMockito.mockStatic(SoftPwm.class); sketch = new Ex05_DoubleColorLed(mocked_gpioController); } @Test @Category(FastTest.class) public void verifySetup(){ sketch.setup(NO_ARGS); PowerMockito.verifyStatic(); Gpio.wiringPiSetup(); PowerMockito.verifyStatic(); SoftPwm.softPwmCreate(LEDPINRED, 0, 100); PowerMockito.verifyStatic();
SoftPwm.softPwmCreate(LEDPINYELLOW, 0, 100);
marcandreuf/sunfounder-sensors-raspi-4j
src/main/java/org/mandfer/sunfunpi4j/Ex15_TiltSwitch.java
// Path: src/main/java/org/mandfer/sunfunpi4j/BaseSketch.java // protected static void wiringPiSetup(){ // if (Gpio.wiringPiSetup() == -1) { // String msg = "==>> GPIO SETUP FAILED"; // logger.debug(msg); // throw new RuntimeException(msg); // } // }
import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalInput; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.RaspiPin; import static org.mandfer.sunfunpi4j.BaseSketch.wiringPiSetup;
/** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ public class Ex15_TiltSwitch extends BaseSketch { private GpioPinDigitalInput tiltSwitch; private GpioPinDigitalOutput ledPin; /** * @param gpio controller */ public Ex15_TiltSwitch(GpioController gpio){ super(gpio); } public static void main(String[] args) throws InterruptedException { Ex15_TiltSwitch sketch = new Ex15_TiltSwitch(GpioFactory.getInstance()); sketch.run(args); } @Override protected void setup(String[] args) {
// Path: src/main/java/org/mandfer/sunfunpi4j/BaseSketch.java // protected static void wiringPiSetup(){ // if (Gpio.wiringPiSetup() == -1) { // String msg = "==>> GPIO SETUP FAILED"; // logger.debug(msg); // throw new RuntimeException(msg); // } // } // Path: src/main/java/org/mandfer/sunfunpi4j/Ex15_TiltSwitch.java import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalInput; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.RaspiPin; import static org.mandfer.sunfunpi4j.BaseSketch.wiringPiSetup; /** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ public class Ex15_TiltSwitch extends BaseSketch { private GpioPinDigitalInput tiltSwitch; private GpioPinDigitalOutput ledPin; /** * @param gpio controller */ public Ex15_TiltSwitch(GpioController gpio){ super(gpio); } public static void main(String[] args) throws InterruptedException { Ex15_TiltSwitch sketch = new Ex15_TiltSwitch(GpioFactory.getInstance()); sketch.run(args); } @Override protected void setup(String[] args) {
wiringPiSetup();
marcandreuf/sunfounder-sensors-raspi-4j
src/main/java/org/mandfer/sunfunpi4j/ADC_Base.java
// Path: src/main/java/org/mandfer/sunfunpi4j/BaseSketch.java // protected static void wiringPiSetup(){ // if (Gpio.wiringPiSetup() == -1) { // String msg = "==>> GPIO SETUP FAILED"; // logger.debug(msg); // throw new RuntimeException(msg); // } // }
import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioPinDigitalMultipurpose; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.PinMode; import com.pi4j.io.gpio.RaspiPin; import static org.mandfer.sunfunpi4j.BaseSketch.wiringPiSetup;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ public abstract class ADC_Base extends BaseSketch { protected GpioPinDigitalOutput ADC_CS; protected GpioPinDigitalOutput ADC_CLK; protected GpioPinDigitalMultipurpose ADC_DIO; public ADC_Base(GpioController gpio) { super(gpio); } @Override protected void setup(String[] args) {
// Path: src/main/java/org/mandfer/sunfunpi4j/BaseSketch.java // protected static void wiringPiSetup(){ // if (Gpio.wiringPiSetup() == -1) { // String msg = "==>> GPIO SETUP FAILED"; // logger.debug(msg); // throw new RuntimeException(msg); // } // } // Path: src/main/java/org/mandfer/sunfunpi4j/ADC_Base.java import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioPinDigitalMultipurpose; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.PinMode; import com.pi4j.io.gpio.RaspiPin; import static org.mandfer.sunfunpi4j.BaseSketch.wiringPiSetup; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ public abstract class ADC_Base extends BaseSketch { protected GpioPinDigitalOutput ADC_CS; protected GpioPinDigitalOutput ADC_CLK; protected GpioPinDigitalMultipurpose ADC_DIO; public ADC_Base(GpioController gpio) { super(gpio); } @Override protected void setup(String[] args) {
wiringPiSetup();
marcandreuf/sunfounder-sensors-raspi-4j
src/main/java/org/mandfer/sunfunpi4j/Ex14_LightBreak.java
// Path: src/main/java/org/mandfer/sunfunpi4j/BaseSketch.java // protected static void wiringPiSetup(){ // if (Gpio.wiringPiSetup() == -1) { // String msg = "==>> GPIO SETUP FAILED"; // logger.debug(msg); // throw new RuntimeException(msg); // } // }
import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalInput; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.RaspiPin; import static org.mandfer.sunfunpi4j.BaseSketch.wiringPiSetup;
/** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ public class Ex14_LightBreak extends BaseSketch { private GpioPinDigitalInput lightBreakPin; private GpioPinDigitalOutput ledPin; /** * @param gpio controller */ public Ex14_LightBreak(GpioController gpio){ super(gpio); } public static void main(String[] args) throws InterruptedException { Ex14_LightBreak sketch = new Ex14_LightBreak(GpioFactory.getInstance()); sketch.run(args); } @Override protected void setup(String[] args) {
// Path: src/main/java/org/mandfer/sunfunpi4j/BaseSketch.java // protected static void wiringPiSetup(){ // if (Gpio.wiringPiSetup() == -1) { // String msg = "==>> GPIO SETUP FAILED"; // logger.debug(msg); // throw new RuntimeException(msg); // } // } // Path: src/main/java/org/mandfer/sunfunpi4j/Ex14_LightBreak.java import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalInput; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.RaspiPin; import static org.mandfer.sunfunpi4j.BaseSketch.wiringPiSetup; /** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ public class Ex14_LightBreak extends BaseSketch { private GpioPinDigitalInput lightBreakPin; private GpioPinDigitalOutput ledPin; /** * @param gpio controller */ public Ex14_LightBreak(GpioController gpio){ super(gpio); } public static void main(String[] args) throws InterruptedException { Ex14_LightBreak sketch = new Ex14_LightBreak(GpioFactory.getInstance()); sketch.run(args); } @Override protected void setup(String[] args) {
wiringPiSetup();
marcandreuf/sunfounder-sensors-raspi-4j
src/main/java/org/mandfer/sunfunpi4j/Ex29_MagicCupListener.java
// Path: src/main/java/org/mandfer/sunfunpi4j/BaseSketch.java // protected static void wiringPiSetup(){ // if (Gpio.wiringPiSetup() == -1) { // String msg = "==>> GPIO SETUP FAILED"; // logger.debug(msg); // throw new RuntimeException(msg); // } // }
import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalInput; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.PinPullResistance; import com.pi4j.io.gpio.RaspiPin; import com.pi4j.io.gpio.event.GpioPinDigitalStateChangeEvent; import com.pi4j.io.gpio.event.GpioPinListenerDigital; import static org.mandfer.sunfunpi4j.BaseSketch.wiringPiSetup;
/** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ public class Ex29_MagicCupListener extends BaseSketch { private GpioPinDigitalInput sigPin; private GpioPinDigitalOutput ledPin; /** * @param gpio controller */ public Ex29_MagicCupListener(GpioController gpio){ super(gpio); } public static void main(String[] args) throws InterruptedException { Ex29_MagicCupListener sketch = new Ex29_MagicCupListener(GpioFactory.getInstance()); sketch.run(args); } @Override protected void setup(String[] args) {
// Path: src/main/java/org/mandfer/sunfunpi4j/BaseSketch.java // protected static void wiringPiSetup(){ // if (Gpio.wiringPiSetup() == -1) { // String msg = "==>> GPIO SETUP FAILED"; // logger.debug(msg); // throw new RuntimeException(msg); // } // } // Path: src/main/java/org/mandfer/sunfunpi4j/Ex29_MagicCupListener.java import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalInput; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.PinPullResistance; import com.pi4j.io.gpio.RaspiPin; import com.pi4j.io.gpio.event.GpioPinDigitalStateChangeEvent; import com.pi4j.io.gpio.event.GpioPinListenerDigital; import static org.mandfer.sunfunpi4j.BaseSketch.wiringPiSetup; /** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ public class Ex29_MagicCupListener extends BaseSketch { private GpioPinDigitalInput sigPin; private GpioPinDigitalOutput ledPin; /** * @param gpio controller */ public Ex29_MagicCupListener(GpioController gpio){ super(gpio); } public static void main(String[] args) throws InterruptedException { Ex29_MagicCupListener sketch = new Ex29_MagicCupListener(GpioFactory.getInstance()); sketch.run(args); } @Override protected void setup(String[] args) {
wiringPiSetup();
marcandreuf/sunfounder-sensors-raspi-4j
src/test/java/org/mandfer/sunfunpi4j/Ex02_03_LinearHallTest.java
// Path: src/test/java/org/mandfer/categories/FastTest.java // public interface FastTest {} // // Path: src/test/java/org/mandfer/categories/SlowTest.java // public interface SlowTest {}
import com.pi4j.io.gpio.GpioPinDigitalMultipurpose; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.PinMode; import com.pi4j.io.gpio.PinState; import com.pi4j.io.gpio.RaspiPin; import com.pi4j.wiringpi.Gpio; import java.util.concurrent.TimeUnit; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.mandfer.categories.FastTest; import org.mandfer.categories.SlowTest; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner;
/** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ @RunWith(PowerMockRunner.class) @PrepareForTest({Gpio.class, TimeUnit.class}) public class Ex02_03_LinearHallTest extends BaseSketchTest{ private GpioPinDigitalOutput mocked_ADC_CS; private GpioPinDigitalOutput mocked_ADC_CLK; private GpioPinDigitalMultipurpose mocked_ADC_DIO; private Ex02_03_LinearHall sketch; @Before
// Path: src/test/java/org/mandfer/categories/FastTest.java // public interface FastTest {} // // Path: src/test/java/org/mandfer/categories/SlowTest.java // public interface SlowTest {} // Path: src/test/java/org/mandfer/sunfunpi4j/Ex02_03_LinearHallTest.java import com.pi4j.io.gpio.GpioPinDigitalMultipurpose; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.PinMode; import com.pi4j.io.gpio.PinState; import com.pi4j.io.gpio.RaspiPin; import com.pi4j.wiringpi.Gpio; import java.util.concurrent.TimeUnit; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.mandfer.categories.FastTest; import org.mandfer.categories.SlowTest; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; /** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ @RunWith(PowerMockRunner.class) @PrepareForTest({Gpio.class, TimeUnit.class}) public class Ex02_03_LinearHallTest extends BaseSketchTest{ private GpioPinDigitalOutput mocked_ADC_CS; private GpioPinDigitalOutput mocked_ADC_CLK; private GpioPinDigitalMultipurpose mocked_ADC_DIO; private Ex02_03_LinearHall sketch; @Before
@Category(FastTest.class)
marcandreuf/sunfounder-sensors-raspi-4j
src/test/java/org/mandfer/sunfunpi4j/Ex02_03_LinearHallTest.java
// Path: src/test/java/org/mandfer/categories/FastTest.java // public interface FastTest {} // // Path: src/test/java/org/mandfer/categories/SlowTest.java // public interface SlowTest {}
import com.pi4j.io.gpio.GpioPinDigitalMultipurpose; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.PinMode; import com.pi4j.io.gpio.PinState; import com.pi4j.io.gpio.RaspiPin; import com.pi4j.wiringpi.Gpio; import java.util.concurrent.TimeUnit; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.mandfer.categories.FastTest; import org.mandfer.categories.SlowTest; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner;
/** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ @RunWith(PowerMockRunner.class) @PrepareForTest({Gpio.class, TimeUnit.class}) public class Ex02_03_LinearHallTest extends BaseSketchTest{ private GpioPinDigitalOutput mocked_ADC_CS; private GpioPinDigitalOutput mocked_ADC_CLK; private GpioPinDigitalMultipurpose mocked_ADC_DIO; private Ex02_03_LinearHall sketch; @Before @Category(FastTest.class) public void setUp(){ PowerMockito.mockStatic(Gpio.class); PowerMockito.mockStatic(TimeUnit.class); mocked_ADC_CS = mock(GpioPinDigitalOutput.class); mocked_ADC_CLK = mock(GpioPinDigitalOutput.class); mocked_ADC_DIO = mock(GpioPinDigitalMultipurpose.class); sketch = new Ex02_03_LinearHall(mocked_gpioController); } @Test
// Path: src/test/java/org/mandfer/categories/FastTest.java // public interface FastTest {} // // Path: src/test/java/org/mandfer/categories/SlowTest.java // public interface SlowTest {} // Path: src/test/java/org/mandfer/sunfunpi4j/Ex02_03_LinearHallTest.java import com.pi4j.io.gpio.GpioPinDigitalMultipurpose; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.PinMode; import com.pi4j.io.gpio.PinState; import com.pi4j.io.gpio.RaspiPin; import com.pi4j.wiringpi.Gpio; import java.util.concurrent.TimeUnit; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.mandfer.categories.FastTest; import org.mandfer.categories.SlowTest; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; /** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ @RunWith(PowerMockRunner.class) @PrepareForTest({Gpio.class, TimeUnit.class}) public class Ex02_03_LinearHallTest extends BaseSketchTest{ private GpioPinDigitalOutput mocked_ADC_CS; private GpioPinDigitalOutput mocked_ADC_CLK; private GpioPinDigitalMultipurpose mocked_ADC_DIO; private Ex02_03_LinearHall sketch; @Before @Category(FastTest.class) public void setUp(){ PowerMockito.mockStatic(Gpio.class); PowerMockito.mockStatic(TimeUnit.class); mocked_ADC_CS = mock(GpioPinDigitalOutput.class); mocked_ADC_CLK = mock(GpioPinDigitalOutput.class); mocked_ADC_DIO = mock(GpioPinDigitalMultipurpose.class); sketch = new Ex02_03_LinearHall(mocked_gpioController); } @Test
@Category(SlowTest.class)
marcandreuf/sunfounder-sensors-raspi-4j
src/main/java/org/mandfer/sunfunpi4j/Ex13_ButtonISR.java
// Path: src/main/java/org/mandfer/sunfunpi4j/BaseSketch.java // protected static final Logger logger = LoggerFactory.getLogger("Sketch"); // // Path: src/main/java/org/mandfer/sunfunpi4j/BaseSketch.java // protected static void wiringPiSetup(){ // if (Gpio.wiringPiSetup() == -1) { // String msg = "==>> GPIO SETUP FAILED"; // logger.debug(msg); // throw new RuntimeException(msg); // } // }
import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.wiringpi.Gpio; import com.pi4j.wiringpi.GpioInterruptCallback; import static org.mandfer.sunfunpi4j.BaseSketch.logger; import static org.mandfer.sunfunpi4j.BaseSketch.wiringPiSetup;
/** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ public class Ex13_ButtonISR extends BaseSketch { private static final int btnPin = 0; private static final int ledPin = 1; public static void main(String[] args) throws InterruptedException { Ex13_ButtonISR sketch = new Ex13_ButtonISR(GpioFactory.getInstance()); sketch.run(args); } /** * @param gpio controller */ public Ex13_ButtonISR(GpioController gpio){ super(gpio); } @Override protected void setup(String[] args) { gpioIsrSetup();
// Path: src/main/java/org/mandfer/sunfunpi4j/BaseSketch.java // protected static final Logger logger = LoggerFactory.getLogger("Sketch"); // // Path: src/main/java/org/mandfer/sunfunpi4j/BaseSketch.java // protected static void wiringPiSetup(){ // if (Gpio.wiringPiSetup() == -1) { // String msg = "==>> GPIO SETUP FAILED"; // logger.debug(msg); // throw new RuntimeException(msg); // } // } // Path: src/main/java/org/mandfer/sunfunpi4j/Ex13_ButtonISR.java import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.wiringpi.Gpio; import com.pi4j.wiringpi.GpioInterruptCallback; import static org.mandfer.sunfunpi4j.BaseSketch.logger; import static org.mandfer.sunfunpi4j.BaseSketch.wiringPiSetup; /** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ public class Ex13_ButtonISR extends BaseSketch { private static final int btnPin = 0; private static final int ledPin = 1; public static void main(String[] args) throws InterruptedException { Ex13_ButtonISR sketch = new Ex13_ButtonISR(GpioFactory.getInstance()); sketch.run(args); } /** * @param gpio controller */ public Ex13_ButtonISR(GpioController gpio){ super(gpio); } @Override protected void setup(String[] args) { gpioIsrSetup();
logger.debug("Button ISR ready.");
marcandreuf/sunfounder-sensors-raspi-4j
src/main/java/org/mandfer/sunfunpi4j/Ex13_ButtonISR.java
// Path: src/main/java/org/mandfer/sunfunpi4j/BaseSketch.java // protected static final Logger logger = LoggerFactory.getLogger("Sketch"); // // Path: src/main/java/org/mandfer/sunfunpi4j/BaseSketch.java // protected static void wiringPiSetup(){ // if (Gpio.wiringPiSetup() == -1) { // String msg = "==>> GPIO SETUP FAILED"; // logger.debug(msg); // throw new RuntimeException(msg); // } // }
import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.wiringpi.Gpio; import com.pi4j.wiringpi.GpioInterruptCallback; import static org.mandfer.sunfunpi4j.BaseSketch.logger; import static org.mandfer.sunfunpi4j.BaseSketch.wiringPiSetup;
/** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ public class Ex13_ButtonISR extends BaseSketch { private static final int btnPin = 0; private static final int ledPin = 1; public static void main(String[] args) throws InterruptedException { Ex13_ButtonISR sketch = new Ex13_ButtonISR(GpioFactory.getInstance()); sketch.run(args); } /** * @param gpio controller */ public Ex13_ButtonISR(GpioController gpio){ super(gpio); } @Override protected void setup(String[] args) { gpioIsrSetup(); logger.debug("Button ISR ready."); } private static volatile long lastTime = System.currentTimeMillis();; private static void gpioIsrSetup() {
// Path: src/main/java/org/mandfer/sunfunpi4j/BaseSketch.java // protected static final Logger logger = LoggerFactory.getLogger("Sketch"); // // Path: src/main/java/org/mandfer/sunfunpi4j/BaseSketch.java // protected static void wiringPiSetup(){ // if (Gpio.wiringPiSetup() == -1) { // String msg = "==>> GPIO SETUP FAILED"; // logger.debug(msg); // throw new RuntimeException(msg); // } // } // Path: src/main/java/org/mandfer/sunfunpi4j/Ex13_ButtonISR.java import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.wiringpi.Gpio; import com.pi4j.wiringpi.GpioInterruptCallback; import static org.mandfer.sunfunpi4j.BaseSketch.logger; import static org.mandfer.sunfunpi4j.BaseSketch.wiringPiSetup; /** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ public class Ex13_ButtonISR extends BaseSketch { private static final int btnPin = 0; private static final int ledPin = 1; public static void main(String[] args) throws InterruptedException { Ex13_ButtonISR sketch = new Ex13_ButtonISR(GpioFactory.getInstance()); sketch.run(args); } /** * @param gpio controller */ public Ex13_ButtonISR(GpioController gpio){ super(gpio); } @Override protected void setup(String[] args) { gpioIsrSetup(); logger.debug("Button ISR ready."); } private static volatile long lastTime = System.currentTimeMillis();; private static void gpioIsrSetup() {
wiringPiSetup();
marcandreuf/sunfounder-sensors-raspi-4j
src/main/java/org/mandfer/sunfunpi4j/Ex13_ButtonListener.java
// Path: src/main/java/org/mandfer/sunfunpi4j/BaseSketch.java // protected static final Logger logger = LoggerFactory.getLogger("Sketch"); // // Path: src/main/java/org/mandfer/sunfunpi4j/BaseSketch.java // protected static void wiringPiSetup(){ // if (Gpio.wiringPiSetup() == -1) { // String msg = "==>> GPIO SETUP FAILED"; // logger.debug(msg); // throw new RuntimeException(msg); // } // }
import java.util.logging.Logger; import static org.mandfer.sunfunpi4j.BaseSketch.logger; import static org.mandfer.sunfunpi4j.BaseSketch.wiringPiSetup; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalInput; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.PinPullResistance; import com.pi4j.io.gpio.RaspiPin; import com.pi4j.io.gpio.event.GpioPinDigitalStateChangeEvent; import com.pi4j.io.gpio.event.GpioPinListenerDigital; import java.util.logging.Level;
/** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ public class Ex13_ButtonListener extends BaseSketch { public static void main(String[] args) throws InterruptedException { Ex13_ButtonListener sketch = new Ex13_ButtonListener(GpioFactory.getInstance()); sketch.run(args); } private GpioPinDigitalInput myButton; private GpioPinDigitalOutput ledPin; /** * @param gpio controller */ public Ex13_ButtonListener(GpioController gpio){ super(gpio); } @Override protected void setup(String[] args) {
// Path: src/main/java/org/mandfer/sunfunpi4j/BaseSketch.java // protected static final Logger logger = LoggerFactory.getLogger("Sketch"); // // Path: src/main/java/org/mandfer/sunfunpi4j/BaseSketch.java // protected static void wiringPiSetup(){ // if (Gpio.wiringPiSetup() == -1) { // String msg = "==>> GPIO SETUP FAILED"; // logger.debug(msg); // throw new RuntimeException(msg); // } // } // Path: src/main/java/org/mandfer/sunfunpi4j/Ex13_ButtonListener.java import java.util.logging.Logger; import static org.mandfer.sunfunpi4j.BaseSketch.logger; import static org.mandfer.sunfunpi4j.BaseSketch.wiringPiSetup; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalInput; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.PinPullResistance; import com.pi4j.io.gpio.RaspiPin; import com.pi4j.io.gpio.event.GpioPinDigitalStateChangeEvent; import com.pi4j.io.gpio.event.GpioPinListenerDigital; import java.util.logging.Level; /** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ public class Ex13_ButtonListener extends BaseSketch { public static void main(String[] args) throws InterruptedException { Ex13_ButtonListener sketch = new Ex13_ButtonListener(GpioFactory.getInstance()); sketch.run(args); } private GpioPinDigitalInput myButton; private GpioPinDigitalOutput ledPin; /** * @param gpio controller */ public Ex13_ButtonListener(GpioController gpio){ super(gpio); } @Override protected void setup(String[] args) {
wiringPiSetup();
marcandreuf/sunfounder-sensors-raspi-4j
src/main/java/org/mandfer/sunfunpi4j/Ex13_ButtonListener.java
// Path: src/main/java/org/mandfer/sunfunpi4j/BaseSketch.java // protected static final Logger logger = LoggerFactory.getLogger("Sketch"); // // Path: src/main/java/org/mandfer/sunfunpi4j/BaseSketch.java // protected static void wiringPiSetup(){ // if (Gpio.wiringPiSetup() == -1) { // String msg = "==>> GPIO SETUP FAILED"; // logger.debug(msg); // throw new RuntimeException(msg); // } // }
import java.util.logging.Logger; import static org.mandfer.sunfunpi4j.BaseSketch.logger; import static org.mandfer.sunfunpi4j.BaseSketch.wiringPiSetup; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalInput; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.PinPullResistance; import com.pi4j.io.gpio.RaspiPin; import com.pi4j.io.gpio.event.GpioPinDigitalStateChangeEvent; import com.pi4j.io.gpio.event.GpioPinListenerDigital; import java.util.logging.Level;
/** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ public class Ex13_ButtonListener extends BaseSketch { public static void main(String[] args) throws InterruptedException { Ex13_ButtonListener sketch = new Ex13_ButtonListener(GpioFactory.getInstance()); sketch.run(args); } private GpioPinDigitalInput myButton; private GpioPinDigitalOutput ledPin; /** * @param gpio controller */ public Ex13_ButtonListener(GpioController gpio){ super(gpio); } @Override protected void setup(String[] args) { wiringPiSetup(); ledPin = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_01); myButton = gpio.provisionDigitalInputPin(RaspiPin.GPIO_00, PinPullResistance.PULL_DOWN); myButton.addListener(new GpioPinListenerDigital() { @Override public void handleGpioPinDigitalStateChangeEvent(GpioPinDigitalStateChangeEvent event) { if(event.getState().isLow()){
// Path: src/main/java/org/mandfer/sunfunpi4j/BaseSketch.java // protected static final Logger logger = LoggerFactory.getLogger("Sketch"); // // Path: src/main/java/org/mandfer/sunfunpi4j/BaseSketch.java // protected static void wiringPiSetup(){ // if (Gpio.wiringPiSetup() == -1) { // String msg = "==>> GPIO SETUP FAILED"; // logger.debug(msg); // throw new RuntimeException(msg); // } // } // Path: src/main/java/org/mandfer/sunfunpi4j/Ex13_ButtonListener.java import java.util.logging.Logger; import static org.mandfer.sunfunpi4j.BaseSketch.logger; import static org.mandfer.sunfunpi4j.BaseSketch.wiringPiSetup; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalInput; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.PinPullResistance; import com.pi4j.io.gpio.RaspiPin; import com.pi4j.io.gpio.event.GpioPinDigitalStateChangeEvent; import com.pi4j.io.gpio.event.GpioPinListenerDigital; import java.util.logging.Level; /** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ public class Ex13_ButtonListener extends BaseSketch { public static void main(String[] args) throws InterruptedException { Ex13_ButtonListener sketch = new Ex13_ButtonListener(GpioFactory.getInstance()); sketch.run(args); } private GpioPinDigitalInput myButton; private GpioPinDigitalOutput ledPin; /** * @param gpio controller */ public Ex13_ButtonListener(GpioController gpio){ super(gpio); } @Override protected void setup(String[] args) { wiringPiSetup(); ledPin = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_01); myButton = gpio.provisionDigitalInputPin(RaspiPin.GPIO_00, PinPullResistance.PULL_DOWN); myButton.addListener(new GpioPinListenerDigital() { @Override public void handleGpioPinDigitalStateChangeEvent(GpioPinDigitalStateChangeEvent event) { if(event.getState().isLow()){
logger.debug("Button is pressed");
marcandreuf/sunfounder-sensors-raspi-4j
src/main/java/org/mandfer/sunfunpi4j/Ex09_Laser.java
// Path: src/main/java/org/mandfer/sunfunpi4j/BaseSketch.java // protected static void wiringPiSetup(){ // if (Gpio.wiringPiSetup() == -1) { // String msg = "==>> GPIO SETUP FAILED"; // logger.debug(msg); // throw new RuntimeException(msg); // } // }
import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.RaspiPin; import static org.mandfer.sunfunpi4j.BaseSketch.wiringPiSetup;
/** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ public class Ex09_Laser extends BaseSketch { private GpioPinDigitalOutput laserPin; /** * @param gpio controller */ public Ex09_Laser(GpioController gpio){ super(gpio); } public static void main(String[] args) throws InterruptedException { Ex09_Laser sketch = new Ex09_Laser(GpioFactory.getInstance()); sketch.run(args); } @Override protected void setup(String[] args) {
// Path: src/main/java/org/mandfer/sunfunpi4j/BaseSketch.java // protected static void wiringPiSetup(){ // if (Gpio.wiringPiSetup() == -1) { // String msg = "==>> GPIO SETUP FAILED"; // logger.debug(msg); // throw new RuntimeException(msg); // } // } // Path: src/main/java/org/mandfer/sunfunpi4j/Ex09_Laser.java import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.RaspiPin; import static org.mandfer.sunfunpi4j.BaseSketch.wiringPiSetup; /** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ public class Ex09_Laser extends BaseSketch { private GpioPinDigitalOutput laserPin; /** * @param gpio controller */ public Ex09_Laser(GpioController gpio){ super(gpio); } public static void main(String[] args) throws InterruptedException { Ex09_Laser sketch = new Ex09_Laser(GpioFactory.getInstance()); sketch.run(args); } @Override protected void setup(String[] args) {
wiringPiSetup();
marcandreuf/sunfounder-sensors-raspi-4j
src/test/java/org/mandfer/sunfunpi4j/Ex01_SwitchHallTest.java
// Path: src/test/java/org/mandfer/categories/FastTest.java // public interface FastTest {} // // Path: src/test/java/org/mandfer/categories/SlowTest.java // public interface SlowTest {}
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import com.pi4j.io.gpio.GpioPinDigitalInput; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.PinState; import com.pi4j.io.gpio.RaspiPin; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.mandfer.categories.FastTest; import org.mandfer.categories.SlowTest;
/** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ public class Ex01_SwitchHallTest extends BaseSketchTest{ private GpioPinDigitalInput mocked_hallPin; private GpioPinDigitalOutput mocked_ledPin; private Ex01_SwitchHall sketch; @Before public void setUp(){ mocked_hallPin = mock(GpioPinDigitalInput.class); mocked_ledPin = mock(GpioPinDigitalOutput.class); sketch = new Ex01_SwitchHall(mocked_gpioController); } @Test
// Path: src/test/java/org/mandfer/categories/FastTest.java // public interface FastTest {} // // Path: src/test/java/org/mandfer/categories/SlowTest.java // public interface SlowTest {} // Path: src/test/java/org/mandfer/sunfunpi4j/Ex01_SwitchHallTest.java import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import com.pi4j.io.gpio.GpioPinDigitalInput; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.PinState; import com.pi4j.io.gpio.RaspiPin; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.mandfer.categories.FastTest; import org.mandfer.categories.SlowTest; /** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ public class Ex01_SwitchHallTest extends BaseSketchTest{ private GpioPinDigitalInput mocked_hallPin; private GpioPinDigitalOutput mocked_ledPin; private Ex01_SwitchHall sketch; @Before public void setUp(){ mocked_hallPin = mock(GpioPinDigitalInput.class); mocked_ledPin = mock(GpioPinDigitalOutput.class); sketch = new Ex01_SwitchHall(mocked_gpioController); } @Test
@Category(FastTest.class)
marcandreuf/sunfounder-sensors-raspi-4j
src/test/java/org/mandfer/sunfunpi4j/Ex01_SwitchHallTest.java
// Path: src/test/java/org/mandfer/categories/FastTest.java // public interface FastTest {} // // Path: src/test/java/org/mandfer/categories/SlowTest.java // public interface SlowTest {}
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import com.pi4j.io.gpio.GpioPinDigitalInput; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.PinState; import com.pi4j.io.gpio.RaspiPin; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.mandfer.categories.FastTest; import org.mandfer.categories.SlowTest;
/** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ public class Ex01_SwitchHallTest extends BaseSketchTest{ private GpioPinDigitalInput mocked_hallPin; private GpioPinDigitalOutput mocked_ledPin; private Ex01_SwitchHall sketch; @Before public void setUp(){ mocked_hallPin = mock(GpioPinDigitalInput.class); mocked_ledPin = mock(GpioPinDigitalOutput.class); sketch = new Ex01_SwitchHall(mocked_gpioController); } @Test @Category(FastTest.class) public void verifySetup(){ sketch.setup(NO_ARGS); verify(mocked_gpioController).provisionDigitalInputPin(RaspiPin.GPIO_00); verify(mocked_gpioController).provisionDigitalOutputPin(RaspiPin.GPIO_01); verifyNoMoreInteractions(mocked_gpioController); } @Test
// Path: src/test/java/org/mandfer/categories/FastTest.java // public interface FastTest {} // // Path: src/test/java/org/mandfer/categories/SlowTest.java // public interface SlowTest {} // Path: src/test/java/org/mandfer/sunfunpi4j/Ex01_SwitchHallTest.java import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import com.pi4j.io.gpio.GpioPinDigitalInput; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.PinState; import com.pi4j.io.gpio.RaspiPin; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.mandfer.categories.FastTest; import org.mandfer.categories.SlowTest; /** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ public class Ex01_SwitchHallTest extends BaseSketchTest{ private GpioPinDigitalInput mocked_hallPin; private GpioPinDigitalOutput mocked_ledPin; private Ex01_SwitchHall sketch; @Before public void setUp(){ mocked_hallPin = mock(GpioPinDigitalInput.class); mocked_ledPin = mock(GpioPinDigitalOutput.class); sketch = new Ex01_SwitchHall(mocked_gpioController); } @Test @Category(FastTest.class) public void verifySetup(){ sketch.setup(NO_ARGS); verify(mocked_gpioController).provisionDigitalInputPin(RaspiPin.GPIO_00); verify(mocked_gpioController).provisionDigitalOutputPin(RaspiPin.GPIO_01); verifyNoMoreInteractions(mocked_gpioController); } @Test
@Category(SlowTest.class)
marcandreuf/sunfounder-sensors-raspi-4j
src/main/java/org/mandfer/sunfunpi4j/Ex21_Obstacle02.java
// Path: src/main/java/org/mandfer/sunfunpi4j/BaseSketch.java // protected static final Logger logger = LoggerFactory.getLogger("Sketch");
import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalInput; import com.pi4j.io.gpio.RaspiPin; import static org.mandfer.sunfunpi4j.BaseSketch.logger;
/** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ public class Ex21_Obstacle02 extends BaseSketch { private GpioPinDigitalInput obstaclePin; /** * @param gpio controller */ public Ex21_Obstacle02(GpioController gpio){ super(gpio); } public static void main(String[] args) throws InterruptedException { Ex21_Obstacle02 sketch = new Ex21_Obstacle02(GpioFactory.getInstance()); sketch.run(args); } @Override protected void setup(String[] args) { obstaclePin = gpio.provisionDigitalInputPin(RaspiPin.GPIO_00);
// Path: src/main/java/org/mandfer/sunfunpi4j/BaseSketch.java // protected static final Logger logger = LoggerFactory.getLogger("Sketch"); // Path: src/main/java/org/mandfer/sunfunpi4j/Ex21_Obstacle02.java import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalInput; import com.pi4j.io.gpio.RaspiPin; import static org.mandfer.sunfunpi4j.BaseSketch.logger; /** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ public class Ex21_Obstacle02 extends BaseSketch { private GpioPinDigitalInput obstaclePin; /** * @param gpio controller */ public Ex21_Obstacle02(GpioController gpio){ super(gpio); } public static void main(String[] args) throws InterruptedException { Ex21_Obstacle02 sketch = new Ex21_Obstacle02(GpioFactory.getInstance()); sketch.run(args); } @Override protected void setup(String[] args) { obstaclePin = gpio.provisionDigitalInputPin(RaspiPin.GPIO_00);
logger.debug("Obstacle sensor ready!");
marcandreuf/sunfounder-sensors-raspi-4j
src/test/java/org/mandfer/sunfunpi4j/Ex04_RGBTest.java
// Path: src/test/java/org/mandfer/categories/FastTest.java // public interface FastTest {} // // Path: src/test/java/org/mandfer/categories/SlowTest.java // public interface SlowTest {} // // Path: src/main/java/org/mandfer/sunfunpi4j/RGB_Base.java // public static final int LEDPINBLUE = 2; // // Path: src/main/java/org/mandfer/sunfunpi4j/RGB_Base.java // public static final int LEDPINGREEN = 1; // // Path: src/main/java/org/mandfer/sunfunpi4j/RGB_Base.java // public static final int LEDPINRED = 0;
import static org.mandfer.sunfunpi4j.RGB_Base.LEDPINGREEN; import static org.mandfer.sunfunpi4j.RGB_Base.LEDPINRED; import static org.mockito.Mockito.atLeast; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.pi4j.wiringpi.Gpio; import com.pi4j.wiringpi.SoftPwm; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.mandfer.categories.FastTest; import org.mandfer.categories.SlowTest; import static org.mandfer.sunfunpi4j.RGB_Base.LEDPINBLUE;
/** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ @RunWith(PowerMockRunner.class) @PrepareForTest({Gpio.class, SoftPwm.class}) public class Ex04_RGBTest extends BaseSketchTest{ private Ex04_RGB sketch; @Before public void setUp(){ PowerMockito.mockStatic(Gpio.class); PowerMockito.mockStatic(SoftPwm.class); sketch = new Ex04_RGB(mocked_gpioController); } @Test
// Path: src/test/java/org/mandfer/categories/FastTest.java // public interface FastTest {} // // Path: src/test/java/org/mandfer/categories/SlowTest.java // public interface SlowTest {} // // Path: src/main/java/org/mandfer/sunfunpi4j/RGB_Base.java // public static final int LEDPINBLUE = 2; // // Path: src/main/java/org/mandfer/sunfunpi4j/RGB_Base.java // public static final int LEDPINGREEN = 1; // // Path: src/main/java/org/mandfer/sunfunpi4j/RGB_Base.java // public static final int LEDPINRED = 0; // Path: src/test/java/org/mandfer/sunfunpi4j/Ex04_RGBTest.java import static org.mandfer.sunfunpi4j.RGB_Base.LEDPINGREEN; import static org.mandfer.sunfunpi4j.RGB_Base.LEDPINRED; import static org.mockito.Mockito.atLeast; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.pi4j.wiringpi.Gpio; import com.pi4j.wiringpi.SoftPwm; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.mandfer.categories.FastTest; import org.mandfer.categories.SlowTest; import static org.mandfer.sunfunpi4j.RGB_Base.LEDPINBLUE; /** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ @RunWith(PowerMockRunner.class) @PrepareForTest({Gpio.class, SoftPwm.class}) public class Ex04_RGBTest extends BaseSketchTest{ private Ex04_RGB sketch; @Before public void setUp(){ PowerMockito.mockStatic(Gpio.class); PowerMockito.mockStatic(SoftPwm.class); sketch = new Ex04_RGB(mocked_gpioController); } @Test
@Category(FastTest.class)
marcandreuf/sunfounder-sensors-raspi-4j
src/test/java/org/mandfer/sunfunpi4j/Ex04_RGBTest.java
// Path: src/test/java/org/mandfer/categories/FastTest.java // public interface FastTest {} // // Path: src/test/java/org/mandfer/categories/SlowTest.java // public interface SlowTest {} // // Path: src/main/java/org/mandfer/sunfunpi4j/RGB_Base.java // public static final int LEDPINBLUE = 2; // // Path: src/main/java/org/mandfer/sunfunpi4j/RGB_Base.java // public static final int LEDPINGREEN = 1; // // Path: src/main/java/org/mandfer/sunfunpi4j/RGB_Base.java // public static final int LEDPINRED = 0;
import static org.mandfer.sunfunpi4j.RGB_Base.LEDPINGREEN; import static org.mandfer.sunfunpi4j.RGB_Base.LEDPINRED; import static org.mockito.Mockito.atLeast; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.pi4j.wiringpi.Gpio; import com.pi4j.wiringpi.SoftPwm; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.mandfer.categories.FastTest; import org.mandfer.categories.SlowTest; import static org.mandfer.sunfunpi4j.RGB_Base.LEDPINBLUE;
/** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ @RunWith(PowerMockRunner.class) @PrepareForTest({Gpio.class, SoftPwm.class}) public class Ex04_RGBTest extends BaseSketchTest{ private Ex04_RGB sketch; @Before public void setUp(){ PowerMockito.mockStatic(Gpio.class); PowerMockito.mockStatic(SoftPwm.class); sketch = new Ex04_RGB(mocked_gpioController); } @Test @Category(FastTest.class) public void verifySetup(){ sketch.setup(NO_ARGS); PowerMockito.verifyStatic(); Gpio.wiringPiSetup(); PowerMockito.verifyStatic();
// Path: src/test/java/org/mandfer/categories/FastTest.java // public interface FastTest {} // // Path: src/test/java/org/mandfer/categories/SlowTest.java // public interface SlowTest {} // // Path: src/main/java/org/mandfer/sunfunpi4j/RGB_Base.java // public static final int LEDPINBLUE = 2; // // Path: src/main/java/org/mandfer/sunfunpi4j/RGB_Base.java // public static final int LEDPINGREEN = 1; // // Path: src/main/java/org/mandfer/sunfunpi4j/RGB_Base.java // public static final int LEDPINRED = 0; // Path: src/test/java/org/mandfer/sunfunpi4j/Ex04_RGBTest.java import static org.mandfer.sunfunpi4j.RGB_Base.LEDPINGREEN; import static org.mandfer.sunfunpi4j.RGB_Base.LEDPINRED; import static org.mockito.Mockito.atLeast; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.pi4j.wiringpi.Gpio; import com.pi4j.wiringpi.SoftPwm; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.mandfer.categories.FastTest; import org.mandfer.categories.SlowTest; import static org.mandfer.sunfunpi4j.RGB_Base.LEDPINBLUE; /** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ @RunWith(PowerMockRunner.class) @PrepareForTest({Gpio.class, SoftPwm.class}) public class Ex04_RGBTest extends BaseSketchTest{ private Ex04_RGB sketch; @Before public void setUp(){ PowerMockito.mockStatic(Gpio.class); PowerMockito.mockStatic(SoftPwm.class); sketch = new Ex04_RGB(mocked_gpioController); } @Test @Category(FastTest.class) public void verifySetup(){ sketch.setup(NO_ARGS); PowerMockito.verifyStatic(); Gpio.wiringPiSetup(); PowerMockito.verifyStatic();
SoftPwm.softPwmCreate(LEDPINRED, 0, 100);
marcandreuf/sunfounder-sensors-raspi-4j
src/test/java/org/mandfer/sunfunpi4j/Ex04_RGBTest.java
// Path: src/test/java/org/mandfer/categories/FastTest.java // public interface FastTest {} // // Path: src/test/java/org/mandfer/categories/SlowTest.java // public interface SlowTest {} // // Path: src/main/java/org/mandfer/sunfunpi4j/RGB_Base.java // public static final int LEDPINBLUE = 2; // // Path: src/main/java/org/mandfer/sunfunpi4j/RGB_Base.java // public static final int LEDPINGREEN = 1; // // Path: src/main/java/org/mandfer/sunfunpi4j/RGB_Base.java // public static final int LEDPINRED = 0;
import static org.mandfer.sunfunpi4j.RGB_Base.LEDPINGREEN; import static org.mandfer.sunfunpi4j.RGB_Base.LEDPINRED; import static org.mockito.Mockito.atLeast; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.pi4j.wiringpi.Gpio; import com.pi4j.wiringpi.SoftPwm; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.mandfer.categories.FastTest; import org.mandfer.categories.SlowTest; import static org.mandfer.sunfunpi4j.RGB_Base.LEDPINBLUE;
/** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ @RunWith(PowerMockRunner.class) @PrepareForTest({Gpio.class, SoftPwm.class}) public class Ex04_RGBTest extends BaseSketchTest{ private Ex04_RGB sketch; @Before public void setUp(){ PowerMockito.mockStatic(Gpio.class); PowerMockito.mockStatic(SoftPwm.class); sketch = new Ex04_RGB(mocked_gpioController); } @Test @Category(FastTest.class) public void verifySetup(){ sketch.setup(NO_ARGS); PowerMockito.verifyStatic(); Gpio.wiringPiSetup(); PowerMockito.verifyStatic(); SoftPwm.softPwmCreate(LEDPINRED, 0, 100); PowerMockito.verifyStatic();
// Path: src/test/java/org/mandfer/categories/FastTest.java // public interface FastTest {} // // Path: src/test/java/org/mandfer/categories/SlowTest.java // public interface SlowTest {} // // Path: src/main/java/org/mandfer/sunfunpi4j/RGB_Base.java // public static final int LEDPINBLUE = 2; // // Path: src/main/java/org/mandfer/sunfunpi4j/RGB_Base.java // public static final int LEDPINGREEN = 1; // // Path: src/main/java/org/mandfer/sunfunpi4j/RGB_Base.java // public static final int LEDPINRED = 0; // Path: src/test/java/org/mandfer/sunfunpi4j/Ex04_RGBTest.java import static org.mandfer.sunfunpi4j.RGB_Base.LEDPINGREEN; import static org.mandfer.sunfunpi4j.RGB_Base.LEDPINRED; import static org.mockito.Mockito.atLeast; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.pi4j.wiringpi.Gpio; import com.pi4j.wiringpi.SoftPwm; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.mandfer.categories.FastTest; import org.mandfer.categories.SlowTest; import static org.mandfer.sunfunpi4j.RGB_Base.LEDPINBLUE; /** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ @RunWith(PowerMockRunner.class) @PrepareForTest({Gpio.class, SoftPwm.class}) public class Ex04_RGBTest extends BaseSketchTest{ private Ex04_RGB sketch; @Before public void setUp(){ PowerMockito.mockStatic(Gpio.class); PowerMockito.mockStatic(SoftPwm.class); sketch = new Ex04_RGB(mocked_gpioController); } @Test @Category(FastTest.class) public void verifySetup(){ sketch.setup(NO_ARGS); PowerMockito.verifyStatic(); Gpio.wiringPiSetup(); PowerMockito.verifyStatic(); SoftPwm.softPwmCreate(LEDPINRED, 0, 100); PowerMockito.verifyStatic();
SoftPwm.softPwmCreate(LEDPINGREEN, 0, 100);
marcandreuf/sunfounder-sensors-raspi-4j
src/test/java/org/mandfer/sunfunpi4j/Ex04_RGBTest.java
// Path: src/test/java/org/mandfer/categories/FastTest.java // public interface FastTest {} // // Path: src/test/java/org/mandfer/categories/SlowTest.java // public interface SlowTest {} // // Path: src/main/java/org/mandfer/sunfunpi4j/RGB_Base.java // public static final int LEDPINBLUE = 2; // // Path: src/main/java/org/mandfer/sunfunpi4j/RGB_Base.java // public static final int LEDPINGREEN = 1; // // Path: src/main/java/org/mandfer/sunfunpi4j/RGB_Base.java // public static final int LEDPINRED = 0;
import static org.mandfer.sunfunpi4j.RGB_Base.LEDPINGREEN; import static org.mandfer.sunfunpi4j.RGB_Base.LEDPINRED; import static org.mockito.Mockito.atLeast; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.pi4j.wiringpi.Gpio; import com.pi4j.wiringpi.SoftPwm; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.mandfer.categories.FastTest; import org.mandfer.categories.SlowTest; import static org.mandfer.sunfunpi4j.RGB_Base.LEDPINBLUE;
/** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ @RunWith(PowerMockRunner.class) @PrepareForTest({Gpio.class, SoftPwm.class}) public class Ex04_RGBTest extends BaseSketchTest{ private Ex04_RGB sketch; @Before public void setUp(){ PowerMockito.mockStatic(Gpio.class); PowerMockito.mockStatic(SoftPwm.class); sketch = new Ex04_RGB(mocked_gpioController); } @Test @Category(FastTest.class) public void verifySetup(){ sketch.setup(NO_ARGS); PowerMockito.verifyStatic(); Gpio.wiringPiSetup(); PowerMockito.verifyStatic(); SoftPwm.softPwmCreate(LEDPINRED, 0, 100); PowerMockito.verifyStatic(); SoftPwm.softPwmCreate(LEDPINGREEN, 0, 100); PowerMockito.verifyStatic();
// Path: src/test/java/org/mandfer/categories/FastTest.java // public interface FastTest {} // // Path: src/test/java/org/mandfer/categories/SlowTest.java // public interface SlowTest {} // // Path: src/main/java/org/mandfer/sunfunpi4j/RGB_Base.java // public static final int LEDPINBLUE = 2; // // Path: src/main/java/org/mandfer/sunfunpi4j/RGB_Base.java // public static final int LEDPINGREEN = 1; // // Path: src/main/java/org/mandfer/sunfunpi4j/RGB_Base.java // public static final int LEDPINRED = 0; // Path: src/test/java/org/mandfer/sunfunpi4j/Ex04_RGBTest.java import static org.mandfer.sunfunpi4j.RGB_Base.LEDPINGREEN; import static org.mandfer.sunfunpi4j.RGB_Base.LEDPINRED; import static org.mockito.Mockito.atLeast; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.pi4j.wiringpi.Gpio; import com.pi4j.wiringpi.SoftPwm; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.mandfer.categories.FastTest; import org.mandfer.categories.SlowTest; import static org.mandfer.sunfunpi4j.RGB_Base.LEDPINBLUE; /** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ @RunWith(PowerMockRunner.class) @PrepareForTest({Gpio.class, SoftPwm.class}) public class Ex04_RGBTest extends BaseSketchTest{ private Ex04_RGB sketch; @Before public void setUp(){ PowerMockito.mockStatic(Gpio.class); PowerMockito.mockStatic(SoftPwm.class); sketch = new Ex04_RGB(mocked_gpioController); } @Test @Category(FastTest.class) public void verifySetup(){ sketch.setup(NO_ARGS); PowerMockito.verifyStatic(); Gpio.wiringPiSetup(); PowerMockito.verifyStatic(); SoftPwm.softPwmCreate(LEDPINRED, 0, 100); PowerMockito.verifyStatic(); SoftPwm.softPwmCreate(LEDPINGREEN, 0, 100); PowerMockito.verifyStatic();
SoftPwm.softPwmCreate(LEDPINBLUE, 0, 100);
marcandreuf/sunfounder-sensors-raspi-4j
src/test/java/org/mandfer/sunfunpi4j/Ex04_RGBTest.java
// Path: src/test/java/org/mandfer/categories/FastTest.java // public interface FastTest {} // // Path: src/test/java/org/mandfer/categories/SlowTest.java // public interface SlowTest {} // // Path: src/main/java/org/mandfer/sunfunpi4j/RGB_Base.java // public static final int LEDPINBLUE = 2; // // Path: src/main/java/org/mandfer/sunfunpi4j/RGB_Base.java // public static final int LEDPINGREEN = 1; // // Path: src/main/java/org/mandfer/sunfunpi4j/RGB_Base.java // public static final int LEDPINRED = 0;
import static org.mandfer.sunfunpi4j.RGB_Base.LEDPINGREEN; import static org.mandfer.sunfunpi4j.RGB_Base.LEDPINRED; import static org.mockito.Mockito.atLeast; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.pi4j.wiringpi.Gpio; import com.pi4j.wiringpi.SoftPwm; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.mandfer.categories.FastTest; import org.mandfer.categories.SlowTest; import static org.mandfer.sunfunpi4j.RGB_Base.LEDPINBLUE;
/** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ @RunWith(PowerMockRunner.class) @PrepareForTest({Gpio.class, SoftPwm.class}) public class Ex04_RGBTest extends BaseSketchTest{ private Ex04_RGB sketch; @Before public void setUp(){ PowerMockito.mockStatic(Gpio.class); PowerMockito.mockStatic(SoftPwm.class); sketch = new Ex04_RGB(mocked_gpioController); } @Test @Category(FastTest.class) public void verifySetup(){ sketch.setup(NO_ARGS); PowerMockito.verifyStatic(); Gpio.wiringPiSetup(); PowerMockito.verifyStatic(); SoftPwm.softPwmCreate(LEDPINRED, 0, 100); PowerMockito.verifyStatic(); SoftPwm.softPwmCreate(LEDPINGREEN, 0, 100); PowerMockito.verifyStatic(); SoftPwm.softPwmCreate(LEDPINBLUE, 0, 100); } @Test
// Path: src/test/java/org/mandfer/categories/FastTest.java // public interface FastTest {} // // Path: src/test/java/org/mandfer/categories/SlowTest.java // public interface SlowTest {} // // Path: src/main/java/org/mandfer/sunfunpi4j/RGB_Base.java // public static final int LEDPINBLUE = 2; // // Path: src/main/java/org/mandfer/sunfunpi4j/RGB_Base.java // public static final int LEDPINGREEN = 1; // // Path: src/main/java/org/mandfer/sunfunpi4j/RGB_Base.java // public static final int LEDPINRED = 0; // Path: src/test/java/org/mandfer/sunfunpi4j/Ex04_RGBTest.java import static org.mandfer.sunfunpi4j.RGB_Base.LEDPINGREEN; import static org.mandfer.sunfunpi4j.RGB_Base.LEDPINRED; import static org.mockito.Mockito.atLeast; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.pi4j.wiringpi.Gpio; import com.pi4j.wiringpi.SoftPwm; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.mandfer.categories.FastTest; import org.mandfer.categories.SlowTest; import static org.mandfer.sunfunpi4j.RGB_Base.LEDPINBLUE; /** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ @RunWith(PowerMockRunner.class) @PrepareForTest({Gpio.class, SoftPwm.class}) public class Ex04_RGBTest extends BaseSketchTest{ private Ex04_RGB sketch; @Before public void setUp(){ PowerMockito.mockStatic(Gpio.class); PowerMockito.mockStatic(SoftPwm.class); sketch = new Ex04_RGB(mocked_gpioController); } @Test @Category(FastTest.class) public void verifySetup(){ sketch.setup(NO_ARGS); PowerMockito.verifyStatic(); Gpio.wiringPiSetup(); PowerMockito.verifyStatic(); SoftPwm.softPwmCreate(LEDPINRED, 0, 100); PowerMockito.verifyStatic(); SoftPwm.softPwmCreate(LEDPINGREEN, 0, 100); PowerMockito.verifyStatic(); SoftPwm.softPwmCreate(LEDPINBLUE, 0, 100); } @Test
@Category(SlowTest.class)
marcandreuf/sunfounder-sensors-raspi-4j
src/main/java/org/mandfer/sunfunpi4j/Ex07_KnockSensor.java
// Path: src/main/java/org/mandfer/sunfunpi4j/BaseSketch.java // protected static void wiringPiSetup(){ // if (Gpio.wiringPiSetup() == -1) { // String msg = "==>> GPIO SETUP FAILED"; // logger.debug(msg); // throw new RuntimeException(msg); // } // }
import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalInput; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.RaspiPin; import static org.mandfer.sunfunpi4j.BaseSketch.wiringPiSetup;
/** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ public class Ex07_KnockSensor extends BaseSketch { private GpioPinDigitalInput knockPin; private GpioPinDigitalOutput ledPin; /** * @param gpio controller */ public Ex07_KnockSensor(GpioController gpio){ super(gpio); } public static void main(String[] args) throws InterruptedException { Ex07_KnockSensor sketch = new Ex07_KnockSensor(GpioFactory.getInstance()); sketch.run(args); } @Override protected void setup(String[] args) {
// Path: src/main/java/org/mandfer/sunfunpi4j/BaseSketch.java // protected static void wiringPiSetup(){ // if (Gpio.wiringPiSetup() == -1) { // String msg = "==>> GPIO SETUP FAILED"; // logger.debug(msg); // throw new RuntimeException(msg); // } // } // Path: src/main/java/org/mandfer/sunfunpi4j/Ex07_KnockSensor.java import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalInput; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.RaspiPin; import static org.mandfer.sunfunpi4j.BaseSketch.wiringPiSetup; /** * * The MIT License (MIT) * * Copyright (c) 2015 Marc Andreu * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package org.mandfer.sunfunpi4j; /** * * @author marcandreuf */ public class Ex07_KnockSensor extends BaseSketch { private GpioPinDigitalInput knockPin; private GpioPinDigitalOutput ledPin; /** * @param gpio controller */ public Ex07_KnockSensor(GpioController gpio){ super(gpio); } public static void main(String[] args) throws InterruptedException { Ex07_KnockSensor sketch = new Ex07_KnockSensor(GpioFactory.getInstance()); sketch.run(args); } @Override protected void setup(String[] args) {
wiringPiSetup();
srcdeps/srcdeps-maven
srcdeps-maven-quickstarts/srcdeps-mvn-git-interdep-modules-quickstart/jar/src/test/java/org/srcdeps/quickstarts/mvn/git/interdep/InterdepTest.java
// Path: srcdeps-maven-quickstarts/srcdeps-mvn-git-include-required-quickstart/jar/src/main/java/org/srcdeps/quickstarts/mvn/git/interdep/Interdep.java // public class Interdep { // final App app = new App(); // // public String getMessage() { // return app.getMessage(); // } // // }
import org.junit.Assert; import org.junit.Test; import org.srcdeps.quickstarts.mvn.git.interdep.Interdep;
/** * Copyright 2015-2016 Maven Source Dependencies * Plugin contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.srcdeps.quickstarts.mvn.git.interdep; public class InterdepTest { @Test public void testInterdep() {
// Path: srcdeps-maven-quickstarts/srcdeps-mvn-git-include-required-quickstart/jar/src/main/java/org/srcdeps/quickstarts/mvn/git/interdep/Interdep.java // public class Interdep { // final App app = new App(); // // public String getMessage() { // return app.getMessage(); // } // // } // Path: srcdeps-maven-quickstarts/srcdeps-mvn-git-interdep-modules-quickstart/jar/src/test/java/org/srcdeps/quickstarts/mvn/git/interdep/InterdepTest.java import org.junit.Assert; import org.junit.Test; import org.srcdeps.quickstarts.mvn.git.interdep.Interdep; /** * Copyright 2015-2016 Maven Source Dependencies * Plugin contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.srcdeps.quickstarts.mvn.git.interdep; public class InterdepTest { @Test public void testInterdep() {
Assert.assertEquals("Hello World!", new Interdep().getService().getApp().getMessage());
srcdeps/srcdeps-maven
srcdeps-maven-quickstarts/srcdeps-mvn-git-include-required-quickstart/jar/src/test/java/org/srcdeps/quickstarts/mvn/git/interdep/InterdepTest.java
// Path: srcdeps-maven-quickstarts/srcdeps-mvn-git-include-required-quickstart/jar/src/main/java/org/srcdeps/quickstarts/mvn/git/interdep/Interdep.java // public class Interdep { // final App app = new App(); // // public String getMessage() { // return app.getMessage(); // } // // }
import org.junit.Assert; import org.junit.Test; import org.srcdeps.quickstarts.mvn.git.interdep.Interdep;
/** * Copyright 2015-2019 Maven Source Dependencies * Plugin contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.srcdeps.quickstarts.mvn.git.interdep; public class InterdepTest { @Test public void testInterdep() {
// Path: srcdeps-maven-quickstarts/srcdeps-mvn-git-include-required-quickstart/jar/src/main/java/org/srcdeps/quickstarts/mvn/git/interdep/Interdep.java // public class Interdep { // final App app = new App(); // // public String getMessage() { // return app.getMessage(); // } // // } // Path: srcdeps-maven-quickstarts/srcdeps-mvn-git-include-required-quickstart/jar/src/test/java/org/srcdeps/quickstarts/mvn/git/interdep/InterdepTest.java import org.junit.Assert; import org.junit.Test; import org.srcdeps.quickstarts.mvn.git.interdep.Interdep; /** * Copyright 2015-2019 Maven Source Dependencies * Plugin contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.srcdeps.quickstarts.mvn.git.interdep; public class InterdepTest { @Test public void testInterdep() {
Assert.assertEquals("Hello World!", new Interdep().getMessage());
srcdeps/srcdeps-maven
srcdeps-maven-local-repository/src/main/java/org/srcdeps/mvn/localrepo/SrcdepsRepositoryManagerFactory.java
// Path: srcdeps-maven-base/src/main/java/org/srcdeps/mvn/config/ConfigurationProducer.java // @Named // public class ConfigurationProducer { // // private final Configuration configuration; // private final Path multimoduleProjectRootDirectory; // // public ConfigurationProducer() throws ConfigurationException { // super(); // // String basePathString = System.getProperty(Constants.MAVEN_MULTI_MODULE_PROJECT_DIRECTORY_PROPERTY); // if (basePathString == null || basePathString.isEmpty()) { // throw new RuntimeException(String.format("The system property %s must not be null or empty", // Constants.MAVEN_MULTI_MODULE_PROJECT_DIRECTORY_PROPERTY)); // } // multimoduleProjectRootDirectory = Paths.get(basePathString).toAbsolutePath(); // // this.configuration = new ConfigurationLocator(System.getProperties(), true) // // .locate(multimoduleProjectRootDirectory, new YamlConfigurationReader()) // // .accept(new OverrideVisitor(System.getProperties())) // // .accept(new DefaultsAndInheritanceVisitor()) // // .forwardPropertyValue(Maven.getSrcdepsMavenVersionProperty(), Constants.SRCDEPS_MAVEN_VERSION) // .build(); // // } // // public Configuration getConfiguration() { // return configuration; // } // // /** // * @return the root directory of the Maven multimodule project. // */ // public Path getMultimoduleProjectRootDirectory() { // return multimoduleProjectRootDirectory; // } // // }
import org.srcdeps.core.BuildService; import org.srcdeps.core.ScmService; import org.srcdeps.core.SrcVersion; import org.srcdeps.core.fs.PathLocker; import org.srcdeps.mvn.config.ConfigurationProducer; import io.takari.aether.localrepo.TakariLocalRepositoryManagerFactory; import java.util.Map; import java.util.Map.Entry; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Provider; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.repository.LocalRepository; import org.eclipse.aether.repository.LocalRepositoryManager; import org.eclipse.aether.repository.NoLocalRepositoryManagerException; import org.eclipse.aether.spi.localrepo.LocalRepositoryManagerFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/** * Copyright 2015-2018 Maven Source Dependencies * Plugin contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.srcdeps.mvn.localrepo; /** * A {@link LocalRepositoryManagerFactory} that produces {@link SrcdepsLocalRepositoryManager}. This is done through * looking up the {@link LocalRepositoryManagerFactory} implementations visible from the present Guice module, choosing * the one specified in the {@code "srcdeps.repomanager.delegate.factory"} system property. If the * {@code "srcdeps.repomanager.delegate.factory"} system property was not set, the * {@value #DEFAULT_SRCDEPS_REPOMANAGER_DELAGATE_FACTORY} is used. The selected {@link LocalRepositoryManagerFactory} * implementation is then used as a delegate. * * @author <a href="https://github.com/ppalaga">Peter Palaga</a> */ @Named("srcdeps") public class SrcdepsRepositoryManagerFactory implements LocalRepositoryManagerFactory { public static final String DEFAULT_SRCDEPS_REPOMANAGER_DELAGATE_FACTORY = TakariLocalRepositoryManagerFactory.class .getName(); public static final float DEFAULT_SRCDEPS_REPOMANAGER_PRIORITY = 30; private static final Logger log = LoggerFactory.getLogger(SrcdepsRepositoryManagerFactory.class); public static final String SRCDEPS_REPOMANAGER_DELAGATE_FACTORY = "srcdeps.repomanager.delegate.factory"; public static final String SRCDEPS_REPOMANAGER_PRIORITY = "srcdeps.repomanager.priority"; /** Passed to {@link SrcdepsLocalRepositoryManager} */ @Inject private BuildService buildService; @Inject
// Path: srcdeps-maven-base/src/main/java/org/srcdeps/mvn/config/ConfigurationProducer.java // @Named // public class ConfigurationProducer { // // private final Configuration configuration; // private final Path multimoduleProjectRootDirectory; // // public ConfigurationProducer() throws ConfigurationException { // super(); // // String basePathString = System.getProperty(Constants.MAVEN_MULTI_MODULE_PROJECT_DIRECTORY_PROPERTY); // if (basePathString == null || basePathString.isEmpty()) { // throw new RuntimeException(String.format("The system property %s must not be null or empty", // Constants.MAVEN_MULTI_MODULE_PROJECT_DIRECTORY_PROPERTY)); // } // multimoduleProjectRootDirectory = Paths.get(basePathString).toAbsolutePath(); // // this.configuration = new ConfigurationLocator(System.getProperties(), true) // // .locate(multimoduleProjectRootDirectory, new YamlConfigurationReader()) // // .accept(new OverrideVisitor(System.getProperties())) // // .accept(new DefaultsAndInheritanceVisitor()) // // .forwardPropertyValue(Maven.getSrcdepsMavenVersionProperty(), Constants.SRCDEPS_MAVEN_VERSION) // .build(); // // } // // public Configuration getConfiguration() { // return configuration; // } // // /** // * @return the root directory of the Maven multimodule project. // */ // public Path getMultimoduleProjectRootDirectory() { // return multimoduleProjectRootDirectory; // } // // } // Path: srcdeps-maven-local-repository/src/main/java/org/srcdeps/mvn/localrepo/SrcdepsRepositoryManagerFactory.java import org.srcdeps.core.BuildService; import org.srcdeps.core.ScmService; import org.srcdeps.core.SrcVersion; import org.srcdeps.core.fs.PathLocker; import org.srcdeps.mvn.config.ConfigurationProducer; import io.takari.aether.localrepo.TakariLocalRepositoryManagerFactory; import java.util.Map; import java.util.Map.Entry; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Provider; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.repository.LocalRepository; import org.eclipse.aether.repository.LocalRepositoryManager; import org.eclipse.aether.repository.NoLocalRepositoryManagerException; import org.eclipse.aether.spi.localrepo.LocalRepositoryManagerFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Copyright 2015-2018 Maven Source Dependencies * Plugin contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.srcdeps.mvn.localrepo; /** * A {@link LocalRepositoryManagerFactory} that produces {@link SrcdepsLocalRepositoryManager}. This is done through * looking up the {@link LocalRepositoryManagerFactory} implementations visible from the present Guice module, choosing * the one specified in the {@code "srcdeps.repomanager.delegate.factory"} system property. If the * {@code "srcdeps.repomanager.delegate.factory"} system property was not set, the * {@value #DEFAULT_SRCDEPS_REPOMANAGER_DELAGATE_FACTORY} is used. The selected {@link LocalRepositoryManagerFactory} * implementation is then used as a delegate. * * @author <a href="https://github.com/ppalaga">Peter Palaga</a> */ @Named("srcdeps") public class SrcdepsRepositoryManagerFactory implements LocalRepositoryManagerFactory { public static final String DEFAULT_SRCDEPS_REPOMANAGER_DELAGATE_FACTORY = TakariLocalRepositoryManagerFactory.class .getName(); public static final float DEFAULT_SRCDEPS_REPOMANAGER_PRIORITY = 30; private static final Logger log = LoggerFactory.getLogger(SrcdepsRepositoryManagerFactory.class); public static final String SRCDEPS_REPOMANAGER_DELAGATE_FACTORY = "srcdeps.repomanager.delegate.factory"; public static final String SRCDEPS_REPOMANAGER_PRIORITY = "srcdeps.repomanager.priority"; /** Passed to {@link SrcdepsLocalRepositoryManager} */ @Inject private BuildService buildService; @Inject
private ConfigurationProducer configurationProducer;
srcdeps/srcdeps-maven
srcdeps-maven-plugin/src/test/java/org/srcdeps/mvn/plugin/SrcdepsInitMojoTest.java
// Path: srcdeps-maven-base/src/main/java/org/srcdeps/mvn/Constants.java // public interface Constants { // // /** See the bin/mvn or bin/mvn.cmd script of your maven distro, where maven.multiModuleProjectDirectory is set */ // String MAVEN_MULTI_MODULE_PROJECT_DIRECTORY_PROPERTY = "maven.multiModuleProjectDirectory"; // // String SRCDEPS_MAVEN_VERSION = "4.0.1-SNAPSHOT"; // @srcdeps.version@ // // }
import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.srcdeps.core.config.Maven; import org.srcdeps.core.util.SrcdepsCoreUtils; import org.srcdeps.mvn.Constants; import io.takari.maven.testing.TestResources; import io.takari.maven.testing.executor.MavenExecution; import io.takari.maven.testing.executor.MavenRuntime; import io.takari.maven.testing.executor.MavenRuntime.MavenRuntimeBuilder; import io.takari.maven.testing.executor.MavenVersions; import io.takari.maven.testing.executor.junit.MavenJUnitTestRunner;
@BeforeClass public static void beforeClass() throws IOException { SrcdepsCoreUtils.ensureDirectoryExistsAndEmpty(mvnLocalRepo); System.setProperty(Maven.getSrcdepsMavenSettingsProperty(), mrmSettingsXmlPath); // Assert.assertTrue("[" + mrmSettingsXmlPath + "] should exist", Files.exists(Paths.get(mrmSettingsXmlPath))); Assert.assertNotNull("project.build.sourceEncoding property must be set", encoding); Assert.assertNotNull("project.version property must be set", projectVersion); } @Rule public final TestResources resources = new TestResources(); public final MavenRuntime verifier; public SrcdepsInitMojoTest(MavenRuntimeBuilder runtimeBuilder) throws Exception { this.verifier = runtimeBuilder.withExtension(new File("target/classes").getCanonicalFile()).build(); } @Test public void initNoArgs() throws Exception { File projDir = resources.getBasedir("parent-with-jar"); MavenExecution mavenExec = verifier.forProject(projDir) // .withCliOption("-e");
// Path: srcdeps-maven-base/src/main/java/org/srcdeps/mvn/Constants.java // public interface Constants { // // /** See the bin/mvn or bin/mvn.cmd script of your maven distro, where maven.multiModuleProjectDirectory is set */ // String MAVEN_MULTI_MODULE_PROJECT_DIRECTORY_PROPERTY = "maven.multiModuleProjectDirectory"; // // String SRCDEPS_MAVEN_VERSION = "4.0.1-SNAPSHOT"; // @srcdeps.version@ // // } // Path: srcdeps-maven-plugin/src/test/java/org/srcdeps/mvn/plugin/SrcdepsInitMojoTest.java import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.srcdeps.core.config.Maven; import org.srcdeps.core.util.SrcdepsCoreUtils; import org.srcdeps.mvn.Constants; import io.takari.maven.testing.TestResources; import io.takari.maven.testing.executor.MavenExecution; import io.takari.maven.testing.executor.MavenRuntime; import io.takari.maven.testing.executor.MavenRuntime.MavenRuntimeBuilder; import io.takari.maven.testing.executor.MavenVersions; import io.takari.maven.testing.executor.junit.MavenJUnitTestRunner; @BeforeClass public static void beforeClass() throws IOException { SrcdepsCoreUtils.ensureDirectoryExistsAndEmpty(mvnLocalRepo); System.setProperty(Maven.getSrcdepsMavenSettingsProperty(), mrmSettingsXmlPath); // Assert.assertTrue("[" + mrmSettingsXmlPath + "] should exist", Files.exists(Paths.get(mrmSettingsXmlPath))); Assert.assertNotNull("project.build.sourceEncoding property must be set", encoding); Assert.assertNotNull("project.version property must be set", projectVersion); } @Rule public final TestResources resources = new TestResources(); public final MavenRuntime verifier; public SrcdepsInitMojoTest(MavenRuntimeBuilder runtimeBuilder) throws Exception { this.verifier = runtimeBuilder.withExtension(new File("target/classes").getCanonicalFile()).build(); } @Test public void initNoArgs() throws Exception { File projDir = resources.getBasedir("parent-with-jar"); MavenExecution mavenExec = verifier.forProject(projDir) // .withCliOption("-e");
final String srcdepsVersion = Constants.SRCDEPS_MAVEN_VERSION;
srcdeps/srcdeps-maven
srcdeps-maven-quickstarts/srcdeps-mvn-git-gradle-source-dependency-quickstart/jar/src/test/java/org/srcdeps/quickstarts/mvn/git/revision/gradle/GreetingAppTest.java
// Path: srcdeps-maven-quickstarts/srcdeps-mvn-git-gradle-source-dependency-quickstart/jar/src/main/java/org/srcdeps/quickstarts/mvn/git/revision/gradle/GreetingApp.java // public class GreetingApp { // private final org.srcdeps.test.gradle.api.Greeter greeter = new org.srcdeps.test.gradle.impl.HelloGreeter(); // // public org.srcdeps.test.gradle.api.Greeter getGreeter() { // return greeter; // } // }
import org.junit.Assert; import org.junit.Test; import org.srcdeps.quickstarts.mvn.git.revision.gradle.GreetingApp;
/** * Copyright 2015-2017 Maven Source Dependencies * Plugin contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.srcdeps.quickstarts.mvn.git.revision.gradle; public class GreetingAppTest { @Test public void test() {
// Path: srcdeps-maven-quickstarts/srcdeps-mvn-git-gradle-source-dependency-quickstart/jar/src/main/java/org/srcdeps/quickstarts/mvn/git/revision/gradle/GreetingApp.java // public class GreetingApp { // private final org.srcdeps.test.gradle.api.Greeter greeter = new org.srcdeps.test.gradle.impl.HelloGreeter(); // // public org.srcdeps.test.gradle.api.Greeter getGreeter() { // return greeter; // } // } // Path: srcdeps-maven-quickstarts/srcdeps-mvn-git-gradle-source-dependency-quickstart/jar/src/test/java/org/srcdeps/quickstarts/mvn/git/revision/gradle/GreetingAppTest.java import org.junit.Assert; import org.junit.Test; import org.srcdeps.quickstarts.mvn.git.revision.gradle.GreetingApp; /** * Copyright 2015-2017 Maven Source Dependencies * Plugin contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.srcdeps.quickstarts.mvn.git.revision.gradle; public class GreetingAppTest { @Test public void test() {
Assert.assertEquals("Hello World!", new GreetingApp().getGreeter().greet("World"));
srcdeps/srcdeps-maven
srcdeps-maven-quickstarts/srcdeps-mvn-git-branch-quickstart/jar/src/test/java/org/srcdeps/quickstarts/mvn/git/branch/AppClientTest.java
// Path: srcdeps-maven-quickstarts/srcdeps-mvn-git-branch-quickstart/jar/src/main/java/org/srcdeps/quickstarts/mvn/git/branch/AppClientImpl.java // public class AppClientImpl { // private final App app = new App(); // // public App getApp() { // return app; // } // }
import org.junit.Assert; import org.junit.Test; import org.srcdeps.quickstarts.mvn.git.branch.AppClientImpl;
/** * Copyright 2015-2018 Maven Source Dependencies * Plugin contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.srcdeps.quickstarts.mvn.git.branch; public class AppClientTest { @Test public void test() {
// Path: srcdeps-maven-quickstarts/srcdeps-mvn-git-branch-quickstart/jar/src/main/java/org/srcdeps/quickstarts/mvn/git/branch/AppClientImpl.java // public class AppClientImpl { // private final App app = new App(); // // public App getApp() { // return app; // } // } // Path: srcdeps-maven-quickstarts/srcdeps-mvn-git-branch-quickstart/jar/src/test/java/org/srcdeps/quickstarts/mvn/git/branch/AppClientTest.java import org.junit.Assert; import org.junit.Test; import org.srcdeps.quickstarts.mvn.git.branch.AppClientImpl; /** * Copyright 2015-2018 Maven Source Dependencies * Plugin contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.srcdeps.quickstarts.mvn.git.branch; public class AppClientTest { @Test public void test() {
Assert.assertEquals("Superior Morning World!", new AppClientImpl().getApp().getMessage());
srcdeps/srcdeps-maven
srcdeps-maven-enforcer/src/main/java/org/srcdeps/mvn/enforcer/SrcdepsEnforcer.java
// Path: srcdeps-maven-base/src/main/java/org/srcdeps/mvn/config/ConfigurationProducer.java // @Named // public class ConfigurationProducer { // // private final Configuration configuration; // private final Path multimoduleProjectRootDirectory; // // public ConfigurationProducer() throws ConfigurationException { // super(); // // String basePathString = System.getProperty(Constants.MAVEN_MULTI_MODULE_PROJECT_DIRECTORY_PROPERTY); // if (basePathString == null || basePathString.isEmpty()) { // throw new RuntimeException(String.format("The system property %s must not be null or empty", // Constants.MAVEN_MULTI_MODULE_PROJECT_DIRECTORY_PROPERTY)); // } // multimoduleProjectRootDirectory = Paths.get(basePathString).toAbsolutePath(); // // this.configuration = new ConfigurationLocator(System.getProperties(), true) // // .locate(multimoduleProjectRootDirectory, new YamlConfigurationReader()) // // .accept(new OverrideVisitor(System.getProperties())) // // .accept(new DefaultsAndInheritanceVisitor()) // // .forwardPropertyValue(Maven.getSrcdepsMavenVersionProperty(), Constants.SRCDEPS_MAVEN_VERSION) // .build(); // // } // // public Configuration getConfiguration() { // return configuration; // } // // /** // * @return the root directory of the Maven multimodule project. // */ // public Path getMultimoduleProjectRootDirectory() { // return multimoduleProjectRootDirectory; // } // // }
import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; import org.apache.maven.artifact.Artifact; import org.apache.maven.execution.ProjectExecutionEvent; import org.apache.maven.execution.ProjectExecutionListener; import org.apache.maven.lifecycle.LifecycleExecutionException; import org.apache.maven.model.Dependency; import org.apache.maven.model.DependencyManagement; import org.apache.maven.model.Profile; import org.apache.maven.plugin.MojoExecution; import org.apache.maven.plugin.descriptor.MojoDescriptor; import org.apache.maven.project.MavenProject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.srcdeps.core.SrcVersion; import org.srcdeps.core.config.Maven; import org.srcdeps.core.config.MavenAssertions; import org.srcdeps.mvn.config.ConfigurationProducer;
for (Entry<Object, Object> prop : properties.entrySet()) { final String key = prop.getKey().toString(); failWithoutProperties.remove(key); final Object val = prop.getValue(); if (val != null) { failWithoutProperties.remove(key + "=" + val.toString()); } } if (!failWithoutProperties.isEmpty()) { return new String[] { "properties missing", failWithoutProperties.toString() }; } return null; } private static void assertNotSrcdeps(List<Dependency> deps, String[] violation) throws LifecycleExecutionException { for (Dependency dep : deps) { assertNotSrcdeps(dep.getGroupId(), dep.getArtifactId(), dep.getVersion(), violation); } } private static void assertNotSrcdeps(String group, String artifact, String version, String[] violation) throws LifecycleExecutionException { if (SrcVersion.isSrcVersion(version)) { throw new LifecycleExecutionException(String.format( "This build was configured to fail if there is a source dependency [%s:%s:%s] and %s [%s]", group, artifact, version, violation[0], violation[1])); } }
// Path: srcdeps-maven-base/src/main/java/org/srcdeps/mvn/config/ConfigurationProducer.java // @Named // public class ConfigurationProducer { // // private final Configuration configuration; // private final Path multimoduleProjectRootDirectory; // // public ConfigurationProducer() throws ConfigurationException { // super(); // // String basePathString = System.getProperty(Constants.MAVEN_MULTI_MODULE_PROJECT_DIRECTORY_PROPERTY); // if (basePathString == null || basePathString.isEmpty()) { // throw new RuntimeException(String.format("The system property %s must not be null or empty", // Constants.MAVEN_MULTI_MODULE_PROJECT_DIRECTORY_PROPERTY)); // } // multimoduleProjectRootDirectory = Paths.get(basePathString).toAbsolutePath(); // // this.configuration = new ConfigurationLocator(System.getProperties(), true) // // .locate(multimoduleProjectRootDirectory, new YamlConfigurationReader()) // // .accept(new OverrideVisitor(System.getProperties())) // // .accept(new DefaultsAndInheritanceVisitor()) // // .forwardPropertyValue(Maven.getSrcdepsMavenVersionProperty(), Constants.SRCDEPS_MAVEN_VERSION) // .build(); // // } // // public Configuration getConfiguration() { // return configuration; // } // // /** // * @return the root directory of the Maven multimodule project. // */ // public Path getMultimoduleProjectRootDirectory() { // return multimoduleProjectRootDirectory; // } // // } // Path: srcdeps-maven-enforcer/src/main/java/org/srcdeps/mvn/enforcer/SrcdepsEnforcer.java import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; import org.apache.maven.artifact.Artifact; import org.apache.maven.execution.ProjectExecutionEvent; import org.apache.maven.execution.ProjectExecutionListener; import org.apache.maven.lifecycle.LifecycleExecutionException; import org.apache.maven.model.Dependency; import org.apache.maven.model.DependencyManagement; import org.apache.maven.model.Profile; import org.apache.maven.plugin.MojoExecution; import org.apache.maven.plugin.descriptor.MojoDescriptor; import org.apache.maven.project.MavenProject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.srcdeps.core.SrcVersion; import org.srcdeps.core.config.Maven; import org.srcdeps.core.config.MavenAssertions; import org.srcdeps.mvn.config.ConfigurationProducer; for (Entry<Object, Object> prop : properties.entrySet()) { final String key = prop.getKey().toString(); failWithoutProperties.remove(key); final Object val = prop.getValue(); if (val != null) { failWithoutProperties.remove(key + "=" + val.toString()); } } if (!failWithoutProperties.isEmpty()) { return new String[] { "properties missing", failWithoutProperties.toString() }; } return null; } private static void assertNotSrcdeps(List<Dependency> deps, String[] violation) throws LifecycleExecutionException { for (Dependency dep : deps) { assertNotSrcdeps(dep.getGroupId(), dep.getArtifactId(), dep.getVersion(), violation); } } private static void assertNotSrcdeps(String group, String artifact, String version, String[] violation) throws LifecycleExecutionException { if (SrcVersion.isSrcVersion(version)) { throw new LifecycleExecutionException(String.format( "This build was configured to fail if there is a source dependency [%s:%s:%s] and %s [%s]", group, artifact, version, violation[0], violation[1])); } }
private final ConfigurationProducer configurationProducer;
srcdeps/srcdeps-maven
srcdeps-maven-quickstarts/srcdeps-mvn-git-profile-and-properties-quickstart/jar/src/test/java/org/srcdeps/quickstarts/mvn/git/prop/profile/GreetingConsumerTest.java
// Path: srcdeps-maven-quickstarts/srcdeps-mvn-git-profile-and-properties-quickstart/jar/src/main/java/org/srcdeps/quickstarts/mvn/git/prop/profile/GreetingConsumer.java // public class GreetingConsumer { // // public String retrieveGreeting() { // return new org.l2x6.maven.srcdeps.itest.api.generated.GeneratedGreeter().getGreeting(); // } // // }
import org.junit.Assert; import org.junit.Test; import org.srcdeps.quickstarts.mvn.git.prop.profile.GreetingConsumer;
/** * Copyright 2015-2016 Maven Source Dependencies * Plugin contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.srcdeps.quickstarts.mvn.git.prop.profile; public class GreetingConsumerTest { @Test public void testGreeting() {
// Path: srcdeps-maven-quickstarts/srcdeps-mvn-git-profile-and-properties-quickstart/jar/src/main/java/org/srcdeps/quickstarts/mvn/git/prop/profile/GreetingConsumer.java // public class GreetingConsumer { // // public String retrieveGreeting() { // return new org.l2x6.maven.srcdeps.itest.api.generated.GeneratedGreeter().getGreeting(); // } // // } // Path: srcdeps-maven-quickstarts/srcdeps-mvn-git-profile-and-properties-quickstart/jar/src/test/java/org/srcdeps/quickstarts/mvn/git/prop/profile/GreetingConsumerTest.java import org.junit.Assert; import org.junit.Test; import org.srcdeps.quickstarts.mvn.git.prop.profile.GreetingConsumer; /** * Copyright 2015-2016 Maven Source Dependencies * Plugin contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.srcdeps.quickstarts.mvn.git.prop.profile; public class GreetingConsumerTest { @Test public void testGreeting() {
Assert.assertEquals("random name KMYTJDb9", new GreetingConsumer().retrieveGreeting());
srcdeps/srcdeps-maven
srcdeps-maven-plugin/src/main/java/org/srcdeps/mvn/plugin/SrcdepsUpgradeMojo.java
// Path: srcdeps-maven-base/src/main/java/org/srcdeps/mvn/Constants.java // public interface Constants { // // /** See the bin/mvn or bin/mvn.cmd script of your maven distro, where maven.multiModuleProjectDirectory is set */ // String MAVEN_MULTI_MODULE_PROJECT_DIRECTORY_PROPERTY = "maven.multiModuleProjectDirectory"; // // String SRCDEPS_MAVEN_VERSION = "4.0.1-SNAPSHOT"; // @srcdeps.version@ // // }
import java.io.File; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerFactoryConfigurationError; import javax.xml.transform.dom.DOMResult; import javax.xml.transform.stream.StreamSource; import org.apache.maven.execution.MavenSession; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugin.logging.Log; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.plugins.annotations.ResolutionScope; import org.apache.xml.serialize.OutputFormat; import org.apache.xml.serialize.XMLSerializer; import org.srcdeps.mvn.Constants; import org.w3c.dom.Document;
/** * Copyright 2015-2018 Maven Source Dependencies * Plugin contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.srcdeps.mvn.plugin; /** * Adds and/or upgrades the srcdeps core extensions in {@code .mvn/extensions.xml} file. If the * {@code .mvn/extensions.xml} does not exist, it creates it from scratch. If the {@code .mvn/extensions.xml} exists, it * adds missing srcdeps core extensions and ensures they have the version specified by {@link #newVersion} parameter. * * @author <a href="https://github.com/ppalaga">Peter Palaga</a> */ @SuppressWarnings("deprecation") @Mojo(name = "up", defaultPhase = LifecyclePhase.NONE, threadSafe = false, requiresProject = true, requiresDependencyResolution = ResolutionScope.NONE) public class SrcdepsUpgradeMojo extends AbstractMojo { protected final File multiModuleRootDir = new File(System.getProperty("user.dir")); protected final Path mvnDir; protected final Path extensionsXmlPath; /** The encoding to use when reading and writing {@code srcdeps.yaml} and {@code extensions.xml} files */ @Parameter(defaultValue = "utf-8", property = "srcdeps.encoding") protected String encoding; public SrcdepsUpgradeMojo() { super(); this.mvnDir = multiModuleRootDir.toPath().resolve(".mvn"); this.extensionsXmlPath = mvnDir.resolve("extensions.xml"); } /** * The version of srcdeps core extensions to add or upgarde to in {@code extensions.xml} file. Default is the * version if the {@code srcdeps-maven-plugin} that runs this mojo. */ @Parameter(property = "srcdeps.newVersion") protected String newVersion; /** The limit for the word wrap in {@code extensions.xml} file */ @Parameter(defaultValue = "128", property = "srcdeps.xmlLineLength") protected int xmlLineLength; /** The number of spaces to use for one level of indentation in {@code extensions.xml} file */ @Parameter(defaultValue = "2", property = "srcdeps.xmlIndentSize") protected int xmlIndentSize; /** * If {@code true} the {@code extensions.xml} file will be indented; otherwise the {@code extensions.xml} file will * not be indented. */ @Parameter(defaultValue = "true", property = "srcdeps.xmlIndent") protected boolean xmlIndent; /** If {@code true} the execution of this mojo will be skipped altogether; otherwise this mojo will be executed. */ @Parameter(defaultValue = "false", property = "srcdeps.skip") protected boolean skip; @Parameter(defaultValue = "${session}") protected MavenSession session; @Override public void execute() throws MojoExecutionException, MojoFailureException { final Log log = getLog(); if (skip) { log.info("srcdeps: ["+ getClass().getSimpleName() + "] skipped per skip parameter"); } else if (!multiModuleRootDir.equals(session.getCurrentProject().getBasedir())) { log.info("srcdeps: ["+ getClass().getSimpleName() + "] skipped because multiModuleRootDir ["+ multiModuleRootDir +"] != current project basedir ["+ session.getCurrentProject().getBasedir() +"]"); } else { if (newVersion == null || newVersion.isEmpty()) {
// Path: srcdeps-maven-base/src/main/java/org/srcdeps/mvn/Constants.java // public interface Constants { // // /** See the bin/mvn or bin/mvn.cmd script of your maven distro, where maven.multiModuleProjectDirectory is set */ // String MAVEN_MULTI_MODULE_PROJECT_DIRECTORY_PROPERTY = "maven.multiModuleProjectDirectory"; // // String SRCDEPS_MAVEN_VERSION = "4.0.1-SNAPSHOT"; // @srcdeps.version@ // // } // Path: srcdeps-maven-plugin/src/main/java/org/srcdeps/mvn/plugin/SrcdepsUpgradeMojo.java import java.io.File; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerFactoryConfigurationError; import javax.xml.transform.dom.DOMResult; import javax.xml.transform.stream.StreamSource; import org.apache.maven.execution.MavenSession; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugin.logging.Log; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.plugins.annotations.ResolutionScope; import org.apache.xml.serialize.OutputFormat; import org.apache.xml.serialize.XMLSerializer; import org.srcdeps.mvn.Constants; import org.w3c.dom.Document; /** * Copyright 2015-2018 Maven Source Dependencies * Plugin contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.srcdeps.mvn.plugin; /** * Adds and/or upgrades the srcdeps core extensions in {@code .mvn/extensions.xml} file. If the * {@code .mvn/extensions.xml} does not exist, it creates it from scratch. If the {@code .mvn/extensions.xml} exists, it * adds missing srcdeps core extensions and ensures they have the version specified by {@link #newVersion} parameter. * * @author <a href="https://github.com/ppalaga">Peter Palaga</a> */ @SuppressWarnings("deprecation") @Mojo(name = "up", defaultPhase = LifecyclePhase.NONE, threadSafe = false, requiresProject = true, requiresDependencyResolution = ResolutionScope.NONE) public class SrcdepsUpgradeMojo extends AbstractMojo { protected final File multiModuleRootDir = new File(System.getProperty("user.dir")); protected final Path mvnDir; protected final Path extensionsXmlPath; /** The encoding to use when reading and writing {@code srcdeps.yaml} and {@code extensions.xml} files */ @Parameter(defaultValue = "utf-8", property = "srcdeps.encoding") protected String encoding; public SrcdepsUpgradeMojo() { super(); this.mvnDir = multiModuleRootDir.toPath().resolve(".mvn"); this.extensionsXmlPath = mvnDir.resolve("extensions.xml"); } /** * The version of srcdeps core extensions to add or upgarde to in {@code extensions.xml} file. Default is the * version if the {@code srcdeps-maven-plugin} that runs this mojo. */ @Parameter(property = "srcdeps.newVersion") protected String newVersion; /** The limit for the word wrap in {@code extensions.xml} file */ @Parameter(defaultValue = "128", property = "srcdeps.xmlLineLength") protected int xmlLineLength; /** The number of spaces to use for one level of indentation in {@code extensions.xml} file */ @Parameter(defaultValue = "2", property = "srcdeps.xmlIndentSize") protected int xmlIndentSize; /** * If {@code true} the {@code extensions.xml} file will be indented; otherwise the {@code extensions.xml} file will * not be indented. */ @Parameter(defaultValue = "true", property = "srcdeps.xmlIndent") protected boolean xmlIndent; /** If {@code true} the execution of this mojo will be skipped altogether; otherwise this mojo will be executed. */ @Parameter(defaultValue = "false", property = "srcdeps.skip") protected boolean skip; @Parameter(defaultValue = "${session}") protected MavenSession session; @Override public void execute() throws MojoExecutionException, MojoFailureException { final Log log = getLog(); if (skip) { log.info("srcdeps: ["+ getClass().getSimpleName() + "] skipped per skip parameter"); } else if (!multiModuleRootDir.equals(session.getCurrentProject().getBasedir())) { log.info("srcdeps: ["+ getClass().getSimpleName() + "] skipped because multiModuleRootDir ["+ multiModuleRootDir +"] != current project basedir ["+ session.getCurrentProject().getBasedir() +"]"); } else { if (newVersion == null || newVersion.isEmpty()) {
newVersion = Constants.SRCDEPS_MAVEN_VERSION;
srcdeps/srcdeps-maven
srcdeps-maven-quickstarts/srcdeps-mvn-git-tag-quickstart/jar/src/test/java/org/srcdeps/quickstarts/mvn/git/revision/AppClientTest.java
// Path: srcdeps-maven-quickstarts/srcdeps-mvn-git-tag-quickstart/jar/src/main/java/org/srcdeps/quickstarts/mvn/git/revision/AppClient.java // public class AppClient { // private final App app = new App(); // // public App getApp() { // return app; // } // }
import org.junit.Assert; import org.junit.Test; import org.srcdeps.quickstarts.mvn.git.revision.AppClient;
/** * Copyright 2015-2016 Maven Source Dependencies * Plugin contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.srcdeps.quickstarts.mvn.git.revision; public class AppClientTest { @Test public void test() {
// Path: srcdeps-maven-quickstarts/srcdeps-mvn-git-tag-quickstart/jar/src/main/java/org/srcdeps/quickstarts/mvn/git/revision/AppClient.java // public class AppClient { // private final App app = new App(); // // public App getApp() { // return app; // } // } // Path: srcdeps-maven-quickstarts/srcdeps-mvn-git-tag-quickstart/jar/src/test/java/org/srcdeps/quickstarts/mvn/git/revision/AppClientTest.java import org.junit.Assert; import org.junit.Test; import org.srcdeps.quickstarts.mvn.git.revision.AppClient; /** * Copyright 2015-2016 Maven Source Dependencies * Plugin contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.srcdeps.quickstarts.mvn.git.revision; public class AppClientTest { @Test public void test() {
Assert.assertEquals("Hello World!", new AppClient().getApp().getMessage());
srcdeps/srcdeps-maven
srcdeps-maven-base/src/main/java/org/srcdeps/mvn/config/ConfigurationProducer.java
// Path: srcdeps-maven-base/src/main/java/org/srcdeps/mvn/Constants.java // public interface Constants { // // /** See the bin/mvn or bin/mvn.cmd script of your maven distro, where maven.multiModuleProjectDirectory is set */ // String MAVEN_MULTI_MODULE_PROJECT_DIRECTORY_PROPERTY = "maven.multiModuleProjectDirectory"; // // String SRCDEPS_MAVEN_VERSION = "4.0.1-SNAPSHOT"; // @srcdeps.version@ // // }
import java.nio.file.Path; import java.nio.file.Paths; import javax.inject.Named; import org.srcdeps.config.yaml.YamlConfigurationReader; import org.srcdeps.core.config.Configuration; import org.srcdeps.core.config.ConfigurationException; import org.srcdeps.core.config.ConfigurationLocator; import org.srcdeps.core.config.Maven; import org.srcdeps.core.config.tree.walk.DefaultsAndInheritanceVisitor; import org.srcdeps.core.config.tree.walk.OverrideVisitor; import org.srcdeps.mvn.Constants;
/** * Copyright 2015-2018 Maven Source Dependencies * Plugin contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.srcdeps.mvn.config; @Named public class ConfigurationProducer { private final Configuration configuration; private final Path multimoduleProjectRootDirectory; public ConfigurationProducer() throws ConfigurationException { super();
// Path: srcdeps-maven-base/src/main/java/org/srcdeps/mvn/Constants.java // public interface Constants { // // /** See the bin/mvn or bin/mvn.cmd script of your maven distro, where maven.multiModuleProjectDirectory is set */ // String MAVEN_MULTI_MODULE_PROJECT_DIRECTORY_PROPERTY = "maven.multiModuleProjectDirectory"; // // String SRCDEPS_MAVEN_VERSION = "4.0.1-SNAPSHOT"; // @srcdeps.version@ // // } // Path: srcdeps-maven-base/src/main/java/org/srcdeps/mvn/config/ConfigurationProducer.java import java.nio.file.Path; import java.nio.file.Paths; import javax.inject.Named; import org.srcdeps.config.yaml.YamlConfigurationReader; import org.srcdeps.core.config.Configuration; import org.srcdeps.core.config.ConfigurationException; import org.srcdeps.core.config.ConfigurationLocator; import org.srcdeps.core.config.Maven; import org.srcdeps.core.config.tree.walk.DefaultsAndInheritanceVisitor; import org.srcdeps.core.config.tree.walk.OverrideVisitor; import org.srcdeps.mvn.Constants; /** * Copyright 2015-2018 Maven Source Dependencies * Plugin contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.srcdeps.mvn.config; @Named public class ConfigurationProducer { private final Configuration configuration; private final Path multimoduleProjectRootDirectory; public ConfigurationProducer() throws ConfigurationException { super();
String basePathString = System.getProperty(Constants.MAVEN_MULTI_MODULE_PROJECT_DIRECTORY_PROPERTY);
cqjjjzr/BiliLiveLib
BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/dispatch/AbstractJSONDispatcher.java
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/Globals.java // public class Globals { // private static final String BILI_PASSPORT_HOST_ROOT = "passport.bilibili.com"; // private static final String BILI_LIVE_HOST_ROOT = "live.bilibili.com"; // @Getter // private static int CONNECTION_ALIVE_TIME_SECOND = 10; // private static Globals instance; // @Getter // private HttpHost biliLiveRoot; // @Getter // private HttpHost biliPassportHttpsRoot; // private ThreadLocal<Gson> gson; // // private HttpClientConnectionManager connectionPool; // @Getter // private SSLContext bilibiliSSLContext; // // public static Globals get() { // if (instance == null) { // instance = new Globals(); // instance.init(); // } // return instance; // } // // private void init() { // biliLiveRoot = new HttpHost(BILI_LIVE_HOST_ROOT); // //Visit bilibili passport via https. 443 is the https port. // biliPassportHttpsRoot = new HttpHost(BILI_PASSPORT_HOST_ROOT, 443, "https"); // gson = ThreadLocal.withInitial(() -> new GsonBuilder() // .setLenient() // .create()); // // try { // bilibiliSSLContext = SSLContextBuilder.create() // .loadTrustMaterial(new BilibiliTrustStrategy()) // .build(); // } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) { // throw new AssertionError("failed initializing bilibili ssl context!"); // } // } // // public Gson gson() { // return gson.get(); // } // // public HttpClientConnectionManager getConnectionPool() { // if (connectionPool == null) { // reInitializeConnectionPool(); // } // return connectionPool; // } // // public void reInitializeConnectionPool() { // connectionPool = new PoolingHttpClientConnectionManager(CONNECTION_ALIVE_TIME_SECOND, TimeUnit.SECONDS); // } // // public void setConnectionAliveTimeSecond(int connectionAliveTimeSecond) { // CONNECTION_ALIVE_TIME_SECOND = connectionAliveTimeSecond; // reInitializeConnectionPool(); // } // // // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuListener.java // public interface DanmakuListener { // void danmakuEvent(@NotNull DanmakuEvent event); // // void watcherCountEvent(@NotNull DanmakuEvent event); // // void errorEvent(@NotNull DanmakuEvent event); // // void startStopEvent(@NotNull DanmakuEvent event); // // void statusEvent(@NotNull DanmakuEvent event); // // void welcomeVipEvent(@NotNull DanmakuEvent event); // // void giveGiftEvent(@NotNull DanmakuEvent event); // // void globalGiftEvent(@NotNull DanmakuEvent event); // // void globalAnnounceEvent(@NotNull DanmakuEvent event); // }
import charlie.bililivelib.Globals; import charlie.bililivelib.danmaku.event.DanmakuListener; import com.google.gson.JsonObject; import org.jetbrains.annotations.Contract; import java.util.List;
package charlie.bililivelib.danmaku.dispatch; /** * 对{@link Dispatcher}的抽象实现,用于事件内容是JSON文本时的处理。 */ public abstract class AbstractJSONDispatcher implements Dispatcher { /** * 获取可以接受的事件命令。 * * @return 事件命令列表 */ protected abstract String[] getAcceptableCommands(); @Contract(pure = true) private boolean isValid(String body) { return body.startsWith("{"); } private boolean checkCanDispatch(JsonObject rootObject) { String command = getCommand(rootObject); if (command == null) return false; for (String acceptable : getAcceptableCommands()) { if (command.equals(acceptable)) return true; } return false; } /** * 检查指定事件是否为JSON对象,且是否能被本监听器处理。 * 如果可以则交由{@link AbstractJSONDispatcher#dispatch(List, JsonObject, Object)}进行分发。 * @param listeners 监听器列表 * @param body 事件内容 * @param source 事件发生源 */ @Override
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/Globals.java // public class Globals { // private static final String BILI_PASSPORT_HOST_ROOT = "passport.bilibili.com"; // private static final String BILI_LIVE_HOST_ROOT = "live.bilibili.com"; // @Getter // private static int CONNECTION_ALIVE_TIME_SECOND = 10; // private static Globals instance; // @Getter // private HttpHost biliLiveRoot; // @Getter // private HttpHost biliPassportHttpsRoot; // private ThreadLocal<Gson> gson; // // private HttpClientConnectionManager connectionPool; // @Getter // private SSLContext bilibiliSSLContext; // // public static Globals get() { // if (instance == null) { // instance = new Globals(); // instance.init(); // } // return instance; // } // // private void init() { // biliLiveRoot = new HttpHost(BILI_LIVE_HOST_ROOT); // //Visit bilibili passport via https. 443 is the https port. // biliPassportHttpsRoot = new HttpHost(BILI_PASSPORT_HOST_ROOT, 443, "https"); // gson = ThreadLocal.withInitial(() -> new GsonBuilder() // .setLenient() // .create()); // // try { // bilibiliSSLContext = SSLContextBuilder.create() // .loadTrustMaterial(new BilibiliTrustStrategy()) // .build(); // } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) { // throw new AssertionError("failed initializing bilibili ssl context!"); // } // } // // public Gson gson() { // return gson.get(); // } // // public HttpClientConnectionManager getConnectionPool() { // if (connectionPool == null) { // reInitializeConnectionPool(); // } // return connectionPool; // } // // public void reInitializeConnectionPool() { // connectionPool = new PoolingHttpClientConnectionManager(CONNECTION_ALIVE_TIME_SECOND, TimeUnit.SECONDS); // } // // public void setConnectionAliveTimeSecond(int connectionAliveTimeSecond) { // CONNECTION_ALIVE_TIME_SECOND = connectionAliveTimeSecond; // reInitializeConnectionPool(); // } // // // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuListener.java // public interface DanmakuListener { // void danmakuEvent(@NotNull DanmakuEvent event); // // void watcherCountEvent(@NotNull DanmakuEvent event); // // void errorEvent(@NotNull DanmakuEvent event); // // void startStopEvent(@NotNull DanmakuEvent event); // // void statusEvent(@NotNull DanmakuEvent event); // // void welcomeVipEvent(@NotNull DanmakuEvent event); // // void giveGiftEvent(@NotNull DanmakuEvent event); // // void globalGiftEvent(@NotNull DanmakuEvent event); // // void globalAnnounceEvent(@NotNull DanmakuEvent event); // } // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/dispatch/AbstractJSONDispatcher.java import charlie.bililivelib.Globals; import charlie.bililivelib.danmaku.event.DanmakuListener; import com.google.gson.JsonObject; import org.jetbrains.annotations.Contract; import java.util.List; package charlie.bililivelib.danmaku.dispatch; /** * 对{@link Dispatcher}的抽象实现,用于事件内容是JSON文本时的处理。 */ public abstract class AbstractJSONDispatcher implements Dispatcher { /** * 获取可以接受的事件命令。 * * @return 事件命令列表 */ protected abstract String[] getAcceptableCommands(); @Contract(pure = true) private boolean isValid(String body) { return body.startsWith("{"); } private boolean checkCanDispatch(JsonObject rootObject) { String command = getCommand(rootObject); if (command == null) return false; for (String acceptable : getAcceptableCommands()) { if (command.equals(acceptable)) return true; } return false; } /** * 检查指定事件是否为JSON对象,且是否能被本监听器处理。 * 如果可以则交由{@link AbstractJSONDispatcher#dispatch(List, JsonObject, Object)}进行分发。 * @param listeners 监听器列表 * @param body 事件内容 * @param source 事件发生源 */ @Override
public void tryDispatch(List<DanmakuListener> listeners, String body, Object source) {
cqjjjzr/BiliLiveLib
BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/dispatch/AbstractJSONDispatcher.java
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/Globals.java // public class Globals { // private static final String BILI_PASSPORT_HOST_ROOT = "passport.bilibili.com"; // private static final String BILI_LIVE_HOST_ROOT = "live.bilibili.com"; // @Getter // private static int CONNECTION_ALIVE_TIME_SECOND = 10; // private static Globals instance; // @Getter // private HttpHost biliLiveRoot; // @Getter // private HttpHost biliPassportHttpsRoot; // private ThreadLocal<Gson> gson; // // private HttpClientConnectionManager connectionPool; // @Getter // private SSLContext bilibiliSSLContext; // // public static Globals get() { // if (instance == null) { // instance = new Globals(); // instance.init(); // } // return instance; // } // // private void init() { // biliLiveRoot = new HttpHost(BILI_LIVE_HOST_ROOT); // //Visit bilibili passport via https. 443 is the https port. // biliPassportHttpsRoot = new HttpHost(BILI_PASSPORT_HOST_ROOT, 443, "https"); // gson = ThreadLocal.withInitial(() -> new GsonBuilder() // .setLenient() // .create()); // // try { // bilibiliSSLContext = SSLContextBuilder.create() // .loadTrustMaterial(new BilibiliTrustStrategy()) // .build(); // } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) { // throw new AssertionError("failed initializing bilibili ssl context!"); // } // } // // public Gson gson() { // return gson.get(); // } // // public HttpClientConnectionManager getConnectionPool() { // if (connectionPool == null) { // reInitializeConnectionPool(); // } // return connectionPool; // } // // public void reInitializeConnectionPool() { // connectionPool = new PoolingHttpClientConnectionManager(CONNECTION_ALIVE_TIME_SECOND, TimeUnit.SECONDS); // } // // public void setConnectionAliveTimeSecond(int connectionAliveTimeSecond) { // CONNECTION_ALIVE_TIME_SECOND = connectionAliveTimeSecond; // reInitializeConnectionPool(); // } // // // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuListener.java // public interface DanmakuListener { // void danmakuEvent(@NotNull DanmakuEvent event); // // void watcherCountEvent(@NotNull DanmakuEvent event); // // void errorEvent(@NotNull DanmakuEvent event); // // void startStopEvent(@NotNull DanmakuEvent event); // // void statusEvent(@NotNull DanmakuEvent event); // // void welcomeVipEvent(@NotNull DanmakuEvent event); // // void giveGiftEvent(@NotNull DanmakuEvent event); // // void globalGiftEvent(@NotNull DanmakuEvent event); // // void globalAnnounceEvent(@NotNull DanmakuEvent event); // }
import charlie.bililivelib.Globals; import charlie.bililivelib.danmaku.event.DanmakuListener; import com.google.gson.JsonObject; import org.jetbrains.annotations.Contract; import java.util.List;
package charlie.bililivelib.danmaku.dispatch; /** * 对{@link Dispatcher}的抽象实现,用于事件内容是JSON文本时的处理。 */ public abstract class AbstractJSONDispatcher implements Dispatcher { /** * 获取可以接受的事件命令。 * * @return 事件命令列表 */ protected abstract String[] getAcceptableCommands(); @Contract(pure = true) private boolean isValid(String body) { return body.startsWith("{"); } private boolean checkCanDispatch(JsonObject rootObject) { String command = getCommand(rootObject); if (command == null) return false; for (String acceptable : getAcceptableCommands()) { if (command.equals(acceptable)) return true; } return false; } /** * 检查指定事件是否为JSON对象,且是否能被本监听器处理。 * 如果可以则交由{@link AbstractJSONDispatcher#dispatch(List, JsonObject, Object)}进行分发。 * @param listeners 监听器列表 * @param body 事件内容 * @param source 事件发生源 */ @Override public void tryDispatch(List<DanmakuListener> listeners, String body, Object source) { if (!isValid(body)) return;
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/Globals.java // public class Globals { // private static final String BILI_PASSPORT_HOST_ROOT = "passport.bilibili.com"; // private static final String BILI_LIVE_HOST_ROOT = "live.bilibili.com"; // @Getter // private static int CONNECTION_ALIVE_TIME_SECOND = 10; // private static Globals instance; // @Getter // private HttpHost biliLiveRoot; // @Getter // private HttpHost biliPassportHttpsRoot; // private ThreadLocal<Gson> gson; // // private HttpClientConnectionManager connectionPool; // @Getter // private SSLContext bilibiliSSLContext; // // public static Globals get() { // if (instance == null) { // instance = new Globals(); // instance.init(); // } // return instance; // } // // private void init() { // biliLiveRoot = new HttpHost(BILI_LIVE_HOST_ROOT); // //Visit bilibili passport via https. 443 is the https port. // biliPassportHttpsRoot = new HttpHost(BILI_PASSPORT_HOST_ROOT, 443, "https"); // gson = ThreadLocal.withInitial(() -> new GsonBuilder() // .setLenient() // .create()); // // try { // bilibiliSSLContext = SSLContextBuilder.create() // .loadTrustMaterial(new BilibiliTrustStrategy()) // .build(); // } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) { // throw new AssertionError("failed initializing bilibili ssl context!"); // } // } // // public Gson gson() { // return gson.get(); // } // // public HttpClientConnectionManager getConnectionPool() { // if (connectionPool == null) { // reInitializeConnectionPool(); // } // return connectionPool; // } // // public void reInitializeConnectionPool() { // connectionPool = new PoolingHttpClientConnectionManager(CONNECTION_ALIVE_TIME_SECOND, TimeUnit.SECONDS); // } // // public void setConnectionAliveTimeSecond(int connectionAliveTimeSecond) { // CONNECTION_ALIVE_TIME_SECOND = connectionAliveTimeSecond; // reInitializeConnectionPool(); // } // // // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuListener.java // public interface DanmakuListener { // void danmakuEvent(@NotNull DanmakuEvent event); // // void watcherCountEvent(@NotNull DanmakuEvent event); // // void errorEvent(@NotNull DanmakuEvent event); // // void startStopEvent(@NotNull DanmakuEvent event); // // void statusEvent(@NotNull DanmakuEvent event); // // void welcomeVipEvent(@NotNull DanmakuEvent event); // // void giveGiftEvent(@NotNull DanmakuEvent event); // // void globalGiftEvent(@NotNull DanmakuEvent event); // // void globalAnnounceEvent(@NotNull DanmakuEvent event); // } // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/dispatch/AbstractJSONDispatcher.java import charlie.bililivelib.Globals; import charlie.bililivelib.danmaku.event.DanmakuListener; import com.google.gson.JsonObject; import org.jetbrains.annotations.Contract; import java.util.List; package charlie.bililivelib.danmaku.dispatch; /** * 对{@link Dispatcher}的抽象实现,用于事件内容是JSON文本时的处理。 */ public abstract class AbstractJSONDispatcher implements Dispatcher { /** * 获取可以接受的事件命令。 * * @return 事件命令列表 */ protected abstract String[] getAcceptableCommands(); @Contract(pure = true) private boolean isValid(String body) { return body.startsWith("{"); } private boolean checkCanDispatch(JsonObject rootObject) { String command = getCommand(rootObject); if (command == null) return false; for (String acceptable : getAcceptableCommands()) { if (command.equals(acceptable)) return true; } return false; } /** * 检查指定事件是否为JSON对象,且是否能被本监听器处理。 * 如果可以则交由{@link AbstractJSONDispatcher#dispatch(List, JsonObject, Object)}进行分发。 * @param listeners 监听器列表 * @param body 事件内容 * @param source 事件发生源 */ @Override public void tryDispatch(List<DanmakuListener> listeners, String body, Object source) { if (!isValid(body)) return;
JsonObject rootObject = Globals.get().gson().fromJson(body, JsonObject.class);
cqjjjzr/BiliLiveLib
BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/datamodel/UserGuardLevel.java
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/I18n.java // public class I18n { // public static final String BUNDLE_NAME = "BiliLiveLib"; // private static Map<String, String> strings; // // static { // init(); // } // // /** // * 重新依照当前Locale获取并填充本地化字符串。在切换Locale后调用。 // */ // public static void init() { // strings = new HashMap<>(); // fillResourceBundle(); // } // // private static void fillResourceBundle() { // ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE_NAME); // for (String key : resourceBundle.keySet()) { // strings.put(key, resourceBundle.getString(key)); // } // } // // /** // * 获取给定Key的本地化文本。 // * @param key 键 // * @return 本地化文本 // */ // @Nls // public static String getString(@NonNls @NotNull String key) { // return strings.get(key); // } // // /** // * 获取基于给定Key的本地化格式化文本。 // * @param key 指向格式化模式的键 // * @param arguments 格式化文本的参数 // * @return 本地化并格式化后的文本 // */ // @NotNull // public static String format(@NonNls @NotNull String key, // @NonNls @NotNull Object... arguments) { // return MessageFormat.format(strings.get(key), arguments); // } // }
import charlie.bililivelib.I18n; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.Nullable;
package charlie.bililivelib.danmaku.datamodel; /** * 标志一个用户的管理员等级。 * * @author Charlie Jiang * @since rv1 */ public enum UserGuardLevel { DEFAULT, GUARD, MASTER; @Nullable @Contract(pure = true) public static UserGuardLevel fromLevel(int level) { if (level < 0 || level > UserGuardLevel.values().length) { return null; } return UserGuardLevel.values()[level]; } public String getDisplayString() {
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/I18n.java // public class I18n { // public static final String BUNDLE_NAME = "BiliLiveLib"; // private static Map<String, String> strings; // // static { // init(); // } // // /** // * 重新依照当前Locale获取并填充本地化字符串。在切换Locale后调用。 // */ // public static void init() { // strings = new HashMap<>(); // fillResourceBundle(); // } // // private static void fillResourceBundle() { // ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE_NAME); // for (String key : resourceBundle.keySet()) { // strings.put(key, resourceBundle.getString(key)); // } // } // // /** // * 获取给定Key的本地化文本。 // * @param key 键 // * @return 本地化文本 // */ // @Nls // public static String getString(@NonNls @NotNull String key) { // return strings.get(key); // } // // /** // * 获取基于给定Key的本地化格式化文本。 // * @param key 指向格式化模式的键 // * @param arguments 格式化文本的参数 // * @return 本地化并格式化后的文本 // */ // @NotNull // public static String format(@NonNls @NotNull String key, // @NonNls @NotNull Object... arguments) { // return MessageFormat.format(strings.get(key), arguments); // } // } // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/datamodel/UserGuardLevel.java import charlie.bililivelib.I18n; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.Nullable; package charlie.bililivelib.danmaku.datamodel; /** * 标志一个用户的管理员等级。 * * @author Charlie Jiang * @since rv1 */ public enum UserGuardLevel { DEFAULT, GUARD, MASTER; @Nullable @Contract(pure = true) public static UserGuardLevel fromLevel(int level) { if (level < 0 || level > UserGuardLevel.values().length) { return null; } return UserGuardLevel.values()[level]; } public String getDisplayString() {
return I18n.getString("user.guard_level_" + this.name().toLowerCase());
cqjjjzr/BiliLiveLib
BiliLiveLib/src/test/java/charlie/bililivelib/freesilver/FreeSilverProtocolTest.java
// Path: BiliLiveLib/src/test/java/charlie/bililivelib/LogUtil.java // public class LogUtil { // private static final String LINE_BREAKING = System.lineSeparator(); // // private static Logger logger; // // public static void init() { // logger = LogManager.getLogger(BiliLiveLib.class); // } // // public static synchronized void logException(Level level, @NotNull @Nls String message, @NotNull Throwable ex) { // if (logger == null) return; // logger.log(level, message); // StringTokenizer tokenizer = getStackTrace(ex); // while(tokenizer.hasMoreTokens()) { // logger.log(level, tokenizer.nextToken()); // } // } // // private static StringTokenizer getStackTrace(Throwable ex) { // ByteArrayOutputStream temp = new ByteArrayOutputStream(); // ex.printStackTrace(new PrintStream(temp)); // String stackTrace = new String(temp.toByteArray()); // return new StringTokenizer(stackTrace, LINE_BREAKING); // } // // @Contract(pure = true) // private static Logger logger() { // return logger; // } // } // // Path: BiliLiveLib/src/test/java/charlie/bililivelib/TestSessionHelper.java // public static Session initSession() throws IOException, BiliLiveException { // BasicCookieStore store = new BasicCookieStore(); // Session session = new Session(HttpClientBuilder.create() // .setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.96 Safari/537.36") // .setConnectionManager(Globals.get().getConnectionPool()) // .setSSLContext(Globals.get().getBilibiliSSLContext()) // .setDefaultCookieStore(store).build(), store); // Path cookieFile = Paths.get("cookies.bin"); // if (Files.exists(cookieFile)) { // loadSessionFromFile(session); // } else { // login(session); // Files.createFile(cookieFile); // } // // ObjectOutputStream stream = new ObjectOutputStream(Files.newOutputStream(cookieFile, StandardOpenOption.TRUNCATE_EXISTING)); // stream.writeObject(store); // stream.close(); // return session; // }
import charlie.bililivelib.LogUtil; import org.junit.BeforeClass; import org.junit.Test; import static charlie.bililivelib.TestSessionHelper.initSession; import static org.junit.Assert.fail;
package charlie.bililivelib.freesilver; public class FreeSilverProtocolTest { @BeforeClass public static void setUp() throws Exception {
// Path: BiliLiveLib/src/test/java/charlie/bililivelib/LogUtil.java // public class LogUtil { // private static final String LINE_BREAKING = System.lineSeparator(); // // private static Logger logger; // // public static void init() { // logger = LogManager.getLogger(BiliLiveLib.class); // } // // public static synchronized void logException(Level level, @NotNull @Nls String message, @NotNull Throwable ex) { // if (logger == null) return; // logger.log(level, message); // StringTokenizer tokenizer = getStackTrace(ex); // while(tokenizer.hasMoreTokens()) { // logger.log(level, tokenizer.nextToken()); // } // } // // private static StringTokenizer getStackTrace(Throwable ex) { // ByteArrayOutputStream temp = new ByteArrayOutputStream(); // ex.printStackTrace(new PrintStream(temp)); // String stackTrace = new String(temp.toByteArray()); // return new StringTokenizer(stackTrace, LINE_BREAKING); // } // // @Contract(pure = true) // private static Logger logger() { // return logger; // } // } // // Path: BiliLiveLib/src/test/java/charlie/bililivelib/TestSessionHelper.java // public static Session initSession() throws IOException, BiliLiveException { // BasicCookieStore store = new BasicCookieStore(); // Session session = new Session(HttpClientBuilder.create() // .setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.96 Safari/537.36") // .setConnectionManager(Globals.get().getConnectionPool()) // .setSSLContext(Globals.get().getBilibiliSSLContext()) // .setDefaultCookieStore(store).build(), store); // Path cookieFile = Paths.get("cookies.bin"); // if (Files.exists(cookieFile)) { // loadSessionFromFile(session); // } else { // login(session); // Files.createFile(cookieFile); // } // // ObjectOutputStream stream = new ObjectOutputStream(Files.newOutputStream(cookieFile, StandardOpenOption.TRUNCATE_EXISTING)); // stream.writeObject(store); // stream.close(); // return session; // } // Path: BiliLiveLib/src/test/java/charlie/bililivelib/freesilver/FreeSilverProtocolTest.java import charlie.bililivelib.LogUtil; import org.junit.BeforeClass; import org.junit.Test; import static charlie.bililivelib.TestSessionHelper.initSession; import static org.junit.Assert.fail; package charlie.bililivelib.freesilver; public class FreeSilverProtocolTest { @BeforeClass public static void setUp() throws Exception {
LogUtil.init();
cqjjjzr/BiliLiveLib
BiliLiveLib/src/test/java/charlie/bililivelib/freesilver/FreeSilverProtocolTest.java
// Path: BiliLiveLib/src/test/java/charlie/bililivelib/LogUtil.java // public class LogUtil { // private static final String LINE_BREAKING = System.lineSeparator(); // // private static Logger logger; // // public static void init() { // logger = LogManager.getLogger(BiliLiveLib.class); // } // // public static synchronized void logException(Level level, @NotNull @Nls String message, @NotNull Throwable ex) { // if (logger == null) return; // logger.log(level, message); // StringTokenizer tokenizer = getStackTrace(ex); // while(tokenizer.hasMoreTokens()) { // logger.log(level, tokenizer.nextToken()); // } // } // // private static StringTokenizer getStackTrace(Throwable ex) { // ByteArrayOutputStream temp = new ByteArrayOutputStream(); // ex.printStackTrace(new PrintStream(temp)); // String stackTrace = new String(temp.toByteArray()); // return new StringTokenizer(stackTrace, LINE_BREAKING); // } // // @Contract(pure = true) // private static Logger logger() { // return logger; // } // } // // Path: BiliLiveLib/src/test/java/charlie/bililivelib/TestSessionHelper.java // public static Session initSession() throws IOException, BiliLiveException { // BasicCookieStore store = new BasicCookieStore(); // Session session = new Session(HttpClientBuilder.create() // .setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.96 Safari/537.36") // .setConnectionManager(Globals.get().getConnectionPool()) // .setSSLContext(Globals.get().getBilibiliSSLContext()) // .setDefaultCookieStore(store).build(), store); // Path cookieFile = Paths.get("cookies.bin"); // if (Files.exists(cookieFile)) { // loadSessionFromFile(session); // } else { // login(session); // Files.createFile(cookieFile); // } // // ObjectOutputStream stream = new ObjectOutputStream(Files.newOutputStream(cookieFile, StandardOpenOption.TRUNCATE_EXISTING)); // stream.writeObject(store); // stream.close(); // return session; // }
import charlie.bililivelib.LogUtil; import org.junit.BeforeClass; import org.junit.Test; import static charlie.bililivelib.TestSessionHelper.initSession; import static org.junit.Assert.fail;
package charlie.bililivelib.freesilver; public class FreeSilverProtocolTest { @BeforeClass public static void setUp() throws Exception { LogUtil.init(); } @Test public void waitToGetSilver() throws Exception {
// Path: BiliLiveLib/src/test/java/charlie/bililivelib/LogUtil.java // public class LogUtil { // private static final String LINE_BREAKING = System.lineSeparator(); // // private static Logger logger; // // public static void init() { // logger = LogManager.getLogger(BiliLiveLib.class); // } // // public static synchronized void logException(Level level, @NotNull @Nls String message, @NotNull Throwable ex) { // if (logger == null) return; // logger.log(level, message); // StringTokenizer tokenizer = getStackTrace(ex); // while(tokenizer.hasMoreTokens()) { // logger.log(level, tokenizer.nextToken()); // } // } // // private static StringTokenizer getStackTrace(Throwable ex) { // ByteArrayOutputStream temp = new ByteArrayOutputStream(); // ex.printStackTrace(new PrintStream(temp)); // String stackTrace = new String(temp.toByteArray()); // return new StringTokenizer(stackTrace, LINE_BREAKING); // } // // @Contract(pure = true) // private static Logger logger() { // return logger; // } // } // // Path: BiliLiveLib/src/test/java/charlie/bililivelib/TestSessionHelper.java // public static Session initSession() throws IOException, BiliLiveException { // BasicCookieStore store = new BasicCookieStore(); // Session session = new Session(HttpClientBuilder.create() // .setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.96 Safari/537.36") // .setConnectionManager(Globals.get().getConnectionPool()) // .setSSLContext(Globals.get().getBilibiliSSLContext()) // .setDefaultCookieStore(store).build(), store); // Path cookieFile = Paths.get("cookies.bin"); // if (Files.exists(cookieFile)) { // loadSessionFromFile(session); // } else { // login(session); // Files.createFile(cookieFile); // } // // ObjectOutputStream stream = new ObjectOutputStream(Files.newOutputStream(cookieFile, StandardOpenOption.TRUNCATE_EXISTING)); // stream.writeObject(store); // stream.close(); // return session; // } // Path: BiliLiveLib/src/test/java/charlie/bililivelib/freesilver/FreeSilverProtocolTest.java import charlie.bililivelib.LogUtil; import org.junit.BeforeClass; import org.junit.Test; import static charlie.bililivelib.TestSessionHelper.initSession; import static org.junit.Assert.fail; package charlie.bililivelib.freesilver; public class FreeSilverProtocolTest { @BeforeClass public static void setUp() throws Exception { LogUtil.init(); } @Test public void waitToGetSilver() throws Exception {
FreeSilverProtocol protocol = new FreeSilverProtocol(initSession());
cqjjjzr/BiliLiveLib
BiliLiveLib/src/main/java/charlie/bililivelib/smalltv/SmallTVReward.java
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/I18n.java // public class I18n { // public static final String BUNDLE_NAME = "BiliLiveLib"; // private static Map<String, String> strings; // // static { // init(); // } // // /** // * 重新依照当前Locale获取并填充本地化字符串。在切换Locale后调用。 // */ // public static void init() { // strings = new HashMap<>(); // fillResourceBundle(); // } // // private static void fillResourceBundle() { // ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE_NAME); // for (String key : resourceBundle.keySet()) { // strings.put(key, resourceBundle.getString(key)); // } // } // // /** // * 获取给定Key的本地化文本。 // * @param key 键 // * @return 本地化文本 // */ // @Nls // public static String getString(@NonNls @NotNull String key) { // return strings.get(key); // } // // /** // * 获取基于给定Key的本地化格式化文本。 // * @param key 指向格式化模式的键 // * @param arguments 格式化文本的参数 // * @return 本地化并格式化后的文本 // */ // @NotNull // public static String format(@NonNls @NotNull String key, // @NonNls @NotNull Object... arguments) { // return MessageFormat.format(strings.get(key), arguments); // } // }
import charlie.bililivelib.I18n; import com.google.gson.annotations.SerializedName; import lombok.AccessLevel; import lombok.Data; import lombok.Getter; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable;
public Kind getKind() { return Kind.forID(id); } public enum Kind { SMALL_TV(1), BLUE_WHITE_PANTS(2), B_KELA(3), NYA_NIANG(4), BENTO(5), SLIVER(6), HOT_STRIP(7), UNKNOWN(-1); @Getter private int id; Kind(int id) { this.id = id; } @NotNull @Contract(pure = true) public static Kind forID(int id) { for (Kind reward : Kind.values()) { if (reward.getId() == id) return reward; } return UNKNOWN; } public String getDisplayName() {
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/I18n.java // public class I18n { // public static final String BUNDLE_NAME = "BiliLiveLib"; // private static Map<String, String> strings; // // static { // init(); // } // // /** // * 重新依照当前Locale获取并填充本地化字符串。在切换Locale后调用。 // */ // public static void init() { // strings = new HashMap<>(); // fillResourceBundle(); // } // // private static void fillResourceBundle() { // ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE_NAME); // for (String key : resourceBundle.keySet()) { // strings.put(key, resourceBundle.getString(key)); // } // } // // /** // * 获取给定Key的本地化文本。 // * @param key 键 // * @return 本地化文本 // */ // @Nls // public static String getString(@NonNls @NotNull String key) { // return strings.get(key); // } // // /** // * 获取基于给定Key的本地化格式化文本。 // * @param key 指向格式化模式的键 // * @param arguments 格式化文本的参数 // * @return 本地化并格式化后的文本 // */ // @NotNull // public static String format(@NonNls @NotNull String key, // @NonNls @NotNull Object... arguments) { // return MessageFormat.format(strings.get(key), arguments); // } // } // Path: BiliLiveLib/src/main/java/charlie/bililivelib/smalltv/SmallTVReward.java import charlie.bililivelib.I18n; import com.google.gson.annotations.SerializedName; import lombok.AccessLevel; import lombok.Data; import lombok.Getter; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public Kind getKind() { return Kind.forID(id); } public enum Kind { SMALL_TV(1), BLUE_WHITE_PANTS(2), B_KELA(3), NYA_NIANG(4), BENTO(5), SLIVER(6), HOT_STRIP(7), UNKNOWN(-1); @Getter private int id; Kind(int id) { this.id = id; } @NotNull @Contract(pure = true) public static Kind forID(int id) { for (Kind reward : Kind.values()) { if (reward.getId() == id) return reward; } return UNKNOWN; } public String getDisplayName() {
return I18n.getString("smalltv.reward." + name().toLowerCase());
cqjjjzr/BiliLiveLib
BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/dispatch/DispatchManager.java
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuEvent.java // @Getter // public class DanmakuEvent extends EventObject { // private Kind kind; // private Object param; // // /** // * Constructs a prototypical Event. // * // * @param source The object on which the Event initially occurred. // * @throws IllegalArgumentException if source is null. // */ // public DanmakuEvent(Object source) { // super(source); // } // // public DanmakuEvent(Object source, Object param, Kind kind) { // super(source); // this.kind = kind; // this.param = param; // } // // public enum Kind { // JOINED, ERROR, ERROR_DOWN, NEW_DANMAKU, WATCHER_COUNT, // START_STOP, WELCOME_VIP, GIVE_GIFT, GLOBAL_GIFT, GLOBAL_ANNOUNCE // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuListener.java // public interface DanmakuListener { // void danmakuEvent(@NotNull DanmakuEvent event); // // void watcherCountEvent(@NotNull DanmakuEvent event); // // void errorEvent(@NotNull DanmakuEvent event); // // void startStopEvent(@NotNull DanmakuEvent event); // // void statusEvent(@NotNull DanmakuEvent event); // // void welcomeVipEvent(@NotNull DanmakuEvent event); // // void giveGiftEvent(@NotNull DanmakuEvent event); // // void globalGiftEvent(@NotNull DanmakuEvent event); // // void globalAnnounceEvent(@NotNull DanmakuEvent event); // }
import charlie.bililivelib.danmaku.event.DanmakuEvent; import charlie.bililivelib.danmaku.event.DanmakuListener; import org.jetbrains.annotations.NotNull; import java.util.LinkedList; import java.util.List;
package charlie.bililivelib.danmaku.dispatch; /** * 用于管理分发器的管理器。 * * @author Charlie Jiang * @since rv1 */ public class DispatchManager { private List<Dispatcher> dispatchers = new LinkedList<>(); /** * 注册新的分发器。 * @param dispatcher 分发器 */ public void registerDispatcher(@NotNull Dispatcher dispatcher) { dispatchers.add(dispatcher); } /** * 注销指定分发器。 * @param dispatcher 分发器 */ public void unregisterDispatcher(@NotNull Dispatcher dispatcher) { dispatchers.remove(dispatcher); } /** * 尝试分发信息。 * @param listeners 监听器列表 * @param body 信息体 * @param source 事件源 */
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuEvent.java // @Getter // public class DanmakuEvent extends EventObject { // private Kind kind; // private Object param; // // /** // * Constructs a prototypical Event. // * // * @param source The object on which the Event initially occurred. // * @throws IllegalArgumentException if source is null. // */ // public DanmakuEvent(Object source) { // super(source); // } // // public DanmakuEvent(Object source, Object param, Kind kind) { // super(source); // this.kind = kind; // this.param = param; // } // // public enum Kind { // JOINED, ERROR, ERROR_DOWN, NEW_DANMAKU, WATCHER_COUNT, // START_STOP, WELCOME_VIP, GIVE_GIFT, GLOBAL_GIFT, GLOBAL_ANNOUNCE // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuListener.java // public interface DanmakuListener { // void danmakuEvent(@NotNull DanmakuEvent event); // // void watcherCountEvent(@NotNull DanmakuEvent event); // // void errorEvent(@NotNull DanmakuEvent event); // // void startStopEvent(@NotNull DanmakuEvent event); // // void statusEvent(@NotNull DanmakuEvent event); // // void welcomeVipEvent(@NotNull DanmakuEvent event); // // void giveGiftEvent(@NotNull DanmakuEvent event); // // void globalGiftEvent(@NotNull DanmakuEvent event); // // void globalAnnounceEvent(@NotNull DanmakuEvent event); // } // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/dispatch/DispatchManager.java import charlie.bililivelib.danmaku.event.DanmakuEvent; import charlie.bililivelib.danmaku.event.DanmakuListener; import org.jetbrains.annotations.NotNull; import java.util.LinkedList; import java.util.List; package charlie.bililivelib.danmaku.dispatch; /** * 用于管理分发器的管理器。 * * @author Charlie Jiang * @since rv1 */ public class DispatchManager { private List<Dispatcher> dispatchers = new LinkedList<>(); /** * 注册新的分发器。 * @param dispatcher 分发器 */ public void registerDispatcher(@NotNull Dispatcher dispatcher) { dispatchers.add(dispatcher); } /** * 注销指定分发器。 * @param dispatcher 分发器 */ public void unregisterDispatcher(@NotNull Dispatcher dispatcher) { dispatchers.remove(dispatcher); } /** * 尝试分发信息。 * @param listeners 监听器列表 * @param body 信息体 * @param source 事件源 */
public void dispatch(@NotNull List<DanmakuListener> listeners, @NotNull String body, @NotNull Object source) {
cqjjjzr/BiliLiveLib
BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/dispatch/DispatchManager.java
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuEvent.java // @Getter // public class DanmakuEvent extends EventObject { // private Kind kind; // private Object param; // // /** // * Constructs a prototypical Event. // * // * @param source The object on which the Event initially occurred. // * @throws IllegalArgumentException if source is null. // */ // public DanmakuEvent(Object source) { // super(source); // } // // public DanmakuEvent(Object source, Object param, Kind kind) { // super(source); // this.kind = kind; // this.param = param; // } // // public enum Kind { // JOINED, ERROR, ERROR_DOWN, NEW_DANMAKU, WATCHER_COUNT, // START_STOP, WELCOME_VIP, GIVE_GIFT, GLOBAL_GIFT, GLOBAL_ANNOUNCE // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuListener.java // public interface DanmakuListener { // void danmakuEvent(@NotNull DanmakuEvent event); // // void watcherCountEvent(@NotNull DanmakuEvent event); // // void errorEvent(@NotNull DanmakuEvent event); // // void startStopEvent(@NotNull DanmakuEvent event); // // void statusEvent(@NotNull DanmakuEvent event); // // void welcomeVipEvent(@NotNull DanmakuEvent event); // // void giveGiftEvent(@NotNull DanmakuEvent event); // // void globalGiftEvent(@NotNull DanmakuEvent event); // // void globalAnnounceEvent(@NotNull DanmakuEvent event); // }
import charlie.bililivelib.danmaku.event.DanmakuEvent; import charlie.bililivelib.danmaku.event.DanmakuListener; import org.jetbrains.annotations.NotNull; import java.util.LinkedList; import java.util.List;
package charlie.bililivelib.danmaku.dispatch; /** * 用于管理分发器的管理器。 * * @author Charlie Jiang * @since rv1 */ public class DispatchManager { private List<Dispatcher> dispatchers = new LinkedList<>(); /** * 注册新的分发器。 * @param dispatcher 分发器 */ public void registerDispatcher(@NotNull Dispatcher dispatcher) { dispatchers.add(dispatcher); } /** * 注销指定分发器。 * @param dispatcher 分发器 */ public void unregisterDispatcher(@NotNull Dispatcher dispatcher) { dispatchers.remove(dispatcher); } /** * 尝试分发信息。 * @param listeners 监听器列表 * @param body 信息体 * @param source 事件源 */ public void dispatch(@NotNull List<DanmakuListener> listeners, @NotNull String body, @NotNull Object source) { for (Dispatcher dispatcher : dispatchers) { try { dispatcher.tryDispatch(listeners, body, source); } catch (Exception ex) {
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuEvent.java // @Getter // public class DanmakuEvent extends EventObject { // private Kind kind; // private Object param; // // /** // * Constructs a prototypical Event. // * // * @param source The object on which the Event initially occurred. // * @throws IllegalArgumentException if source is null. // */ // public DanmakuEvent(Object source) { // super(source); // } // // public DanmakuEvent(Object source, Object param, Kind kind) { // super(source); // this.kind = kind; // this.param = param; // } // // public enum Kind { // JOINED, ERROR, ERROR_DOWN, NEW_DANMAKU, WATCHER_COUNT, // START_STOP, WELCOME_VIP, GIVE_GIFT, GLOBAL_GIFT, GLOBAL_ANNOUNCE // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuListener.java // public interface DanmakuListener { // void danmakuEvent(@NotNull DanmakuEvent event); // // void watcherCountEvent(@NotNull DanmakuEvent event); // // void errorEvent(@NotNull DanmakuEvent event); // // void startStopEvent(@NotNull DanmakuEvent event); // // void statusEvent(@NotNull DanmakuEvent event); // // void welcomeVipEvent(@NotNull DanmakuEvent event); // // void giveGiftEvent(@NotNull DanmakuEvent event); // // void globalGiftEvent(@NotNull DanmakuEvent event); // // void globalAnnounceEvent(@NotNull DanmakuEvent event); // } // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/dispatch/DispatchManager.java import charlie.bililivelib.danmaku.event.DanmakuEvent; import charlie.bililivelib.danmaku.event.DanmakuListener; import org.jetbrains.annotations.NotNull; import java.util.LinkedList; import java.util.List; package charlie.bililivelib.danmaku.dispatch; /** * 用于管理分发器的管理器。 * * @author Charlie Jiang * @since rv1 */ public class DispatchManager { private List<Dispatcher> dispatchers = new LinkedList<>(); /** * 注册新的分发器。 * @param dispatcher 分发器 */ public void registerDispatcher(@NotNull Dispatcher dispatcher) { dispatchers.add(dispatcher); } /** * 注销指定分发器。 * @param dispatcher 分发器 */ public void unregisterDispatcher(@NotNull Dispatcher dispatcher) { dispatchers.remove(dispatcher); } /** * 尝试分发信息。 * @param listeners 监听器列表 * @param body 信息体 * @param source 事件源 */ public void dispatch(@NotNull List<DanmakuListener> listeners, @NotNull String body, @NotNull Object source) { for (Dispatcher dispatcher : dispatchers) { try { dispatcher.tryDispatch(listeners, body, source); } catch (Exception ex) {
DanmakuEvent event = new DanmakuEvent(dispatcher, ex, DanmakuEvent.Kind.ERROR);
cqjjjzr/BiliLiveLib
BiliLiveLib/src/test/java/charlie/bililivelib/streamer/DirectStreamDownloaderTest.java
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/BiliLiveLib.java // public class BiliLiveLib { // public static final String PROJECT_NAME = "BiliLiveLib"; // // public static final String VERSION = "rv5"; // public static String DEFAULT_USER_AGENT = PROJECT_NAME + " " + VERSION; // } // // Path: BiliLiveLib/src/test/java/charlie/bililivelib/LogUtil.java // public class LogUtil { // private static final String LINE_BREAKING = System.lineSeparator(); // // private static Logger logger; // // public static void init() { // logger = LogManager.getLogger(BiliLiveLib.class); // } // // public static synchronized void logException(Level level, @NotNull @Nls String message, @NotNull Throwable ex) { // if (logger == null) return; // logger.log(level, message); // StringTokenizer tokenizer = getStackTrace(ex); // while(tokenizer.hasMoreTokens()) { // logger.log(level, tokenizer.nextToken()); // } // } // // private static StringTokenizer getStackTrace(Throwable ex) { // ByteArrayOutputStream temp = new ByteArrayOutputStream(); // ex.printStackTrace(new PrintStream(temp)); // String stackTrace = new String(temp.toByteArray()); // return new StringTokenizer(stackTrace, LINE_BREAKING); // } // // @Contract(pure = true) // private static Logger logger() { // return logger; // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/streamer/event/DownloadEvent.java // @Getter // @ToString // public class DownloadEvent extends EventObject { // private String message; // private Kind kind; // // public DownloadEvent(Object source) { // super(source); // message = ""; // kind = Kind.OTHER; // } // // public DownloadEvent(Object source, @Nls String message, Kind kind) { // super(source); // this.message = message; // this.kind = kind; // } // // public enum Kind { // STARTING, STARTED, STOPPED, LIVE_STOPPED, ERROR, OTHER // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/streamer/event/DownloadListener.java // public interface DownloadListener { // /** // * 在发生事件时调用。 // * @param event 事件对象 // */ // void downloadEvent(DownloadEvent event); // }
import charlie.bililivelib.BiliLiveLib; import charlie.bililivelib.LogUtil; import charlie.bililivelib.streamer.event.DownloadEvent; import charlie.bililivelib.streamer.event.DownloadListener; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.BeforeClass; import org.junit.Test; import java.io.File; import java.net.URL;
package charlie.bililivelib.streamer; public class DirectStreamDownloaderTest { private static final String ADDRESS = "http://cn-cq3-dx.acgvideo.com/vg5/b/08/12352769-1.flv?expires=1481970900&ssig=VF0xLtY-fVWNsCXyl-Belw&oi=3736312299&nfa=jh1gYOK5yu5onKTDA7JgFw==&dynamic=1"; @BeforeClass public static void init() {
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/BiliLiveLib.java // public class BiliLiveLib { // public static final String PROJECT_NAME = "BiliLiveLib"; // // public static final String VERSION = "rv5"; // public static String DEFAULT_USER_AGENT = PROJECT_NAME + " " + VERSION; // } // // Path: BiliLiveLib/src/test/java/charlie/bililivelib/LogUtil.java // public class LogUtil { // private static final String LINE_BREAKING = System.lineSeparator(); // // private static Logger logger; // // public static void init() { // logger = LogManager.getLogger(BiliLiveLib.class); // } // // public static synchronized void logException(Level level, @NotNull @Nls String message, @NotNull Throwable ex) { // if (logger == null) return; // logger.log(level, message); // StringTokenizer tokenizer = getStackTrace(ex); // while(tokenizer.hasMoreTokens()) { // logger.log(level, tokenizer.nextToken()); // } // } // // private static StringTokenizer getStackTrace(Throwable ex) { // ByteArrayOutputStream temp = new ByteArrayOutputStream(); // ex.printStackTrace(new PrintStream(temp)); // String stackTrace = new String(temp.toByteArray()); // return new StringTokenizer(stackTrace, LINE_BREAKING); // } // // @Contract(pure = true) // private static Logger logger() { // return logger; // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/streamer/event/DownloadEvent.java // @Getter // @ToString // public class DownloadEvent extends EventObject { // private String message; // private Kind kind; // // public DownloadEvent(Object source) { // super(source); // message = ""; // kind = Kind.OTHER; // } // // public DownloadEvent(Object source, @Nls String message, Kind kind) { // super(source); // this.message = message; // this.kind = kind; // } // // public enum Kind { // STARTING, STARTED, STOPPED, LIVE_STOPPED, ERROR, OTHER // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/streamer/event/DownloadListener.java // public interface DownloadListener { // /** // * 在发生事件时调用。 // * @param event 事件对象 // */ // void downloadEvent(DownloadEvent event); // } // Path: BiliLiveLib/src/test/java/charlie/bililivelib/streamer/DirectStreamDownloaderTest.java import charlie.bililivelib.BiliLiveLib; import charlie.bililivelib.LogUtil; import charlie.bililivelib.streamer.event.DownloadEvent; import charlie.bililivelib.streamer.event.DownloadListener; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.BeforeClass; import org.junit.Test; import java.io.File; import java.net.URL; package charlie.bililivelib.streamer; public class DirectStreamDownloaderTest { private static final String ADDRESS = "http://cn-cq3-dx.acgvideo.com/vg5/b/08/12352769-1.flv?expires=1481970900&ssig=VF0xLtY-fVWNsCXyl-Belw&oi=3736312299&nfa=jh1gYOK5yu5onKTDA7JgFw==&dynamic=1"; @BeforeClass public static void init() {
LogUtil.init();
cqjjjzr/BiliLiveLib
BiliLiveLib/src/test/java/charlie/bililivelib/streamer/DirectStreamDownloaderTest.java
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/BiliLiveLib.java // public class BiliLiveLib { // public static final String PROJECT_NAME = "BiliLiveLib"; // // public static final String VERSION = "rv5"; // public static String DEFAULT_USER_AGENT = PROJECT_NAME + " " + VERSION; // } // // Path: BiliLiveLib/src/test/java/charlie/bililivelib/LogUtil.java // public class LogUtil { // private static final String LINE_BREAKING = System.lineSeparator(); // // private static Logger logger; // // public static void init() { // logger = LogManager.getLogger(BiliLiveLib.class); // } // // public static synchronized void logException(Level level, @NotNull @Nls String message, @NotNull Throwable ex) { // if (logger == null) return; // logger.log(level, message); // StringTokenizer tokenizer = getStackTrace(ex); // while(tokenizer.hasMoreTokens()) { // logger.log(level, tokenizer.nextToken()); // } // } // // private static StringTokenizer getStackTrace(Throwable ex) { // ByteArrayOutputStream temp = new ByteArrayOutputStream(); // ex.printStackTrace(new PrintStream(temp)); // String stackTrace = new String(temp.toByteArray()); // return new StringTokenizer(stackTrace, LINE_BREAKING); // } // // @Contract(pure = true) // private static Logger logger() { // return logger; // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/streamer/event/DownloadEvent.java // @Getter // @ToString // public class DownloadEvent extends EventObject { // private String message; // private Kind kind; // // public DownloadEvent(Object source) { // super(source); // message = ""; // kind = Kind.OTHER; // } // // public DownloadEvent(Object source, @Nls String message, Kind kind) { // super(source); // this.message = message; // this.kind = kind; // } // // public enum Kind { // STARTING, STARTED, STOPPED, LIVE_STOPPED, ERROR, OTHER // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/streamer/event/DownloadListener.java // public interface DownloadListener { // /** // * 在发生事件时调用。 // * @param event 事件对象 // */ // void downloadEvent(DownloadEvent event); // }
import charlie.bililivelib.BiliLiveLib; import charlie.bililivelib.LogUtil; import charlie.bililivelib.streamer.event.DownloadEvent; import charlie.bililivelib.streamer.event.DownloadListener; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.BeforeClass; import org.junit.Test; import java.io.File; import java.net.URL;
downloader.start(); synchronized (downloader) { downloader.wait(); } } @Test public void testForceExit() throws Exception { DirectStreamDownloader downloader = new DirectStreamDownloader(new URL(ADDRESS), null, new File("D:\\Test2.flv")); downloader.addDownloadListener(new TestListener()); downloader.start(); Thread.sleep(10000); downloader.forceStop(); } @Test public void testManuallyExit() throws Exception { DirectStreamDownloader downloader = new DirectStreamDownloader(new URL(ADDRESS), null, new File("D:\\Test3.flv")); downloader.addDownloadListener(new TestListener()); downloader.start(); Thread.sleep(3000); downloader.tryStop(); synchronized (downloader) { downloader.wait(); } }
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/BiliLiveLib.java // public class BiliLiveLib { // public static final String PROJECT_NAME = "BiliLiveLib"; // // public static final String VERSION = "rv5"; // public static String DEFAULT_USER_AGENT = PROJECT_NAME + " " + VERSION; // } // // Path: BiliLiveLib/src/test/java/charlie/bililivelib/LogUtil.java // public class LogUtil { // private static final String LINE_BREAKING = System.lineSeparator(); // // private static Logger logger; // // public static void init() { // logger = LogManager.getLogger(BiliLiveLib.class); // } // // public static synchronized void logException(Level level, @NotNull @Nls String message, @NotNull Throwable ex) { // if (logger == null) return; // logger.log(level, message); // StringTokenizer tokenizer = getStackTrace(ex); // while(tokenizer.hasMoreTokens()) { // logger.log(level, tokenizer.nextToken()); // } // } // // private static StringTokenizer getStackTrace(Throwable ex) { // ByteArrayOutputStream temp = new ByteArrayOutputStream(); // ex.printStackTrace(new PrintStream(temp)); // String stackTrace = new String(temp.toByteArray()); // return new StringTokenizer(stackTrace, LINE_BREAKING); // } // // @Contract(pure = true) // private static Logger logger() { // return logger; // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/streamer/event/DownloadEvent.java // @Getter // @ToString // public class DownloadEvent extends EventObject { // private String message; // private Kind kind; // // public DownloadEvent(Object source) { // super(source); // message = ""; // kind = Kind.OTHER; // } // // public DownloadEvent(Object source, @Nls String message, Kind kind) { // super(source); // this.message = message; // this.kind = kind; // } // // public enum Kind { // STARTING, STARTED, STOPPED, LIVE_STOPPED, ERROR, OTHER // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/streamer/event/DownloadListener.java // public interface DownloadListener { // /** // * 在发生事件时调用。 // * @param event 事件对象 // */ // void downloadEvent(DownloadEvent event); // } // Path: BiliLiveLib/src/test/java/charlie/bililivelib/streamer/DirectStreamDownloaderTest.java import charlie.bililivelib.BiliLiveLib; import charlie.bililivelib.LogUtil; import charlie.bililivelib.streamer.event.DownloadEvent; import charlie.bililivelib.streamer.event.DownloadListener; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.BeforeClass; import org.junit.Test; import java.io.File; import java.net.URL; downloader.start(); synchronized (downloader) { downloader.wait(); } } @Test public void testForceExit() throws Exception { DirectStreamDownloader downloader = new DirectStreamDownloader(new URL(ADDRESS), null, new File("D:\\Test2.flv")); downloader.addDownloadListener(new TestListener()); downloader.start(); Thread.sleep(10000); downloader.forceStop(); } @Test public void testManuallyExit() throws Exception { DirectStreamDownloader downloader = new DirectStreamDownloader(new URL(ADDRESS), null, new File("D:\\Test3.flv")); downloader.addDownloadListener(new TestListener()); downloader.start(); Thread.sleep(3000); downloader.tryStop(); synchronized (downloader) { downloader.wait(); } }
private class TestListener implements DownloadListener {
cqjjjzr/BiliLiveLib
BiliLiveLib/src/test/java/charlie/bililivelib/streamer/DirectStreamDownloaderTest.java
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/BiliLiveLib.java // public class BiliLiveLib { // public static final String PROJECT_NAME = "BiliLiveLib"; // // public static final String VERSION = "rv5"; // public static String DEFAULT_USER_AGENT = PROJECT_NAME + " " + VERSION; // } // // Path: BiliLiveLib/src/test/java/charlie/bililivelib/LogUtil.java // public class LogUtil { // private static final String LINE_BREAKING = System.lineSeparator(); // // private static Logger logger; // // public static void init() { // logger = LogManager.getLogger(BiliLiveLib.class); // } // // public static synchronized void logException(Level level, @NotNull @Nls String message, @NotNull Throwable ex) { // if (logger == null) return; // logger.log(level, message); // StringTokenizer tokenizer = getStackTrace(ex); // while(tokenizer.hasMoreTokens()) { // logger.log(level, tokenizer.nextToken()); // } // } // // private static StringTokenizer getStackTrace(Throwable ex) { // ByteArrayOutputStream temp = new ByteArrayOutputStream(); // ex.printStackTrace(new PrintStream(temp)); // String stackTrace = new String(temp.toByteArray()); // return new StringTokenizer(stackTrace, LINE_BREAKING); // } // // @Contract(pure = true) // private static Logger logger() { // return logger; // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/streamer/event/DownloadEvent.java // @Getter // @ToString // public class DownloadEvent extends EventObject { // private String message; // private Kind kind; // // public DownloadEvent(Object source) { // super(source); // message = ""; // kind = Kind.OTHER; // } // // public DownloadEvent(Object source, @Nls String message, Kind kind) { // super(source); // this.message = message; // this.kind = kind; // } // // public enum Kind { // STARTING, STARTED, STOPPED, LIVE_STOPPED, ERROR, OTHER // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/streamer/event/DownloadListener.java // public interface DownloadListener { // /** // * 在发生事件时调用。 // * @param event 事件对象 // */ // void downloadEvent(DownloadEvent event); // }
import charlie.bililivelib.BiliLiveLib; import charlie.bililivelib.LogUtil; import charlie.bililivelib.streamer.event.DownloadEvent; import charlie.bililivelib.streamer.event.DownloadListener; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.BeforeClass; import org.junit.Test; import java.io.File; import java.net.URL;
synchronized (downloader) { downloader.wait(); } } @Test public void testForceExit() throws Exception { DirectStreamDownloader downloader = new DirectStreamDownloader(new URL(ADDRESS), null, new File("D:\\Test2.flv")); downloader.addDownloadListener(new TestListener()); downloader.start(); Thread.sleep(10000); downloader.forceStop(); } @Test public void testManuallyExit() throws Exception { DirectStreamDownloader downloader = new DirectStreamDownloader(new URL(ADDRESS), null, new File("D:\\Test3.flv")); downloader.addDownloadListener(new TestListener()); downloader.start(); Thread.sleep(3000); downloader.tryStop(); synchronized (downloader) { downloader.wait(); } } private class TestListener implements DownloadListener {
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/BiliLiveLib.java // public class BiliLiveLib { // public static final String PROJECT_NAME = "BiliLiveLib"; // // public static final String VERSION = "rv5"; // public static String DEFAULT_USER_AGENT = PROJECT_NAME + " " + VERSION; // } // // Path: BiliLiveLib/src/test/java/charlie/bililivelib/LogUtil.java // public class LogUtil { // private static final String LINE_BREAKING = System.lineSeparator(); // // private static Logger logger; // // public static void init() { // logger = LogManager.getLogger(BiliLiveLib.class); // } // // public static synchronized void logException(Level level, @NotNull @Nls String message, @NotNull Throwable ex) { // if (logger == null) return; // logger.log(level, message); // StringTokenizer tokenizer = getStackTrace(ex); // while(tokenizer.hasMoreTokens()) { // logger.log(level, tokenizer.nextToken()); // } // } // // private static StringTokenizer getStackTrace(Throwable ex) { // ByteArrayOutputStream temp = new ByteArrayOutputStream(); // ex.printStackTrace(new PrintStream(temp)); // String stackTrace = new String(temp.toByteArray()); // return new StringTokenizer(stackTrace, LINE_BREAKING); // } // // @Contract(pure = true) // private static Logger logger() { // return logger; // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/streamer/event/DownloadEvent.java // @Getter // @ToString // public class DownloadEvent extends EventObject { // private String message; // private Kind kind; // // public DownloadEvent(Object source) { // super(source); // message = ""; // kind = Kind.OTHER; // } // // public DownloadEvent(Object source, @Nls String message, Kind kind) { // super(source); // this.message = message; // this.kind = kind; // } // // public enum Kind { // STARTING, STARTED, STOPPED, LIVE_STOPPED, ERROR, OTHER // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/streamer/event/DownloadListener.java // public interface DownloadListener { // /** // * 在发生事件时调用。 // * @param event 事件对象 // */ // void downloadEvent(DownloadEvent event); // } // Path: BiliLiveLib/src/test/java/charlie/bililivelib/streamer/DirectStreamDownloaderTest.java import charlie.bililivelib.BiliLiveLib; import charlie.bililivelib.LogUtil; import charlie.bililivelib.streamer.event.DownloadEvent; import charlie.bililivelib.streamer.event.DownloadListener; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.BeforeClass; import org.junit.Test; import java.io.File; import java.net.URL; synchronized (downloader) { downloader.wait(); } } @Test public void testForceExit() throws Exception { DirectStreamDownloader downloader = new DirectStreamDownloader(new URL(ADDRESS), null, new File("D:\\Test2.flv")); downloader.addDownloadListener(new TestListener()); downloader.start(); Thread.sleep(10000); downloader.forceStop(); } @Test public void testManuallyExit() throws Exception { DirectStreamDownloader downloader = new DirectStreamDownloader(new URL(ADDRESS), null, new File("D:\\Test3.flv")); downloader.addDownloadListener(new TestListener()); downloader.start(); Thread.sleep(3000); downloader.tryStop(); synchronized (downloader) { downloader.wait(); } } private class TestListener implements DownloadListener {
private Logger logger = LogManager.getLogger(BiliLiveLib.class);
cqjjjzr/BiliLiveLib
BiliLiveLib/src/test/java/charlie/bililivelib/streamer/DirectStreamDownloaderTest.java
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/BiliLiveLib.java // public class BiliLiveLib { // public static final String PROJECT_NAME = "BiliLiveLib"; // // public static final String VERSION = "rv5"; // public static String DEFAULT_USER_AGENT = PROJECT_NAME + " " + VERSION; // } // // Path: BiliLiveLib/src/test/java/charlie/bililivelib/LogUtil.java // public class LogUtil { // private static final String LINE_BREAKING = System.lineSeparator(); // // private static Logger logger; // // public static void init() { // logger = LogManager.getLogger(BiliLiveLib.class); // } // // public static synchronized void logException(Level level, @NotNull @Nls String message, @NotNull Throwable ex) { // if (logger == null) return; // logger.log(level, message); // StringTokenizer tokenizer = getStackTrace(ex); // while(tokenizer.hasMoreTokens()) { // logger.log(level, tokenizer.nextToken()); // } // } // // private static StringTokenizer getStackTrace(Throwable ex) { // ByteArrayOutputStream temp = new ByteArrayOutputStream(); // ex.printStackTrace(new PrintStream(temp)); // String stackTrace = new String(temp.toByteArray()); // return new StringTokenizer(stackTrace, LINE_BREAKING); // } // // @Contract(pure = true) // private static Logger logger() { // return logger; // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/streamer/event/DownloadEvent.java // @Getter // @ToString // public class DownloadEvent extends EventObject { // private String message; // private Kind kind; // // public DownloadEvent(Object source) { // super(source); // message = ""; // kind = Kind.OTHER; // } // // public DownloadEvent(Object source, @Nls String message, Kind kind) { // super(source); // this.message = message; // this.kind = kind; // } // // public enum Kind { // STARTING, STARTED, STOPPED, LIVE_STOPPED, ERROR, OTHER // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/streamer/event/DownloadListener.java // public interface DownloadListener { // /** // * 在发生事件时调用。 // * @param event 事件对象 // */ // void downloadEvent(DownloadEvent event); // }
import charlie.bililivelib.BiliLiveLib; import charlie.bililivelib.LogUtil; import charlie.bililivelib.streamer.event.DownloadEvent; import charlie.bililivelib.streamer.event.DownloadListener; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.BeforeClass; import org.junit.Test; import java.io.File; import java.net.URL;
} } @Test public void testForceExit() throws Exception { DirectStreamDownloader downloader = new DirectStreamDownloader(new URL(ADDRESS), null, new File("D:\\Test2.flv")); downloader.addDownloadListener(new TestListener()); downloader.start(); Thread.sleep(10000); downloader.forceStop(); } @Test public void testManuallyExit() throws Exception { DirectStreamDownloader downloader = new DirectStreamDownloader(new URL(ADDRESS), null, new File("D:\\Test3.flv")); downloader.addDownloadListener(new TestListener()); downloader.start(); Thread.sleep(3000); downloader.tryStop(); synchronized (downloader) { downloader.wait(); } } private class TestListener implements DownloadListener { private Logger logger = LogManager.getLogger(BiliLiveLib.class); @Override
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/BiliLiveLib.java // public class BiliLiveLib { // public static final String PROJECT_NAME = "BiliLiveLib"; // // public static final String VERSION = "rv5"; // public static String DEFAULT_USER_AGENT = PROJECT_NAME + " " + VERSION; // } // // Path: BiliLiveLib/src/test/java/charlie/bililivelib/LogUtil.java // public class LogUtil { // private static final String LINE_BREAKING = System.lineSeparator(); // // private static Logger logger; // // public static void init() { // logger = LogManager.getLogger(BiliLiveLib.class); // } // // public static synchronized void logException(Level level, @NotNull @Nls String message, @NotNull Throwable ex) { // if (logger == null) return; // logger.log(level, message); // StringTokenizer tokenizer = getStackTrace(ex); // while(tokenizer.hasMoreTokens()) { // logger.log(level, tokenizer.nextToken()); // } // } // // private static StringTokenizer getStackTrace(Throwable ex) { // ByteArrayOutputStream temp = new ByteArrayOutputStream(); // ex.printStackTrace(new PrintStream(temp)); // String stackTrace = new String(temp.toByteArray()); // return new StringTokenizer(stackTrace, LINE_BREAKING); // } // // @Contract(pure = true) // private static Logger logger() { // return logger; // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/streamer/event/DownloadEvent.java // @Getter // @ToString // public class DownloadEvent extends EventObject { // private String message; // private Kind kind; // // public DownloadEvent(Object source) { // super(source); // message = ""; // kind = Kind.OTHER; // } // // public DownloadEvent(Object source, @Nls String message, Kind kind) { // super(source); // this.message = message; // this.kind = kind; // } // // public enum Kind { // STARTING, STARTED, STOPPED, LIVE_STOPPED, ERROR, OTHER // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/streamer/event/DownloadListener.java // public interface DownloadListener { // /** // * 在发生事件时调用。 // * @param event 事件对象 // */ // void downloadEvent(DownloadEvent event); // } // Path: BiliLiveLib/src/test/java/charlie/bililivelib/streamer/DirectStreamDownloaderTest.java import charlie.bililivelib.BiliLiveLib; import charlie.bililivelib.LogUtil; import charlie.bililivelib.streamer.event.DownloadEvent; import charlie.bililivelib.streamer.event.DownloadListener; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.BeforeClass; import org.junit.Test; import java.io.File; import java.net.URL; } } @Test public void testForceExit() throws Exception { DirectStreamDownloader downloader = new DirectStreamDownloader(new URL(ADDRESS), null, new File("D:\\Test2.flv")); downloader.addDownloadListener(new TestListener()); downloader.start(); Thread.sleep(10000); downloader.forceStop(); } @Test public void testManuallyExit() throws Exception { DirectStreamDownloader downloader = new DirectStreamDownloader(new URL(ADDRESS), null, new File("D:\\Test3.flv")); downloader.addDownloadListener(new TestListener()); downloader.start(); Thread.sleep(3000); downloader.tryStop(); synchronized (downloader) { downloader.wait(); } } private class TestListener implements DownloadListener { private Logger logger = LogManager.getLogger(BiliLiveLib.class); @Override
public void downloadEvent(DownloadEvent event) {
cqjjjzr/BiliLiveLib
BiliLiveLib/src/main/java/charlie/bililivelib/exceptions/NetworkException.java
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/I18n.java // public class I18n { // public static final String BUNDLE_NAME = "BiliLiveLib"; // private static Map<String, String> strings; // // static { // init(); // } // // /** // * 重新依照当前Locale获取并填充本地化字符串。在切换Locale后调用。 // */ // public static void init() { // strings = new HashMap<>(); // fillResourceBundle(); // } // // private static void fillResourceBundle() { // ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE_NAME); // for (String key : resourceBundle.keySet()) { // strings.put(key, resourceBundle.getString(key)); // } // } // // /** // * 获取给定Key的本地化文本。 // * @param key 键 // * @return 本地化文本 // */ // @Nls // public static String getString(@NonNls @NotNull String key) { // return strings.get(key); // } // // /** // * 获取基于给定Key的本地化格式化文本。 // * @param key 指向格式化模式的键 // * @param arguments 格式化文本的参数 // * @return 本地化并格式化后的文本 // */ // @NotNull // public static String format(@NonNls @NotNull String key, // @NonNls @NotNull Object... arguments) { // return MessageFormat.format(strings.get(key), arguments); // } // }
import charlie.bililivelib.I18n; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.Nls;
package charlie.bililivelib.exceptions; /** * 标志发生了网络问题的异常。 * * @author Charlie Jiang * @since rv1 */ public class NetworkException extends BiliLiveException { public NetworkException() { } public NetworkException(String message) { super(message); } public NetworkException(String message, Throwable cause) { super(message, cause); } /** * 对于给定信息和Http错误,创建一个NetworkException。 * * @param message 信息 * @param status Http状态码 * @return NetworkException */ @Contract("_, _ -> !null") public static NetworkException createHttpError( @Nls String message, int status) {
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/I18n.java // public class I18n { // public static final String BUNDLE_NAME = "BiliLiveLib"; // private static Map<String, String> strings; // // static { // init(); // } // // /** // * 重新依照当前Locale获取并填充本地化字符串。在切换Locale后调用。 // */ // public static void init() { // strings = new HashMap<>(); // fillResourceBundle(); // } // // private static void fillResourceBundle() { // ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE_NAME); // for (String key : resourceBundle.keySet()) { // strings.put(key, resourceBundle.getString(key)); // } // } // // /** // * 获取给定Key的本地化文本。 // * @param key 键 // * @return 本地化文本 // */ // @Nls // public static String getString(@NonNls @NotNull String key) { // return strings.get(key); // } // // /** // * 获取基于给定Key的本地化格式化文本。 // * @param key 指向格式化模式的键 // * @param arguments 格式化文本的参数 // * @return 本地化并格式化后的文本 // */ // @NotNull // public static String format(@NonNls @NotNull String key, // @NonNls @NotNull Object... arguments) { // return MessageFormat.format(strings.get(key), arguments); // } // } // Path: BiliLiveLib/src/main/java/charlie/bililivelib/exceptions/NetworkException.java import charlie.bililivelib.I18n; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.Nls; package charlie.bililivelib.exceptions; /** * 标志发生了网络问题的异常。 * * @author Charlie Jiang * @since rv1 */ public class NetworkException extends BiliLiveException { public NetworkException() { } public NetworkException(String message) { super(message); } public NetworkException(String message, Throwable cause) { super(message, cause); } /** * 对于给定信息和Http错误,创建一个NetworkException。 * * @param message 信息 * @param status Http状态码 * @return NetworkException */ @Contract("_, _ -> !null") public static NetworkException createHttpError( @Nls String message, int status) {
return new NetworkException(message + I18n.format("exception.http_error", status));
cqjjjzr/BiliLiveLib
BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/dispatch/GlobalAnnounceDispatcher.java
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/Globals.java // public class Globals { // private static final String BILI_PASSPORT_HOST_ROOT = "passport.bilibili.com"; // private static final String BILI_LIVE_HOST_ROOT = "live.bilibili.com"; // @Getter // private static int CONNECTION_ALIVE_TIME_SECOND = 10; // private static Globals instance; // @Getter // private HttpHost biliLiveRoot; // @Getter // private HttpHost biliPassportHttpsRoot; // private ThreadLocal<Gson> gson; // // private HttpClientConnectionManager connectionPool; // @Getter // private SSLContext bilibiliSSLContext; // // public static Globals get() { // if (instance == null) { // instance = new Globals(); // instance.init(); // } // return instance; // } // // private void init() { // biliLiveRoot = new HttpHost(BILI_LIVE_HOST_ROOT); // //Visit bilibili passport via https. 443 is the https port. // biliPassportHttpsRoot = new HttpHost(BILI_PASSPORT_HOST_ROOT, 443, "https"); // gson = ThreadLocal.withInitial(() -> new GsonBuilder() // .setLenient() // .create()); // // try { // bilibiliSSLContext = SSLContextBuilder.create() // .loadTrustMaterial(new BilibiliTrustStrategy()) // .build(); // } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) { // throw new AssertionError("failed initializing bilibili ssl context!"); // } // } // // public Gson gson() { // return gson.get(); // } // // public HttpClientConnectionManager getConnectionPool() { // if (connectionPool == null) { // reInitializeConnectionPool(); // } // return connectionPool; // } // // public void reInitializeConnectionPool() { // connectionPool = new PoolingHttpClientConnectionManager(CONNECTION_ALIVE_TIME_SECOND, TimeUnit.SECONDS); // } // // public void setConnectionAliveTimeSecond(int connectionAliveTimeSecond) { // CONNECTION_ALIVE_TIME_SECOND = connectionAliveTimeSecond; // reInitializeConnectionPool(); // } // // // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/datamodel/GlobalAnnounceInfo.java // @Data // public class GlobalAnnounceInfo { // @SerializedName("msg") // private String message; // private int rep; // @SerializedName("url") // private String URL; // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuEvent.java // @Getter // public class DanmakuEvent extends EventObject { // private Kind kind; // private Object param; // // /** // * Constructs a prototypical Event. // * // * @param source The object on which the Event initially occurred. // * @throws IllegalArgumentException if source is null. // */ // public DanmakuEvent(Object source) { // super(source); // } // // public DanmakuEvent(Object source, Object param, Kind kind) { // super(source); // this.kind = kind; // this.param = param; // } // // public enum Kind { // JOINED, ERROR, ERROR_DOWN, NEW_DANMAKU, WATCHER_COUNT, // START_STOP, WELCOME_VIP, GIVE_GIFT, GLOBAL_GIFT, GLOBAL_ANNOUNCE // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuListener.java // public interface DanmakuListener { // void danmakuEvent(@NotNull DanmakuEvent event); // // void watcherCountEvent(@NotNull DanmakuEvent event); // // void errorEvent(@NotNull DanmakuEvent event); // // void startStopEvent(@NotNull DanmakuEvent event); // // void statusEvent(@NotNull DanmakuEvent event); // // void welcomeVipEvent(@NotNull DanmakuEvent event); // // void giveGiftEvent(@NotNull DanmakuEvent event); // // void globalGiftEvent(@NotNull DanmakuEvent event); // // void globalAnnounceEvent(@NotNull DanmakuEvent event); // }
import charlie.bililivelib.Globals; import charlie.bililivelib.danmaku.datamodel.GlobalAnnounceInfo; import charlie.bililivelib.danmaku.event.DanmakuEvent; import charlie.bililivelib.danmaku.event.DanmakuListener; import com.google.gson.JsonObject; import org.jetbrains.annotations.NotNull; import java.util.List;
package charlie.bililivelib.danmaku.dispatch; /** * 分发公告的分发器。对COMMAND为'SYS_MSG'的事件有效。 * * @author Charlie Jiang * @since rv1 */ public class GlobalAnnounceDispatcher extends AbstractJSONDispatcher { public static final String[] ACCEPTABLE_COMMANDS = { "SYS_MSG" }; private static GlobalAnnounceDispatcher GLOBAL_INSTANCE; @NotNull public static GlobalAnnounceDispatcher getGlobalInstance() { if (GLOBAL_INSTANCE == null) { GLOBAL_INSTANCE = new GlobalAnnounceDispatcher(); } return GLOBAL_INSTANCE; } @Override protected String[] getAcceptableCommands() { return ACCEPTABLE_COMMANDS; } /** * {@inheritDoc} * @param listeners 监听器列表 * @param rootObject 事件内容产生的JSON对象结构 * @param source 事件发生源 */ @Override
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/Globals.java // public class Globals { // private static final String BILI_PASSPORT_HOST_ROOT = "passport.bilibili.com"; // private static final String BILI_LIVE_HOST_ROOT = "live.bilibili.com"; // @Getter // private static int CONNECTION_ALIVE_TIME_SECOND = 10; // private static Globals instance; // @Getter // private HttpHost biliLiveRoot; // @Getter // private HttpHost biliPassportHttpsRoot; // private ThreadLocal<Gson> gson; // // private HttpClientConnectionManager connectionPool; // @Getter // private SSLContext bilibiliSSLContext; // // public static Globals get() { // if (instance == null) { // instance = new Globals(); // instance.init(); // } // return instance; // } // // private void init() { // biliLiveRoot = new HttpHost(BILI_LIVE_HOST_ROOT); // //Visit bilibili passport via https. 443 is the https port. // biliPassportHttpsRoot = new HttpHost(BILI_PASSPORT_HOST_ROOT, 443, "https"); // gson = ThreadLocal.withInitial(() -> new GsonBuilder() // .setLenient() // .create()); // // try { // bilibiliSSLContext = SSLContextBuilder.create() // .loadTrustMaterial(new BilibiliTrustStrategy()) // .build(); // } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) { // throw new AssertionError("failed initializing bilibili ssl context!"); // } // } // // public Gson gson() { // return gson.get(); // } // // public HttpClientConnectionManager getConnectionPool() { // if (connectionPool == null) { // reInitializeConnectionPool(); // } // return connectionPool; // } // // public void reInitializeConnectionPool() { // connectionPool = new PoolingHttpClientConnectionManager(CONNECTION_ALIVE_TIME_SECOND, TimeUnit.SECONDS); // } // // public void setConnectionAliveTimeSecond(int connectionAliveTimeSecond) { // CONNECTION_ALIVE_TIME_SECOND = connectionAliveTimeSecond; // reInitializeConnectionPool(); // } // // // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/datamodel/GlobalAnnounceInfo.java // @Data // public class GlobalAnnounceInfo { // @SerializedName("msg") // private String message; // private int rep; // @SerializedName("url") // private String URL; // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuEvent.java // @Getter // public class DanmakuEvent extends EventObject { // private Kind kind; // private Object param; // // /** // * Constructs a prototypical Event. // * // * @param source The object on which the Event initially occurred. // * @throws IllegalArgumentException if source is null. // */ // public DanmakuEvent(Object source) { // super(source); // } // // public DanmakuEvent(Object source, Object param, Kind kind) { // super(source); // this.kind = kind; // this.param = param; // } // // public enum Kind { // JOINED, ERROR, ERROR_DOWN, NEW_DANMAKU, WATCHER_COUNT, // START_STOP, WELCOME_VIP, GIVE_GIFT, GLOBAL_GIFT, GLOBAL_ANNOUNCE // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuListener.java // public interface DanmakuListener { // void danmakuEvent(@NotNull DanmakuEvent event); // // void watcherCountEvent(@NotNull DanmakuEvent event); // // void errorEvent(@NotNull DanmakuEvent event); // // void startStopEvent(@NotNull DanmakuEvent event); // // void statusEvent(@NotNull DanmakuEvent event); // // void welcomeVipEvent(@NotNull DanmakuEvent event); // // void giveGiftEvent(@NotNull DanmakuEvent event); // // void globalGiftEvent(@NotNull DanmakuEvent event); // // void globalAnnounceEvent(@NotNull DanmakuEvent event); // } // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/dispatch/GlobalAnnounceDispatcher.java import charlie.bililivelib.Globals; import charlie.bililivelib.danmaku.datamodel.GlobalAnnounceInfo; import charlie.bililivelib.danmaku.event.DanmakuEvent; import charlie.bililivelib.danmaku.event.DanmakuListener; import com.google.gson.JsonObject; import org.jetbrains.annotations.NotNull; import java.util.List; package charlie.bililivelib.danmaku.dispatch; /** * 分发公告的分发器。对COMMAND为'SYS_MSG'的事件有效。 * * @author Charlie Jiang * @since rv1 */ public class GlobalAnnounceDispatcher extends AbstractJSONDispatcher { public static final String[] ACCEPTABLE_COMMANDS = { "SYS_MSG" }; private static GlobalAnnounceDispatcher GLOBAL_INSTANCE; @NotNull public static GlobalAnnounceDispatcher getGlobalInstance() { if (GLOBAL_INSTANCE == null) { GLOBAL_INSTANCE = new GlobalAnnounceDispatcher(); } return GLOBAL_INSTANCE; } @Override protected String[] getAcceptableCommands() { return ACCEPTABLE_COMMANDS; } /** * {@inheritDoc} * @param listeners 监听器列表 * @param rootObject 事件内容产生的JSON对象结构 * @param source 事件发生源 */ @Override
public void dispatch(List<DanmakuListener> listeners, JsonObject rootObject, Object source) {
cqjjjzr/BiliLiveLib
BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/dispatch/GlobalAnnounceDispatcher.java
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/Globals.java // public class Globals { // private static final String BILI_PASSPORT_HOST_ROOT = "passport.bilibili.com"; // private static final String BILI_LIVE_HOST_ROOT = "live.bilibili.com"; // @Getter // private static int CONNECTION_ALIVE_TIME_SECOND = 10; // private static Globals instance; // @Getter // private HttpHost biliLiveRoot; // @Getter // private HttpHost biliPassportHttpsRoot; // private ThreadLocal<Gson> gson; // // private HttpClientConnectionManager connectionPool; // @Getter // private SSLContext bilibiliSSLContext; // // public static Globals get() { // if (instance == null) { // instance = new Globals(); // instance.init(); // } // return instance; // } // // private void init() { // biliLiveRoot = new HttpHost(BILI_LIVE_HOST_ROOT); // //Visit bilibili passport via https. 443 is the https port. // biliPassportHttpsRoot = new HttpHost(BILI_PASSPORT_HOST_ROOT, 443, "https"); // gson = ThreadLocal.withInitial(() -> new GsonBuilder() // .setLenient() // .create()); // // try { // bilibiliSSLContext = SSLContextBuilder.create() // .loadTrustMaterial(new BilibiliTrustStrategy()) // .build(); // } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) { // throw new AssertionError("failed initializing bilibili ssl context!"); // } // } // // public Gson gson() { // return gson.get(); // } // // public HttpClientConnectionManager getConnectionPool() { // if (connectionPool == null) { // reInitializeConnectionPool(); // } // return connectionPool; // } // // public void reInitializeConnectionPool() { // connectionPool = new PoolingHttpClientConnectionManager(CONNECTION_ALIVE_TIME_SECOND, TimeUnit.SECONDS); // } // // public void setConnectionAliveTimeSecond(int connectionAliveTimeSecond) { // CONNECTION_ALIVE_TIME_SECOND = connectionAliveTimeSecond; // reInitializeConnectionPool(); // } // // // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/datamodel/GlobalAnnounceInfo.java // @Data // public class GlobalAnnounceInfo { // @SerializedName("msg") // private String message; // private int rep; // @SerializedName("url") // private String URL; // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuEvent.java // @Getter // public class DanmakuEvent extends EventObject { // private Kind kind; // private Object param; // // /** // * Constructs a prototypical Event. // * // * @param source The object on which the Event initially occurred. // * @throws IllegalArgumentException if source is null. // */ // public DanmakuEvent(Object source) { // super(source); // } // // public DanmakuEvent(Object source, Object param, Kind kind) { // super(source); // this.kind = kind; // this.param = param; // } // // public enum Kind { // JOINED, ERROR, ERROR_DOWN, NEW_DANMAKU, WATCHER_COUNT, // START_STOP, WELCOME_VIP, GIVE_GIFT, GLOBAL_GIFT, GLOBAL_ANNOUNCE // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuListener.java // public interface DanmakuListener { // void danmakuEvent(@NotNull DanmakuEvent event); // // void watcherCountEvent(@NotNull DanmakuEvent event); // // void errorEvent(@NotNull DanmakuEvent event); // // void startStopEvent(@NotNull DanmakuEvent event); // // void statusEvent(@NotNull DanmakuEvent event); // // void welcomeVipEvent(@NotNull DanmakuEvent event); // // void giveGiftEvent(@NotNull DanmakuEvent event); // // void globalGiftEvent(@NotNull DanmakuEvent event); // // void globalAnnounceEvent(@NotNull DanmakuEvent event); // }
import charlie.bililivelib.Globals; import charlie.bililivelib.danmaku.datamodel.GlobalAnnounceInfo; import charlie.bililivelib.danmaku.event.DanmakuEvent; import charlie.bililivelib.danmaku.event.DanmakuListener; import com.google.gson.JsonObject; import org.jetbrains.annotations.NotNull; import java.util.List;
package charlie.bililivelib.danmaku.dispatch; /** * 分发公告的分发器。对COMMAND为'SYS_MSG'的事件有效。 * * @author Charlie Jiang * @since rv1 */ public class GlobalAnnounceDispatcher extends AbstractJSONDispatcher { public static final String[] ACCEPTABLE_COMMANDS = { "SYS_MSG" }; private static GlobalAnnounceDispatcher GLOBAL_INSTANCE; @NotNull public static GlobalAnnounceDispatcher getGlobalInstance() { if (GLOBAL_INSTANCE == null) { GLOBAL_INSTANCE = new GlobalAnnounceDispatcher(); } return GLOBAL_INSTANCE; } @Override protected String[] getAcceptableCommands() { return ACCEPTABLE_COMMANDS; } /** * {@inheritDoc} * @param listeners 监听器列表 * @param rootObject 事件内容产生的JSON对象结构 * @param source 事件发生源 */ @Override public void dispatch(List<DanmakuListener> listeners, JsonObject rootObject, Object source) { if (rootObject.has("tv_id")) return; //SMALL TV.
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/Globals.java // public class Globals { // private static final String BILI_PASSPORT_HOST_ROOT = "passport.bilibili.com"; // private static final String BILI_LIVE_HOST_ROOT = "live.bilibili.com"; // @Getter // private static int CONNECTION_ALIVE_TIME_SECOND = 10; // private static Globals instance; // @Getter // private HttpHost biliLiveRoot; // @Getter // private HttpHost biliPassportHttpsRoot; // private ThreadLocal<Gson> gson; // // private HttpClientConnectionManager connectionPool; // @Getter // private SSLContext bilibiliSSLContext; // // public static Globals get() { // if (instance == null) { // instance = new Globals(); // instance.init(); // } // return instance; // } // // private void init() { // biliLiveRoot = new HttpHost(BILI_LIVE_HOST_ROOT); // //Visit bilibili passport via https. 443 is the https port. // biliPassportHttpsRoot = new HttpHost(BILI_PASSPORT_HOST_ROOT, 443, "https"); // gson = ThreadLocal.withInitial(() -> new GsonBuilder() // .setLenient() // .create()); // // try { // bilibiliSSLContext = SSLContextBuilder.create() // .loadTrustMaterial(new BilibiliTrustStrategy()) // .build(); // } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) { // throw new AssertionError("failed initializing bilibili ssl context!"); // } // } // // public Gson gson() { // return gson.get(); // } // // public HttpClientConnectionManager getConnectionPool() { // if (connectionPool == null) { // reInitializeConnectionPool(); // } // return connectionPool; // } // // public void reInitializeConnectionPool() { // connectionPool = new PoolingHttpClientConnectionManager(CONNECTION_ALIVE_TIME_SECOND, TimeUnit.SECONDS); // } // // public void setConnectionAliveTimeSecond(int connectionAliveTimeSecond) { // CONNECTION_ALIVE_TIME_SECOND = connectionAliveTimeSecond; // reInitializeConnectionPool(); // } // // // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/datamodel/GlobalAnnounceInfo.java // @Data // public class GlobalAnnounceInfo { // @SerializedName("msg") // private String message; // private int rep; // @SerializedName("url") // private String URL; // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuEvent.java // @Getter // public class DanmakuEvent extends EventObject { // private Kind kind; // private Object param; // // /** // * Constructs a prototypical Event. // * // * @param source The object on which the Event initially occurred. // * @throws IllegalArgumentException if source is null. // */ // public DanmakuEvent(Object source) { // super(source); // } // // public DanmakuEvent(Object source, Object param, Kind kind) { // super(source); // this.kind = kind; // this.param = param; // } // // public enum Kind { // JOINED, ERROR, ERROR_DOWN, NEW_DANMAKU, WATCHER_COUNT, // START_STOP, WELCOME_VIP, GIVE_GIFT, GLOBAL_GIFT, GLOBAL_ANNOUNCE // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuListener.java // public interface DanmakuListener { // void danmakuEvent(@NotNull DanmakuEvent event); // // void watcherCountEvent(@NotNull DanmakuEvent event); // // void errorEvent(@NotNull DanmakuEvent event); // // void startStopEvent(@NotNull DanmakuEvent event); // // void statusEvent(@NotNull DanmakuEvent event); // // void welcomeVipEvent(@NotNull DanmakuEvent event); // // void giveGiftEvent(@NotNull DanmakuEvent event); // // void globalGiftEvent(@NotNull DanmakuEvent event); // // void globalAnnounceEvent(@NotNull DanmakuEvent event); // } // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/dispatch/GlobalAnnounceDispatcher.java import charlie.bililivelib.Globals; import charlie.bililivelib.danmaku.datamodel.GlobalAnnounceInfo; import charlie.bililivelib.danmaku.event.DanmakuEvent; import charlie.bililivelib.danmaku.event.DanmakuListener; import com.google.gson.JsonObject; import org.jetbrains.annotations.NotNull; import java.util.List; package charlie.bililivelib.danmaku.dispatch; /** * 分发公告的分发器。对COMMAND为'SYS_MSG'的事件有效。 * * @author Charlie Jiang * @since rv1 */ public class GlobalAnnounceDispatcher extends AbstractJSONDispatcher { public static final String[] ACCEPTABLE_COMMANDS = { "SYS_MSG" }; private static GlobalAnnounceDispatcher GLOBAL_INSTANCE; @NotNull public static GlobalAnnounceDispatcher getGlobalInstance() { if (GLOBAL_INSTANCE == null) { GLOBAL_INSTANCE = new GlobalAnnounceDispatcher(); } return GLOBAL_INSTANCE; } @Override protected String[] getAcceptableCommands() { return ACCEPTABLE_COMMANDS; } /** * {@inheritDoc} * @param listeners 监听器列表 * @param rootObject 事件内容产生的JSON对象结构 * @param source 事件发生源 */ @Override public void dispatch(List<DanmakuListener> listeners, JsonObject rootObject, Object source) { if (rootObject.has("tv_id")) return; //SMALL TV.
GlobalAnnounceInfo announce = Globals.get().gson()
cqjjjzr/BiliLiveLib
BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/dispatch/GlobalAnnounceDispatcher.java
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/Globals.java // public class Globals { // private static final String BILI_PASSPORT_HOST_ROOT = "passport.bilibili.com"; // private static final String BILI_LIVE_HOST_ROOT = "live.bilibili.com"; // @Getter // private static int CONNECTION_ALIVE_TIME_SECOND = 10; // private static Globals instance; // @Getter // private HttpHost biliLiveRoot; // @Getter // private HttpHost biliPassportHttpsRoot; // private ThreadLocal<Gson> gson; // // private HttpClientConnectionManager connectionPool; // @Getter // private SSLContext bilibiliSSLContext; // // public static Globals get() { // if (instance == null) { // instance = new Globals(); // instance.init(); // } // return instance; // } // // private void init() { // biliLiveRoot = new HttpHost(BILI_LIVE_HOST_ROOT); // //Visit bilibili passport via https. 443 is the https port. // biliPassportHttpsRoot = new HttpHost(BILI_PASSPORT_HOST_ROOT, 443, "https"); // gson = ThreadLocal.withInitial(() -> new GsonBuilder() // .setLenient() // .create()); // // try { // bilibiliSSLContext = SSLContextBuilder.create() // .loadTrustMaterial(new BilibiliTrustStrategy()) // .build(); // } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) { // throw new AssertionError("failed initializing bilibili ssl context!"); // } // } // // public Gson gson() { // return gson.get(); // } // // public HttpClientConnectionManager getConnectionPool() { // if (connectionPool == null) { // reInitializeConnectionPool(); // } // return connectionPool; // } // // public void reInitializeConnectionPool() { // connectionPool = new PoolingHttpClientConnectionManager(CONNECTION_ALIVE_TIME_SECOND, TimeUnit.SECONDS); // } // // public void setConnectionAliveTimeSecond(int connectionAliveTimeSecond) { // CONNECTION_ALIVE_TIME_SECOND = connectionAliveTimeSecond; // reInitializeConnectionPool(); // } // // // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/datamodel/GlobalAnnounceInfo.java // @Data // public class GlobalAnnounceInfo { // @SerializedName("msg") // private String message; // private int rep; // @SerializedName("url") // private String URL; // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuEvent.java // @Getter // public class DanmakuEvent extends EventObject { // private Kind kind; // private Object param; // // /** // * Constructs a prototypical Event. // * // * @param source The object on which the Event initially occurred. // * @throws IllegalArgumentException if source is null. // */ // public DanmakuEvent(Object source) { // super(source); // } // // public DanmakuEvent(Object source, Object param, Kind kind) { // super(source); // this.kind = kind; // this.param = param; // } // // public enum Kind { // JOINED, ERROR, ERROR_DOWN, NEW_DANMAKU, WATCHER_COUNT, // START_STOP, WELCOME_VIP, GIVE_GIFT, GLOBAL_GIFT, GLOBAL_ANNOUNCE // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuListener.java // public interface DanmakuListener { // void danmakuEvent(@NotNull DanmakuEvent event); // // void watcherCountEvent(@NotNull DanmakuEvent event); // // void errorEvent(@NotNull DanmakuEvent event); // // void startStopEvent(@NotNull DanmakuEvent event); // // void statusEvent(@NotNull DanmakuEvent event); // // void welcomeVipEvent(@NotNull DanmakuEvent event); // // void giveGiftEvent(@NotNull DanmakuEvent event); // // void globalGiftEvent(@NotNull DanmakuEvent event); // // void globalAnnounceEvent(@NotNull DanmakuEvent event); // }
import charlie.bililivelib.Globals; import charlie.bililivelib.danmaku.datamodel.GlobalAnnounceInfo; import charlie.bililivelib.danmaku.event.DanmakuEvent; import charlie.bililivelib.danmaku.event.DanmakuListener; import com.google.gson.JsonObject; import org.jetbrains.annotations.NotNull; import java.util.List;
package charlie.bililivelib.danmaku.dispatch; /** * 分发公告的分发器。对COMMAND为'SYS_MSG'的事件有效。 * * @author Charlie Jiang * @since rv1 */ public class GlobalAnnounceDispatcher extends AbstractJSONDispatcher { public static final String[] ACCEPTABLE_COMMANDS = { "SYS_MSG" }; private static GlobalAnnounceDispatcher GLOBAL_INSTANCE; @NotNull public static GlobalAnnounceDispatcher getGlobalInstance() { if (GLOBAL_INSTANCE == null) { GLOBAL_INSTANCE = new GlobalAnnounceDispatcher(); } return GLOBAL_INSTANCE; } @Override protected String[] getAcceptableCommands() { return ACCEPTABLE_COMMANDS; } /** * {@inheritDoc} * @param listeners 监听器列表 * @param rootObject 事件内容产生的JSON对象结构 * @param source 事件发生源 */ @Override public void dispatch(List<DanmakuListener> listeners, JsonObject rootObject, Object source) { if (rootObject.has("tv_id")) return; //SMALL TV.
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/Globals.java // public class Globals { // private static final String BILI_PASSPORT_HOST_ROOT = "passport.bilibili.com"; // private static final String BILI_LIVE_HOST_ROOT = "live.bilibili.com"; // @Getter // private static int CONNECTION_ALIVE_TIME_SECOND = 10; // private static Globals instance; // @Getter // private HttpHost biliLiveRoot; // @Getter // private HttpHost biliPassportHttpsRoot; // private ThreadLocal<Gson> gson; // // private HttpClientConnectionManager connectionPool; // @Getter // private SSLContext bilibiliSSLContext; // // public static Globals get() { // if (instance == null) { // instance = new Globals(); // instance.init(); // } // return instance; // } // // private void init() { // biliLiveRoot = new HttpHost(BILI_LIVE_HOST_ROOT); // //Visit bilibili passport via https. 443 is the https port. // biliPassportHttpsRoot = new HttpHost(BILI_PASSPORT_HOST_ROOT, 443, "https"); // gson = ThreadLocal.withInitial(() -> new GsonBuilder() // .setLenient() // .create()); // // try { // bilibiliSSLContext = SSLContextBuilder.create() // .loadTrustMaterial(new BilibiliTrustStrategy()) // .build(); // } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) { // throw new AssertionError("failed initializing bilibili ssl context!"); // } // } // // public Gson gson() { // return gson.get(); // } // // public HttpClientConnectionManager getConnectionPool() { // if (connectionPool == null) { // reInitializeConnectionPool(); // } // return connectionPool; // } // // public void reInitializeConnectionPool() { // connectionPool = new PoolingHttpClientConnectionManager(CONNECTION_ALIVE_TIME_SECOND, TimeUnit.SECONDS); // } // // public void setConnectionAliveTimeSecond(int connectionAliveTimeSecond) { // CONNECTION_ALIVE_TIME_SECOND = connectionAliveTimeSecond; // reInitializeConnectionPool(); // } // // // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/datamodel/GlobalAnnounceInfo.java // @Data // public class GlobalAnnounceInfo { // @SerializedName("msg") // private String message; // private int rep; // @SerializedName("url") // private String URL; // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuEvent.java // @Getter // public class DanmakuEvent extends EventObject { // private Kind kind; // private Object param; // // /** // * Constructs a prototypical Event. // * // * @param source The object on which the Event initially occurred. // * @throws IllegalArgumentException if source is null. // */ // public DanmakuEvent(Object source) { // super(source); // } // // public DanmakuEvent(Object source, Object param, Kind kind) { // super(source); // this.kind = kind; // this.param = param; // } // // public enum Kind { // JOINED, ERROR, ERROR_DOWN, NEW_DANMAKU, WATCHER_COUNT, // START_STOP, WELCOME_VIP, GIVE_GIFT, GLOBAL_GIFT, GLOBAL_ANNOUNCE // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuListener.java // public interface DanmakuListener { // void danmakuEvent(@NotNull DanmakuEvent event); // // void watcherCountEvent(@NotNull DanmakuEvent event); // // void errorEvent(@NotNull DanmakuEvent event); // // void startStopEvent(@NotNull DanmakuEvent event); // // void statusEvent(@NotNull DanmakuEvent event); // // void welcomeVipEvent(@NotNull DanmakuEvent event); // // void giveGiftEvent(@NotNull DanmakuEvent event); // // void globalGiftEvent(@NotNull DanmakuEvent event); // // void globalAnnounceEvent(@NotNull DanmakuEvent event); // } // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/dispatch/GlobalAnnounceDispatcher.java import charlie.bililivelib.Globals; import charlie.bililivelib.danmaku.datamodel.GlobalAnnounceInfo; import charlie.bililivelib.danmaku.event.DanmakuEvent; import charlie.bililivelib.danmaku.event.DanmakuListener; import com.google.gson.JsonObject; import org.jetbrains.annotations.NotNull; import java.util.List; package charlie.bililivelib.danmaku.dispatch; /** * 分发公告的分发器。对COMMAND为'SYS_MSG'的事件有效。 * * @author Charlie Jiang * @since rv1 */ public class GlobalAnnounceDispatcher extends AbstractJSONDispatcher { public static final String[] ACCEPTABLE_COMMANDS = { "SYS_MSG" }; private static GlobalAnnounceDispatcher GLOBAL_INSTANCE; @NotNull public static GlobalAnnounceDispatcher getGlobalInstance() { if (GLOBAL_INSTANCE == null) { GLOBAL_INSTANCE = new GlobalAnnounceDispatcher(); } return GLOBAL_INSTANCE; } @Override protected String[] getAcceptableCommands() { return ACCEPTABLE_COMMANDS; } /** * {@inheritDoc} * @param listeners 监听器列表 * @param rootObject 事件内容产生的JSON对象结构 * @param source 事件发生源 */ @Override public void dispatch(List<DanmakuListener> listeners, JsonObject rootObject, Object source) { if (rootObject.has("tv_id")) return; //SMALL TV.
GlobalAnnounceInfo announce = Globals.get().gson()
cqjjjzr/BiliLiveLib
BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/dispatch/GlobalAnnounceDispatcher.java
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/Globals.java // public class Globals { // private static final String BILI_PASSPORT_HOST_ROOT = "passport.bilibili.com"; // private static final String BILI_LIVE_HOST_ROOT = "live.bilibili.com"; // @Getter // private static int CONNECTION_ALIVE_TIME_SECOND = 10; // private static Globals instance; // @Getter // private HttpHost biliLiveRoot; // @Getter // private HttpHost biliPassportHttpsRoot; // private ThreadLocal<Gson> gson; // // private HttpClientConnectionManager connectionPool; // @Getter // private SSLContext bilibiliSSLContext; // // public static Globals get() { // if (instance == null) { // instance = new Globals(); // instance.init(); // } // return instance; // } // // private void init() { // biliLiveRoot = new HttpHost(BILI_LIVE_HOST_ROOT); // //Visit bilibili passport via https. 443 is the https port. // biliPassportHttpsRoot = new HttpHost(BILI_PASSPORT_HOST_ROOT, 443, "https"); // gson = ThreadLocal.withInitial(() -> new GsonBuilder() // .setLenient() // .create()); // // try { // bilibiliSSLContext = SSLContextBuilder.create() // .loadTrustMaterial(new BilibiliTrustStrategy()) // .build(); // } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) { // throw new AssertionError("failed initializing bilibili ssl context!"); // } // } // // public Gson gson() { // return gson.get(); // } // // public HttpClientConnectionManager getConnectionPool() { // if (connectionPool == null) { // reInitializeConnectionPool(); // } // return connectionPool; // } // // public void reInitializeConnectionPool() { // connectionPool = new PoolingHttpClientConnectionManager(CONNECTION_ALIVE_TIME_SECOND, TimeUnit.SECONDS); // } // // public void setConnectionAliveTimeSecond(int connectionAliveTimeSecond) { // CONNECTION_ALIVE_TIME_SECOND = connectionAliveTimeSecond; // reInitializeConnectionPool(); // } // // // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/datamodel/GlobalAnnounceInfo.java // @Data // public class GlobalAnnounceInfo { // @SerializedName("msg") // private String message; // private int rep; // @SerializedName("url") // private String URL; // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuEvent.java // @Getter // public class DanmakuEvent extends EventObject { // private Kind kind; // private Object param; // // /** // * Constructs a prototypical Event. // * // * @param source The object on which the Event initially occurred. // * @throws IllegalArgumentException if source is null. // */ // public DanmakuEvent(Object source) { // super(source); // } // // public DanmakuEvent(Object source, Object param, Kind kind) { // super(source); // this.kind = kind; // this.param = param; // } // // public enum Kind { // JOINED, ERROR, ERROR_DOWN, NEW_DANMAKU, WATCHER_COUNT, // START_STOP, WELCOME_VIP, GIVE_GIFT, GLOBAL_GIFT, GLOBAL_ANNOUNCE // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuListener.java // public interface DanmakuListener { // void danmakuEvent(@NotNull DanmakuEvent event); // // void watcherCountEvent(@NotNull DanmakuEvent event); // // void errorEvent(@NotNull DanmakuEvent event); // // void startStopEvent(@NotNull DanmakuEvent event); // // void statusEvent(@NotNull DanmakuEvent event); // // void welcomeVipEvent(@NotNull DanmakuEvent event); // // void giveGiftEvent(@NotNull DanmakuEvent event); // // void globalGiftEvent(@NotNull DanmakuEvent event); // // void globalAnnounceEvent(@NotNull DanmakuEvent event); // }
import charlie.bililivelib.Globals; import charlie.bililivelib.danmaku.datamodel.GlobalAnnounceInfo; import charlie.bililivelib.danmaku.event.DanmakuEvent; import charlie.bililivelib.danmaku.event.DanmakuListener; import com.google.gson.JsonObject; import org.jetbrains.annotations.NotNull; import java.util.List;
package charlie.bililivelib.danmaku.dispatch; /** * 分发公告的分发器。对COMMAND为'SYS_MSG'的事件有效。 * * @author Charlie Jiang * @since rv1 */ public class GlobalAnnounceDispatcher extends AbstractJSONDispatcher { public static final String[] ACCEPTABLE_COMMANDS = { "SYS_MSG" }; private static GlobalAnnounceDispatcher GLOBAL_INSTANCE; @NotNull public static GlobalAnnounceDispatcher getGlobalInstance() { if (GLOBAL_INSTANCE == null) { GLOBAL_INSTANCE = new GlobalAnnounceDispatcher(); } return GLOBAL_INSTANCE; } @Override protected String[] getAcceptableCommands() { return ACCEPTABLE_COMMANDS; } /** * {@inheritDoc} * @param listeners 监听器列表 * @param rootObject 事件内容产生的JSON对象结构 * @param source 事件发生源 */ @Override public void dispatch(List<DanmakuListener> listeners, JsonObject rootObject, Object source) { if (rootObject.has("tv_id")) return; //SMALL TV. GlobalAnnounceInfo announce = Globals.get().gson() .fromJson(rootObject, GlobalAnnounceInfo.class);
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/Globals.java // public class Globals { // private static final String BILI_PASSPORT_HOST_ROOT = "passport.bilibili.com"; // private static final String BILI_LIVE_HOST_ROOT = "live.bilibili.com"; // @Getter // private static int CONNECTION_ALIVE_TIME_SECOND = 10; // private static Globals instance; // @Getter // private HttpHost biliLiveRoot; // @Getter // private HttpHost biliPassportHttpsRoot; // private ThreadLocal<Gson> gson; // // private HttpClientConnectionManager connectionPool; // @Getter // private SSLContext bilibiliSSLContext; // // public static Globals get() { // if (instance == null) { // instance = new Globals(); // instance.init(); // } // return instance; // } // // private void init() { // biliLiveRoot = new HttpHost(BILI_LIVE_HOST_ROOT); // //Visit bilibili passport via https. 443 is the https port. // biliPassportHttpsRoot = new HttpHost(BILI_PASSPORT_HOST_ROOT, 443, "https"); // gson = ThreadLocal.withInitial(() -> new GsonBuilder() // .setLenient() // .create()); // // try { // bilibiliSSLContext = SSLContextBuilder.create() // .loadTrustMaterial(new BilibiliTrustStrategy()) // .build(); // } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) { // throw new AssertionError("failed initializing bilibili ssl context!"); // } // } // // public Gson gson() { // return gson.get(); // } // // public HttpClientConnectionManager getConnectionPool() { // if (connectionPool == null) { // reInitializeConnectionPool(); // } // return connectionPool; // } // // public void reInitializeConnectionPool() { // connectionPool = new PoolingHttpClientConnectionManager(CONNECTION_ALIVE_TIME_SECOND, TimeUnit.SECONDS); // } // // public void setConnectionAliveTimeSecond(int connectionAliveTimeSecond) { // CONNECTION_ALIVE_TIME_SECOND = connectionAliveTimeSecond; // reInitializeConnectionPool(); // } // // // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/datamodel/GlobalAnnounceInfo.java // @Data // public class GlobalAnnounceInfo { // @SerializedName("msg") // private String message; // private int rep; // @SerializedName("url") // private String URL; // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuEvent.java // @Getter // public class DanmakuEvent extends EventObject { // private Kind kind; // private Object param; // // /** // * Constructs a prototypical Event. // * // * @param source The object on which the Event initially occurred. // * @throws IllegalArgumentException if source is null. // */ // public DanmakuEvent(Object source) { // super(source); // } // // public DanmakuEvent(Object source, Object param, Kind kind) { // super(source); // this.kind = kind; // this.param = param; // } // // public enum Kind { // JOINED, ERROR, ERROR_DOWN, NEW_DANMAKU, WATCHER_COUNT, // START_STOP, WELCOME_VIP, GIVE_GIFT, GLOBAL_GIFT, GLOBAL_ANNOUNCE // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuListener.java // public interface DanmakuListener { // void danmakuEvent(@NotNull DanmakuEvent event); // // void watcherCountEvent(@NotNull DanmakuEvent event); // // void errorEvent(@NotNull DanmakuEvent event); // // void startStopEvent(@NotNull DanmakuEvent event); // // void statusEvent(@NotNull DanmakuEvent event); // // void welcomeVipEvent(@NotNull DanmakuEvent event); // // void giveGiftEvent(@NotNull DanmakuEvent event); // // void globalGiftEvent(@NotNull DanmakuEvent event); // // void globalAnnounceEvent(@NotNull DanmakuEvent event); // } // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/dispatch/GlobalAnnounceDispatcher.java import charlie.bililivelib.Globals; import charlie.bililivelib.danmaku.datamodel.GlobalAnnounceInfo; import charlie.bililivelib.danmaku.event.DanmakuEvent; import charlie.bililivelib.danmaku.event.DanmakuListener; import com.google.gson.JsonObject; import org.jetbrains.annotations.NotNull; import java.util.List; package charlie.bililivelib.danmaku.dispatch; /** * 分发公告的分发器。对COMMAND为'SYS_MSG'的事件有效。 * * @author Charlie Jiang * @since rv1 */ public class GlobalAnnounceDispatcher extends AbstractJSONDispatcher { public static final String[] ACCEPTABLE_COMMANDS = { "SYS_MSG" }; private static GlobalAnnounceDispatcher GLOBAL_INSTANCE; @NotNull public static GlobalAnnounceDispatcher getGlobalInstance() { if (GLOBAL_INSTANCE == null) { GLOBAL_INSTANCE = new GlobalAnnounceDispatcher(); } return GLOBAL_INSTANCE; } @Override protected String[] getAcceptableCommands() { return ACCEPTABLE_COMMANDS; } /** * {@inheritDoc} * @param listeners 监听器列表 * @param rootObject 事件内容产生的JSON对象结构 * @param source 事件发生源 */ @Override public void dispatch(List<DanmakuListener> listeners, JsonObject rootObject, Object source) { if (rootObject.has("tv_id")) return; //SMALL TV. GlobalAnnounceInfo announce = Globals.get().gson() .fromJson(rootObject, GlobalAnnounceInfo.class);
DanmakuEvent event = new DanmakuEvent(source, announce, DanmakuEvent.Kind.GLOBAL_ANNOUNCE);
cqjjjzr/BiliLiveLib
BiliLiveLib/src/test/java/charlie/bililivelib/capsuletoy/CapsuleToyProtocolTest.java
// Path: BiliLiveLib/src/test/java/charlie/bililivelib/TestSessionHelper.java // public class TestSessionHelper { // public static Session initSession() throws IOException, BiliLiveException { // BasicCookieStore store = new BasicCookieStore(); // Session session = new Session(HttpClientBuilder.create() // .setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.96 Safari/537.36") // .setConnectionManager(Globals.get().getConnectionPool()) // .setSSLContext(Globals.get().getBilibiliSSLContext()) // .setDefaultCookieStore(store).build(), store); // Path cookieFile = Paths.get("cookies.bin"); // if (Files.exists(cookieFile)) { // loadSessionFromFile(session); // } else { // login(session); // Files.createFile(cookieFile); // } // // ObjectOutputStream stream = new ObjectOutputStream(Files.newOutputStream(cookieFile, StandardOpenOption.TRUNCATE_EXISTING)); // stream.writeObject(store); // stream.close(); // return session; // } // // private static void login(Session session) throws BiliLiveException { // String email = testInput("E-Mail:"); // String password = testInput("Password:"); // // SessionLoginHelper helper = new SessionLoginHelper(email, password, // SessionLoginHelper.DEFAULT_LOGIN_TIMEOUT_MILLIS, // true, BiliLiveLib.DEFAULT_USER_AGENT); // JOptionPane.showMessageDialog(null, "Captcha", "Captcha", // JOptionPane.PLAIN_MESSAGE, new ImageIcon(helper.getCaptcha())); // // String captcha = testInput("Captcha:"); // helper.loginWithCaptcha(captcha); // // System.out.println(helper.getStatus()); // assertTrue(helper.getStatus() == SessionLoginHelper.LoginStatus.SUCCESS); // // helper.fillSession(session); // } // // private static void loadSessionFromFile(Session session) throws IOException { // String xml = new String(Files.readAllBytes(Paths.get("cookies.bin"))); // session.fromBase64(xml); // } // // static String testInput(String message) { // return JOptionPane.showInputDialog(null, message, "Test", // JOptionPane.PLAIN_MESSAGE); // } // // public static void main(String[] args) throws IOException, BiliLiveException { // initSession(); // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/exceptions/BiliLiveException.java // public class BiliLiveException extends Exception { // public BiliLiveException() { // super(); // } // // public BiliLiveException(String message) { // super(message); // } // // public BiliLiveException(String message, Throwable cause) { // super(message, cause); // } // }
import charlie.bililivelib.TestSessionHelper; import charlie.bililivelib.exceptions.BiliLiveException; import lombok.Getter; import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; import java.io.IOException;
package charlie.bililivelib.capsuletoy; @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class CapsuleToyProtocolTest { private static CapsuleToyProtocol protocol; @BeforeClass
// Path: BiliLiveLib/src/test/java/charlie/bililivelib/TestSessionHelper.java // public class TestSessionHelper { // public static Session initSession() throws IOException, BiliLiveException { // BasicCookieStore store = new BasicCookieStore(); // Session session = new Session(HttpClientBuilder.create() // .setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.96 Safari/537.36") // .setConnectionManager(Globals.get().getConnectionPool()) // .setSSLContext(Globals.get().getBilibiliSSLContext()) // .setDefaultCookieStore(store).build(), store); // Path cookieFile = Paths.get("cookies.bin"); // if (Files.exists(cookieFile)) { // loadSessionFromFile(session); // } else { // login(session); // Files.createFile(cookieFile); // } // // ObjectOutputStream stream = new ObjectOutputStream(Files.newOutputStream(cookieFile, StandardOpenOption.TRUNCATE_EXISTING)); // stream.writeObject(store); // stream.close(); // return session; // } // // private static void login(Session session) throws BiliLiveException { // String email = testInput("E-Mail:"); // String password = testInput("Password:"); // // SessionLoginHelper helper = new SessionLoginHelper(email, password, // SessionLoginHelper.DEFAULT_LOGIN_TIMEOUT_MILLIS, // true, BiliLiveLib.DEFAULT_USER_AGENT); // JOptionPane.showMessageDialog(null, "Captcha", "Captcha", // JOptionPane.PLAIN_MESSAGE, new ImageIcon(helper.getCaptcha())); // // String captcha = testInput("Captcha:"); // helper.loginWithCaptcha(captcha); // // System.out.println(helper.getStatus()); // assertTrue(helper.getStatus() == SessionLoginHelper.LoginStatus.SUCCESS); // // helper.fillSession(session); // } // // private static void loadSessionFromFile(Session session) throws IOException { // String xml = new String(Files.readAllBytes(Paths.get("cookies.bin"))); // session.fromBase64(xml); // } // // static String testInput(String message) { // return JOptionPane.showInputDialog(null, message, "Test", // JOptionPane.PLAIN_MESSAGE); // } // // public static void main(String[] args) throws IOException, BiliLiveException { // initSession(); // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/exceptions/BiliLiveException.java // public class BiliLiveException extends Exception { // public BiliLiveException() { // super(); // } // // public BiliLiveException(String message) { // super(message); // } // // public BiliLiveException(String message, Throwable cause) { // super(message, cause); // } // } // Path: BiliLiveLib/src/test/java/charlie/bililivelib/capsuletoy/CapsuleToyProtocolTest.java import charlie.bililivelib.TestSessionHelper; import charlie.bililivelib.exceptions.BiliLiveException; import lombok.Getter; import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; import java.io.IOException; package charlie.bililivelib.capsuletoy; @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class CapsuleToyProtocolTest { private static CapsuleToyProtocol protocol; @BeforeClass
public static void init() throws IOException, BiliLiveException {
cqjjjzr/BiliLiveLib
BiliLiveLib/src/test/java/charlie/bililivelib/capsuletoy/CapsuleToyProtocolTest.java
// Path: BiliLiveLib/src/test/java/charlie/bililivelib/TestSessionHelper.java // public class TestSessionHelper { // public static Session initSession() throws IOException, BiliLiveException { // BasicCookieStore store = new BasicCookieStore(); // Session session = new Session(HttpClientBuilder.create() // .setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.96 Safari/537.36") // .setConnectionManager(Globals.get().getConnectionPool()) // .setSSLContext(Globals.get().getBilibiliSSLContext()) // .setDefaultCookieStore(store).build(), store); // Path cookieFile = Paths.get("cookies.bin"); // if (Files.exists(cookieFile)) { // loadSessionFromFile(session); // } else { // login(session); // Files.createFile(cookieFile); // } // // ObjectOutputStream stream = new ObjectOutputStream(Files.newOutputStream(cookieFile, StandardOpenOption.TRUNCATE_EXISTING)); // stream.writeObject(store); // stream.close(); // return session; // } // // private static void login(Session session) throws BiliLiveException { // String email = testInput("E-Mail:"); // String password = testInput("Password:"); // // SessionLoginHelper helper = new SessionLoginHelper(email, password, // SessionLoginHelper.DEFAULT_LOGIN_TIMEOUT_MILLIS, // true, BiliLiveLib.DEFAULT_USER_AGENT); // JOptionPane.showMessageDialog(null, "Captcha", "Captcha", // JOptionPane.PLAIN_MESSAGE, new ImageIcon(helper.getCaptcha())); // // String captcha = testInput("Captcha:"); // helper.loginWithCaptcha(captcha); // // System.out.println(helper.getStatus()); // assertTrue(helper.getStatus() == SessionLoginHelper.LoginStatus.SUCCESS); // // helper.fillSession(session); // } // // private static void loadSessionFromFile(Session session) throws IOException { // String xml = new String(Files.readAllBytes(Paths.get("cookies.bin"))); // session.fromBase64(xml); // } // // static String testInput(String message) { // return JOptionPane.showInputDialog(null, message, "Test", // JOptionPane.PLAIN_MESSAGE); // } // // public static void main(String[] args) throws IOException, BiliLiveException { // initSession(); // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/exceptions/BiliLiveException.java // public class BiliLiveException extends Exception { // public BiliLiveException() { // super(); // } // // public BiliLiveException(String message) { // super(message); // } // // public BiliLiveException(String message, Throwable cause) { // super(message, cause); // } // }
import charlie.bililivelib.TestSessionHelper; import charlie.bililivelib.exceptions.BiliLiveException; import lombok.Getter; import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; import java.io.IOException;
package charlie.bililivelib.capsuletoy; @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class CapsuleToyProtocolTest { private static CapsuleToyProtocol protocol; @BeforeClass public static void init() throws IOException, BiliLiveException {
// Path: BiliLiveLib/src/test/java/charlie/bililivelib/TestSessionHelper.java // public class TestSessionHelper { // public static Session initSession() throws IOException, BiliLiveException { // BasicCookieStore store = new BasicCookieStore(); // Session session = new Session(HttpClientBuilder.create() // .setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.96 Safari/537.36") // .setConnectionManager(Globals.get().getConnectionPool()) // .setSSLContext(Globals.get().getBilibiliSSLContext()) // .setDefaultCookieStore(store).build(), store); // Path cookieFile = Paths.get("cookies.bin"); // if (Files.exists(cookieFile)) { // loadSessionFromFile(session); // } else { // login(session); // Files.createFile(cookieFile); // } // // ObjectOutputStream stream = new ObjectOutputStream(Files.newOutputStream(cookieFile, StandardOpenOption.TRUNCATE_EXISTING)); // stream.writeObject(store); // stream.close(); // return session; // } // // private static void login(Session session) throws BiliLiveException { // String email = testInput("E-Mail:"); // String password = testInput("Password:"); // // SessionLoginHelper helper = new SessionLoginHelper(email, password, // SessionLoginHelper.DEFAULT_LOGIN_TIMEOUT_MILLIS, // true, BiliLiveLib.DEFAULT_USER_AGENT); // JOptionPane.showMessageDialog(null, "Captcha", "Captcha", // JOptionPane.PLAIN_MESSAGE, new ImageIcon(helper.getCaptcha())); // // String captcha = testInput("Captcha:"); // helper.loginWithCaptcha(captcha); // // System.out.println(helper.getStatus()); // assertTrue(helper.getStatus() == SessionLoginHelper.LoginStatus.SUCCESS); // // helper.fillSession(session); // } // // private static void loadSessionFromFile(Session session) throws IOException { // String xml = new String(Files.readAllBytes(Paths.get("cookies.bin"))); // session.fromBase64(xml); // } // // static String testInput(String message) { // return JOptionPane.showInputDialog(null, message, "Test", // JOptionPane.PLAIN_MESSAGE); // } // // public static void main(String[] args) throws IOException, BiliLiveException { // initSession(); // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/exceptions/BiliLiveException.java // public class BiliLiveException extends Exception { // public BiliLiveException() { // super(); // } // // public BiliLiveException(String message) { // super(message); // } // // public BiliLiveException(String message, Throwable cause) { // super(message, cause); // } // } // Path: BiliLiveLib/src/test/java/charlie/bililivelib/capsuletoy/CapsuleToyProtocolTest.java import charlie.bililivelib.TestSessionHelper; import charlie.bililivelib.exceptions.BiliLiveException; import lombok.Getter; import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; import java.io.IOException; package charlie.bililivelib.capsuletoy; @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class CapsuleToyProtocolTest { private static CapsuleToyProtocol protocol; @BeforeClass public static void init() throws IOException, BiliLiveException {
protocol = new CapsuleToyProtocol(TestSessionHelper.initSession());
cqjjjzr/BiliLiveLib
BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/datamodel/JoinServerJson.java
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/Globals.java // public class Globals { // private static final String BILI_PASSPORT_HOST_ROOT = "passport.bilibili.com"; // private static final String BILI_LIVE_HOST_ROOT = "live.bilibili.com"; // @Getter // private static int CONNECTION_ALIVE_TIME_SECOND = 10; // private static Globals instance; // @Getter // private HttpHost biliLiveRoot; // @Getter // private HttpHost biliPassportHttpsRoot; // private ThreadLocal<Gson> gson; // // private HttpClientConnectionManager connectionPool; // @Getter // private SSLContext bilibiliSSLContext; // // public static Globals get() { // if (instance == null) { // instance = new Globals(); // instance.init(); // } // return instance; // } // // private void init() { // biliLiveRoot = new HttpHost(BILI_LIVE_HOST_ROOT); // //Visit bilibili passport via https. 443 is the https port. // biliPassportHttpsRoot = new HttpHost(BILI_PASSPORT_HOST_ROOT, 443, "https"); // gson = ThreadLocal.withInitial(() -> new GsonBuilder() // .setLenient() // .create()); // // try { // bilibiliSSLContext = SSLContextBuilder.create() // .loadTrustMaterial(new BilibiliTrustStrategy()) // .build(); // } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) { // throw new AssertionError("failed initializing bilibili ssl context!"); // } // } // // public Gson gson() { // return gson.get(); // } // // public HttpClientConnectionManager getConnectionPool() { // if (connectionPool == null) { // reInitializeConnectionPool(); // } // return connectionPool; // } // // public void reInitializeConnectionPool() { // connectionPool = new PoolingHttpClientConnectionManager(CONNECTION_ALIVE_TIME_SECOND, TimeUnit.SECONDS); // } // // public void setConnectionAliveTimeSecond(int connectionAliveTimeSecond) { // CONNECTION_ALIVE_TIME_SECOND = connectionAliveTimeSecond; // reInitializeConnectionPool(); // } // // // }
import charlie.bililivelib.Globals; import com.google.gson.annotations.SerializedName; import lombok.AllArgsConstructor; import lombok.Data;
package charlie.bililivelib.danmaku.datamodel; /** * 用于封装加入服务器的请求信息。仅内部使用。 * * @author Charlie Jiang * @since rv1 */ @Data @AllArgsConstructor public class JoinServerJson { @SerializedName("roomid") private int roomID; @SerializedName("uid") private long userID; private String generateJSON() {
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/Globals.java // public class Globals { // private static final String BILI_PASSPORT_HOST_ROOT = "passport.bilibili.com"; // private static final String BILI_LIVE_HOST_ROOT = "live.bilibili.com"; // @Getter // private static int CONNECTION_ALIVE_TIME_SECOND = 10; // private static Globals instance; // @Getter // private HttpHost biliLiveRoot; // @Getter // private HttpHost biliPassportHttpsRoot; // private ThreadLocal<Gson> gson; // // private HttpClientConnectionManager connectionPool; // @Getter // private SSLContext bilibiliSSLContext; // // public static Globals get() { // if (instance == null) { // instance = new Globals(); // instance.init(); // } // return instance; // } // // private void init() { // biliLiveRoot = new HttpHost(BILI_LIVE_HOST_ROOT); // //Visit bilibili passport via https. 443 is the https port. // biliPassportHttpsRoot = new HttpHost(BILI_PASSPORT_HOST_ROOT, 443, "https"); // gson = ThreadLocal.withInitial(() -> new GsonBuilder() // .setLenient() // .create()); // // try { // bilibiliSSLContext = SSLContextBuilder.create() // .loadTrustMaterial(new BilibiliTrustStrategy()) // .build(); // } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) { // throw new AssertionError("failed initializing bilibili ssl context!"); // } // } // // public Gson gson() { // return gson.get(); // } // // public HttpClientConnectionManager getConnectionPool() { // if (connectionPool == null) { // reInitializeConnectionPool(); // } // return connectionPool; // } // // public void reInitializeConnectionPool() { // connectionPool = new PoolingHttpClientConnectionManager(CONNECTION_ALIVE_TIME_SECOND, TimeUnit.SECONDS); // } // // public void setConnectionAliveTimeSecond(int connectionAliveTimeSecond) { // CONNECTION_ALIVE_TIME_SECOND = connectionAliveTimeSecond; // reInitializeConnectionPool(); // } // // // } // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/datamodel/JoinServerJson.java import charlie.bililivelib.Globals; import com.google.gson.annotations.SerializedName; import lombok.AllArgsConstructor; import lombok.Data; package charlie.bililivelib.danmaku.datamodel; /** * 用于封装加入服务器的请求信息。仅内部使用。 * * @author Charlie Jiang * @since rv1 */ @Data @AllArgsConstructor public class JoinServerJson { @SerializedName("roomid") private int roomID; @SerializedName("uid") private long userID; private String generateJSON() {
return Globals.get().gson().toJson(this);
cqjjjzr/BiliLiveLib
BiliLiveLib/src/main/java/charlie/bililivelib/streamer/AbstractThreadBasedDownloader.java
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/I18n.java // public class I18n { // public static final String BUNDLE_NAME = "BiliLiveLib"; // private static Map<String, String> strings; // // static { // init(); // } // // /** // * 重新依照当前Locale获取并填充本地化字符串。在切换Locale后调用。 // */ // public static void init() { // strings = new HashMap<>(); // fillResourceBundle(); // } // // private static void fillResourceBundle() { // ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE_NAME); // for (String key : resourceBundle.keySet()) { // strings.put(key, resourceBundle.getString(key)); // } // } // // /** // * 获取给定Key的本地化文本。 // * @param key 键 // * @return 本地化文本 // */ // @Nls // public static String getString(@NonNls @NotNull String key) { // return strings.get(key); // } // // /** // * 获取基于给定Key的本地化格式化文本。 // * @param key 指向格式化模式的键 // * @param arguments 格式化文本的参数 // * @return 本地化并格式化后的文本 // */ // @NotNull // public static String format(@NonNls @NotNull String key, // @NonNls @NotNull Object... arguments) { // return MessageFormat.format(strings.get(key), arguments); // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/streamer/event/DownloadEvent.java // @Getter // @ToString // public class DownloadEvent extends EventObject { // private String message; // private Kind kind; // // public DownloadEvent(Object source) { // super(source); // message = ""; // kind = Kind.OTHER; // } // // public DownloadEvent(Object source, @Nls String message, Kind kind) { // super(source); // this.message = message; // this.kind = kind; // } // // public enum Kind { // STARTING, STARTED, STOPPED, LIVE_STOPPED, ERROR, OTHER // } // }
import charlie.bililivelib.I18n; import charlie.bililivelib.streamer.event.DownloadEvent;
package charlie.bililivelib.streamer; public abstract class AbstractThreadBasedDownloader extends AbstractDownloader implements Runnable { private Thread thread; /** * {@inheritDoc} * * @throws IllegalStateException 当本下载器状态非停止或错误时抛出 */ @Override public void start() { if (status != Status.STOPPED && status != Status.ERROR) throw new IllegalStateException("status != STOPPED || ERROR"); thread = new Thread(this); thread.start(); } /** * {@inheritDoc} */ @Override public void tryStop() { status = Status.STOPPING; thread.interrupt();
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/I18n.java // public class I18n { // public static final String BUNDLE_NAME = "BiliLiveLib"; // private static Map<String, String> strings; // // static { // init(); // } // // /** // * 重新依照当前Locale获取并填充本地化字符串。在切换Locale后调用。 // */ // public static void init() { // strings = new HashMap<>(); // fillResourceBundle(); // } // // private static void fillResourceBundle() { // ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE_NAME); // for (String key : resourceBundle.keySet()) { // strings.put(key, resourceBundle.getString(key)); // } // } // // /** // * 获取给定Key的本地化文本。 // * @param key 键 // * @return 本地化文本 // */ // @Nls // public static String getString(@NonNls @NotNull String key) { // return strings.get(key); // } // // /** // * 获取基于给定Key的本地化格式化文本。 // * @param key 指向格式化模式的键 // * @param arguments 格式化文本的参数 // * @return 本地化并格式化后的文本 // */ // @NotNull // public static String format(@NonNls @NotNull String key, // @NonNls @NotNull Object... arguments) { // return MessageFormat.format(strings.get(key), arguments); // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/streamer/event/DownloadEvent.java // @Getter // @ToString // public class DownloadEvent extends EventObject { // private String message; // private Kind kind; // // public DownloadEvent(Object source) { // super(source); // message = ""; // kind = Kind.OTHER; // } // // public DownloadEvent(Object source, @Nls String message, Kind kind) { // super(source); // this.message = message; // this.kind = kind; // } // // public enum Kind { // STARTING, STARTED, STOPPED, LIVE_STOPPED, ERROR, OTHER // } // } // Path: BiliLiveLib/src/main/java/charlie/bililivelib/streamer/AbstractThreadBasedDownloader.java import charlie.bililivelib.I18n; import charlie.bililivelib.streamer.event.DownloadEvent; package charlie.bililivelib.streamer; public abstract class AbstractThreadBasedDownloader extends AbstractDownloader implements Runnable { private Thread thread; /** * {@inheritDoc} * * @throws IllegalStateException 当本下载器状态非停止或错误时抛出 */ @Override public void start() { if (status != Status.STOPPED && status != Status.ERROR) throw new IllegalStateException("status != STOPPED || ERROR"); thread = new Thread(this); thread.start(); } /** * {@inheritDoc} */ @Override public void tryStop() { status = Status.STOPPING; thread.interrupt();
fireDownloadEvent(I18n.getString("msg.try_stopping"), DownloadEvent.Kind.STOPPED);
cqjjjzr/BiliLiveLib
BiliLiveLib/src/main/java/charlie/bililivelib/streamer/AbstractThreadBasedDownloader.java
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/I18n.java // public class I18n { // public static final String BUNDLE_NAME = "BiliLiveLib"; // private static Map<String, String> strings; // // static { // init(); // } // // /** // * 重新依照当前Locale获取并填充本地化字符串。在切换Locale后调用。 // */ // public static void init() { // strings = new HashMap<>(); // fillResourceBundle(); // } // // private static void fillResourceBundle() { // ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE_NAME); // for (String key : resourceBundle.keySet()) { // strings.put(key, resourceBundle.getString(key)); // } // } // // /** // * 获取给定Key的本地化文本。 // * @param key 键 // * @return 本地化文本 // */ // @Nls // public static String getString(@NonNls @NotNull String key) { // return strings.get(key); // } // // /** // * 获取基于给定Key的本地化格式化文本。 // * @param key 指向格式化模式的键 // * @param arguments 格式化文本的参数 // * @return 本地化并格式化后的文本 // */ // @NotNull // public static String format(@NonNls @NotNull String key, // @NonNls @NotNull Object... arguments) { // return MessageFormat.format(strings.get(key), arguments); // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/streamer/event/DownloadEvent.java // @Getter // @ToString // public class DownloadEvent extends EventObject { // private String message; // private Kind kind; // // public DownloadEvent(Object source) { // super(source); // message = ""; // kind = Kind.OTHER; // } // // public DownloadEvent(Object source, @Nls String message, Kind kind) { // super(source); // this.message = message; // this.kind = kind; // } // // public enum Kind { // STARTING, STARTED, STOPPED, LIVE_STOPPED, ERROR, OTHER // } // }
import charlie.bililivelib.I18n; import charlie.bililivelib.streamer.event.DownloadEvent;
package charlie.bililivelib.streamer; public abstract class AbstractThreadBasedDownloader extends AbstractDownloader implements Runnable { private Thread thread; /** * {@inheritDoc} * * @throws IllegalStateException 当本下载器状态非停止或错误时抛出 */ @Override public void start() { if (status != Status.STOPPED && status != Status.ERROR) throw new IllegalStateException("status != STOPPED || ERROR"); thread = new Thread(this); thread.start(); } /** * {@inheritDoc} */ @Override public void tryStop() { status = Status.STOPPING; thread.interrupt();
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/I18n.java // public class I18n { // public static final String BUNDLE_NAME = "BiliLiveLib"; // private static Map<String, String> strings; // // static { // init(); // } // // /** // * 重新依照当前Locale获取并填充本地化字符串。在切换Locale后调用。 // */ // public static void init() { // strings = new HashMap<>(); // fillResourceBundle(); // } // // private static void fillResourceBundle() { // ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE_NAME); // for (String key : resourceBundle.keySet()) { // strings.put(key, resourceBundle.getString(key)); // } // } // // /** // * 获取给定Key的本地化文本。 // * @param key 键 // * @return 本地化文本 // */ // @Nls // public static String getString(@NonNls @NotNull String key) { // return strings.get(key); // } // // /** // * 获取基于给定Key的本地化格式化文本。 // * @param key 指向格式化模式的键 // * @param arguments 格式化文本的参数 // * @return 本地化并格式化后的文本 // */ // @NotNull // public static String format(@NonNls @NotNull String key, // @NonNls @NotNull Object... arguments) { // return MessageFormat.format(strings.get(key), arguments); // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/streamer/event/DownloadEvent.java // @Getter // @ToString // public class DownloadEvent extends EventObject { // private String message; // private Kind kind; // // public DownloadEvent(Object source) { // super(source); // message = ""; // kind = Kind.OTHER; // } // // public DownloadEvent(Object source, @Nls String message, Kind kind) { // super(source); // this.message = message; // this.kind = kind; // } // // public enum Kind { // STARTING, STARTED, STOPPED, LIVE_STOPPED, ERROR, OTHER // } // } // Path: BiliLiveLib/src/main/java/charlie/bililivelib/streamer/AbstractThreadBasedDownloader.java import charlie.bililivelib.I18n; import charlie.bililivelib.streamer.event.DownloadEvent; package charlie.bililivelib.streamer; public abstract class AbstractThreadBasedDownloader extends AbstractDownloader implements Runnable { private Thread thread; /** * {@inheritDoc} * * @throws IllegalStateException 当本下载器状态非停止或错误时抛出 */ @Override public void start() { if (status != Status.STOPPED && status != Status.ERROR) throw new IllegalStateException("status != STOPPED || ERROR"); thread = new Thread(this); thread.start(); } /** * {@inheritDoc} */ @Override public void tryStop() { status = Status.STOPPING; thread.interrupt();
fireDownloadEvent(I18n.getString("msg.try_stopping"), DownloadEvent.Kind.STOPPED);
cqjjjzr/BiliLiveLib
BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/dispatch/StartStopDispatcher.java
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/datamodel/StartStopInfo.java // @Data // @AllArgsConstructor // public class StartStopInfo { // private int roomID; // private boolean living; // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuEvent.java // @Getter // public class DanmakuEvent extends EventObject { // private Kind kind; // private Object param; // // /** // * Constructs a prototypical Event. // * // * @param source The object on which the Event initially occurred. // * @throws IllegalArgumentException if source is null. // */ // public DanmakuEvent(Object source) { // super(source); // } // // public DanmakuEvent(Object source, Object param, Kind kind) { // super(source); // this.kind = kind; // this.param = param; // } // // public enum Kind { // JOINED, ERROR, ERROR_DOWN, NEW_DANMAKU, WATCHER_COUNT, // START_STOP, WELCOME_VIP, GIVE_GIFT, GLOBAL_GIFT, GLOBAL_ANNOUNCE // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuListener.java // public interface DanmakuListener { // void danmakuEvent(@NotNull DanmakuEvent event); // // void watcherCountEvent(@NotNull DanmakuEvent event); // // void errorEvent(@NotNull DanmakuEvent event); // // void startStopEvent(@NotNull DanmakuEvent event); // // void statusEvent(@NotNull DanmakuEvent event); // // void welcomeVipEvent(@NotNull DanmakuEvent event); // // void giveGiftEvent(@NotNull DanmakuEvent event); // // void globalGiftEvent(@NotNull DanmakuEvent event); // // void globalAnnounceEvent(@NotNull DanmakuEvent event); // }
import charlie.bililivelib.danmaku.datamodel.StartStopInfo; import charlie.bililivelib.danmaku.event.DanmakuEvent; import charlie.bililivelib.danmaku.event.DanmakuListener; import com.google.gson.JsonObject; import org.jetbrains.annotations.NotNull; import java.util.List;
package charlie.bililivelib.danmaku.dispatch; /** * 分发直播间状态改变事件的分发器。对COMMAND为'LIVE', 'PREPARING'和'ROUND'的事件有效。 * * @author Charlie Jiang * @since rv1 */ public class StartStopDispatcher extends AbstractJSONDispatcher { public static final String[] ACCEPTABLE_COMMANDS = { "LIVE", "PREPARING", "ROUND" }; private static StartStopDispatcher GLOBAL_INSTANCE; @NotNull public static StartStopDispatcher getGlobalInstance() { if (GLOBAL_INSTANCE == null) { GLOBAL_INSTANCE = new StartStopDispatcher(); } return GLOBAL_INSTANCE; } @Override protected String[] getAcceptableCommands() { return ACCEPTABLE_COMMANDS; } /** * {@inheritDoc} * @param listeners 监听器列表 * @param rootObject 事件内容产生的JSON对象结构 * @param source 事件发生源 */ @Override
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/datamodel/StartStopInfo.java // @Data // @AllArgsConstructor // public class StartStopInfo { // private int roomID; // private boolean living; // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuEvent.java // @Getter // public class DanmakuEvent extends EventObject { // private Kind kind; // private Object param; // // /** // * Constructs a prototypical Event. // * // * @param source The object on which the Event initially occurred. // * @throws IllegalArgumentException if source is null. // */ // public DanmakuEvent(Object source) { // super(source); // } // // public DanmakuEvent(Object source, Object param, Kind kind) { // super(source); // this.kind = kind; // this.param = param; // } // // public enum Kind { // JOINED, ERROR, ERROR_DOWN, NEW_DANMAKU, WATCHER_COUNT, // START_STOP, WELCOME_VIP, GIVE_GIFT, GLOBAL_GIFT, GLOBAL_ANNOUNCE // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuListener.java // public interface DanmakuListener { // void danmakuEvent(@NotNull DanmakuEvent event); // // void watcherCountEvent(@NotNull DanmakuEvent event); // // void errorEvent(@NotNull DanmakuEvent event); // // void startStopEvent(@NotNull DanmakuEvent event); // // void statusEvent(@NotNull DanmakuEvent event); // // void welcomeVipEvent(@NotNull DanmakuEvent event); // // void giveGiftEvent(@NotNull DanmakuEvent event); // // void globalGiftEvent(@NotNull DanmakuEvent event); // // void globalAnnounceEvent(@NotNull DanmakuEvent event); // } // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/dispatch/StartStopDispatcher.java import charlie.bililivelib.danmaku.datamodel.StartStopInfo; import charlie.bililivelib.danmaku.event.DanmakuEvent; import charlie.bililivelib.danmaku.event.DanmakuListener; import com.google.gson.JsonObject; import org.jetbrains.annotations.NotNull; import java.util.List; package charlie.bililivelib.danmaku.dispatch; /** * 分发直播间状态改变事件的分发器。对COMMAND为'LIVE', 'PREPARING'和'ROUND'的事件有效。 * * @author Charlie Jiang * @since rv1 */ public class StartStopDispatcher extends AbstractJSONDispatcher { public static final String[] ACCEPTABLE_COMMANDS = { "LIVE", "PREPARING", "ROUND" }; private static StartStopDispatcher GLOBAL_INSTANCE; @NotNull public static StartStopDispatcher getGlobalInstance() { if (GLOBAL_INSTANCE == null) { GLOBAL_INSTANCE = new StartStopDispatcher(); } return GLOBAL_INSTANCE; } @Override protected String[] getAcceptableCommands() { return ACCEPTABLE_COMMANDS; } /** * {@inheritDoc} * @param listeners 监听器列表 * @param rootObject 事件内容产生的JSON对象结构 * @param source 事件发生源 */ @Override
public void dispatch(List<DanmakuListener> listeners, JsonObject rootObject, Object source) {
cqjjjzr/BiliLiveLib
BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/dispatch/StartStopDispatcher.java
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/datamodel/StartStopInfo.java // @Data // @AllArgsConstructor // public class StartStopInfo { // private int roomID; // private boolean living; // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuEvent.java // @Getter // public class DanmakuEvent extends EventObject { // private Kind kind; // private Object param; // // /** // * Constructs a prototypical Event. // * // * @param source The object on which the Event initially occurred. // * @throws IllegalArgumentException if source is null. // */ // public DanmakuEvent(Object source) { // super(source); // } // // public DanmakuEvent(Object source, Object param, Kind kind) { // super(source); // this.kind = kind; // this.param = param; // } // // public enum Kind { // JOINED, ERROR, ERROR_DOWN, NEW_DANMAKU, WATCHER_COUNT, // START_STOP, WELCOME_VIP, GIVE_GIFT, GLOBAL_GIFT, GLOBAL_ANNOUNCE // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuListener.java // public interface DanmakuListener { // void danmakuEvent(@NotNull DanmakuEvent event); // // void watcherCountEvent(@NotNull DanmakuEvent event); // // void errorEvent(@NotNull DanmakuEvent event); // // void startStopEvent(@NotNull DanmakuEvent event); // // void statusEvent(@NotNull DanmakuEvent event); // // void welcomeVipEvent(@NotNull DanmakuEvent event); // // void giveGiftEvent(@NotNull DanmakuEvent event); // // void globalGiftEvent(@NotNull DanmakuEvent event); // // void globalAnnounceEvent(@NotNull DanmakuEvent event); // }
import charlie.bililivelib.danmaku.datamodel.StartStopInfo; import charlie.bililivelib.danmaku.event.DanmakuEvent; import charlie.bililivelib.danmaku.event.DanmakuListener; import com.google.gson.JsonObject; import org.jetbrains.annotations.NotNull; import java.util.List;
package charlie.bililivelib.danmaku.dispatch; /** * 分发直播间状态改变事件的分发器。对COMMAND为'LIVE', 'PREPARING'和'ROUND'的事件有效。 * * @author Charlie Jiang * @since rv1 */ public class StartStopDispatcher extends AbstractJSONDispatcher { public static final String[] ACCEPTABLE_COMMANDS = { "LIVE", "PREPARING", "ROUND" }; private static StartStopDispatcher GLOBAL_INSTANCE; @NotNull public static StartStopDispatcher getGlobalInstance() { if (GLOBAL_INSTANCE == null) { GLOBAL_INSTANCE = new StartStopDispatcher(); } return GLOBAL_INSTANCE; } @Override protected String[] getAcceptableCommands() { return ACCEPTABLE_COMMANDS; } /** * {@inheritDoc} * @param listeners 监听器列表 * @param rootObject 事件内容产生的JSON对象结构 * @param source 事件发生源 */ @Override public void dispatch(List<DanmakuListener> listeners, JsonObject rootObject, Object source) { boolean living = getCommand(rootObject).equals("LIVE"); int roomID = rootObject.get("roomid").getAsInt();
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/datamodel/StartStopInfo.java // @Data // @AllArgsConstructor // public class StartStopInfo { // private int roomID; // private boolean living; // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuEvent.java // @Getter // public class DanmakuEvent extends EventObject { // private Kind kind; // private Object param; // // /** // * Constructs a prototypical Event. // * // * @param source The object on which the Event initially occurred. // * @throws IllegalArgumentException if source is null. // */ // public DanmakuEvent(Object source) { // super(source); // } // // public DanmakuEvent(Object source, Object param, Kind kind) { // super(source); // this.kind = kind; // this.param = param; // } // // public enum Kind { // JOINED, ERROR, ERROR_DOWN, NEW_DANMAKU, WATCHER_COUNT, // START_STOP, WELCOME_VIP, GIVE_GIFT, GLOBAL_GIFT, GLOBAL_ANNOUNCE // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuListener.java // public interface DanmakuListener { // void danmakuEvent(@NotNull DanmakuEvent event); // // void watcherCountEvent(@NotNull DanmakuEvent event); // // void errorEvent(@NotNull DanmakuEvent event); // // void startStopEvent(@NotNull DanmakuEvent event); // // void statusEvent(@NotNull DanmakuEvent event); // // void welcomeVipEvent(@NotNull DanmakuEvent event); // // void giveGiftEvent(@NotNull DanmakuEvent event); // // void globalGiftEvent(@NotNull DanmakuEvent event); // // void globalAnnounceEvent(@NotNull DanmakuEvent event); // } // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/dispatch/StartStopDispatcher.java import charlie.bililivelib.danmaku.datamodel.StartStopInfo; import charlie.bililivelib.danmaku.event.DanmakuEvent; import charlie.bililivelib.danmaku.event.DanmakuListener; import com.google.gson.JsonObject; import org.jetbrains.annotations.NotNull; import java.util.List; package charlie.bililivelib.danmaku.dispatch; /** * 分发直播间状态改变事件的分发器。对COMMAND为'LIVE', 'PREPARING'和'ROUND'的事件有效。 * * @author Charlie Jiang * @since rv1 */ public class StartStopDispatcher extends AbstractJSONDispatcher { public static final String[] ACCEPTABLE_COMMANDS = { "LIVE", "PREPARING", "ROUND" }; private static StartStopDispatcher GLOBAL_INSTANCE; @NotNull public static StartStopDispatcher getGlobalInstance() { if (GLOBAL_INSTANCE == null) { GLOBAL_INSTANCE = new StartStopDispatcher(); } return GLOBAL_INSTANCE; } @Override protected String[] getAcceptableCommands() { return ACCEPTABLE_COMMANDS; } /** * {@inheritDoc} * @param listeners 监听器列表 * @param rootObject 事件内容产生的JSON对象结构 * @param source 事件发生源 */ @Override public void dispatch(List<DanmakuListener> listeners, JsonObject rootObject, Object source) { boolean living = getCommand(rootObject).equals("LIVE"); int roomID = rootObject.get("roomid").getAsInt();
DanmakuEvent event = new DanmakuEvent(source, new StartStopInfo(roomID, living),
cqjjjzr/BiliLiveLib
BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/dispatch/StartStopDispatcher.java
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/datamodel/StartStopInfo.java // @Data // @AllArgsConstructor // public class StartStopInfo { // private int roomID; // private boolean living; // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuEvent.java // @Getter // public class DanmakuEvent extends EventObject { // private Kind kind; // private Object param; // // /** // * Constructs a prototypical Event. // * // * @param source The object on which the Event initially occurred. // * @throws IllegalArgumentException if source is null. // */ // public DanmakuEvent(Object source) { // super(source); // } // // public DanmakuEvent(Object source, Object param, Kind kind) { // super(source); // this.kind = kind; // this.param = param; // } // // public enum Kind { // JOINED, ERROR, ERROR_DOWN, NEW_DANMAKU, WATCHER_COUNT, // START_STOP, WELCOME_VIP, GIVE_GIFT, GLOBAL_GIFT, GLOBAL_ANNOUNCE // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuListener.java // public interface DanmakuListener { // void danmakuEvent(@NotNull DanmakuEvent event); // // void watcherCountEvent(@NotNull DanmakuEvent event); // // void errorEvent(@NotNull DanmakuEvent event); // // void startStopEvent(@NotNull DanmakuEvent event); // // void statusEvent(@NotNull DanmakuEvent event); // // void welcomeVipEvent(@NotNull DanmakuEvent event); // // void giveGiftEvent(@NotNull DanmakuEvent event); // // void globalGiftEvent(@NotNull DanmakuEvent event); // // void globalAnnounceEvent(@NotNull DanmakuEvent event); // }
import charlie.bililivelib.danmaku.datamodel.StartStopInfo; import charlie.bililivelib.danmaku.event.DanmakuEvent; import charlie.bililivelib.danmaku.event.DanmakuListener; import com.google.gson.JsonObject; import org.jetbrains.annotations.NotNull; import java.util.List;
package charlie.bililivelib.danmaku.dispatch; /** * 分发直播间状态改变事件的分发器。对COMMAND为'LIVE', 'PREPARING'和'ROUND'的事件有效。 * * @author Charlie Jiang * @since rv1 */ public class StartStopDispatcher extends AbstractJSONDispatcher { public static final String[] ACCEPTABLE_COMMANDS = { "LIVE", "PREPARING", "ROUND" }; private static StartStopDispatcher GLOBAL_INSTANCE; @NotNull public static StartStopDispatcher getGlobalInstance() { if (GLOBAL_INSTANCE == null) { GLOBAL_INSTANCE = new StartStopDispatcher(); } return GLOBAL_INSTANCE; } @Override protected String[] getAcceptableCommands() { return ACCEPTABLE_COMMANDS; } /** * {@inheritDoc} * @param listeners 监听器列表 * @param rootObject 事件内容产生的JSON对象结构 * @param source 事件发生源 */ @Override public void dispatch(List<DanmakuListener> listeners, JsonObject rootObject, Object source) { boolean living = getCommand(rootObject).equals("LIVE"); int roomID = rootObject.get("roomid").getAsInt();
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/datamodel/StartStopInfo.java // @Data // @AllArgsConstructor // public class StartStopInfo { // private int roomID; // private boolean living; // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuEvent.java // @Getter // public class DanmakuEvent extends EventObject { // private Kind kind; // private Object param; // // /** // * Constructs a prototypical Event. // * // * @param source The object on which the Event initially occurred. // * @throws IllegalArgumentException if source is null. // */ // public DanmakuEvent(Object source) { // super(source); // } // // public DanmakuEvent(Object source, Object param, Kind kind) { // super(source); // this.kind = kind; // this.param = param; // } // // public enum Kind { // JOINED, ERROR, ERROR_DOWN, NEW_DANMAKU, WATCHER_COUNT, // START_STOP, WELCOME_VIP, GIVE_GIFT, GLOBAL_GIFT, GLOBAL_ANNOUNCE // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuListener.java // public interface DanmakuListener { // void danmakuEvent(@NotNull DanmakuEvent event); // // void watcherCountEvent(@NotNull DanmakuEvent event); // // void errorEvent(@NotNull DanmakuEvent event); // // void startStopEvent(@NotNull DanmakuEvent event); // // void statusEvent(@NotNull DanmakuEvent event); // // void welcomeVipEvent(@NotNull DanmakuEvent event); // // void giveGiftEvent(@NotNull DanmakuEvent event); // // void globalGiftEvent(@NotNull DanmakuEvent event); // // void globalAnnounceEvent(@NotNull DanmakuEvent event); // } // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/dispatch/StartStopDispatcher.java import charlie.bililivelib.danmaku.datamodel.StartStopInfo; import charlie.bililivelib.danmaku.event.DanmakuEvent; import charlie.bililivelib.danmaku.event.DanmakuListener; import com.google.gson.JsonObject; import org.jetbrains.annotations.NotNull; import java.util.List; package charlie.bililivelib.danmaku.dispatch; /** * 分发直播间状态改变事件的分发器。对COMMAND为'LIVE', 'PREPARING'和'ROUND'的事件有效。 * * @author Charlie Jiang * @since rv1 */ public class StartStopDispatcher extends AbstractJSONDispatcher { public static final String[] ACCEPTABLE_COMMANDS = { "LIVE", "PREPARING", "ROUND" }; private static StartStopDispatcher GLOBAL_INSTANCE; @NotNull public static StartStopDispatcher getGlobalInstance() { if (GLOBAL_INSTANCE == null) { GLOBAL_INSTANCE = new StartStopDispatcher(); } return GLOBAL_INSTANCE; } @Override protected String[] getAcceptableCommands() { return ACCEPTABLE_COMMANDS; } /** * {@inheritDoc} * @param listeners 监听器列表 * @param rootObject 事件内容产生的JSON对象结构 * @param source 事件发生源 */ @Override public void dispatch(List<DanmakuListener> listeners, JsonObject rootObject, Object source) { boolean living = getCommand(rootObject).equals("LIVE"); int roomID = rootObject.get("roomid").getAsInt();
DanmakuEvent event = new DanmakuEvent(source, new StartStopInfo(roomID, living),
cqjjjzr/BiliLiveLib
BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/DanmakuReceivePacket.java
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/I18n.java // public class I18n { // public static final String BUNDLE_NAME = "BiliLiveLib"; // private static Map<String, String> strings; // // static { // init(); // } // // /** // * 重新依照当前Locale获取并填充本地化字符串。在切换Locale后调用。 // */ // public static void init() { // strings = new HashMap<>(); // fillResourceBundle(); // } // // private static void fillResourceBundle() { // ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE_NAME); // for (String key : resourceBundle.keySet()) { // strings.put(key, resourceBundle.getString(key)); // } // } // // /** // * 获取给定Key的本地化文本。 // * @param key 键 // * @return 本地化文本 // */ // @Nls // public static String getString(@NonNls @NotNull String key) { // return strings.get(key); // } // // /** // * 获取基于给定Key的本地化格式化文本。 // * @param key 指向格式化模式的键 // * @param arguments 格式化文本的参数 // * @return 本地化并格式化后的文本 // */ // @NotNull // public static String format(@NonNls @NotNull String key, // @NonNls @NotNull Object... arguments) { // return MessageFormat.format(strings.get(key), arguments); // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/exceptions/BiliLiveException.java // public class BiliLiveException extends Exception { // public BiliLiveException() { // super(); // } // // public BiliLiveException(String message) { // super(message); // } // // public BiliLiveException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/internalutil/ByteArrayOperation.java // @Contract(pure = true) // public static int byteArrayToInt(@NotNull byte[] bytes) { // int value = 0; // //由高位到低位 // for (int i = 0; i < 4; i++) { // int shift = (4 - 1 - i) * 8; // value += (bytes[i] & 0x000000FF) << shift;//往高位游 // } // return value; // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/internalutil/ByteArrayOperation.java // @Contract(pure = true) // public static short byteArrayToShort(@NotNull byte[] b) { // short s0 = (short) b[1]; // short s1 = (short) b[0]; // s1 <<= 8; // return (short) (s0 | s1); // }
import charlie.bililivelib.I18n; import charlie.bililivelib.exceptions.BiliLiveException; import lombok.Getter; import java.io.IOException; import java.io.InputStream; import static charlie.bililivelib.internalutil.ByteArrayOperation.byteArrayToInt; import static charlie.bililivelib.internalutil.ByteArrayOperation.byteArrayToShort;
package charlie.bililivelib.danmaku; /** * 用于从弹幕服务器发回的数据包。<br> * 数据包的结构如下:<br> * {@code +-----+-------+-----+--------+-------+----------+}<br> * {@code | LEN | MAGIC | UNK | OPCODE | B.LEN | --BODY-- |}<br> * {@code | -4- | X'0F' | -2- | --4--- | --4-- | Variable |}<br> * {@code +-----+-------+-----+--------+-------+----------+}<br> * - LEN: 数据包长度,包含自身长度,int类型;<br> * - MAGIC: 魔数,short类型,固定0x0F;<br> * - UNK: 未知参数,int类型;<br> * - OPCODE: 操作码,int类型。具体见{@link DanmakuReceivePacket.Operation};<br> * - B.LEN: BODY的长度,int类型;<br> * - BODY: 数据包体,长度可变。 * * @author Charlie Jiang * @since rv1 */ @Getter public final class DanmakuReceivePacket { private static final int PACKET_HEADER_SIZE = 16; private Operation operation = null; private byte[] body = null; /** * 对于指定输入流,读取并构造数据包结构。 * * @param inputStream 输入流 * @throws IOException 发生网络错误时抛出 * @throws BiliLiveException 协议错误时抛出 */
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/I18n.java // public class I18n { // public static final String BUNDLE_NAME = "BiliLiveLib"; // private static Map<String, String> strings; // // static { // init(); // } // // /** // * 重新依照当前Locale获取并填充本地化字符串。在切换Locale后调用。 // */ // public static void init() { // strings = new HashMap<>(); // fillResourceBundle(); // } // // private static void fillResourceBundle() { // ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE_NAME); // for (String key : resourceBundle.keySet()) { // strings.put(key, resourceBundle.getString(key)); // } // } // // /** // * 获取给定Key的本地化文本。 // * @param key 键 // * @return 本地化文本 // */ // @Nls // public static String getString(@NonNls @NotNull String key) { // return strings.get(key); // } // // /** // * 获取基于给定Key的本地化格式化文本。 // * @param key 指向格式化模式的键 // * @param arguments 格式化文本的参数 // * @return 本地化并格式化后的文本 // */ // @NotNull // public static String format(@NonNls @NotNull String key, // @NonNls @NotNull Object... arguments) { // return MessageFormat.format(strings.get(key), arguments); // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/exceptions/BiliLiveException.java // public class BiliLiveException extends Exception { // public BiliLiveException() { // super(); // } // // public BiliLiveException(String message) { // super(message); // } // // public BiliLiveException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/internalutil/ByteArrayOperation.java // @Contract(pure = true) // public static int byteArrayToInt(@NotNull byte[] bytes) { // int value = 0; // //由高位到低位 // for (int i = 0; i < 4; i++) { // int shift = (4 - 1 - i) * 8; // value += (bytes[i] & 0x000000FF) << shift;//往高位游 // } // return value; // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/internalutil/ByteArrayOperation.java // @Contract(pure = true) // public static short byteArrayToShort(@NotNull byte[] b) { // short s0 = (short) b[1]; // short s1 = (short) b[0]; // s1 <<= 8; // return (short) (s0 | s1); // } // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/DanmakuReceivePacket.java import charlie.bililivelib.I18n; import charlie.bililivelib.exceptions.BiliLiveException; import lombok.Getter; import java.io.IOException; import java.io.InputStream; import static charlie.bililivelib.internalutil.ByteArrayOperation.byteArrayToInt; import static charlie.bililivelib.internalutil.ByteArrayOperation.byteArrayToShort; package charlie.bililivelib.danmaku; /** * 用于从弹幕服务器发回的数据包。<br> * 数据包的结构如下:<br> * {@code +-----+-------+-----+--------+-------+----------+}<br> * {@code | LEN | MAGIC | UNK | OPCODE | B.LEN | --BODY-- |}<br> * {@code | -4- | X'0F' | -2- | --4--- | --4-- | Variable |}<br> * {@code +-----+-------+-----+--------+-------+----------+}<br> * - LEN: 数据包长度,包含自身长度,int类型;<br> * - MAGIC: 魔数,short类型,固定0x0F;<br> * - UNK: 未知参数,int类型;<br> * - OPCODE: 操作码,int类型。具体见{@link DanmakuReceivePacket.Operation};<br> * - B.LEN: BODY的长度,int类型;<br> * - BODY: 数据包体,长度可变。 * * @author Charlie Jiang * @since rv1 */ @Getter public final class DanmakuReceivePacket { private static final int PACKET_HEADER_SIZE = 16; private Operation operation = null; private byte[] body = null; /** * 对于指定输入流,读取并构造数据包结构。 * * @param inputStream 输入流 * @throws IOException 发生网络错误时抛出 * @throws BiliLiveException 协议错误时抛出 */
public DanmakuReceivePacket(InputStream inputStream) throws IOException, BiliLiveException {
cqjjjzr/BiliLiveLib
BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/DanmakuReceivePacket.java
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/I18n.java // public class I18n { // public static final String BUNDLE_NAME = "BiliLiveLib"; // private static Map<String, String> strings; // // static { // init(); // } // // /** // * 重新依照当前Locale获取并填充本地化字符串。在切换Locale后调用。 // */ // public static void init() { // strings = new HashMap<>(); // fillResourceBundle(); // } // // private static void fillResourceBundle() { // ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE_NAME); // for (String key : resourceBundle.keySet()) { // strings.put(key, resourceBundle.getString(key)); // } // } // // /** // * 获取给定Key的本地化文本。 // * @param key 键 // * @return 本地化文本 // */ // @Nls // public static String getString(@NonNls @NotNull String key) { // return strings.get(key); // } // // /** // * 获取基于给定Key的本地化格式化文本。 // * @param key 指向格式化模式的键 // * @param arguments 格式化文本的参数 // * @return 本地化并格式化后的文本 // */ // @NotNull // public static String format(@NonNls @NotNull String key, // @NonNls @NotNull Object... arguments) { // return MessageFormat.format(strings.get(key), arguments); // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/exceptions/BiliLiveException.java // public class BiliLiveException extends Exception { // public BiliLiveException() { // super(); // } // // public BiliLiveException(String message) { // super(message); // } // // public BiliLiveException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/internalutil/ByteArrayOperation.java // @Contract(pure = true) // public static int byteArrayToInt(@NotNull byte[] bytes) { // int value = 0; // //由高位到低位 // for (int i = 0; i < 4; i++) { // int shift = (4 - 1 - i) * 8; // value += (bytes[i] & 0x000000FF) << shift;//往高位游 // } // return value; // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/internalutil/ByteArrayOperation.java // @Contract(pure = true) // public static short byteArrayToShort(@NotNull byte[] b) { // short s0 = (short) b[1]; // short s1 = (short) b[0]; // s1 <<= 8; // return (short) (s0 | s1); // }
import charlie.bililivelib.I18n; import charlie.bililivelib.exceptions.BiliLiveException; import lombok.Getter; import java.io.IOException; import java.io.InputStream; import static charlie.bililivelib.internalutil.ByteArrayOperation.byteArrayToInt; import static charlie.bililivelib.internalutil.ByteArrayOperation.byteArrayToShort;
package charlie.bililivelib.danmaku; /** * 用于从弹幕服务器发回的数据包。<br> * 数据包的结构如下:<br> * {@code +-----+-------+-----+--------+-------+----------+}<br> * {@code | LEN | MAGIC | UNK | OPCODE | B.LEN | --BODY-- |}<br> * {@code | -4- | X'0F' | -2- | --4--- | --4-- | Variable |}<br> * {@code +-----+-------+-----+--------+-------+----------+}<br> * - LEN: 数据包长度,包含自身长度,int类型;<br> * - MAGIC: 魔数,short类型,固定0x0F;<br> * - UNK: 未知参数,int类型;<br> * - OPCODE: 操作码,int类型。具体见{@link DanmakuReceivePacket.Operation};<br> * - B.LEN: BODY的长度,int类型;<br> * - BODY: 数据包体,长度可变。 * * @author Charlie Jiang * @since rv1 */ @Getter public final class DanmakuReceivePacket { private static final int PACKET_HEADER_SIZE = 16; private Operation operation = null; private byte[] body = null; /** * 对于指定输入流,读取并构造数据包结构。 * * @param inputStream 输入流 * @throws IOException 发生网络错误时抛出 * @throws BiliLiveException 协议错误时抛出 */ public DanmakuReceivePacket(InputStream inputStream) throws IOException, BiliLiveException { byte[] tempBuf = new byte[4]; readArray(inputStream, tempBuf, 4);
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/I18n.java // public class I18n { // public static final String BUNDLE_NAME = "BiliLiveLib"; // private static Map<String, String> strings; // // static { // init(); // } // // /** // * 重新依照当前Locale获取并填充本地化字符串。在切换Locale后调用。 // */ // public static void init() { // strings = new HashMap<>(); // fillResourceBundle(); // } // // private static void fillResourceBundle() { // ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE_NAME); // for (String key : resourceBundle.keySet()) { // strings.put(key, resourceBundle.getString(key)); // } // } // // /** // * 获取给定Key的本地化文本。 // * @param key 键 // * @return 本地化文本 // */ // @Nls // public static String getString(@NonNls @NotNull String key) { // return strings.get(key); // } // // /** // * 获取基于给定Key的本地化格式化文本。 // * @param key 指向格式化模式的键 // * @param arguments 格式化文本的参数 // * @return 本地化并格式化后的文本 // */ // @NotNull // public static String format(@NonNls @NotNull String key, // @NonNls @NotNull Object... arguments) { // return MessageFormat.format(strings.get(key), arguments); // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/exceptions/BiliLiveException.java // public class BiliLiveException extends Exception { // public BiliLiveException() { // super(); // } // // public BiliLiveException(String message) { // super(message); // } // // public BiliLiveException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/internalutil/ByteArrayOperation.java // @Contract(pure = true) // public static int byteArrayToInt(@NotNull byte[] bytes) { // int value = 0; // //由高位到低位 // for (int i = 0; i < 4; i++) { // int shift = (4 - 1 - i) * 8; // value += (bytes[i] & 0x000000FF) << shift;//往高位游 // } // return value; // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/internalutil/ByteArrayOperation.java // @Contract(pure = true) // public static short byteArrayToShort(@NotNull byte[] b) { // short s0 = (short) b[1]; // short s1 = (short) b[0]; // s1 <<= 8; // return (short) (s0 | s1); // } // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/DanmakuReceivePacket.java import charlie.bililivelib.I18n; import charlie.bililivelib.exceptions.BiliLiveException; import lombok.Getter; import java.io.IOException; import java.io.InputStream; import static charlie.bililivelib.internalutil.ByteArrayOperation.byteArrayToInt; import static charlie.bililivelib.internalutil.ByteArrayOperation.byteArrayToShort; package charlie.bililivelib.danmaku; /** * 用于从弹幕服务器发回的数据包。<br> * 数据包的结构如下:<br> * {@code +-----+-------+-----+--------+-------+----------+}<br> * {@code | LEN | MAGIC | UNK | OPCODE | B.LEN | --BODY-- |}<br> * {@code | -4- | X'0F' | -2- | --4--- | --4-- | Variable |}<br> * {@code +-----+-------+-----+--------+-------+----------+}<br> * - LEN: 数据包长度,包含自身长度,int类型;<br> * - MAGIC: 魔数,short类型,固定0x0F;<br> * - UNK: 未知参数,int类型;<br> * - OPCODE: 操作码,int类型。具体见{@link DanmakuReceivePacket.Operation};<br> * - B.LEN: BODY的长度,int类型;<br> * - BODY: 数据包体,长度可变。 * * @author Charlie Jiang * @since rv1 */ @Getter public final class DanmakuReceivePacket { private static final int PACKET_HEADER_SIZE = 16; private Operation operation = null; private byte[] body = null; /** * 对于指定输入流,读取并构造数据包结构。 * * @param inputStream 输入流 * @throws IOException 发生网络错误时抛出 * @throws BiliLiveException 协议错误时抛出 */ public DanmakuReceivePacket(InputStream inputStream) throws IOException, BiliLiveException { byte[] tempBuf = new byte[4]; readArray(inputStream, tempBuf, 4);
int length = byteArrayToInt(tempBuf);
cqjjjzr/BiliLiveLib
BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/DanmakuReceivePacket.java
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/I18n.java // public class I18n { // public static final String BUNDLE_NAME = "BiliLiveLib"; // private static Map<String, String> strings; // // static { // init(); // } // // /** // * 重新依照当前Locale获取并填充本地化字符串。在切换Locale后调用。 // */ // public static void init() { // strings = new HashMap<>(); // fillResourceBundle(); // } // // private static void fillResourceBundle() { // ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE_NAME); // for (String key : resourceBundle.keySet()) { // strings.put(key, resourceBundle.getString(key)); // } // } // // /** // * 获取给定Key的本地化文本。 // * @param key 键 // * @return 本地化文本 // */ // @Nls // public static String getString(@NonNls @NotNull String key) { // return strings.get(key); // } // // /** // * 获取基于给定Key的本地化格式化文本。 // * @param key 指向格式化模式的键 // * @param arguments 格式化文本的参数 // * @return 本地化并格式化后的文本 // */ // @NotNull // public static String format(@NonNls @NotNull String key, // @NonNls @NotNull Object... arguments) { // return MessageFormat.format(strings.get(key), arguments); // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/exceptions/BiliLiveException.java // public class BiliLiveException extends Exception { // public BiliLiveException() { // super(); // } // // public BiliLiveException(String message) { // super(message); // } // // public BiliLiveException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/internalutil/ByteArrayOperation.java // @Contract(pure = true) // public static int byteArrayToInt(@NotNull byte[] bytes) { // int value = 0; // //由高位到低位 // for (int i = 0; i < 4; i++) { // int shift = (4 - 1 - i) * 8; // value += (bytes[i] & 0x000000FF) << shift;//往高位游 // } // return value; // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/internalutil/ByteArrayOperation.java // @Contract(pure = true) // public static short byteArrayToShort(@NotNull byte[] b) { // short s0 = (short) b[1]; // short s1 = (short) b[0]; // s1 <<= 8; // return (short) (s0 | s1); // }
import charlie.bililivelib.I18n; import charlie.bililivelib.exceptions.BiliLiveException; import lombok.Getter; import java.io.IOException; import java.io.InputStream; import static charlie.bililivelib.internalutil.ByteArrayOperation.byteArrayToInt; import static charlie.bililivelib.internalutil.ByteArrayOperation.byteArrayToShort;
package charlie.bililivelib.danmaku; /** * 用于从弹幕服务器发回的数据包。<br> * 数据包的结构如下:<br> * {@code +-----+-------+-----+--------+-------+----------+}<br> * {@code | LEN | MAGIC | UNK | OPCODE | B.LEN | --BODY-- |}<br> * {@code | -4- | X'0F' | -2- | --4--- | --4-- | Variable |}<br> * {@code +-----+-------+-----+--------+-------+----------+}<br> * - LEN: 数据包长度,包含自身长度,int类型;<br> * - MAGIC: 魔数,short类型,固定0x0F;<br> * - UNK: 未知参数,int类型;<br> * - OPCODE: 操作码,int类型。具体见{@link DanmakuReceivePacket.Operation};<br> * - B.LEN: BODY的长度,int类型;<br> * - BODY: 数据包体,长度可变。 * * @author Charlie Jiang * @since rv1 */ @Getter public final class DanmakuReceivePacket { private static final int PACKET_HEADER_SIZE = 16; private Operation operation = null; private byte[] body = null; /** * 对于指定输入流,读取并构造数据包结构。 * * @param inputStream 输入流 * @throws IOException 发生网络错误时抛出 * @throws BiliLiveException 协议错误时抛出 */ public DanmakuReceivePacket(InputStream inputStream) throws IOException, BiliLiveException { byte[] tempBuf = new byte[4]; readArray(inputStream, tempBuf, 4); int length = byteArrayToInt(tempBuf); checkValidLength(length); readArray(inputStream, tempBuf, 2); // Magic Number byte[] shortBuf = new byte[2]; readArray(inputStream, shortBuf, 2);
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/I18n.java // public class I18n { // public static final String BUNDLE_NAME = "BiliLiveLib"; // private static Map<String, String> strings; // // static { // init(); // } // // /** // * 重新依照当前Locale获取并填充本地化字符串。在切换Locale后调用。 // */ // public static void init() { // strings = new HashMap<>(); // fillResourceBundle(); // } // // private static void fillResourceBundle() { // ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE_NAME); // for (String key : resourceBundle.keySet()) { // strings.put(key, resourceBundle.getString(key)); // } // } // // /** // * 获取给定Key的本地化文本。 // * @param key 键 // * @return 本地化文本 // */ // @Nls // public static String getString(@NonNls @NotNull String key) { // return strings.get(key); // } // // /** // * 获取基于给定Key的本地化格式化文本。 // * @param key 指向格式化模式的键 // * @param arguments 格式化文本的参数 // * @return 本地化并格式化后的文本 // */ // @NotNull // public static String format(@NonNls @NotNull String key, // @NonNls @NotNull Object... arguments) { // return MessageFormat.format(strings.get(key), arguments); // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/exceptions/BiliLiveException.java // public class BiliLiveException extends Exception { // public BiliLiveException() { // super(); // } // // public BiliLiveException(String message) { // super(message); // } // // public BiliLiveException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/internalutil/ByteArrayOperation.java // @Contract(pure = true) // public static int byteArrayToInt(@NotNull byte[] bytes) { // int value = 0; // //由高位到低位 // for (int i = 0; i < 4; i++) { // int shift = (4 - 1 - i) * 8; // value += (bytes[i] & 0x000000FF) << shift;//往高位游 // } // return value; // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/internalutil/ByteArrayOperation.java // @Contract(pure = true) // public static short byteArrayToShort(@NotNull byte[] b) { // short s0 = (short) b[1]; // short s1 = (short) b[0]; // s1 <<= 8; // return (short) (s0 | s1); // } // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/DanmakuReceivePacket.java import charlie.bililivelib.I18n; import charlie.bililivelib.exceptions.BiliLiveException; import lombok.Getter; import java.io.IOException; import java.io.InputStream; import static charlie.bililivelib.internalutil.ByteArrayOperation.byteArrayToInt; import static charlie.bililivelib.internalutil.ByteArrayOperation.byteArrayToShort; package charlie.bililivelib.danmaku; /** * 用于从弹幕服务器发回的数据包。<br> * 数据包的结构如下:<br> * {@code +-----+-------+-----+--------+-------+----------+}<br> * {@code | LEN | MAGIC | UNK | OPCODE | B.LEN | --BODY-- |}<br> * {@code | -4- | X'0F' | -2- | --4--- | --4-- | Variable |}<br> * {@code +-----+-------+-----+--------+-------+----------+}<br> * - LEN: 数据包长度,包含自身长度,int类型;<br> * - MAGIC: 魔数,short类型,固定0x0F;<br> * - UNK: 未知参数,int类型;<br> * - OPCODE: 操作码,int类型。具体见{@link DanmakuReceivePacket.Operation};<br> * - B.LEN: BODY的长度,int类型;<br> * - BODY: 数据包体,长度可变。 * * @author Charlie Jiang * @since rv1 */ @Getter public final class DanmakuReceivePacket { private static final int PACKET_HEADER_SIZE = 16; private Operation operation = null; private byte[] body = null; /** * 对于指定输入流,读取并构造数据包结构。 * * @param inputStream 输入流 * @throws IOException 发生网络错误时抛出 * @throws BiliLiveException 协议错误时抛出 */ public DanmakuReceivePacket(InputStream inputStream) throws IOException, BiliLiveException { byte[] tempBuf = new byte[4]; readArray(inputStream, tempBuf, 4); int length = byteArrayToInt(tempBuf); checkValidLength(length); readArray(inputStream, tempBuf, 2); // Magic Number byte[] shortBuf = new byte[2]; readArray(inputStream, shortBuf, 2);
short unknown = byteArrayToShort(shortBuf);
cqjjjzr/BiliLiveLib
BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/DanmakuReceivePacket.java
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/I18n.java // public class I18n { // public static final String BUNDLE_NAME = "BiliLiveLib"; // private static Map<String, String> strings; // // static { // init(); // } // // /** // * 重新依照当前Locale获取并填充本地化字符串。在切换Locale后调用。 // */ // public static void init() { // strings = new HashMap<>(); // fillResourceBundle(); // } // // private static void fillResourceBundle() { // ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE_NAME); // for (String key : resourceBundle.keySet()) { // strings.put(key, resourceBundle.getString(key)); // } // } // // /** // * 获取给定Key的本地化文本。 // * @param key 键 // * @return 本地化文本 // */ // @Nls // public static String getString(@NonNls @NotNull String key) { // return strings.get(key); // } // // /** // * 获取基于给定Key的本地化格式化文本。 // * @param key 指向格式化模式的键 // * @param arguments 格式化文本的参数 // * @return 本地化并格式化后的文本 // */ // @NotNull // public static String format(@NonNls @NotNull String key, // @NonNls @NotNull Object... arguments) { // return MessageFormat.format(strings.get(key), arguments); // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/exceptions/BiliLiveException.java // public class BiliLiveException extends Exception { // public BiliLiveException() { // super(); // } // // public BiliLiveException(String message) { // super(message); // } // // public BiliLiveException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/internalutil/ByteArrayOperation.java // @Contract(pure = true) // public static int byteArrayToInt(@NotNull byte[] bytes) { // int value = 0; // //由高位到低位 // for (int i = 0; i < 4; i++) { // int shift = (4 - 1 - i) * 8; // value += (bytes[i] & 0x000000FF) << shift;//往高位游 // } // return value; // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/internalutil/ByteArrayOperation.java // @Contract(pure = true) // public static short byteArrayToShort(@NotNull byte[] b) { // short s0 = (short) b[1]; // short s1 = (short) b[0]; // s1 <<= 8; // return (short) (s0 | s1); // }
import charlie.bililivelib.I18n; import charlie.bililivelib.exceptions.BiliLiveException; import lombok.Getter; import java.io.IOException; import java.io.InputStream; import static charlie.bililivelib.internalutil.ByteArrayOperation.byteArrayToInt; import static charlie.bililivelib.internalutil.ByteArrayOperation.byteArrayToShort;
readArray(inputStream, tempBuf, 4); // Magic and params int bodyLength = length - PACKET_HEADER_SIZE; if (bodyLength == 0) return; operationID -= 1; // I don't know what this means... operation = DanmakuReceivePacket.Operation.forID(operationID); body = new byte[bodyLength]; readArray(inputStream, body, bodyLength); } private int readArray(InputStream stream, byte[] buffer, int length) throws IOException { if (length > buffer.length) throw new IOException("offset + length > buffer.length"); int readLength = 0; while (readLength < length) { int available = stream.read(buffer, 0, length - readLength); if (available == 0) throw new IOException("available == 0"); readLength += available; } return readLength; //return stream.read(buffer, 0, length); } private void checkValidProtocolVersion(short version) throws BiliLiveException { if (version != 1)
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/I18n.java // public class I18n { // public static final String BUNDLE_NAME = "BiliLiveLib"; // private static Map<String, String> strings; // // static { // init(); // } // // /** // * 重新依照当前Locale获取并填充本地化字符串。在切换Locale后调用。 // */ // public static void init() { // strings = new HashMap<>(); // fillResourceBundle(); // } // // private static void fillResourceBundle() { // ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE_NAME); // for (String key : resourceBundle.keySet()) { // strings.put(key, resourceBundle.getString(key)); // } // } // // /** // * 获取给定Key的本地化文本。 // * @param key 键 // * @return 本地化文本 // */ // @Nls // public static String getString(@NonNls @NotNull String key) { // return strings.get(key); // } // // /** // * 获取基于给定Key的本地化格式化文本。 // * @param key 指向格式化模式的键 // * @param arguments 格式化文本的参数 // * @return 本地化并格式化后的文本 // */ // @NotNull // public static String format(@NonNls @NotNull String key, // @NonNls @NotNull Object... arguments) { // return MessageFormat.format(strings.get(key), arguments); // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/exceptions/BiliLiveException.java // public class BiliLiveException extends Exception { // public BiliLiveException() { // super(); // } // // public BiliLiveException(String message) { // super(message); // } // // public BiliLiveException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/internalutil/ByteArrayOperation.java // @Contract(pure = true) // public static int byteArrayToInt(@NotNull byte[] bytes) { // int value = 0; // //由高位到低位 // for (int i = 0; i < 4; i++) { // int shift = (4 - 1 - i) * 8; // value += (bytes[i] & 0x000000FF) << shift;//往高位游 // } // return value; // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/internalutil/ByteArrayOperation.java // @Contract(pure = true) // public static short byteArrayToShort(@NotNull byte[] b) { // short s0 = (short) b[1]; // short s1 = (short) b[0]; // s1 <<= 8; // return (short) (s0 | s1); // } // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/DanmakuReceivePacket.java import charlie.bililivelib.I18n; import charlie.bililivelib.exceptions.BiliLiveException; import lombok.Getter; import java.io.IOException; import java.io.InputStream; import static charlie.bililivelib.internalutil.ByteArrayOperation.byteArrayToInt; import static charlie.bililivelib.internalutil.ByteArrayOperation.byteArrayToShort; readArray(inputStream, tempBuf, 4); // Magic and params int bodyLength = length - PACKET_HEADER_SIZE; if (bodyLength == 0) return; operationID -= 1; // I don't know what this means... operation = DanmakuReceivePacket.Operation.forID(operationID); body = new byte[bodyLength]; readArray(inputStream, body, bodyLength); } private int readArray(InputStream stream, byte[] buffer, int length) throws IOException { if (length > buffer.length) throw new IOException("offset + length > buffer.length"); int readLength = 0; while (readLength < length) { int available = stream.read(buffer, 0, length - readLength); if (available == 0) throw new IOException("available == 0"); readLength += available; } return readLength; //return stream.read(buffer, 0, length); } private void checkValidProtocolVersion(short version) throws BiliLiveException { if (version != 1)
throw new BiliLiveException(I18n.format("msg.danmaku_protocol_error"));
cqjjjzr/BiliLiveLib
BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/dispatch/WelcomeVipDispatcher.java
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/datamodel/WelcomeVipInfo.java // @Data // @AllArgsConstructor // public class WelcomeVipInfo { // private String username; // private boolean admin; // // public WelcomeVipInfo(JsonObject rootObject) { // JsonObject dataObject = rootObject.get("data").getAsJsonObject(); // // username = dataObject.get("uname").getAsString(); // admin = dataObject.get("is_admin").getAsBoolean(); // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuEvent.java // @Getter // public class DanmakuEvent extends EventObject { // private Kind kind; // private Object param; // // /** // * Constructs a prototypical Event. // * // * @param source The object on which the Event initially occurred. // * @throws IllegalArgumentException if source is null. // */ // public DanmakuEvent(Object source) { // super(source); // } // // public DanmakuEvent(Object source, Object param, Kind kind) { // super(source); // this.kind = kind; // this.param = param; // } // // public enum Kind { // JOINED, ERROR, ERROR_DOWN, NEW_DANMAKU, WATCHER_COUNT, // START_STOP, WELCOME_VIP, GIVE_GIFT, GLOBAL_GIFT, GLOBAL_ANNOUNCE // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuListener.java // public interface DanmakuListener { // void danmakuEvent(@NotNull DanmakuEvent event); // // void watcherCountEvent(@NotNull DanmakuEvent event); // // void errorEvent(@NotNull DanmakuEvent event); // // void startStopEvent(@NotNull DanmakuEvent event); // // void statusEvent(@NotNull DanmakuEvent event); // // void welcomeVipEvent(@NotNull DanmakuEvent event); // // void giveGiftEvent(@NotNull DanmakuEvent event); // // void globalGiftEvent(@NotNull DanmakuEvent event); // // void globalAnnounceEvent(@NotNull DanmakuEvent event); // }
import charlie.bililivelib.danmaku.datamodel.WelcomeVipInfo; import charlie.bililivelib.danmaku.event.DanmakuEvent; import charlie.bililivelib.danmaku.event.DanmakuListener; import com.google.gson.JsonObject; import org.jetbrains.annotations.NotNull; import java.util.List;
package charlie.bililivelib.danmaku.dispatch; /** * 分发老爷进直播间事件的分发器。对COMMAND为'WELCOME'的事件有效。 * * @author Charlie Jiang * @since rv1 */ public class WelcomeVipDispatcher extends AbstractJSONDispatcher { public static final String[] ACCEPTABLE_COMMANDS = { "WELCOME" }; private static WelcomeVipDispatcher GLOBAL_INSTANCE; @NotNull public static WelcomeVipDispatcher getGlobalInstance() { if (GLOBAL_INSTANCE == null) { GLOBAL_INSTANCE = new WelcomeVipDispatcher(); } return GLOBAL_INSTANCE; } @Override protected String[] getAcceptableCommands() { return ACCEPTABLE_COMMANDS; } /** * {@inheritDoc} * @param listeners 监听器列表 * @param rootObject 事件内容产生的JSON对象结构 * @param source 事件发生源 */ @Override
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/datamodel/WelcomeVipInfo.java // @Data // @AllArgsConstructor // public class WelcomeVipInfo { // private String username; // private boolean admin; // // public WelcomeVipInfo(JsonObject rootObject) { // JsonObject dataObject = rootObject.get("data").getAsJsonObject(); // // username = dataObject.get("uname").getAsString(); // admin = dataObject.get("is_admin").getAsBoolean(); // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuEvent.java // @Getter // public class DanmakuEvent extends EventObject { // private Kind kind; // private Object param; // // /** // * Constructs a prototypical Event. // * // * @param source The object on which the Event initially occurred. // * @throws IllegalArgumentException if source is null. // */ // public DanmakuEvent(Object source) { // super(source); // } // // public DanmakuEvent(Object source, Object param, Kind kind) { // super(source); // this.kind = kind; // this.param = param; // } // // public enum Kind { // JOINED, ERROR, ERROR_DOWN, NEW_DANMAKU, WATCHER_COUNT, // START_STOP, WELCOME_VIP, GIVE_GIFT, GLOBAL_GIFT, GLOBAL_ANNOUNCE // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuListener.java // public interface DanmakuListener { // void danmakuEvent(@NotNull DanmakuEvent event); // // void watcherCountEvent(@NotNull DanmakuEvent event); // // void errorEvent(@NotNull DanmakuEvent event); // // void startStopEvent(@NotNull DanmakuEvent event); // // void statusEvent(@NotNull DanmakuEvent event); // // void welcomeVipEvent(@NotNull DanmakuEvent event); // // void giveGiftEvent(@NotNull DanmakuEvent event); // // void globalGiftEvent(@NotNull DanmakuEvent event); // // void globalAnnounceEvent(@NotNull DanmakuEvent event); // } // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/dispatch/WelcomeVipDispatcher.java import charlie.bililivelib.danmaku.datamodel.WelcomeVipInfo; import charlie.bililivelib.danmaku.event.DanmakuEvent; import charlie.bililivelib.danmaku.event.DanmakuListener; import com.google.gson.JsonObject; import org.jetbrains.annotations.NotNull; import java.util.List; package charlie.bililivelib.danmaku.dispatch; /** * 分发老爷进直播间事件的分发器。对COMMAND为'WELCOME'的事件有效。 * * @author Charlie Jiang * @since rv1 */ public class WelcomeVipDispatcher extends AbstractJSONDispatcher { public static final String[] ACCEPTABLE_COMMANDS = { "WELCOME" }; private static WelcomeVipDispatcher GLOBAL_INSTANCE; @NotNull public static WelcomeVipDispatcher getGlobalInstance() { if (GLOBAL_INSTANCE == null) { GLOBAL_INSTANCE = new WelcomeVipDispatcher(); } return GLOBAL_INSTANCE; } @Override protected String[] getAcceptableCommands() { return ACCEPTABLE_COMMANDS; } /** * {@inheritDoc} * @param listeners 监听器列表 * @param rootObject 事件内容产生的JSON对象结构 * @param source 事件发生源 */ @Override
public void dispatch(List<DanmakuListener> listeners, JsonObject rootObject, Object source) {
cqjjjzr/BiliLiveLib
BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/dispatch/WelcomeVipDispatcher.java
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/datamodel/WelcomeVipInfo.java // @Data // @AllArgsConstructor // public class WelcomeVipInfo { // private String username; // private boolean admin; // // public WelcomeVipInfo(JsonObject rootObject) { // JsonObject dataObject = rootObject.get("data").getAsJsonObject(); // // username = dataObject.get("uname").getAsString(); // admin = dataObject.get("is_admin").getAsBoolean(); // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuEvent.java // @Getter // public class DanmakuEvent extends EventObject { // private Kind kind; // private Object param; // // /** // * Constructs a prototypical Event. // * // * @param source The object on which the Event initially occurred. // * @throws IllegalArgumentException if source is null. // */ // public DanmakuEvent(Object source) { // super(source); // } // // public DanmakuEvent(Object source, Object param, Kind kind) { // super(source); // this.kind = kind; // this.param = param; // } // // public enum Kind { // JOINED, ERROR, ERROR_DOWN, NEW_DANMAKU, WATCHER_COUNT, // START_STOP, WELCOME_VIP, GIVE_GIFT, GLOBAL_GIFT, GLOBAL_ANNOUNCE // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuListener.java // public interface DanmakuListener { // void danmakuEvent(@NotNull DanmakuEvent event); // // void watcherCountEvent(@NotNull DanmakuEvent event); // // void errorEvent(@NotNull DanmakuEvent event); // // void startStopEvent(@NotNull DanmakuEvent event); // // void statusEvent(@NotNull DanmakuEvent event); // // void welcomeVipEvent(@NotNull DanmakuEvent event); // // void giveGiftEvent(@NotNull DanmakuEvent event); // // void globalGiftEvent(@NotNull DanmakuEvent event); // // void globalAnnounceEvent(@NotNull DanmakuEvent event); // }
import charlie.bililivelib.danmaku.datamodel.WelcomeVipInfo; import charlie.bililivelib.danmaku.event.DanmakuEvent; import charlie.bililivelib.danmaku.event.DanmakuListener; import com.google.gson.JsonObject; import org.jetbrains.annotations.NotNull; import java.util.List;
package charlie.bililivelib.danmaku.dispatch; /** * 分发老爷进直播间事件的分发器。对COMMAND为'WELCOME'的事件有效。 * * @author Charlie Jiang * @since rv1 */ public class WelcomeVipDispatcher extends AbstractJSONDispatcher { public static final String[] ACCEPTABLE_COMMANDS = { "WELCOME" }; private static WelcomeVipDispatcher GLOBAL_INSTANCE; @NotNull public static WelcomeVipDispatcher getGlobalInstance() { if (GLOBAL_INSTANCE == null) { GLOBAL_INSTANCE = new WelcomeVipDispatcher(); } return GLOBAL_INSTANCE; } @Override protected String[] getAcceptableCommands() { return ACCEPTABLE_COMMANDS; } /** * {@inheritDoc} * @param listeners 监听器列表 * @param rootObject 事件内容产生的JSON对象结构 * @param source 事件发生源 */ @Override public void dispatch(List<DanmakuListener> listeners, JsonObject rootObject, Object source) {
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/datamodel/WelcomeVipInfo.java // @Data // @AllArgsConstructor // public class WelcomeVipInfo { // private String username; // private boolean admin; // // public WelcomeVipInfo(JsonObject rootObject) { // JsonObject dataObject = rootObject.get("data").getAsJsonObject(); // // username = dataObject.get("uname").getAsString(); // admin = dataObject.get("is_admin").getAsBoolean(); // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuEvent.java // @Getter // public class DanmakuEvent extends EventObject { // private Kind kind; // private Object param; // // /** // * Constructs a prototypical Event. // * // * @param source The object on which the Event initially occurred. // * @throws IllegalArgumentException if source is null. // */ // public DanmakuEvent(Object source) { // super(source); // } // // public DanmakuEvent(Object source, Object param, Kind kind) { // super(source); // this.kind = kind; // this.param = param; // } // // public enum Kind { // JOINED, ERROR, ERROR_DOWN, NEW_DANMAKU, WATCHER_COUNT, // START_STOP, WELCOME_VIP, GIVE_GIFT, GLOBAL_GIFT, GLOBAL_ANNOUNCE // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuListener.java // public interface DanmakuListener { // void danmakuEvent(@NotNull DanmakuEvent event); // // void watcherCountEvent(@NotNull DanmakuEvent event); // // void errorEvent(@NotNull DanmakuEvent event); // // void startStopEvent(@NotNull DanmakuEvent event); // // void statusEvent(@NotNull DanmakuEvent event); // // void welcomeVipEvent(@NotNull DanmakuEvent event); // // void giveGiftEvent(@NotNull DanmakuEvent event); // // void globalGiftEvent(@NotNull DanmakuEvent event); // // void globalAnnounceEvent(@NotNull DanmakuEvent event); // } // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/dispatch/WelcomeVipDispatcher.java import charlie.bililivelib.danmaku.datamodel.WelcomeVipInfo; import charlie.bililivelib.danmaku.event.DanmakuEvent; import charlie.bililivelib.danmaku.event.DanmakuListener; import com.google.gson.JsonObject; import org.jetbrains.annotations.NotNull; import java.util.List; package charlie.bililivelib.danmaku.dispatch; /** * 分发老爷进直播间事件的分发器。对COMMAND为'WELCOME'的事件有效。 * * @author Charlie Jiang * @since rv1 */ public class WelcomeVipDispatcher extends AbstractJSONDispatcher { public static final String[] ACCEPTABLE_COMMANDS = { "WELCOME" }; private static WelcomeVipDispatcher GLOBAL_INSTANCE; @NotNull public static WelcomeVipDispatcher getGlobalInstance() { if (GLOBAL_INSTANCE == null) { GLOBAL_INSTANCE = new WelcomeVipDispatcher(); } return GLOBAL_INSTANCE; } @Override protected String[] getAcceptableCommands() { return ACCEPTABLE_COMMANDS; } /** * {@inheritDoc} * @param listeners 监听器列表 * @param rootObject 事件内容产生的JSON对象结构 * @param source 事件发生源 */ @Override public void dispatch(List<DanmakuListener> listeners, JsonObject rootObject, Object source) {
DanmakuEvent event = new DanmakuEvent(source, new WelcomeVipInfo(rootObject),
cqjjjzr/BiliLiveLib
BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/dispatch/WelcomeVipDispatcher.java
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/datamodel/WelcomeVipInfo.java // @Data // @AllArgsConstructor // public class WelcomeVipInfo { // private String username; // private boolean admin; // // public WelcomeVipInfo(JsonObject rootObject) { // JsonObject dataObject = rootObject.get("data").getAsJsonObject(); // // username = dataObject.get("uname").getAsString(); // admin = dataObject.get("is_admin").getAsBoolean(); // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuEvent.java // @Getter // public class DanmakuEvent extends EventObject { // private Kind kind; // private Object param; // // /** // * Constructs a prototypical Event. // * // * @param source The object on which the Event initially occurred. // * @throws IllegalArgumentException if source is null. // */ // public DanmakuEvent(Object source) { // super(source); // } // // public DanmakuEvent(Object source, Object param, Kind kind) { // super(source); // this.kind = kind; // this.param = param; // } // // public enum Kind { // JOINED, ERROR, ERROR_DOWN, NEW_DANMAKU, WATCHER_COUNT, // START_STOP, WELCOME_VIP, GIVE_GIFT, GLOBAL_GIFT, GLOBAL_ANNOUNCE // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuListener.java // public interface DanmakuListener { // void danmakuEvent(@NotNull DanmakuEvent event); // // void watcherCountEvent(@NotNull DanmakuEvent event); // // void errorEvent(@NotNull DanmakuEvent event); // // void startStopEvent(@NotNull DanmakuEvent event); // // void statusEvent(@NotNull DanmakuEvent event); // // void welcomeVipEvent(@NotNull DanmakuEvent event); // // void giveGiftEvent(@NotNull DanmakuEvent event); // // void globalGiftEvent(@NotNull DanmakuEvent event); // // void globalAnnounceEvent(@NotNull DanmakuEvent event); // }
import charlie.bililivelib.danmaku.datamodel.WelcomeVipInfo; import charlie.bililivelib.danmaku.event.DanmakuEvent; import charlie.bililivelib.danmaku.event.DanmakuListener; import com.google.gson.JsonObject; import org.jetbrains.annotations.NotNull; import java.util.List;
package charlie.bililivelib.danmaku.dispatch; /** * 分发老爷进直播间事件的分发器。对COMMAND为'WELCOME'的事件有效。 * * @author Charlie Jiang * @since rv1 */ public class WelcomeVipDispatcher extends AbstractJSONDispatcher { public static final String[] ACCEPTABLE_COMMANDS = { "WELCOME" }; private static WelcomeVipDispatcher GLOBAL_INSTANCE; @NotNull public static WelcomeVipDispatcher getGlobalInstance() { if (GLOBAL_INSTANCE == null) { GLOBAL_INSTANCE = new WelcomeVipDispatcher(); } return GLOBAL_INSTANCE; } @Override protected String[] getAcceptableCommands() { return ACCEPTABLE_COMMANDS; } /** * {@inheritDoc} * @param listeners 监听器列表 * @param rootObject 事件内容产生的JSON对象结构 * @param source 事件发生源 */ @Override public void dispatch(List<DanmakuListener> listeners, JsonObject rootObject, Object source) {
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/datamodel/WelcomeVipInfo.java // @Data // @AllArgsConstructor // public class WelcomeVipInfo { // private String username; // private boolean admin; // // public WelcomeVipInfo(JsonObject rootObject) { // JsonObject dataObject = rootObject.get("data").getAsJsonObject(); // // username = dataObject.get("uname").getAsString(); // admin = dataObject.get("is_admin").getAsBoolean(); // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuEvent.java // @Getter // public class DanmakuEvent extends EventObject { // private Kind kind; // private Object param; // // /** // * Constructs a prototypical Event. // * // * @param source The object on which the Event initially occurred. // * @throws IllegalArgumentException if source is null. // */ // public DanmakuEvent(Object source) { // super(source); // } // // public DanmakuEvent(Object source, Object param, Kind kind) { // super(source); // this.kind = kind; // this.param = param; // } // // public enum Kind { // JOINED, ERROR, ERROR_DOWN, NEW_DANMAKU, WATCHER_COUNT, // START_STOP, WELCOME_VIP, GIVE_GIFT, GLOBAL_GIFT, GLOBAL_ANNOUNCE // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuListener.java // public interface DanmakuListener { // void danmakuEvent(@NotNull DanmakuEvent event); // // void watcherCountEvent(@NotNull DanmakuEvent event); // // void errorEvent(@NotNull DanmakuEvent event); // // void startStopEvent(@NotNull DanmakuEvent event); // // void statusEvent(@NotNull DanmakuEvent event); // // void welcomeVipEvent(@NotNull DanmakuEvent event); // // void giveGiftEvent(@NotNull DanmakuEvent event); // // void globalGiftEvent(@NotNull DanmakuEvent event); // // void globalAnnounceEvent(@NotNull DanmakuEvent event); // } // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/dispatch/WelcomeVipDispatcher.java import charlie.bililivelib.danmaku.datamodel.WelcomeVipInfo; import charlie.bililivelib.danmaku.event.DanmakuEvent; import charlie.bililivelib.danmaku.event.DanmakuListener; import com.google.gson.JsonObject; import org.jetbrains.annotations.NotNull; import java.util.List; package charlie.bililivelib.danmaku.dispatch; /** * 分发老爷进直播间事件的分发器。对COMMAND为'WELCOME'的事件有效。 * * @author Charlie Jiang * @since rv1 */ public class WelcomeVipDispatcher extends AbstractJSONDispatcher { public static final String[] ACCEPTABLE_COMMANDS = { "WELCOME" }; private static WelcomeVipDispatcher GLOBAL_INSTANCE; @NotNull public static WelcomeVipDispatcher getGlobalInstance() { if (GLOBAL_INSTANCE == null) { GLOBAL_INSTANCE = new WelcomeVipDispatcher(); } return GLOBAL_INSTANCE; } @Override protected String[] getAcceptableCommands() { return ACCEPTABLE_COMMANDS; } /** * {@inheritDoc} * @param listeners 监听器列表 * @param rootObject 事件内容产生的JSON对象结构 * @param source 事件发生源 */ @Override public void dispatch(List<DanmakuListener> listeners, JsonObject rootObject, Object source) {
DanmakuEvent event = new DanmakuEvent(source, new WelcomeVipInfo(rootObject),
cqjjjzr/BiliLiveLib
BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/DanmakuPacket.java
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/DanmakuReceiver.java // public static final Charset UTF8 = Charset.forName("UTF-8");
import lombok.AllArgsConstructor; import lombok.Data; import lombok.Getter; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import static charlie.bililivelib.danmaku.DanmakuReceiver.UTF8;
package charlie.bililivelib.danmaku; /** * 用于封装发送到弹幕服务器的数据包。<br> * 数据包的结构如下:<br> * {@code +-----+-------+-----+--------+-------+----------+}<br> * {@code | LEN | H Len | VER | OPCODE | PARAM | --BODY-- |}<br> * {@code | -4- | -2- | -2- | --4--- | --4-- | Variable |}<br> * {@code +-----+-------+-----+--------+-------+----------+}<br> * - LEN: 数据包长度,包含自身长度,int类型;<br> * - H Len: 包头部长度,默认包类型长度为16 Bytes, short类型;<br> * - VER: 协议版本,short类型,目前仅支持0x01;<br> * - OPCODE: 操作码,int类型。具体见{@link DanmakuPacket.Action};<br> * - PARAM: 操作参数,int类型,默认0x01;<br> * - BODY: 数据包体,长度可变。 * * @author Charlie Jiang * @since rv1 */ @Data @AllArgsConstructor public final class DanmakuPacket { private static final short DEFAULT_HEADER_LENGTH = 0x10; private static final short DEFAULT_PROTOCOL_VERSION = 1; private static final int DEFAULT_PARAM = 1; private static final int DEFAULT_LENGTH = -1; private static final int PACKET_HEADER_SIZE = 16; private short headerLength = DEFAULT_HEADER_LENGTH; private short protocolVersion = DEFAULT_PROTOCOL_VERSION; private int length; private Action action; private int param = DEFAULT_PARAM; private String body = ""; public DanmakuPacket(Action action) { this(action, ""); } public DanmakuPacket(Action action, String body) { this(DEFAULT_HEADER_LENGTH, DEFAULT_PROTOCOL_VERSION, DEFAULT_LENGTH, action, DEFAULT_PARAM, body); } /** * 由本类生成byte[]数组 * @return byte[]数组 */ public byte[] generate() {
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/DanmakuReceiver.java // public static final Charset UTF8 = Charset.forName("UTF-8"); // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/DanmakuPacket.java import lombok.AllArgsConstructor; import lombok.Data; import lombok.Getter; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import static charlie.bililivelib.danmaku.DanmakuReceiver.UTF8; package charlie.bililivelib.danmaku; /** * 用于封装发送到弹幕服务器的数据包。<br> * 数据包的结构如下:<br> * {@code +-----+-------+-----+--------+-------+----------+}<br> * {@code | LEN | H Len | VER | OPCODE | PARAM | --BODY-- |}<br> * {@code | -4- | -2- | -2- | --4--- | --4-- | Variable |}<br> * {@code +-----+-------+-----+--------+-------+----------+}<br> * - LEN: 数据包长度,包含自身长度,int类型;<br> * - H Len: 包头部长度,默认包类型长度为16 Bytes, short类型;<br> * - VER: 协议版本,short类型,目前仅支持0x01;<br> * - OPCODE: 操作码,int类型。具体见{@link DanmakuPacket.Action};<br> * - PARAM: 操作参数,int类型,默认0x01;<br> * - BODY: 数据包体,长度可变。 * * @author Charlie Jiang * @since rv1 */ @Data @AllArgsConstructor public final class DanmakuPacket { private static final short DEFAULT_HEADER_LENGTH = 0x10; private static final short DEFAULT_PROTOCOL_VERSION = 1; private static final int DEFAULT_PARAM = 1; private static final int DEFAULT_LENGTH = -1; private static final int PACKET_HEADER_SIZE = 16; private short headerLength = DEFAULT_HEADER_LENGTH; private short protocolVersion = DEFAULT_PROTOCOL_VERSION; private int length; private Action action; private int param = DEFAULT_PARAM; private String body = ""; public DanmakuPacket(Action action) { this(action, ""); } public DanmakuPacket(Action action, String body) { this(DEFAULT_HEADER_LENGTH, DEFAULT_PROTOCOL_VERSION, DEFAULT_LENGTH, action, DEFAULT_PARAM, body); } /** * 由本类生成byte[]数组 * @return byte[]数组 */ public byte[] generate() {
byte[] bodyBytes = body.getBytes(UTF8);
cqjjjzr/BiliLiveLib
BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/dispatch/GlobalGiftDispatcher.java
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/Globals.java // public class Globals { // private static final String BILI_PASSPORT_HOST_ROOT = "passport.bilibili.com"; // private static final String BILI_LIVE_HOST_ROOT = "live.bilibili.com"; // @Getter // private static int CONNECTION_ALIVE_TIME_SECOND = 10; // private static Globals instance; // @Getter // private HttpHost biliLiveRoot; // @Getter // private HttpHost biliPassportHttpsRoot; // private ThreadLocal<Gson> gson; // // private HttpClientConnectionManager connectionPool; // @Getter // private SSLContext bilibiliSSLContext; // // public static Globals get() { // if (instance == null) { // instance = new Globals(); // instance.init(); // } // return instance; // } // // private void init() { // biliLiveRoot = new HttpHost(BILI_LIVE_HOST_ROOT); // //Visit bilibili passport via https. 443 is the https port. // biliPassportHttpsRoot = new HttpHost(BILI_PASSPORT_HOST_ROOT, 443, "https"); // gson = ThreadLocal.withInitial(() -> new GsonBuilder() // .setLenient() // .create()); // // try { // bilibiliSSLContext = SSLContextBuilder.create() // .loadTrustMaterial(new BilibiliTrustStrategy()) // .build(); // } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) { // throw new AssertionError("failed initializing bilibili ssl context!"); // } // } // // public Gson gson() { // return gson.get(); // } // // public HttpClientConnectionManager getConnectionPool() { // if (connectionPool == null) { // reInitializeConnectionPool(); // } // return connectionPool; // } // // public void reInitializeConnectionPool() { // connectionPool = new PoolingHttpClientConnectionManager(CONNECTION_ALIVE_TIME_SECOND, TimeUnit.SECONDS); // } // // public void setConnectionAliveTimeSecond(int connectionAliveTimeSecond) { // CONNECTION_ALIVE_TIME_SECOND = connectionAliveTimeSecond; // reInitializeConnectionPool(); // } // // // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuEvent.java // @Getter // public class DanmakuEvent extends EventObject { // private Kind kind; // private Object param; // // /** // * Constructs a prototypical Event. // * // * @param source The object on which the Event initially occurred. // * @throws IllegalArgumentException if source is null. // */ // public DanmakuEvent(Object source) { // super(source); // } // // public DanmakuEvent(Object source, Object param, Kind kind) { // super(source); // this.kind = kind; // this.param = param; // } // // public enum Kind { // JOINED, ERROR, ERROR_DOWN, NEW_DANMAKU, WATCHER_COUNT, // START_STOP, WELCOME_VIP, GIVE_GIFT, GLOBAL_GIFT, GLOBAL_ANNOUNCE // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuListener.java // public interface DanmakuListener { // void danmakuEvent(@NotNull DanmakuEvent event); // // void watcherCountEvent(@NotNull DanmakuEvent event); // // void errorEvent(@NotNull DanmakuEvent event); // // void startStopEvent(@NotNull DanmakuEvent event); // // void statusEvent(@NotNull DanmakuEvent event); // // void welcomeVipEvent(@NotNull DanmakuEvent event); // // void giveGiftEvent(@NotNull DanmakuEvent event); // // void globalGiftEvent(@NotNull DanmakuEvent event); // // void globalAnnounceEvent(@NotNull DanmakuEvent event); // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/smalltv/SmallTV.java // @Data // public class SmallTV { // @SerializedName("msg") // private String message; // @SerializedName("url") // private String roomURL; // @SerializedName("roomid") // private int roomID; // @SerializedName("real_roomid") // private int realRoomID; // @SerializedName("tv_id") // private int smallTVID; // }
import charlie.bililivelib.Globals; import charlie.bililivelib.danmaku.event.DanmakuEvent; import charlie.bililivelib.danmaku.event.DanmakuListener; import charlie.bililivelib.smalltv.SmallTV; import com.google.gson.JsonObject; import org.jetbrains.annotations.NotNull; import java.util.List;
package charlie.bililivelib.danmaku.dispatch; /** * 分发小电视事件的分发器。对COMMAND为'SYS_MSG'且含有'tv_id'值的事件有效。 * * @author Charlie Jiang * @since rv1 */ public class GlobalGiftDispatcher extends AbstractJSONDispatcher { public static final String[] ACCEPTABLE_COMMANDS = { "SYS_MSG" }; private static GlobalGiftDispatcher GLOBAL_INSTANCE; @NotNull public static GlobalGiftDispatcher getGlobalInstance() { if (GLOBAL_INSTANCE == null) { GLOBAL_INSTANCE = new GlobalGiftDispatcher(); } return GLOBAL_INSTANCE; } @Override protected String[] getAcceptableCommands() { return ACCEPTABLE_COMMANDS; } /** * {@inheritDoc} * @param listeners 监听器列表 * @param rootObject 事件内容产生的JSON对象结构 * @param source 事件发生源 */ @Override
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/Globals.java // public class Globals { // private static final String BILI_PASSPORT_HOST_ROOT = "passport.bilibili.com"; // private static final String BILI_LIVE_HOST_ROOT = "live.bilibili.com"; // @Getter // private static int CONNECTION_ALIVE_TIME_SECOND = 10; // private static Globals instance; // @Getter // private HttpHost biliLiveRoot; // @Getter // private HttpHost biliPassportHttpsRoot; // private ThreadLocal<Gson> gson; // // private HttpClientConnectionManager connectionPool; // @Getter // private SSLContext bilibiliSSLContext; // // public static Globals get() { // if (instance == null) { // instance = new Globals(); // instance.init(); // } // return instance; // } // // private void init() { // biliLiveRoot = new HttpHost(BILI_LIVE_HOST_ROOT); // //Visit bilibili passport via https. 443 is the https port. // biliPassportHttpsRoot = new HttpHost(BILI_PASSPORT_HOST_ROOT, 443, "https"); // gson = ThreadLocal.withInitial(() -> new GsonBuilder() // .setLenient() // .create()); // // try { // bilibiliSSLContext = SSLContextBuilder.create() // .loadTrustMaterial(new BilibiliTrustStrategy()) // .build(); // } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) { // throw new AssertionError("failed initializing bilibili ssl context!"); // } // } // // public Gson gson() { // return gson.get(); // } // // public HttpClientConnectionManager getConnectionPool() { // if (connectionPool == null) { // reInitializeConnectionPool(); // } // return connectionPool; // } // // public void reInitializeConnectionPool() { // connectionPool = new PoolingHttpClientConnectionManager(CONNECTION_ALIVE_TIME_SECOND, TimeUnit.SECONDS); // } // // public void setConnectionAliveTimeSecond(int connectionAliveTimeSecond) { // CONNECTION_ALIVE_TIME_SECOND = connectionAliveTimeSecond; // reInitializeConnectionPool(); // } // // // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuEvent.java // @Getter // public class DanmakuEvent extends EventObject { // private Kind kind; // private Object param; // // /** // * Constructs a prototypical Event. // * // * @param source The object on which the Event initially occurred. // * @throws IllegalArgumentException if source is null. // */ // public DanmakuEvent(Object source) { // super(source); // } // // public DanmakuEvent(Object source, Object param, Kind kind) { // super(source); // this.kind = kind; // this.param = param; // } // // public enum Kind { // JOINED, ERROR, ERROR_DOWN, NEW_DANMAKU, WATCHER_COUNT, // START_STOP, WELCOME_VIP, GIVE_GIFT, GLOBAL_GIFT, GLOBAL_ANNOUNCE // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuListener.java // public interface DanmakuListener { // void danmakuEvent(@NotNull DanmakuEvent event); // // void watcherCountEvent(@NotNull DanmakuEvent event); // // void errorEvent(@NotNull DanmakuEvent event); // // void startStopEvent(@NotNull DanmakuEvent event); // // void statusEvent(@NotNull DanmakuEvent event); // // void welcomeVipEvent(@NotNull DanmakuEvent event); // // void giveGiftEvent(@NotNull DanmakuEvent event); // // void globalGiftEvent(@NotNull DanmakuEvent event); // // void globalAnnounceEvent(@NotNull DanmakuEvent event); // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/smalltv/SmallTV.java // @Data // public class SmallTV { // @SerializedName("msg") // private String message; // @SerializedName("url") // private String roomURL; // @SerializedName("roomid") // private int roomID; // @SerializedName("real_roomid") // private int realRoomID; // @SerializedName("tv_id") // private int smallTVID; // } // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/dispatch/GlobalGiftDispatcher.java import charlie.bililivelib.Globals; import charlie.bililivelib.danmaku.event.DanmakuEvent; import charlie.bililivelib.danmaku.event.DanmakuListener; import charlie.bililivelib.smalltv.SmallTV; import com.google.gson.JsonObject; import org.jetbrains.annotations.NotNull; import java.util.List; package charlie.bililivelib.danmaku.dispatch; /** * 分发小电视事件的分发器。对COMMAND为'SYS_MSG'且含有'tv_id'值的事件有效。 * * @author Charlie Jiang * @since rv1 */ public class GlobalGiftDispatcher extends AbstractJSONDispatcher { public static final String[] ACCEPTABLE_COMMANDS = { "SYS_MSG" }; private static GlobalGiftDispatcher GLOBAL_INSTANCE; @NotNull public static GlobalGiftDispatcher getGlobalInstance() { if (GLOBAL_INSTANCE == null) { GLOBAL_INSTANCE = new GlobalGiftDispatcher(); } return GLOBAL_INSTANCE; } @Override protected String[] getAcceptableCommands() { return ACCEPTABLE_COMMANDS; } /** * {@inheritDoc} * @param listeners 监听器列表 * @param rootObject 事件内容产生的JSON对象结构 * @param source 事件发生源 */ @Override
public void dispatch(List<DanmakuListener> listeners, JsonObject rootObject, Object source) {
cqjjjzr/BiliLiveLib
BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/dispatch/GlobalGiftDispatcher.java
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/Globals.java // public class Globals { // private static final String BILI_PASSPORT_HOST_ROOT = "passport.bilibili.com"; // private static final String BILI_LIVE_HOST_ROOT = "live.bilibili.com"; // @Getter // private static int CONNECTION_ALIVE_TIME_SECOND = 10; // private static Globals instance; // @Getter // private HttpHost biliLiveRoot; // @Getter // private HttpHost biliPassportHttpsRoot; // private ThreadLocal<Gson> gson; // // private HttpClientConnectionManager connectionPool; // @Getter // private SSLContext bilibiliSSLContext; // // public static Globals get() { // if (instance == null) { // instance = new Globals(); // instance.init(); // } // return instance; // } // // private void init() { // biliLiveRoot = new HttpHost(BILI_LIVE_HOST_ROOT); // //Visit bilibili passport via https. 443 is the https port. // biliPassportHttpsRoot = new HttpHost(BILI_PASSPORT_HOST_ROOT, 443, "https"); // gson = ThreadLocal.withInitial(() -> new GsonBuilder() // .setLenient() // .create()); // // try { // bilibiliSSLContext = SSLContextBuilder.create() // .loadTrustMaterial(new BilibiliTrustStrategy()) // .build(); // } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) { // throw new AssertionError("failed initializing bilibili ssl context!"); // } // } // // public Gson gson() { // return gson.get(); // } // // public HttpClientConnectionManager getConnectionPool() { // if (connectionPool == null) { // reInitializeConnectionPool(); // } // return connectionPool; // } // // public void reInitializeConnectionPool() { // connectionPool = new PoolingHttpClientConnectionManager(CONNECTION_ALIVE_TIME_SECOND, TimeUnit.SECONDS); // } // // public void setConnectionAliveTimeSecond(int connectionAliveTimeSecond) { // CONNECTION_ALIVE_TIME_SECOND = connectionAliveTimeSecond; // reInitializeConnectionPool(); // } // // // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuEvent.java // @Getter // public class DanmakuEvent extends EventObject { // private Kind kind; // private Object param; // // /** // * Constructs a prototypical Event. // * // * @param source The object on which the Event initially occurred. // * @throws IllegalArgumentException if source is null. // */ // public DanmakuEvent(Object source) { // super(source); // } // // public DanmakuEvent(Object source, Object param, Kind kind) { // super(source); // this.kind = kind; // this.param = param; // } // // public enum Kind { // JOINED, ERROR, ERROR_DOWN, NEW_DANMAKU, WATCHER_COUNT, // START_STOP, WELCOME_VIP, GIVE_GIFT, GLOBAL_GIFT, GLOBAL_ANNOUNCE // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuListener.java // public interface DanmakuListener { // void danmakuEvent(@NotNull DanmakuEvent event); // // void watcherCountEvent(@NotNull DanmakuEvent event); // // void errorEvent(@NotNull DanmakuEvent event); // // void startStopEvent(@NotNull DanmakuEvent event); // // void statusEvent(@NotNull DanmakuEvent event); // // void welcomeVipEvent(@NotNull DanmakuEvent event); // // void giveGiftEvent(@NotNull DanmakuEvent event); // // void globalGiftEvent(@NotNull DanmakuEvent event); // // void globalAnnounceEvent(@NotNull DanmakuEvent event); // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/smalltv/SmallTV.java // @Data // public class SmallTV { // @SerializedName("msg") // private String message; // @SerializedName("url") // private String roomURL; // @SerializedName("roomid") // private int roomID; // @SerializedName("real_roomid") // private int realRoomID; // @SerializedName("tv_id") // private int smallTVID; // }
import charlie.bililivelib.Globals; import charlie.bililivelib.danmaku.event.DanmakuEvent; import charlie.bililivelib.danmaku.event.DanmakuListener; import charlie.bililivelib.smalltv.SmallTV; import com.google.gson.JsonObject; import org.jetbrains.annotations.NotNull; import java.util.List;
package charlie.bililivelib.danmaku.dispatch; /** * 分发小电视事件的分发器。对COMMAND为'SYS_MSG'且含有'tv_id'值的事件有效。 * * @author Charlie Jiang * @since rv1 */ public class GlobalGiftDispatcher extends AbstractJSONDispatcher { public static final String[] ACCEPTABLE_COMMANDS = { "SYS_MSG" }; private static GlobalGiftDispatcher GLOBAL_INSTANCE; @NotNull public static GlobalGiftDispatcher getGlobalInstance() { if (GLOBAL_INSTANCE == null) { GLOBAL_INSTANCE = new GlobalGiftDispatcher(); } return GLOBAL_INSTANCE; } @Override protected String[] getAcceptableCommands() { return ACCEPTABLE_COMMANDS; } /** * {@inheritDoc} * @param listeners 监听器列表 * @param rootObject 事件内容产生的JSON对象结构 * @param source 事件发生源 */ @Override public void dispatch(List<DanmakuListener> listeners, JsonObject rootObject, Object source) { if (!rootObject.has("tv_id")) return; //NOT A SMALL TV OBJECT.
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/Globals.java // public class Globals { // private static final String BILI_PASSPORT_HOST_ROOT = "passport.bilibili.com"; // private static final String BILI_LIVE_HOST_ROOT = "live.bilibili.com"; // @Getter // private static int CONNECTION_ALIVE_TIME_SECOND = 10; // private static Globals instance; // @Getter // private HttpHost biliLiveRoot; // @Getter // private HttpHost biliPassportHttpsRoot; // private ThreadLocal<Gson> gson; // // private HttpClientConnectionManager connectionPool; // @Getter // private SSLContext bilibiliSSLContext; // // public static Globals get() { // if (instance == null) { // instance = new Globals(); // instance.init(); // } // return instance; // } // // private void init() { // biliLiveRoot = new HttpHost(BILI_LIVE_HOST_ROOT); // //Visit bilibili passport via https. 443 is the https port. // biliPassportHttpsRoot = new HttpHost(BILI_PASSPORT_HOST_ROOT, 443, "https"); // gson = ThreadLocal.withInitial(() -> new GsonBuilder() // .setLenient() // .create()); // // try { // bilibiliSSLContext = SSLContextBuilder.create() // .loadTrustMaterial(new BilibiliTrustStrategy()) // .build(); // } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) { // throw new AssertionError("failed initializing bilibili ssl context!"); // } // } // // public Gson gson() { // return gson.get(); // } // // public HttpClientConnectionManager getConnectionPool() { // if (connectionPool == null) { // reInitializeConnectionPool(); // } // return connectionPool; // } // // public void reInitializeConnectionPool() { // connectionPool = new PoolingHttpClientConnectionManager(CONNECTION_ALIVE_TIME_SECOND, TimeUnit.SECONDS); // } // // public void setConnectionAliveTimeSecond(int connectionAliveTimeSecond) { // CONNECTION_ALIVE_TIME_SECOND = connectionAliveTimeSecond; // reInitializeConnectionPool(); // } // // // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuEvent.java // @Getter // public class DanmakuEvent extends EventObject { // private Kind kind; // private Object param; // // /** // * Constructs a prototypical Event. // * // * @param source The object on which the Event initially occurred. // * @throws IllegalArgumentException if source is null. // */ // public DanmakuEvent(Object source) { // super(source); // } // // public DanmakuEvent(Object source, Object param, Kind kind) { // super(source); // this.kind = kind; // this.param = param; // } // // public enum Kind { // JOINED, ERROR, ERROR_DOWN, NEW_DANMAKU, WATCHER_COUNT, // START_STOP, WELCOME_VIP, GIVE_GIFT, GLOBAL_GIFT, GLOBAL_ANNOUNCE // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuListener.java // public interface DanmakuListener { // void danmakuEvent(@NotNull DanmakuEvent event); // // void watcherCountEvent(@NotNull DanmakuEvent event); // // void errorEvent(@NotNull DanmakuEvent event); // // void startStopEvent(@NotNull DanmakuEvent event); // // void statusEvent(@NotNull DanmakuEvent event); // // void welcomeVipEvent(@NotNull DanmakuEvent event); // // void giveGiftEvent(@NotNull DanmakuEvent event); // // void globalGiftEvent(@NotNull DanmakuEvent event); // // void globalAnnounceEvent(@NotNull DanmakuEvent event); // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/smalltv/SmallTV.java // @Data // public class SmallTV { // @SerializedName("msg") // private String message; // @SerializedName("url") // private String roomURL; // @SerializedName("roomid") // private int roomID; // @SerializedName("real_roomid") // private int realRoomID; // @SerializedName("tv_id") // private int smallTVID; // } // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/dispatch/GlobalGiftDispatcher.java import charlie.bililivelib.Globals; import charlie.bililivelib.danmaku.event.DanmakuEvent; import charlie.bililivelib.danmaku.event.DanmakuListener; import charlie.bililivelib.smalltv.SmallTV; import com.google.gson.JsonObject; import org.jetbrains.annotations.NotNull; import java.util.List; package charlie.bililivelib.danmaku.dispatch; /** * 分发小电视事件的分发器。对COMMAND为'SYS_MSG'且含有'tv_id'值的事件有效。 * * @author Charlie Jiang * @since rv1 */ public class GlobalGiftDispatcher extends AbstractJSONDispatcher { public static final String[] ACCEPTABLE_COMMANDS = { "SYS_MSG" }; private static GlobalGiftDispatcher GLOBAL_INSTANCE; @NotNull public static GlobalGiftDispatcher getGlobalInstance() { if (GLOBAL_INSTANCE == null) { GLOBAL_INSTANCE = new GlobalGiftDispatcher(); } return GLOBAL_INSTANCE; } @Override protected String[] getAcceptableCommands() { return ACCEPTABLE_COMMANDS; } /** * {@inheritDoc} * @param listeners 监听器列表 * @param rootObject 事件内容产生的JSON对象结构 * @param source 事件发生源 */ @Override public void dispatch(List<DanmakuListener> listeners, JsonObject rootObject, Object source) { if (!rootObject.has("tv_id")) return; //NOT A SMALL TV OBJECT.
SmallTV smallTV = Globals.get().gson()
cqjjjzr/BiliLiveLib
BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/dispatch/GlobalGiftDispatcher.java
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/Globals.java // public class Globals { // private static final String BILI_PASSPORT_HOST_ROOT = "passport.bilibili.com"; // private static final String BILI_LIVE_HOST_ROOT = "live.bilibili.com"; // @Getter // private static int CONNECTION_ALIVE_TIME_SECOND = 10; // private static Globals instance; // @Getter // private HttpHost biliLiveRoot; // @Getter // private HttpHost biliPassportHttpsRoot; // private ThreadLocal<Gson> gson; // // private HttpClientConnectionManager connectionPool; // @Getter // private SSLContext bilibiliSSLContext; // // public static Globals get() { // if (instance == null) { // instance = new Globals(); // instance.init(); // } // return instance; // } // // private void init() { // biliLiveRoot = new HttpHost(BILI_LIVE_HOST_ROOT); // //Visit bilibili passport via https. 443 is the https port. // biliPassportHttpsRoot = new HttpHost(BILI_PASSPORT_HOST_ROOT, 443, "https"); // gson = ThreadLocal.withInitial(() -> new GsonBuilder() // .setLenient() // .create()); // // try { // bilibiliSSLContext = SSLContextBuilder.create() // .loadTrustMaterial(new BilibiliTrustStrategy()) // .build(); // } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) { // throw new AssertionError("failed initializing bilibili ssl context!"); // } // } // // public Gson gson() { // return gson.get(); // } // // public HttpClientConnectionManager getConnectionPool() { // if (connectionPool == null) { // reInitializeConnectionPool(); // } // return connectionPool; // } // // public void reInitializeConnectionPool() { // connectionPool = new PoolingHttpClientConnectionManager(CONNECTION_ALIVE_TIME_SECOND, TimeUnit.SECONDS); // } // // public void setConnectionAliveTimeSecond(int connectionAliveTimeSecond) { // CONNECTION_ALIVE_TIME_SECOND = connectionAliveTimeSecond; // reInitializeConnectionPool(); // } // // // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuEvent.java // @Getter // public class DanmakuEvent extends EventObject { // private Kind kind; // private Object param; // // /** // * Constructs a prototypical Event. // * // * @param source The object on which the Event initially occurred. // * @throws IllegalArgumentException if source is null. // */ // public DanmakuEvent(Object source) { // super(source); // } // // public DanmakuEvent(Object source, Object param, Kind kind) { // super(source); // this.kind = kind; // this.param = param; // } // // public enum Kind { // JOINED, ERROR, ERROR_DOWN, NEW_DANMAKU, WATCHER_COUNT, // START_STOP, WELCOME_VIP, GIVE_GIFT, GLOBAL_GIFT, GLOBAL_ANNOUNCE // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuListener.java // public interface DanmakuListener { // void danmakuEvent(@NotNull DanmakuEvent event); // // void watcherCountEvent(@NotNull DanmakuEvent event); // // void errorEvent(@NotNull DanmakuEvent event); // // void startStopEvent(@NotNull DanmakuEvent event); // // void statusEvent(@NotNull DanmakuEvent event); // // void welcomeVipEvent(@NotNull DanmakuEvent event); // // void giveGiftEvent(@NotNull DanmakuEvent event); // // void globalGiftEvent(@NotNull DanmakuEvent event); // // void globalAnnounceEvent(@NotNull DanmakuEvent event); // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/smalltv/SmallTV.java // @Data // public class SmallTV { // @SerializedName("msg") // private String message; // @SerializedName("url") // private String roomURL; // @SerializedName("roomid") // private int roomID; // @SerializedName("real_roomid") // private int realRoomID; // @SerializedName("tv_id") // private int smallTVID; // }
import charlie.bililivelib.Globals; import charlie.bililivelib.danmaku.event.DanmakuEvent; import charlie.bililivelib.danmaku.event.DanmakuListener; import charlie.bililivelib.smalltv.SmallTV; import com.google.gson.JsonObject; import org.jetbrains.annotations.NotNull; import java.util.List;
package charlie.bililivelib.danmaku.dispatch; /** * 分发小电视事件的分发器。对COMMAND为'SYS_MSG'且含有'tv_id'值的事件有效。 * * @author Charlie Jiang * @since rv1 */ public class GlobalGiftDispatcher extends AbstractJSONDispatcher { public static final String[] ACCEPTABLE_COMMANDS = { "SYS_MSG" }; private static GlobalGiftDispatcher GLOBAL_INSTANCE; @NotNull public static GlobalGiftDispatcher getGlobalInstance() { if (GLOBAL_INSTANCE == null) { GLOBAL_INSTANCE = new GlobalGiftDispatcher(); } return GLOBAL_INSTANCE; } @Override protected String[] getAcceptableCommands() { return ACCEPTABLE_COMMANDS; } /** * {@inheritDoc} * @param listeners 监听器列表 * @param rootObject 事件内容产生的JSON对象结构 * @param source 事件发生源 */ @Override public void dispatch(List<DanmakuListener> listeners, JsonObject rootObject, Object source) { if (!rootObject.has("tv_id")) return; //NOT A SMALL TV OBJECT.
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/Globals.java // public class Globals { // private static final String BILI_PASSPORT_HOST_ROOT = "passport.bilibili.com"; // private static final String BILI_LIVE_HOST_ROOT = "live.bilibili.com"; // @Getter // private static int CONNECTION_ALIVE_TIME_SECOND = 10; // private static Globals instance; // @Getter // private HttpHost biliLiveRoot; // @Getter // private HttpHost biliPassportHttpsRoot; // private ThreadLocal<Gson> gson; // // private HttpClientConnectionManager connectionPool; // @Getter // private SSLContext bilibiliSSLContext; // // public static Globals get() { // if (instance == null) { // instance = new Globals(); // instance.init(); // } // return instance; // } // // private void init() { // biliLiveRoot = new HttpHost(BILI_LIVE_HOST_ROOT); // //Visit bilibili passport via https. 443 is the https port. // biliPassportHttpsRoot = new HttpHost(BILI_PASSPORT_HOST_ROOT, 443, "https"); // gson = ThreadLocal.withInitial(() -> new GsonBuilder() // .setLenient() // .create()); // // try { // bilibiliSSLContext = SSLContextBuilder.create() // .loadTrustMaterial(new BilibiliTrustStrategy()) // .build(); // } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) { // throw new AssertionError("failed initializing bilibili ssl context!"); // } // } // // public Gson gson() { // return gson.get(); // } // // public HttpClientConnectionManager getConnectionPool() { // if (connectionPool == null) { // reInitializeConnectionPool(); // } // return connectionPool; // } // // public void reInitializeConnectionPool() { // connectionPool = new PoolingHttpClientConnectionManager(CONNECTION_ALIVE_TIME_SECOND, TimeUnit.SECONDS); // } // // public void setConnectionAliveTimeSecond(int connectionAliveTimeSecond) { // CONNECTION_ALIVE_TIME_SECOND = connectionAliveTimeSecond; // reInitializeConnectionPool(); // } // // // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuEvent.java // @Getter // public class DanmakuEvent extends EventObject { // private Kind kind; // private Object param; // // /** // * Constructs a prototypical Event. // * // * @param source The object on which the Event initially occurred. // * @throws IllegalArgumentException if source is null. // */ // public DanmakuEvent(Object source) { // super(source); // } // // public DanmakuEvent(Object source, Object param, Kind kind) { // super(source); // this.kind = kind; // this.param = param; // } // // public enum Kind { // JOINED, ERROR, ERROR_DOWN, NEW_DANMAKU, WATCHER_COUNT, // START_STOP, WELCOME_VIP, GIVE_GIFT, GLOBAL_GIFT, GLOBAL_ANNOUNCE // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuListener.java // public interface DanmakuListener { // void danmakuEvent(@NotNull DanmakuEvent event); // // void watcherCountEvent(@NotNull DanmakuEvent event); // // void errorEvent(@NotNull DanmakuEvent event); // // void startStopEvent(@NotNull DanmakuEvent event); // // void statusEvent(@NotNull DanmakuEvent event); // // void welcomeVipEvent(@NotNull DanmakuEvent event); // // void giveGiftEvent(@NotNull DanmakuEvent event); // // void globalGiftEvent(@NotNull DanmakuEvent event); // // void globalAnnounceEvent(@NotNull DanmakuEvent event); // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/smalltv/SmallTV.java // @Data // public class SmallTV { // @SerializedName("msg") // private String message; // @SerializedName("url") // private String roomURL; // @SerializedName("roomid") // private int roomID; // @SerializedName("real_roomid") // private int realRoomID; // @SerializedName("tv_id") // private int smallTVID; // } // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/dispatch/GlobalGiftDispatcher.java import charlie.bililivelib.Globals; import charlie.bililivelib.danmaku.event.DanmakuEvent; import charlie.bililivelib.danmaku.event.DanmakuListener; import charlie.bililivelib.smalltv.SmallTV; import com.google.gson.JsonObject; import org.jetbrains.annotations.NotNull; import java.util.List; package charlie.bililivelib.danmaku.dispatch; /** * 分发小电视事件的分发器。对COMMAND为'SYS_MSG'且含有'tv_id'值的事件有效。 * * @author Charlie Jiang * @since rv1 */ public class GlobalGiftDispatcher extends AbstractJSONDispatcher { public static final String[] ACCEPTABLE_COMMANDS = { "SYS_MSG" }; private static GlobalGiftDispatcher GLOBAL_INSTANCE; @NotNull public static GlobalGiftDispatcher getGlobalInstance() { if (GLOBAL_INSTANCE == null) { GLOBAL_INSTANCE = new GlobalGiftDispatcher(); } return GLOBAL_INSTANCE; } @Override protected String[] getAcceptableCommands() { return ACCEPTABLE_COMMANDS; } /** * {@inheritDoc} * @param listeners 监听器列表 * @param rootObject 事件内容产生的JSON对象结构 * @param source 事件发生源 */ @Override public void dispatch(List<DanmakuListener> listeners, JsonObject rootObject, Object source) { if (!rootObject.has("tv_id")) return; //NOT A SMALL TV OBJECT.
SmallTV smallTV = Globals.get().gson()
cqjjjzr/BiliLiveLib
BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/dispatch/GlobalGiftDispatcher.java
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/Globals.java // public class Globals { // private static final String BILI_PASSPORT_HOST_ROOT = "passport.bilibili.com"; // private static final String BILI_LIVE_HOST_ROOT = "live.bilibili.com"; // @Getter // private static int CONNECTION_ALIVE_TIME_SECOND = 10; // private static Globals instance; // @Getter // private HttpHost biliLiveRoot; // @Getter // private HttpHost biliPassportHttpsRoot; // private ThreadLocal<Gson> gson; // // private HttpClientConnectionManager connectionPool; // @Getter // private SSLContext bilibiliSSLContext; // // public static Globals get() { // if (instance == null) { // instance = new Globals(); // instance.init(); // } // return instance; // } // // private void init() { // biliLiveRoot = new HttpHost(BILI_LIVE_HOST_ROOT); // //Visit bilibili passport via https. 443 is the https port. // biliPassportHttpsRoot = new HttpHost(BILI_PASSPORT_HOST_ROOT, 443, "https"); // gson = ThreadLocal.withInitial(() -> new GsonBuilder() // .setLenient() // .create()); // // try { // bilibiliSSLContext = SSLContextBuilder.create() // .loadTrustMaterial(new BilibiliTrustStrategy()) // .build(); // } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) { // throw new AssertionError("failed initializing bilibili ssl context!"); // } // } // // public Gson gson() { // return gson.get(); // } // // public HttpClientConnectionManager getConnectionPool() { // if (connectionPool == null) { // reInitializeConnectionPool(); // } // return connectionPool; // } // // public void reInitializeConnectionPool() { // connectionPool = new PoolingHttpClientConnectionManager(CONNECTION_ALIVE_TIME_SECOND, TimeUnit.SECONDS); // } // // public void setConnectionAliveTimeSecond(int connectionAliveTimeSecond) { // CONNECTION_ALIVE_TIME_SECOND = connectionAliveTimeSecond; // reInitializeConnectionPool(); // } // // // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuEvent.java // @Getter // public class DanmakuEvent extends EventObject { // private Kind kind; // private Object param; // // /** // * Constructs a prototypical Event. // * // * @param source The object on which the Event initially occurred. // * @throws IllegalArgumentException if source is null. // */ // public DanmakuEvent(Object source) { // super(source); // } // // public DanmakuEvent(Object source, Object param, Kind kind) { // super(source); // this.kind = kind; // this.param = param; // } // // public enum Kind { // JOINED, ERROR, ERROR_DOWN, NEW_DANMAKU, WATCHER_COUNT, // START_STOP, WELCOME_VIP, GIVE_GIFT, GLOBAL_GIFT, GLOBAL_ANNOUNCE // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuListener.java // public interface DanmakuListener { // void danmakuEvent(@NotNull DanmakuEvent event); // // void watcherCountEvent(@NotNull DanmakuEvent event); // // void errorEvent(@NotNull DanmakuEvent event); // // void startStopEvent(@NotNull DanmakuEvent event); // // void statusEvent(@NotNull DanmakuEvent event); // // void welcomeVipEvent(@NotNull DanmakuEvent event); // // void giveGiftEvent(@NotNull DanmakuEvent event); // // void globalGiftEvent(@NotNull DanmakuEvent event); // // void globalAnnounceEvent(@NotNull DanmakuEvent event); // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/smalltv/SmallTV.java // @Data // public class SmallTV { // @SerializedName("msg") // private String message; // @SerializedName("url") // private String roomURL; // @SerializedName("roomid") // private int roomID; // @SerializedName("real_roomid") // private int realRoomID; // @SerializedName("tv_id") // private int smallTVID; // }
import charlie.bililivelib.Globals; import charlie.bililivelib.danmaku.event.DanmakuEvent; import charlie.bililivelib.danmaku.event.DanmakuListener; import charlie.bililivelib.smalltv.SmallTV; import com.google.gson.JsonObject; import org.jetbrains.annotations.NotNull; import java.util.List;
package charlie.bililivelib.danmaku.dispatch; /** * 分发小电视事件的分发器。对COMMAND为'SYS_MSG'且含有'tv_id'值的事件有效。 * * @author Charlie Jiang * @since rv1 */ public class GlobalGiftDispatcher extends AbstractJSONDispatcher { public static final String[] ACCEPTABLE_COMMANDS = { "SYS_MSG" }; private static GlobalGiftDispatcher GLOBAL_INSTANCE; @NotNull public static GlobalGiftDispatcher getGlobalInstance() { if (GLOBAL_INSTANCE == null) { GLOBAL_INSTANCE = new GlobalGiftDispatcher(); } return GLOBAL_INSTANCE; } @Override protected String[] getAcceptableCommands() { return ACCEPTABLE_COMMANDS; } /** * {@inheritDoc} * @param listeners 监听器列表 * @param rootObject 事件内容产生的JSON对象结构 * @param source 事件发生源 */ @Override public void dispatch(List<DanmakuListener> listeners, JsonObject rootObject, Object source) { if (!rootObject.has("tv_id")) return; //NOT A SMALL TV OBJECT. SmallTV smallTV = Globals.get().gson() .fromJson(rootObject, SmallTV.class);
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/Globals.java // public class Globals { // private static final String BILI_PASSPORT_HOST_ROOT = "passport.bilibili.com"; // private static final String BILI_LIVE_HOST_ROOT = "live.bilibili.com"; // @Getter // private static int CONNECTION_ALIVE_TIME_SECOND = 10; // private static Globals instance; // @Getter // private HttpHost biliLiveRoot; // @Getter // private HttpHost biliPassportHttpsRoot; // private ThreadLocal<Gson> gson; // // private HttpClientConnectionManager connectionPool; // @Getter // private SSLContext bilibiliSSLContext; // // public static Globals get() { // if (instance == null) { // instance = new Globals(); // instance.init(); // } // return instance; // } // // private void init() { // biliLiveRoot = new HttpHost(BILI_LIVE_HOST_ROOT); // //Visit bilibili passport via https. 443 is the https port. // biliPassportHttpsRoot = new HttpHost(BILI_PASSPORT_HOST_ROOT, 443, "https"); // gson = ThreadLocal.withInitial(() -> new GsonBuilder() // .setLenient() // .create()); // // try { // bilibiliSSLContext = SSLContextBuilder.create() // .loadTrustMaterial(new BilibiliTrustStrategy()) // .build(); // } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) { // throw new AssertionError("failed initializing bilibili ssl context!"); // } // } // // public Gson gson() { // return gson.get(); // } // // public HttpClientConnectionManager getConnectionPool() { // if (connectionPool == null) { // reInitializeConnectionPool(); // } // return connectionPool; // } // // public void reInitializeConnectionPool() { // connectionPool = new PoolingHttpClientConnectionManager(CONNECTION_ALIVE_TIME_SECOND, TimeUnit.SECONDS); // } // // public void setConnectionAliveTimeSecond(int connectionAliveTimeSecond) { // CONNECTION_ALIVE_TIME_SECOND = connectionAliveTimeSecond; // reInitializeConnectionPool(); // } // // // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuEvent.java // @Getter // public class DanmakuEvent extends EventObject { // private Kind kind; // private Object param; // // /** // * Constructs a prototypical Event. // * // * @param source The object on which the Event initially occurred. // * @throws IllegalArgumentException if source is null. // */ // public DanmakuEvent(Object source) { // super(source); // } // // public DanmakuEvent(Object source, Object param, Kind kind) { // super(source); // this.kind = kind; // this.param = param; // } // // public enum Kind { // JOINED, ERROR, ERROR_DOWN, NEW_DANMAKU, WATCHER_COUNT, // START_STOP, WELCOME_VIP, GIVE_GIFT, GLOBAL_GIFT, GLOBAL_ANNOUNCE // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuListener.java // public interface DanmakuListener { // void danmakuEvent(@NotNull DanmakuEvent event); // // void watcherCountEvent(@NotNull DanmakuEvent event); // // void errorEvent(@NotNull DanmakuEvent event); // // void startStopEvent(@NotNull DanmakuEvent event); // // void statusEvent(@NotNull DanmakuEvent event); // // void welcomeVipEvent(@NotNull DanmakuEvent event); // // void giveGiftEvent(@NotNull DanmakuEvent event); // // void globalGiftEvent(@NotNull DanmakuEvent event); // // void globalAnnounceEvent(@NotNull DanmakuEvent event); // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/smalltv/SmallTV.java // @Data // public class SmallTV { // @SerializedName("msg") // private String message; // @SerializedName("url") // private String roomURL; // @SerializedName("roomid") // private int roomID; // @SerializedName("real_roomid") // private int realRoomID; // @SerializedName("tv_id") // private int smallTVID; // } // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/dispatch/GlobalGiftDispatcher.java import charlie.bililivelib.Globals; import charlie.bililivelib.danmaku.event.DanmakuEvent; import charlie.bililivelib.danmaku.event.DanmakuListener; import charlie.bililivelib.smalltv.SmallTV; import com.google.gson.JsonObject; import org.jetbrains.annotations.NotNull; import java.util.List; package charlie.bililivelib.danmaku.dispatch; /** * 分发小电视事件的分发器。对COMMAND为'SYS_MSG'且含有'tv_id'值的事件有效。 * * @author Charlie Jiang * @since rv1 */ public class GlobalGiftDispatcher extends AbstractJSONDispatcher { public static final String[] ACCEPTABLE_COMMANDS = { "SYS_MSG" }; private static GlobalGiftDispatcher GLOBAL_INSTANCE; @NotNull public static GlobalGiftDispatcher getGlobalInstance() { if (GLOBAL_INSTANCE == null) { GLOBAL_INSTANCE = new GlobalGiftDispatcher(); } return GLOBAL_INSTANCE; } @Override protected String[] getAcceptableCommands() { return ACCEPTABLE_COMMANDS; } /** * {@inheritDoc} * @param listeners 监听器列表 * @param rootObject 事件内容产生的JSON对象结构 * @param source 事件发生源 */ @Override public void dispatch(List<DanmakuListener> listeners, JsonObject rootObject, Object source) { if (!rootObject.has("tv_id")) return; //NOT A SMALL TV OBJECT. SmallTV smallTV = Globals.get().gson() .fromJson(rootObject, SmallTV.class);
DanmakuEvent event = new DanmakuEvent(source, smallTV, DanmakuEvent.Kind.GLOBAL_GIFT);
cqjjjzr/BiliLiveLib
BiliLiveLib/src/main/java/charlie/bililivelib/Globals.java
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/internalutil/net/BilibiliTrustStrategy.java // public class BilibiliTrustStrategy implements TrustStrategy { // //UPDATE IF BILIBILI's CERT CHANGES. // public static final String BILIBILI_CERT_FINGERPRINT = "3F1455BB9988290A4019687C799C507A54BA143A"; // // @Contract(pure = true) // private static String digestMD5(byte[] data) { // MessageDigest messageDigest; // String md5Str; // try { // messageDigest = MessageDigest.getInstance("SHA1"); // messageDigest.update(data); // md5Str = new BigInteger(1, messageDigest.digest()).toString(16).toUpperCase(); // } catch (NoSuchAlgorithmException e) { // throw new AssertionError(); // } // return md5Str; // } // // @Override // public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { // for (X509Certificate certificate : chain) { // if (digestMD5(certificate.getEncoded()).equals(BILIBILI_CERT_FINGERPRINT)) // return true; // } // return false; // } // }
import charlie.bililivelib.internalutil.net.BilibiliTrustStrategy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import lombok.Getter; import org.apache.http.HttpHost; import org.apache.http.conn.HttpClientConnectionManager; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.ssl.SSLContextBuilder; import javax.net.ssl.SSLContext; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.util.concurrent.TimeUnit;
package charlie.bililivelib; /** * 本单例类定义了一组在整个应用程序中的全局变量,这些变量仅用于Library内部使用且随时可能修改,请勿随意访问该类中的对象。 * * @author Charlie Jiang * @since rv1 */ public class Globals { private static final String BILI_PASSPORT_HOST_ROOT = "passport.bilibili.com"; private static final String BILI_LIVE_HOST_ROOT = "live.bilibili.com"; @Getter private static int CONNECTION_ALIVE_TIME_SECOND = 10; private static Globals instance; @Getter private HttpHost biliLiveRoot; @Getter private HttpHost biliPassportHttpsRoot; private ThreadLocal<Gson> gson; private HttpClientConnectionManager connectionPool; @Getter private SSLContext bilibiliSSLContext; public static Globals get() { if (instance == null) { instance = new Globals(); instance.init(); } return instance; } private void init() { biliLiveRoot = new HttpHost(BILI_LIVE_HOST_ROOT); //Visit bilibili passport via https. 443 is the https port. biliPassportHttpsRoot = new HttpHost(BILI_PASSPORT_HOST_ROOT, 443, "https"); gson = ThreadLocal.withInitial(() -> new GsonBuilder() .setLenient() .create()); try { bilibiliSSLContext = SSLContextBuilder.create()
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/internalutil/net/BilibiliTrustStrategy.java // public class BilibiliTrustStrategy implements TrustStrategy { // //UPDATE IF BILIBILI's CERT CHANGES. // public static final String BILIBILI_CERT_FINGERPRINT = "3F1455BB9988290A4019687C799C507A54BA143A"; // // @Contract(pure = true) // private static String digestMD5(byte[] data) { // MessageDigest messageDigest; // String md5Str; // try { // messageDigest = MessageDigest.getInstance("SHA1"); // messageDigest.update(data); // md5Str = new BigInteger(1, messageDigest.digest()).toString(16).toUpperCase(); // } catch (NoSuchAlgorithmException e) { // throw new AssertionError(); // } // return md5Str; // } // // @Override // public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { // for (X509Certificate certificate : chain) { // if (digestMD5(certificate.getEncoded()).equals(BILIBILI_CERT_FINGERPRINT)) // return true; // } // return false; // } // } // Path: BiliLiveLib/src/main/java/charlie/bililivelib/Globals.java import charlie.bililivelib.internalutil.net.BilibiliTrustStrategy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import lombok.Getter; import org.apache.http.HttpHost; import org.apache.http.conn.HttpClientConnectionManager; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.ssl.SSLContextBuilder; import javax.net.ssl.SSLContext; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.util.concurrent.TimeUnit; package charlie.bililivelib; /** * 本单例类定义了一组在整个应用程序中的全局变量,这些变量仅用于Library内部使用且随时可能修改,请勿随意访问该类中的对象。 * * @author Charlie Jiang * @since rv1 */ public class Globals { private static final String BILI_PASSPORT_HOST_ROOT = "passport.bilibili.com"; private static final String BILI_LIVE_HOST_ROOT = "live.bilibili.com"; @Getter private static int CONNECTION_ALIVE_TIME_SECOND = 10; private static Globals instance; @Getter private HttpHost biliLiveRoot; @Getter private HttpHost biliPassportHttpsRoot; private ThreadLocal<Gson> gson; private HttpClientConnectionManager connectionPool; @Getter private SSLContext bilibiliSSLContext; public static Globals get() { if (instance == null) { instance = new Globals(); instance.init(); } return instance; } private void init() { biliLiveRoot = new HttpHost(BILI_LIVE_HOST_ROOT); //Visit bilibili passport via https. 443 is the https port. biliPassportHttpsRoot = new HttpHost(BILI_PASSPORT_HOST_ROOT, 443, "https"); gson = ThreadLocal.withInitial(() -> new GsonBuilder() .setLenient() .create()); try { bilibiliSSLContext = SSLContextBuilder.create()
.loadTrustMaterial(new BilibiliTrustStrategy())
cqjjjzr/BiliLiveLib
BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/dispatch/GiveGiftDispatcher.java
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/Globals.java // public class Globals { // private static final String BILI_PASSPORT_HOST_ROOT = "passport.bilibili.com"; // private static final String BILI_LIVE_HOST_ROOT = "live.bilibili.com"; // @Getter // private static int CONNECTION_ALIVE_TIME_SECOND = 10; // private static Globals instance; // @Getter // private HttpHost biliLiveRoot; // @Getter // private HttpHost biliPassportHttpsRoot; // private ThreadLocal<Gson> gson; // // private HttpClientConnectionManager connectionPool; // @Getter // private SSLContext bilibiliSSLContext; // // public static Globals get() { // if (instance == null) { // instance = new Globals(); // instance.init(); // } // return instance; // } // // private void init() { // biliLiveRoot = new HttpHost(BILI_LIVE_HOST_ROOT); // //Visit bilibili passport via https. 443 is the https port. // biliPassportHttpsRoot = new HttpHost(BILI_PASSPORT_HOST_ROOT, 443, "https"); // gson = ThreadLocal.withInitial(() -> new GsonBuilder() // .setLenient() // .create()); // // try { // bilibiliSSLContext = SSLContextBuilder.create() // .loadTrustMaterial(new BilibiliTrustStrategy()) // .build(); // } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) { // throw new AssertionError("failed initializing bilibili ssl context!"); // } // } // // public Gson gson() { // return gson.get(); // } // // public HttpClientConnectionManager getConnectionPool() { // if (connectionPool == null) { // reInitializeConnectionPool(); // } // return connectionPool; // } // // public void reInitializeConnectionPool() { // connectionPool = new PoolingHttpClientConnectionManager(CONNECTION_ALIVE_TIME_SECOND, TimeUnit.SECONDS); // } // // public void setConnectionAliveTimeSecond(int connectionAliveTimeSecond) { // CONNECTION_ALIVE_TIME_SECOND = connectionAliveTimeSecond; // reInitializeConnectionPool(); // } // // // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/datamodel/GiveGiftInfo.java // @Data // public class GiveGiftInfo { // @SerializedName("data") // private DataBean content; // // @Data // public static class DataBean { // private String giftName; // @SerializedName("num") // private int count; // @SerializedName("uname") // private String username; // private int uid; // @SerializedName("giftId") // private int giftID; // private int giftType; // private int price; // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuEvent.java // @Getter // public class DanmakuEvent extends EventObject { // private Kind kind; // private Object param; // // /** // * Constructs a prototypical Event. // * // * @param source The object on which the Event initially occurred. // * @throws IllegalArgumentException if source is null. // */ // public DanmakuEvent(Object source) { // super(source); // } // // public DanmakuEvent(Object source, Object param, Kind kind) { // super(source); // this.kind = kind; // this.param = param; // } // // public enum Kind { // JOINED, ERROR, ERROR_DOWN, NEW_DANMAKU, WATCHER_COUNT, // START_STOP, WELCOME_VIP, GIVE_GIFT, GLOBAL_GIFT, GLOBAL_ANNOUNCE // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuListener.java // public interface DanmakuListener { // void danmakuEvent(@NotNull DanmakuEvent event); // // void watcherCountEvent(@NotNull DanmakuEvent event); // // void errorEvent(@NotNull DanmakuEvent event); // // void startStopEvent(@NotNull DanmakuEvent event); // // void statusEvent(@NotNull DanmakuEvent event); // // void welcomeVipEvent(@NotNull DanmakuEvent event); // // void giveGiftEvent(@NotNull DanmakuEvent event); // // void globalGiftEvent(@NotNull DanmakuEvent event); // // void globalAnnounceEvent(@NotNull DanmakuEvent event); // }
import charlie.bililivelib.Globals; import charlie.bililivelib.danmaku.datamodel.GiveGiftInfo; import charlie.bililivelib.danmaku.event.DanmakuEvent; import charlie.bililivelib.danmaku.event.DanmakuListener; import com.google.gson.JsonObject; import org.jetbrains.annotations.NotNull; import java.util.List;
package charlie.bililivelib.danmaku.dispatch; /** * 分发送礼触发全屏公告的分发器。对COMMAND为'GIVE_GIFT'的事件有效。 * * @author Charlie Jiang * @since rv1 */ public class GiveGiftDispatcher extends AbstractJSONDispatcher { public static final String[] ACCEPTABLE_COMMANDS = { "SEND_GIFT" }; private static GiveGiftDispatcher GLOBAL_INSTANCE; @NotNull public static GiveGiftDispatcher getGlobalInstance() { if (GLOBAL_INSTANCE == null) { GLOBAL_INSTANCE = new GiveGiftDispatcher(); } return GLOBAL_INSTANCE; } @Override protected String[] getAcceptableCommands() { return ACCEPTABLE_COMMANDS; } /** * {@inheritDoc} * @param listeners 监听器列表 * @param rootObject 事件内容产生的JSON对象结构 * @param source 事件发生源 */ @Override
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/Globals.java // public class Globals { // private static final String BILI_PASSPORT_HOST_ROOT = "passport.bilibili.com"; // private static final String BILI_LIVE_HOST_ROOT = "live.bilibili.com"; // @Getter // private static int CONNECTION_ALIVE_TIME_SECOND = 10; // private static Globals instance; // @Getter // private HttpHost biliLiveRoot; // @Getter // private HttpHost biliPassportHttpsRoot; // private ThreadLocal<Gson> gson; // // private HttpClientConnectionManager connectionPool; // @Getter // private SSLContext bilibiliSSLContext; // // public static Globals get() { // if (instance == null) { // instance = new Globals(); // instance.init(); // } // return instance; // } // // private void init() { // biliLiveRoot = new HttpHost(BILI_LIVE_HOST_ROOT); // //Visit bilibili passport via https. 443 is the https port. // biliPassportHttpsRoot = new HttpHost(BILI_PASSPORT_HOST_ROOT, 443, "https"); // gson = ThreadLocal.withInitial(() -> new GsonBuilder() // .setLenient() // .create()); // // try { // bilibiliSSLContext = SSLContextBuilder.create() // .loadTrustMaterial(new BilibiliTrustStrategy()) // .build(); // } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) { // throw new AssertionError("failed initializing bilibili ssl context!"); // } // } // // public Gson gson() { // return gson.get(); // } // // public HttpClientConnectionManager getConnectionPool() { // if (connectionPool == null) { // reInitializeConnectionPool(); // } // return connectionPool; // } // // public void reInitializeConnectionPool() { // connectionPool = new PoolingHttpClientConnectionManager(CONNECTION_ALIVE_TIME_SECOND, TimeUnit.SECONDS); // } // // public void setConnectionAliveTimeSecond(int connectionAliveTimeSecond) { // CONNECTION_ALIVE_TIME_SECOND = connectionAliveTimeSecond; // reInitializeConnectionPool(); // } // // // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/datamodel/GiveGiftInfo.java // @Data // public class GiveGiftInfo { // @SerializedName("data") // private DataBean content; // // @Data // public static class DataBean { // private String giftName; // @SerializedName("num") // private int count; // @SerializedName("uname") // private String username; // private int uid; // @SerializedName("giftId") // private int giftID; // private int giftType; // private int price; // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuEvent.java // @Getter // public class DanmakuEvent extends EventObject { // private Kind kind; // private Object param; // // /** // * Constructs a prototypical Event. // * // * @param source The object on which the Event initially occurred. // * @throws IllegalArgumentException if source is null. // */ // public DanmakuEvent(Object source) { // super(source); // } // // public DanmakuEvent(Object source, Object param, Kind kind) { // super(source); // this.kind = kind; // this.param = param; // } // // public enum Kind { // JOINED, ERROR, ERROR_DOWN, NEW_DANMAKU, WATCHER_COUNT, // START_STOP, WELCOME_VIP, GIVE_GIFT, GLOBAL_GIFT, GLOBAL_ANNOUNCE // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuListener.java // public interface DanmakuListener { // void danmakuEvent(@NotNull DanmakuEvent event); // // void watcherCountEvent(@NotNull DanmakuEvent event); // // void errorEvent(@NotNull DanmakuEvent event); // // void startStopEvent(@NotNull DanmakuEvent event); // // void statusEvent(@NotNull DanmakuEvent event); // // void welcomeVipEvent(@NotNull DanmakuEvent event); // // void giveGiftEvent(@NotNull DanmakuEvent event); // // void globalGiftEvent(@NotNull DanmakuEvent event); // // void globalAnnounceEvent(@NotNull DanmakuEvent event); // } // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/dispatch/GiveGiftDispatcher.java import charlie.bililivelib.Globals; import charlie.bililivelib.danmaku.datamodel.GiveGiftInfo; import charlie.bililivelib.danmaku.event.DanmakuEvent; import charlie.bililivelib.danmaku.event.DanmakuListener; import com.google.gson.JsonObject; import org.jetbrains.annotations.NotNull; import java.util.List; package charlie.bililivelib.danmaku.dispatch; /** * 分发送礼触发全屏公告的分发器。对COMMAND为'GIVE_GIFT'的事件有效。 * * @author Charlie Jiang * @since rv1 */ public class GiveGiftDispatcher extends AbstractJSONDispatcher { public static final String[] ACCEPTABLE_COMMANDS = { "SEND_GIFT" }; private static GiveGiftDispatcher GLOBAL_INSTANCE; @NotNull public static GiveGiftDispatcher getGlobalInstance() { if (GLOBAL_INSTANCE == null) { GLOBAL_INSTANCE = new GiveGiftDispatcher(); } return GLOBAL_INSTANCE; } @Override protected String[] getAcceptableCommands() { return ACCEPTABLE_COMMANDS; } /** * {@inheritDoc} * @param listeners 监听器列表 * @param rootObject 事件内容产生的JSON对象结构 * @param source 事件发生源 */ @Override
public void dispatch(List<DanmakuListener> listeners, JsonObject rootObject, Object source) {
cqjjjzr/BiliLiveLib
BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/dispatch/GiveGiftDispatcher.java
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/Globals.java // public class Globals { // private static final String BILI_PASSPORT_HOST_ROOT = "passport.bilibili.com"; // private static final String BILI_LIVE_HOST_ROOT = "live.bilibili.com"; // @Getter // private static int CONNECTION_ALIVE_TIME_SECOND = 10; // private static Globals instance; // @Getter // private HttpHost biliLiveRoot; // @Getter // private HttpHost biliPassportHttpsRoot; // private ThreadLocal<Gson> gson; // // private HttpClientConnectionManager connectionPool; // @Getter // private SSLContext bilibiliSSLContext; // // public static Globals get() { // if (instance == null) { // instance = new Globals(); // instance.init(); // } // return instance; // } // // private void init() { // biliLiveRoot = new HttpHost(BILI_LIVE_HOST_ROOT); // //Visit bilibili passport via https. 443 is the https port. // biliPassportHttpsRoot = new HttpHost(BILI_PASSPORT_HOST_ROOT, 443, "https"); // gson = ThreadLocal.withInitial(() -> new GsonBuilder() // .setLenient() // .create()); // // try { // bilibiliSSLContext = SSLContextBuilder.create() // .loadTrustMaterial(new BilibiliTrustStrategy()) // .build(); // } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) { // throw new AssertionError("failed initializing bilibili ssl context!"); // } // } // // public Gson gson() { // return gson.get(); // } // // public HttpClientConnectionManager getConnectionPool() { // if (connectionPool == null) { // reInitializeConnectionPool(); // } // return connectionPool; // } // // public void reInitializeConnectionPool() { // connectionPool = new PoolingHttpClientConnectionManager(CONNECTION_ALIVE_TIME_SECOND, TimeUnit.SECONDS); // } // // public void setConnectionAliveTimeSecond(int connectionAliveTimeSecond) { // CONNECTION_ALIVE_TIME_SECOND = connectionAliveTimeSecond; // reInitializeConnectionPool(); // } // // // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/datamodel/GiveGiftInfo.java // @Data // public class GiveGiftInfo { // @SerializedName("data") // private DataBean content; // // @Data // public static class DataBean { // private String giftName; // @SerializedName("num") // private int count; // @SerializedName("uname") // private String username; // private int uid; // @SerializedName("giftId") // private int giftID; // private int giftType; // private int price; // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuEvent.java // @Getter // public class DanmakuEvent extends EventObject { // private Kind kind; // private Object param; // // /** // * Constructs a prototypical Event. // * // * @param source The object on which the Event initially occurred. // * @throws IllegalArgumentException if source is null. // */ // public DanmakuEvent(Object source) { // super(source); // } // // public DanmakuEvent(Object source, Object param, Kind kind) { // super(source); // this.kind = kind; // this.param = param; // } // // public enum Kind { // JOINED, ERROR, ERROR_DOWN, NEW_DANMAKU, WATCHER_COUNT, // START_STOP, WELCOME_VIP, GIVE_GIFT, GLOBAL_GIFT, GLOBAL_ANNOUNCE // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuListener.java // public interface DanmakuListener { // void danmakuEvent(@NotNull DanmakuEvent event); // // void watcherCountEvent(@NotNull DanmakuEvent event); // // void errorEvent(@NotNull DanmakuEvent event); // // void startStopEvent(@NotNull DanmakuEvent event); // // void statusEvent(@NotNull DanmakuEvent event); // // void welcomeVipEvent(@NotNull DanmakuEvent event); // // void giveGiftEvent(@NotNull DanmakuEvent event); // // void globalGiftEvent(@NotNull DanmakuEvent event); // // void globalAnnounceEvent(@NotNull DanmakuEvent event); // }
import charlie.bililivelib.Globals; import charlie.bililivelib.danmaku.datamodel.GiveGiftInfo; import charlie.bililivelib.danmaku.event.DanmakuEvent; import charlie.bililivelib.danmaku.event.DanmakuListener; import com.google.gson.JsonObject; import org.jetbrains.annotations.NotNull; import java.util.List;
package charlie.bililivelib.danmaku.dispatch; /** * 分发送礼触发全屏公告的分发器。对COMMAND为'GIVE_GIFT'的事件有效。 * * @author Charlie Jiang * @since rv1 */ public class GiveGiftDispatcher extends AbstractJSONDispatcher { public static final String[] ACCEPTABLE_COMMANDS = { "SEND_GIFT" }; private static GiveGiftDispatcher GLOBAL_INSTANCE; @NotNull public static GiveGiftDispatcher getGlobalInstance() { if (GLOBAL_INSTANCE == null) { GLOBAL_INSTANCE = new GiveGiftDispatcher(); } return GLOBAL_INSTANCE; } @Override protected String[] getAcceptableCommands() { return ACCEPTABLE_COMMANDS; } /** * {@inheritDoc} * @param listeners 监听器列表 * @param rootObject 事件内容产生的JSON对象结构 * @param source 事件发生源 */ @Override public void dispatch(List<DanmakuListener> listeners, JsonObject rootObject, Object source) {
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/Globals.java // public class Globals { // private static final String BILI_PASSPORT_HOST_ROOT = "passport.bilibili.com"; // private static final String BILI_LIVE_HOST_ROOT = "live.bilibili.com"; // @Getter // private static int CONNECTION_ALIVE_TIME_SECOND = 10; // private static Globals instance; // @Getter // private HttpHost biliLiveRoot; // @Getter // private HttpHost biliPassportHttpsRoot; // private ThreadLocal<Gson> gson; // // private HttpClientConnectionManager connectionPool; // @Getter // private SSLContext bilibiliSSLContext; // // public static Globals get() { // if (instance == null) { // instance = new Globals(); // instance.init(); // } // return instance; // } // // private void init() { // biliLiveRoot = new HttpHost(BILI_LIVE_HOST_ROOT); // //Visit bilibili passport via https. 443 is the https port. // biliPassportHttpsRoot = new HttpHost(BILI_PASSPORT_HOST_ROOT, 443, "https"); // gson = ThreadLocal.withInitial(() -> new GsonBuilder() // .setLenient() // .create()); // // try { // bilibiliSSLContext = SSLContextBuilder.create() // .loadTrustMaterial(new BilibiliTrustStrategy()) // .build(); // } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) { // throw new AssertionError("failed initializing bilibili ssl context!"); // } // } // // public Gson gson() { // return gson.get(); // } // // public HttpClientConnectionManager getConnectionPool() { // if (connectionPool == null) { // reInitializeConnectionPool(); // } // return connectionPool; // } // // public void reInitializeConnectionPool() { // connectionPool = new PoolingHttpClientConnectionManager(CONNECTION_ALIVE_TIME_SECOND, TimeUnit.SECONDS); // } // // public void setConnectionAliveTimeSecond(int connectionAliveTimeSecond) { // CONNECTION_ALIVE_TIME_SECOND = connectionAliveTimeSecond; // reInitializeConnectionPool(); // } // // // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/datamodel/GiveGiftInfo.java // @Data // public class GiveGiftInfo { // @SerializedName("data") // private DataBean content; // // @Data // public static class DataBean { // private String giftName; // @SerializedName("num") // private int count; // @SerializedName("uname") // private String username; // private int uid; // @SerializedName("giftId") // private int giftID; // private int giftType; // private int price; // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuEvent.java // @Getter // public class DanmakuEvent extends EventObject { // private Kind kind; // private Object param; // // /** // * Constructs a prototypical Event. // * // * @param source The object on which the Event initially occurred. // * @throws IllegalArgumentException if source is null. // */ // public DanmakuEvent(Object source) { // super(source); // } // // public DanmakuEvent(Object source, Object param, Kind kind) { // super(source); // this.kind = kind; // this.param = param; // } // // public enum Kind { // JOINED, ERROR, ERROR_DOWN, NEW_DANMAKU, WATCHER_COUNT, // START_STOP, WELCOME_VIP, GIVE_GIFT, GLOBAL_GIFT, GLOBAL_ANNOUNCE // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuListener.java // public interface DanmakuListener { // void danmakuEvent(@NotNull DanmakuEvent event); // // void watcherCountEvent(@NotNull DanmakuEvent event); // // void errorEvent(@NotNull DanmakuEvent event); // // void startStopEvent(@NotNull DanmakuEvent event); // // void statusEvent(@NotNull DanmakuEvent event); // // void welcomeVipEvent(@NotNull DanmakuEvent event); // // void giveGiftEvent(@NotNull DanmakuEvent event); // // void globalGiftEvent(@NotNull DanmakuEvent event); // // void globalAnnounceEvent(@NotNull DanmakuEvent event); // } // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/dispatch/GiveGiftDispatcher.java import charlie.bililivelib.Globals; import charlie.bililivelib.danmaku.datamodel.GiveGiftInfo; import charlie.bililivelib.danmaku.event.DanmakuEvent; import charlie.bililivelib.danmaku.event.DanmakuListener; import com.google.gson.JsonObject; import org.jetbrains.annotations.NotNull; import java.util.List; package charlie.bililivelib.danmaku.dispatch; /** * 分发送礼触发全屏公告的分发器。对COMMAND为'GIVE_GIFT'的事件有效。 * * @author Charlie Jiang * @since rv1 */ public class GiveGiftDispatcher extends AbstractJSONDispatcher { public static final String[] ACCEPTABLE_COMMANDS = { "SEND_GIFT" }; private static GiveGiftDispatcher GLOBAL_INSTANCE; @NotNull public static GiveGiftDispatcher getGlobalInstance() { if (GLOBAL_INSTANCE == null) { GLOBAL_INSTANCE = new GiveGiftDispatcher(); } return GLOBAL_INSTANCE; } @Override protected String[] getAcceptableCommands() { return ACCEPTABLE_COMMANDS; } /** * {@inheritDoc} * @param listeners 监听器列表 * @param rootObject 事件内容产生的JSON对象结构 * @param source 事件发生源 */ @Override public void dispatch(List<DanmakuListener> listeners, JsonObject rootObject, Object source) {
GiveGiftInfo giveGiftInfo = Globals.get().gson()
cqjjjzr/BiliLiveLib
BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/dispatch/GiveGiftDispatcher.java
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/Globals.java // public class Globals { // private static final String BILI_PASSPORT_HOST_ROOT = "passport.bilibili.com"; // private static final String BILI_LIVE_HOST_ROOT = "live.bilibili.com"; // @Getter // private static int CONNECTION_ALIVE_TIME_SECOND = 10; // private static Globals instance; // @Getter // private HttpHost biliLiveRoot; // @Getter // private HttpHost biliPassportHttpsRoot; // private ThreadLocal<Gson> gson; // // private HttpClientConnectionManager connectionPool; // @Getter // private SSLContext bilibiliSSLContext; // // public static Globals get() { // if (instance == null) { // instance = new Globals(); // instance.init(); // } // return instance; // } // // private void init() { // biliLiveRoot = new HttpHost(BILI_LIVE_HOST_ROOT); // //Visit bilibili passport via https. 443 is the https port. // biliPassportHttpsRoot = new HttpHost(BILI_PASSPORT_HOST_ROOT, 443, "https"); // gson = ThreadLocal.withInitial(() -> new GsonBuilder() // .setLenient() // .create()); // // try { // bilibiliSSLContext = SSLContextBuilder.create() // .loadTrustMaterial(new BilibiliTrustStrategy()) // .build(); // } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) { // throw new AssertionError("failed initializing bilibili ssl context!"); // } // } // // public Gson gson() { // return gson.get(); // } // // public HttpClientConnectionManager getConnectionPool() { // if (connectionPool == null) { // reInitializeConnectionPool(); // } // return connectionPool; // } // // public void reInitializeConnectionPool() { // connectionPool = new PoolingHttpClientConnectionManager(CONNECTION_ALIVE_TIME_SECOND, TimeUnit.SECONDS); // } // // public void setConnectionAliveTimeSecond(int connectionAliveTimeSecond) { // CONNECTION_ALIVE_TIME_SECOND = connectionAliveTimeSecond; // reInitializeConnectionPool(); // } // // // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/datamodel/GiveGiftInfo.java // @Data // public class GiveGiftInfo { // @SerializedName("data") // private DataBean content; // // @Data // public static class DataBean { // private String giftName; // @SerializedName("num") // private int count; // @SerializedName("uname") // private String username; // private int uid; // @SerializedName("giftId") // private int giftID; // private int giftType; // private int price; // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuEvent.java // @Getter // public class DanmakuEvent extends EventObject { // private Kind kind; // private Object param; // // /** // * Constructs a prototypical Event. // * // * @param source The object on which the Event initially occurred. // * @throws IllegalArgumentException if source is null. // */ // public DanmakuEvent(Object source) { // super(source); // } // // public DanmakuEvent(Object source, Object param, Kind kind) { // super(source); // this.kind = kind; // this.param = param; // } // // public enum Kind { // JOINED, ERROR, ERROR_DOWN, NEW_DANMAKU, WATCHER_COUNT, // START_STOP, WELCOME_VIP, GIVE_GIFT, GLOBAL_GIFT, GLOBAL_ANNOUNCE // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuListener.java // public interface DanmakuListener { // void danmakuEvent(@NotNull DanmakuEvent event); // // void watcherCountEvent(@NotNull DanmakuEvent event); // // void errorEvent(@NotNull DanmakuEvent event); // // void startStopEvent(@NotNull DanmakuEvent event); // // void statusEvent(@NotNull DanmakuEvent event); // // void welcomeVipEvent(@NotNull DanmakuEvent event); // // void giveGiftEvent(@NotNull DanmakuEvent event); // // void globalGiftEvent(@NotNull DanmakuEvent event); // // void globalAnnounceEvent(@NotNull DanmakuEvent event); // }
import charlie.bililivelib.Globals; import charlie.bililivelib.danmaku.datamodel.GiveGiftInfo; import charlie.bililivelib.danmaku.event.DanmakuEvent; import charlie.bililivelib.danmaku.event.DanmakuListener; import com.google.gson.JsonObject; import org.jetbrains.annotations.NotNull; import java.util.List;
package charlie.bililivelib.danmaku.dispatch; /** * 分发送礼触发全屏公告的分发器。对COMMAND为'GIVE_GIFT'的事件有效。 * * @author Charlie Jiang * @since rv1 */ public class GiveGiftDispatcher extends AbstractJSONDispatcher { public static final String[] ACCEPTABLE_COMMANDS = { "SEND_GIFT" }; private static GiveGiftDispatcher GLOBAL_INSTANCE; @NotNull public static GiveGiftDispatcher getGlobalInstance() { if (GLOBAL_INSTANCE == null) { GLOBAL_INSTANCE = new GiveGiftDispatcher(); } return GLOBAL_INSTANCE; } @Override protected String[] getAcceptableCommands() { return ACCEPTABLE_COMMANDS; } /** * {@inheritDoc} * @param listeners 监听器列表 * @param rootObject 事件内容产生的JSON对象结构 * @param source 事件发生源 */ @Override public void dispatch(List<DanmakuListener> listeners, JsonObject rootObject, Object source) {
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/Globals.java // public class Globals { // private static final String BILI_PASSPORT_HOST_ROOT = "passport.bilibili.com"; // private static final String BILI_LIVE_HOST_ROOT = "live.bilibili.com"; // @Getter // private static int CONNECTION_ALIVE_TIME_SECOND = 10; // private static Globals instance; // @Getter // private HttpHost biliLiveRoot; // @Getter // private HttpHost biliPassportHttpsRoot; // private ThreadLocal<Gson> gson; // // private HttpClientConnectionManager connectionPool; // @Getter // private SSLContext bilibiliSSLContext; // // public static Globals get() { // if (instance == null) { // instance = new Globals(); // instance.init(); // } // return instance; // } // // private void init() { // biliLiveRoot = new HttpHost(BILI_LIVE_HOST_ROOT); // //Visit bilibili passport via https. 443 is the https port. // biliPassportHttpsRoot = new HttpHost(BILI_PASSPORT_HOST_ROOT, 443, "https"); // gson = ThreadLocal.withInitial(() -> new GsonBuilder() // .setLenient() // .create()); // // try { // bilibiliSSLContext = SSLContextBuilder.create() // .loadTrustMaterial(new BilibiliTrustStrategy()) // .build(); // } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) { // throw new AssertionError("failed initializing bilibili ssl context!"); // } // } // // public Gson gson() { // return gson.get(); // } // // public HttpClientConnectionManager getConnectionPool() { // if (connectionPool == null) { // reInitializeConnectionPool(); // } // return connectionPool; // } // // public void reInitializeConnectionPool() { // connectionPool = new PoolingHttpClientConnectionManager(CONNECTION_ALIVE_TIME_SECOND, TimeUnit.SECONDS); // } // // public void setConnectionAliveTimeSecond(int connectionAliveTimeSecond) { // CONNECTION_ALIVE_TIME_SECOND = connectionAliveTimeSecond; // reInitializeConnectionPool(); // } // // // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/datamodel/GiveGiftInfo.java // @Data // public class GiveGiftInfo { // @SerializedName("data") // private DataBean content; // // @Data // public static class DataBean { // private String giftName; // @SerializedName("num") // private int count; // @SerializedName("uname") // private String username; // private int uid; // @SerializedName("giftId") // private int giftID; // private int giftType; // private int price; // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuEvent.java // @Getter // public class DanmakuEvent extends EventObject { // private Kind kind; // private Object param; // // /** // * Constructs a prototypical Event. // * // * @param source The object on which the Event initially occurred. // * @throws IllegalArgumentException if source is null. // */ // public DanmakuEvent(Object source) { // super(source); // } // // public DanmakuEvent(Object source, Object param, Kind kind) { // super(source); // this.kind = kind; // this.param = param; // } // // public enum Kind { // JOINED, ERROR, ERROR_DOWN, NEW_DANMAKU, WATCHER_COUNT, // START_STOP, WELCOME_VIP, GIVE_GIFT, GLOBAL_GIFT, GLOBAL_ANNOUNCE // } // } // // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/event/DanmakuListener.java // public interface DanmakuListener { // void danmakuEvent(@NotNull DanmakuEvent event); // // void watcherCountEvent(@NotNull DanmakuEvent event); // // void errorEvent(@NotNull DanmakuEvent event); // // void startStopEvent(@NotNull DanmakuEvent event); // // void statusEvent(@NotNull DanmakuEvent event); // // void welcomeVipEvent(@NotNull DanmakuEvent event); // // void giveGiftEvent(@NotNull DanmakuEvent event); // // void globalGiftEvent(@NotNull DanmakuEvent event); // // void globalAnnounceEvent(@NotNull DanmakuEvent event); // } // Path: BiliLiveLib/src/main/java/charlie/bililivelib/danmaku/dispatch/GiveGiftDispatcher.java import charlie.bililivelib.Globals; import charlie.bililivelib.danmaku.datamodel.GiveGiftInfo; import charlie.bililivelib.danmaku.event.DanmakuEvent; import charlie.bililivelib.danmaku.event.DanmakuListener; import com.google.gson.JsonObject; import org.jetbrains.annotations.NotNull; import java.util.List; package charlie.bililivelib.danmaku.dispatch; /** * 分发送礼触发全屏公告的分发器。对COMMAND为'GIVE_GIFT'的事件有效。 * * @author Charlie Jiang * @since rv1 */ public class GiveGiftDispatcher extends AbstractJSONDispatcher { public static final String[] ACCEPTABLE_COMMANDS = { "SEND_GIFT" }; private static GiveGiftDispatcher GLOBAL_INSTANCE; @NotNull public static GiveGiftDispatcher getGlobalInstance() { if (GLOBAL_INSTANCE == null) { GLOBAL_INSTANCE = new GiveGiftDispatcher(); } return GLOBAL_INSTANCE; } @Override protected String[] getAcceptableCommands() { return ACCEPTABLE_COMMANDS; } /** * {@inheritDoc} * @param listeners 监听器列表 * @param rootObject 事件内容产生的JSON对象结构 * @param source 事件发生源 */ @Override public void dispatch(List<DanmakuListener> listeners, JsonObject rootObject, Object source) {
GiveGiftInfo giveGiftInfo = Globals.get().gson()
cqjjjzr/BiliLiveLib
BiliLiveLib/src/main/java/charlie/bililivelib/OptionalGlobals.java
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/internalutil/OCRUtil.java // public class OCRUtil { // public static final int SINGLE_LINE_MODE = 7; // private Tesseract tesseract; // // public OCRUtil() { // tesseract = new Tesseract(); // tesseract.setLanguage("captcha"); // tesseract.setPageSegMode(SINGLE_LINE_MODE); // } // // @Contract(pure = true) // public String ocrCalcCaptcha(@NotNull BufferedImage image) { // try { // return tesseract.doOCR(image); // } catch (TesseractException e) { // return null; // } // } // }
import charlie.bililivelib.internalutil.OCRUtil; import com.gargoylesoftware.htmlunit.Cache;
package charlie.bililivelib; /** * 本单例类定义了一组在整个应用程序中的*可选*全局变量,这些变量仅用于Library内部使用且随时可能修改,请勿随意访问该类中的对象。 * * @author Charlie Jiang * @since rv1 */ public class OptionalGlobals { private static OptionalGlobals instance; private ThreadLocal<Cache> htmlUnitCache;
// Path: BiliLiveLib/src/main/java/charlie/bililivelib/internalutil/OCRUtil.java // public class OCRUtil { // public static final int SINGLE_LINE_MODE = 7; // private Tesseract tesseract; // // public OCRUtil() { // tesseract = new Tesseract(); // tesseract.setLanguage("captcha"); // tesseract.setPageSegMode(SINGLE_LINE_MODE); // } // // @Contract(pure = true) // public String ocrCalcCaptcha(@NotNull BufferedImage image) { // try { // return tesseract.doOCR(image); // } catch (TesseractException e) { // return null; // } // } // } // Path: BiliLiveLib/src/main/java/charlie/bililivelib/OptionalGlobals.java import charlie.bililivelib.internalutil.OCRUtil; import com.gargoylesoftware.htmlunit.Cache; package charlie.bililivelib; /** * 本单例类定义了一组在整个应用程序中的*可选*全局变量,这些变量仅用于Library内部使用且随时可能修改,请勿随意访问该类中的对象。 * * @author Charlie Jiang * @since rv1 */ public class OptionalGlobals { private static OptionalGlobals instance; private ThreadLocal<Cache> htmlUnitCache;
private OCRUtil ocrUtil;
cqjjjzr/BiliLiveLib
BiliLiveLib/src/test/java/charlie/bililivelib/user/SignProtocolTest.java
// Path: BiliLiveLib/src/test/java/charlie/bililivelib/TestSessionHelper.java // public class TestSessionHelper { // public static Session initSession() throws IOException, BiliLiveException { // BasicCookieStore store = new BasicCookieStore(); // Session session = new Session(HttpClientBuilder.create() // .setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.96 Safari/537.36") // .setConnectionManager(Globals.get().getConnectionPool()) // .setSSLContext(Globals.get().getBilibiliSSLContext()) // .setDefaultCookieStore(store).build(), store); // Path cookieFile = Paths.get("cookies.bin"); // if (Files.exists(cookieFile)) { // loadSessionFromFile(session); // } else { // login(session); // Files.createFile(cookieFile); // } // // ObjectOutputStream stream = new ObjectOutputStream(Files.newOutputStream(cookieFile, StandardOpenOption.TRUNCATE_EXISTING)); // stream.writeObject(store); // stream.close(); // return session; // } // // private static void login(Session session) throws BiliLiveException { // String email = testInput("E-Mail:"); // String password = testInput("Password:"); // // SessionLoginHelper helper = new SessionLoginHelper(email, password, // SessionLoginHelper.DEFAULT_LOGIN_TIMEOUT_MILLIS, // true, BiliLiveLib.DEFAULT_USER_AGENT); // JOptionPane.showMessageDialog(null, "Captcha", "Captcha", // JOptionPane.PLAIN_MESSAGE, new ImageIcon(helper.getCaptcha())); // // String captcha = testInput("Captcha:"); // helper.loginWithCaptcha(captcha); // // System.out.println(helper.getStatus()); // assertTrue(helper.getStatus() == SessionLoginHelper.LoginStatus.SUCCESS); // // helper.fillSession(session); // } // // private static void loadSessionFromFile(Session session) throws IOException { // String xml = new String(Files.readAllBytes(Paths.get("cookies.bin"))); // session.fromBase64(xml); // } // // static String testInput(String message) { // return JOptionPane.showInputDialog(null, message, "Test", // JOptionPane.PLAIN_MESSAGE); // } // // public static void main(String[] args) throws IOException, BiliLiveException { // initSession(); // } // }
import charlie.bililivelib.TestSessionHelper; import org.junit.Test; import static org.junit.Assert.fail;
package charlie.bililivelib.user; public class SignProtocolTest { @Test public void signIn() throws Exception {
// Path: BiliLiveLib/src/test/java/charlie/bililivelib/TestSessionHelper.java // public class TestSessionHelper { // public static Session initSession() throws IOException, BiliLiveException { // BasicCookieStore store = new BasicCookieStore(); // Session session = new Session(HttpClientBuilder.create() // .setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.96 Safari/537.36") // .setConnectionManager(Globals.get().getConnectionPool()) // .setSSLContext(Globals.get().getBilibiliSSLContext()) // .setDefaultCookieStore(store).build(), store); // Path cookieFile = Paths.get("cookies.bin"); // if (Files.exists(cookieFile)) { // loadSessionFromFile(session); // } else { // login(session); // Files.createFile(cookieFile); // } // // ObjectOutputStream stream = new ObjectOutputStream(Files.newOutputStream(cookieFile, StandardOpenOption.TRUNCATE_EXISTING)); // stream.writeObject(store); // stream.close(); // return session; // } // // private static void login(Session session) throws BiliLiveException { // String email = testInput("E-Mail:"); // String password = testInput("Password:"); // // SessionLoginHelper helper = new SessionLoginHelper(email, password, // SessionLoginHelper.DEFAULT_LOGIN_TIMEOUT_MILLIS, // true, BiliLiveLib.DEFAULT_USER_AGENT); // JOptionPane.showMessageDialog(null, "Captcha", "Captcha", // JOptionPane.PLAIN_MESSAGE, new ImageIcon(helper.getCaptcha())); // // String captcha = testInput("Captcha:"); // helper.loginWithCaptcha(captcha); // // System.out.println(helper.getStatus()); // assertTrue(helper.getStatus() == SessionLoginHelper.LoginStatus.SUCCESS); // // helper.fillSession(session); // } // // private static void loadSessionFromFile(Session session) throws IOException { // String xml = new String(Files.readAllBytes(Paths.get("cookies.bin"))); // session.fromBase64(xml); // } // // static String testInput(String message) { // return JOptionPane.showInputDialog(null, message, "Test", // JOptionPane.PLAIN_MESSAGE); // } // // public static void main(String[] args) throws IOException, BiliLiveException { // initSession(); // } // } // Path: BiliLiveLib/src/test/java/charlie/bililivelib/user/SignProtocolTest.java import charlie.bililivelib.TestSessionHelper; import org.junit.Test; import static org.junit.Assert.fail; package charlie.bililivelib.user; public class SignProtocolTest { @Test public void signIn() throws Exception {
SignProtocol signProtocol = new SignProtocol(TestSessionHelper.initSession());
eshioji/trident-tutorial
src/main/java/tutorial/storm/trident/example/GlobalTop20Hashtags.java
// Path: src/main/java/tutorial/storm/trident/operations/ExtractFollowerClassAndContentName.java // public class ExtractFollowerClassAndContentName extends BaseFunction { // @Override // public void execute(TridentTuple tuple, TridentCollector collector) { // Content content = (Content)tuple.get(0); // User user = (User)tuple.get(1); // // String followerClass = classify(user.getFollowersCount()); // // collector.emit(new Values(followerClass, content.getContentName())); // } // // private String classify(int followersCount) { // if (followersCount < 100){ // return "< 100"; // } else if (followersCount < 10*1000){ // return "< 10K"; // } else if (followersCount < 100*1000){ // return "< 100K"; // } else { // return ">= 100K"; // } // } // // } // // Path: src/main/java/tutorial/storm/trident/operations/OnlyEnglish.java // public class OnlyEnglish extends BaseFilter { // @Override // public boolean isKeep(TridentTuple tuple) { // User user = (User)tuple.get(0); // // return "en".equals(user.getLang()); // } // } // // Path: src/main/java/tutorial/storm/trident/operations/OnlyHashtags.java // public class OnlyHashtags extends BaseFilter { // @Override // public boolean isKeep(TridentTuple tuple) { // Content content = (Content)tuple.get(0); // return "hashtag".equals(content.getContentType()); // } // } // // Path: src/main/java/tutorial/storm/trident/operations/ParseTweet.java // public class ParseTweet extends BaseFunction { // private static final Logger log = LoggerFactory.getLogger(ParseTweet.class); // // private ContentExtracter extracter; // // @Override // public void execute(TridentTuple tuple, TridentCollector collector) { // if(extracter == null) extracter = new ContentExtracter(); // // String rawTweetJson = (String)tuple.get(0); // Status parsed = parse(rawTweetJson); // User user = parsed.getUser(); // // for (Content content : extracter.extract(parsed)) { // collector.emit(new Values(parsed, content, user)); // } // } // // private Status parse(String rawJson){ // try { // Status parsed = DataObjectFactory.createStatus(rawJson); // return parsed; // } catch (TwitterException e) { // log.warn("Invalid tweet json -> " + rawJson, e); // return null; // } // } // } // // Path: src/main/java/tutorial/storm/trident/testutil/TestUtils.java // public class TestUtils { // public static TransactionalTridentKafkaSpout testTweetSpout(BrokerHosts hosts) { // TridentKafkaConfig kafkaConfig = new TridentKafkaConfig(hosts, "test", "storm"); // kafkaConfig.scheme = new SchemeAsMultiScheme(new StringScheme()); // return new TransactionalTridentKafkaSpout(kafkaConfig); // } // // }
import backtype.storm.Config; import backtype.storm.LocalCluster; import backtype.storm.LocalDRPC; import backtype.storm.StormSubmitter; import backtype.storm.generated.StormTopology; import backtype.storm.spout.SchemeAsMultiScheme; import backtype.storm.tuple.Fields; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import storm.kafka.BrokerHosts; import storm.kafka.KafkaConfig; import storm.kafka.StringScheme; import storm.kafka.ZkHosts; import storm.kafka.trident.TransactionalTridentKafkaSpout; import storm.kafka.trident.TridentKafkaConfig; import storm.trident.TridentState; import storm.trident.TridentTopology; import storm.trident.operation.builtin.Count; import storm.trident.operation.builtin.FirstN; import storm.trident.operation.builtin.MapGet; import storm.trident.operation.builtin.TupleCollectionGet; import storm.trident.testing.MemoryMapState; import tutorial.storm.trident.operations.ExtractFollowerClassAndContentName; import tutorial.storm.trident.operations.OnlyEnglish; import tutorial.storm.trident.operations.OnlyHashtags; import tutorial.storm.trident.operations.ParseTweet; import tutorial.storm.trident.testutil.TestUtils; import java.io.IOException;
package tutorial.storm.trident.example; /** * */ public class GlobalTop20Hashtags { public static StormTopology buildTopology(TransactionalTridentKafkaSpout spout) throws IOException { TridentTopology topology = new TridentTopology(); TridentState count = topology .newStream("tweets", spout)
// Path: src/main/java/tutorial/storm/trident/operations/ExtractFollowerClassAndContentName.java // public class ExtractFollowerClassAndContentName extends BaseFunction { // @Override // public void execute(TridentTuple tuple, TridentCollector collector) { // Content content = (Content)tuple.get(0); // User user = (User)tuple.get(1); // // String followerClass = classify(user.getFollowersCount()); // // collector.emit(new Values(followerClass, content.getContentName())); // } // // private String classify(int followersCount) { // if (followersCount < 100){ // return "< 100"; // } else if (followersCount < 10*1000){ // return "< 10K"; // } else if (followersCount < 100*1000){ // return "< 100K"; // } else { // return ">= 100K"; // } // } // // } // // Path: src/main/java/tutorial/storm/trident/operations/OnlyEnglish.java // public class OnlyEnglish extends BaseFilter { // @Override // public boolean isKeep(TridentTuple tuple) { // User user = (User)tuple.get(0); // // return "en".equals(user.getLang()); // } // } // // Path: src/main/java/tutorial/storm/trident/operations/OnlyHashtags.java // public class OnlyHashtags extends BaseFilter { // @Override // public boolean isKeep(TridentTuple tuple) { // Content content = (Content)tuple.get(0); // return "hashtag".equals(content.getContentType()); // } // } // // Path: src/main/java/tutorial/storm/trident/operations/ParseTweet.java // public class ParseTweet extends BaseFunction { // private static final Logger log = LoggerFactory.getLogger(ParseTweet.class); // // private ContentExtracter extracter; // // @Override // public void execute(TridentTuple tuple, TridentCollector collector) { // if(extracter == null) extracter = new ContentExtracter(); // // String rawTweetJson = (String)tuple.get(0); // Status parsed = parse(rawTweetJson); // User user = parsed.getUser(); // // for (Content content : extracter.extract(parsed)) { // collector.emit(new Values(parsed, content, user)); // } // } // // private Status parse(String rawJson){ // try { // Status parsed = DataObjectFactory.createStatus(rawJson); // return parsed; // } catch (TwitterException e) { // log.warn("Invalid tweet json -> " + rawJson, e); // return null; // } // } // } // // Path: src/main/java/tutorial/storm/trident/testutil/TestUtils.java // public class TestUtils { // public static TransactionalTridentKafkaSpout testTweetSpout(BrokerHosts hosts) { // TridentKafkaConfig kafkaConfig = new TridentKafkaConfig(hosts, "test", "storm"); // kafkaConfig.scheme = new SchemeAsMultiScheme(new StringScheme()); // return new TransactionalTridentKafkaSpout(kafkaConfig); // } // // } // Path: src/main/java/tutorial/storm/trident/example/GlobalTop20Hashtags.java import backtype.storm.Config; import backtype.storm.LocalCluster; import backtype.storm.LocalDRPC; import backtype.storm.StormSubmitter; import backtype.storm.generated.StormTopology; import backtype.storm.spout.SchemeAsMultiScheme; import backtype.storm.tuple.Fields; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import storm.kafka.BrokerHosts; import storm.kafka.KafkaConfig; import storm.kafka.StringScheme; import storm.kafka.ZkHosts; import storm.kafka.trident.TransactionalTridentKafkaSpout; import storm.kafka.trident.TridentKafkaConfig; import storm.trident.TridentState; import storm.trident.TridentTopology; import storm.trident.operation.builtin.Count; import storm.trident.operation.builtin.FirstN; import storm.trident.operation.builtin.MapGet; import storm.trident.operation.builtin.TupleCollectionGet; import storm.trident.testing.MemoryMapState; import tutorial.storm.trident.operations.ExtractFollowerClassAndContentName; import tutorial.storm.trident.operations.OnlyEnglish; import tutorial.storm.trident.operations.OnlyHashtags; import tutorial.storm.trident.operations.ParseTweet; import tutorial.storm.trident.testutil.TestUtils; import java.io.IOException; package tutorial.storm.trident.example; /** * */ public class GlobalTop20Hashtags { public static StormTopology buildTopology(TransactionalTridentKafkaSpout spout) throws IOException { TridentTopology topology = new TridentTopology(); TridentState count = topology .newStream("tweets", spout)
.each(new Fields("str"), new ParseTweet(), new Fields("text", "content", "user"))
eshioji/trident-tutorial
src/main/java/tutorial/storm/trident/example/GlobalTop20Hashtags.java
// Path: src/main/java/tutorial/storm/trident/operations/ExtractFollowerClassAndContentName.java // public class ExtractFollowerClassAndContentName extends BaseFunction { // @Override // public void execute(TridentTuple tuple, TridentCollector collector) { // Content content = (Content)tuple.get(0); // User user = (User)tuple.get(1); // // String followerClass = classify(user.getFollowersCount()); // // collector.emit(new Values(followerClass, content.getContentName())); // } // // private String classify(int followersCount) { // if (followersCount < 100){ // return "< 100"; // } else if (followersCount < 10*1000){ // return "< 10K"; // } else if (followersCount < 100*1000){ // return "< 100K"; // } else { // return ">= 100K"; // } // } // // } // // Path: src/main/java/tutorial/storm/trident/operations/OnlyEnglish.java // public class OnlyEnglish extends BaseFilter { // @Override // public boolean isKeep(TridentTuple tuple) { // User user = (User)tuple.get(0); // // return "en".equals(user.getLang()); // } // } // // Path: src/main/java/tutorial/storm/trident/operations/OnlyHashtags.java // public class OnlyHashtags extends BaseFilter { // @Override // public boolean isKeep(TridentTuple tuple) { // Content content = (Content)tuple.get(0); // return "hashtag".equals(content.getContentType()); // } // } // // Path: src/main/java/tutorial/storm/trident/operations/ParseTweet.java // public class ParseTweet extends BaseFunction { // private static final Logger log = LoggerFactory.getLogger(ParseTweet.class); // // private ContentExtracter extracter; // // @Override // public void execute(TridentTuple tuple, TridentCollector collector) { // if(extracter == null) extracter = new ContentExtracter(); // // String rawTweetJson = (String)tuple.get(0); // Status parsed = parse(rawTweetJson); // User user = parsed.getUser(); // // for (Content content : extracter.extract(parsed)) { // collector.emit(new Values(parsed, content, user)); // } // } // // private Status parse(String rawJson){ // try { // Status parsed = DataObjectFactory.createStatus(rawJson); // return parsed; // } catch (TwitterException e) { // log.warn("Invalid tweet json -> " + rawJson, e); // return null; // } // } // } // // Path: src/main/java/tutorial/storm/trident/testutil/TestUtils.java // public class TestUtils { // public static TransactionalTridentKafkaSpout testTweetSpout(BrokerHosts hosts) { // TridentKafkaConfig kafkaConfig = new TridentKafkaConfig(hosts, "test", "storm"); // kafkaConfig.scheme = new SchemeAsMultiScheme(new StringScheme()); // return new TransactionalTridentKafkaSpout(kafkaConfig); // } // // }
import backtype.storm.Config; import backtype.storm.LocalCluster; import backtype.storm.LocalDRPC; import backtype.storm.StormSubmitter; import backtype.storm.generated.StormTopology; import backtype.storm.spout.SchemeAsMultiScheme; import backtype.storm.tuple.Fields; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import storm.kafka.BrokerHosts; import storm.kafka.KafkaConfig; import storm.kafka.StringScheme; import storm.kafka.ZkHosts; import storm.kafka.trident.TransactionalTridentKafkaSpout; import storm.kafka.trident.TridentKafkaConfig; import storm.trident.TridentState; import storm.trident.TridentTopology; import storm.trident.operation.builtin.Count; import storm.trident.operation.builtin.FirstN; import storm.trident.operation.builtin.MapGet; import storm.trident.operation.builtin.TupleCollectionGet; import storm.trident.testing.MemoryMapState; import tutorial.storm.trident.operations.ExtractFollowerClassAndContentName; import tutorial.storm.trident.operations.OnlyEnglish; import tutorial.storm.trident.operations.OnlyHashtags; import tutorial.storm.trident.operations.ParseTweet; import tutorial.storm.trident.testutil.TestUtils; import java.io.IOException;
package tutorial.storm.trident.example; /** * */ public class GlobalTop20Hashtags { public static StormTopology buildTopology(TransactionalTridentKafkaSpout spout) throws IOException { TridentTopology topology = new TridentTopology(); TridentState count = topology .newStream("tweets", spout) .each(new Fields("str"), new ParseTweet(), new Fields("text", "content", "user")) .project(new Fields("content", "user"))
// Path: src/main/java/tutorial/storm/trident/operations/ExtractFollowerClassAndContentName.java // public class ExtractFollowerClassAndContentName extends BaseFunction { // @Override // public void execute(TridentTuple tuple, TridentCollector collector) { // Content content = (Content)tuple.get(0); // User user = (User)tuple.get(1); // // String followerClass = classify(user.getFollowersCount()); // // collector.emit(new Values(followerClass, content.getContentName())); // } // // private String classify(int followersCount) { // if (followersCount < 100){ // return "< 100"; // } else if (followersCount < 10*1000){ // return "< 10K"; // } else if (followersCount < 100*1000){ // return "< 100K"; // } else { // return ">= 100K"; // } // } // // } // // Path: src/main/java/tutorial/storm/trident/operations/OnlyEnglish.java // public class OnlyEnglish extends BaseFilter { // @Override // public boolean isKeep(TridentTuple tuple) { // User user = (User)tuple.get(0); // // return "en".equals(user.getLang()); // } // } // // Path: src/main/java/tutorial/storm/trident/operations/OnlyHashtags.java // public class OnlyHashtags extends BaseFilter { // @Override // public boolean isKeep(TridentTuple tuple) { // Content content = (Content)tuple.get(0); // return "hashtag".equals(content.getContentType()); // } // } // // Path: src/main/java/tutorial/storm/trident/operations/ParseTweet.java // public class ParseTweet extends BaseFunction { // private static final Logger log = LoggerFactory.getLogger(ParseTweet.class); // // private ContentExtracter extracter; // // @Override // public void execute(TridentTuple tuple, TridentCollector collector) { // if(extracter == null) extracter = new ContentExtracter(); // // String rawTweetJson = (String)tuple.get(0); // Status parsed = parse(rawTweetJson); // User user = parsed.getUser(); // // for (Content content : extracter.extract(parsed)) { // collector.emit(new Values(parsed, content, user)); // } // } // // private Status parse(String rawJson){ // try { // Status parsed = DataObjectFactory.createStatus(rawJson); // return parsed; // } catch (TwitterException e) { // log.warn("Invalid tweet json -> " + rawJson, e); // return null; // } // } // } // // Path: src/main/java/tutorial/storm/trident/testutil/TestUtils.java // public class TestUtils { // public static TransactionalTridentKafkaSpout testTweetSpout(BrokerHosts hosts) { // TridentKafkaConfig kafkaConfig = new TridentKafkaConfig(hosts, "test", "storm"); // kafkaConfig.scheme = new SchemeAsMultiScheme(new StringScheme()); // return new TransactionalTridentKafkaSpout(kafkaConfig); // } // // } // Path: src/main/java/tutorial/storm/trident/example/GlobalTop20Hashtags.java import backtype.storm.Config; import backtype.storm.LocalCluster; import backtype.storm.LocalDRPC; import backtype.storm.StormSubmitter; import backtype.storm.generated.StormTopology; import backtype.storm.spout.SchemeAsMultiScheme; import backtype.storm.tuple.Fields; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import storm.kafka.BrokerHosts; import storm.kafka.KafkaConfig; import storm.kafka.StringScheme; import storm.kafka.ZkHosts; import storm.kafka.trident.TransactionalTridentKafkaSpout; import storm.kafka.trident.TridentKafkaConfig; import storm.trident.TridentState; import storm.trident.TridentTopology; import storm.trident.operation.builtin.Count; import storm.trident.operation.builtin.FirstN; import storm.trident.operation.builtin.MapGet; import storm.trident.operation.builtin.TupleCollectionGet; import storm.trident.testing.MemoryMapState; import tutorial.storm.trident.operations.ExtractFollowerClassAndContentName; import tutorial.storm.trident.operations.OnlyEnglish; import tutorial.storm.trident.operations.OnlyHashtags; import tutorial.storm.trident.operations.ParseTweet; import tutorial.storm.trident.testutil.TestUtils; import java.io.IOException; package tutorial.storm.trident.example; /** * */ public class GlobalTop20Hashtags { public static StormTopology buildTopology(TransactionalTridentKafkaSpout spout) throws IOException { TridentTopology topology = new TridentTopology(); TridentState count = topology .newStream("tweets", spout) .each(new Fields("str"), new ParseTweet(), new Fields("text", "content", "user")) .project(new Fields("content", "user"))
.each(new Fields("content"), new OnlyHashtags())
eshioji/trident-tutorial
src/main/java/tutorial/storm/trident/example/GlobalTop20Hashtags.java
// Path: src/main/java/tutorial/storm/trident/operations/ExtractFollowerClassAndContentName.java // public class ExtractFollowerClassAndContentName extends BaseFunction { // @Override // public void execute(TridentTuple tuple, TridentCollector collector) { // Content content = (Content)tuple.get(0); // User user = (User)tuple.get(1); // // String followerClass = classify(user.getFollowersCount()); // // collector.emit(new Values(followerClass, content.getContentName())); // } // // private String classify(int followersCount) { // if (followersCount < 100){ // return "< 100"; // } else if (followersCount < 10*1000){ // return "< 10K"; // } else if (followersCount < 100*1000){ // return "< 100K"; // } else { // return ">= 100K"; // } // } // // } // // Path: src/main/java/tutorial/storm/trident/operations/OnlyEnglish.java // public class OnlyEnglish extends BaseFilter { // @Override // public boolean isKeep(TridentTuple tuple) { // User user = (User)tuple.get(0); // // return "en".equals(user.getLang()); // } // } // // Path: src/main/java/tutorial/storm/trident/operations/OnlyHashtags.java // public class OnlyHashtags extends BaseFilter { // @Override // public boolean isKeep(TridentTuple tuple) { // Content content = (Content)tuple.get(0); // return "hashtag".equals(content.getContentType()); // } // } // // Path: src/main/java/tutorial/storm/trident/operations/ParseTweet.java // public class ParseTweet extends BaseFunction { // private static final Logger log = LoggerFactory.getLogger(ParseTweet.class); // // private ContentExtracter extracter; // // @Override // public void execute(TridentTuple tuple, TridentCollector collector) { // if(extracter == null) extracter = new ContentExtracter(); // // String rawTweetJson = (String)tuple.get(0); // Status parsed = parse(rawTweetJson); // User user = parsed.getUser(); // // for (Content content : extracter.extract(parsed)) { // collector.emit(new Values(parsed, content, user)); // } // } // // private Status parse(String rawJson){ // try { // Status parsed = DataObjectFactory.createStatus(rawJson); // return parsed; // } catch (TwitterException e) { // log.warn("Invalid tweet json -> " + rawJson, e); // return null; // } // } // } // // Path: src/main/java/tutorial/storm/trident/testutil/TestUtils.java // public class TestUtils { // public static TransactionalTridentKafkaSpout testTweetSpout(BrokerHosts hosts) { // TridentKafkaConfig kafkaConfig = new TridentKafkaConfig(hosts, "test", "storm"); // kafkaConfig.scheme = new SchemeAsMultiScheme(new StringScheme()); // return new TransactionalTridentKafkaSpout(kafkaConfig); // } // // }
import backtype.storm.Config; import backtype.storm.LocalCluster; import backtype.storm.LocalDRPC; import backtype.storm.StormSubmitter; import backtype.storm.generated.StormTopology; import backtype.storm.spout.SchemeAsMultiScheme; import backtype.storm.tuple.Fields; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import storm.kafka.BrokerHosts; import storm.kafka.KafkaConfig; import storm.kafka.StringScheme; import storm.kafka.ZkHosts; import storm.kafka.trident.TransactionalTridentKafkaSpout; import storm.kafka.trident.TridentKafkaConfig; import storm.trident.TridentState; import storm.trident.TridentTopology; import storm.trident.operation.builtin.Count; import storm.trident.operation.builtin.FirstN; import storm.trident.operation.builtin.MapGet; import storm.trident.operation.builtin.TupleCollectionGet; import storm.trident.testing.MemoryMapState; import tutorial.storm.trident.operations.ExtractFollowerClassAndContentName; import tutorial.storm.trident.operations.OnlyEnglish; import tutorial.storm.trident.operations.OnlyHashtags; import tutorial.storm.trident.operations.ParseTweet; import tutorial.storm.trident.testutil.TestUtils; import java.io.IOException;
package tutorial.storm.trident.example; /** * */ public class GlobalTop20Hashtags { public static StormTopology buildTopology(TransactionalTridentKafkaSpout spout) throws IOException { TridentTopology topology = new TridentTopology(); TridentState count = topology .newStream("tweets", spout) .each(new Fields("str"), new ParseTweet(), new Fields("text", "content", "user")) .project(new Fields("content", "user")) .each(new Fields("content"), new OnlyHashtags())
// Path: src/main/java/tutorial/storm/trident/operations/ExtractFollowerClassAndContentName.java // public class ExtractFollowerClassAndContentName extends BaseFunction { // @Override // public void execute(TridentTuple tuple, TridentCollector collector) { // Content content = (Content)tuple.get(0); // User user = (User)tuple.get(1); // // String followerClass = classify(user.getFollowersCount()); // // collector.emit(new Values(followerClass, content.getContentName())); // } // // private String classify(int followersCount) { // if (followersCount < 100){ // return "< 100"; // } else if (followersCount < 10*1000){ // return "< 10K"; // } else if (followersCount < 100*1000){ // return "< 100K"; // } else { // return ">= 100K"; // } // } // // } // // Path: src/main/java/tutorial/storm/trident/operations/OnlyEnglish.java // public class OnlyEnglish extends BaseFilter { // @Override // public boolean isKeep(TridentTuple tuple) { // User user = (User)tuple.get(0); // // return "en".equals(user.getLang()); // } // } // // Path: src/main/java/tutorial/storm/trident/operations/OnlyHashtags.java // public class OnlyHashtags extends BaseFilter { // @Override // public boolean isKeep(TridentTuple tuple) { // Content content = (Content)tuple.get(0); // return "hashtag".equals(content.getContentType()); // } // } // // Path: src/main/java/tutorial/storm/trident/operations/ParseTweet.java // public class ParseTweet extends BaseFunction { // private static final Logger log = LoggerFactory.getLogger(ParseTweet.class); // // private ContentExtracter extracter; // // @Override // public void execute(TridentTuple tuple, TridentCollector collector) { // if(extracter == null) extracter = new ContentExtracter(); // // String rawTweetJson = (String)tuple.get(0); // Status parsed = parse(rawTweetJson); // User user = parsed.getUser(); // // for (Content content : extracter.extract(parsed)) { // collector.emit(new Values(parsed, content, user)); // } // } // // private Status parse(String rawJson){ // try { // Status parsed = DataObjectFactory.createStatus(rawJson); // return parsed; // } catch (TwitterException e) { // log.warn("Invalid tweet json -> " + rawJson, e); // return null; // } // } // } // // Path: src/main/java/tutorial/storm/trident/testutil/TestUtils.java // public class TestUtils { // public static TransactionalTridentKafkaSpout testTweetSpout(BrokerHosts hosts) { // TridentKafkaConfig kafkaConfig = new TridentKafkaConfig(hosts, "test", "storm"); // kafkaConfig.scheme = new SchemeAsMultiScheme(new StringScheme()); // return new TransactionalTridentKafkaSpout(kafkaConfig); // } // // } // Path: src/main/java/tutorial/storm/trident/example/GlobalTop20Hashtags.java import backtype.storm.Config; import backtype.storm.LocalCluster; import backtype.storm.LocalDRPC; import backtype.storm.StormSubmitter; import backtype.storm.generated.StormTopology; import backtype.storm.spout.SchemeAsMultiScheme; import backtype.storm.tuple.Fields; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import storm.kafka.BrokerHosts; import storm.kafka.KafkaConfig; import storm.kafka.StringScheme; import storm.kafka.ZkHosts; import storm.kafka.trident.TransactionalTridentKafkaSpout; import storm.kafka.trident.TridentKafkaConfig; import storm.trident.TridentState; import storm.trident.TridentTopology; import storm.trident.operation.builtin.Count; import storm.trident.operation.builtin.FirstN; import storm.trident.operation.builtin.MapGet; import storm.trident.operation.builtin.TupleCollectionGet; import storm.trident.testing.MemoryMapState; import tutorial.storm.trident.operations.ExtractFollowerClassAndContentName; import tutorial.storm.trident.operations.OnlyEnglish; import tutorial.storm.trident.operations.OnlyHashtags; import tutorial.storm.trident.operations.ParseTweet; import tutorial.storm.trident.testutil.TestUtils; import java.io.IOException; package tutorial.storm.trident.example; /** * */ public class GlobalTop20Hashtags { public static StormTopology buildTopology(TransactionalTridentKafkaSpout spout) throws IOException { TridentTopology topology = new TridentTopology(); TridentState count = topology .newStream("tweets", spout) .each(new Fields("str"), new ParseTweet(), new Fields("text", "content", "user")) .project(new Fields("content", "user")) .each(new Fields("content"), new OnlyHashtags())
.each(new Fields("user"), new OnlyEnglish())
eshioji/trident-tutorial
src/main/java/tutorial/storm/trident/example/GlobalTop20Hashtags.java
// Path: src/main/java/tutorial/storm/trident/operations/ExtractFollowerClassAndContentName.java // public class ExtractFollowerClassAndContentName extends BaseFunction { // @Override // public void execute(TridentTuple tuple, TridentCollector collector) { // Content content = (Content)tuple.get(0); // User user = (User)tuple.get(1); // // String followerClass = classify(user.getFollowersCount()); // // collector.emit(new Values(followerClass, content.getContentName())); // } // // private String classify(int followersCount) { // if (followersCount < 100){ // return "< 100"; // } else if (followersCount < 10*1000){ // return "< 10K"; // } else if (followersCount < 100*1000){ // return "< 100K"; // } else { // return ">= 100K"; // } // } // // } // // Path: src/main/java/tutorial/storm/trident/operations/OnlyEnglish.java // public class OnlyEnglish extends BaseFilter { // @Override // public boolean isKeep(TridentTuple tuple) { // User user = (User)tuple.get(0); // // return "en".equals(user.getLang()); // } // } // // Path: src/main/java/tutorial/storm/trident/operations/OnlyHashtags.java // public class OnlyHashtags extends BaseFilter { // @Override // public boolean isKeep(TridentTuple tuple) { // Content content = (Content)tuple.get(0); // return "hashtag".equals(content.getContentType()); // } // } // // Path: src/main/java/tutorial/storm/trident/operations/ParseTweet.java // public class ParseTweet extends BaseFunction { // private static final Logger log = LoggerFactory.getLogger(ParseTweet.class); // // private ContentExtracter extracter; // // @Override // public void execute(TridentTuple tuple, TridentCollector collector) { // if(extracter == null) extracter = new ContentExtracter(); // // String rawTweetJson = (String)tuple.get(0); // Status parsed = parse(rawTweetJson); // User user = parsed.getUser(); // // for (Content content : extracter.extract(parsed)) { // collector.emit(new Values(parsed, content, user)); // } // } // // private Status parse(String rawJson){ // try { // Status parsed = DataObjectFactory.createStatus(rawJson); // return parsed; // } catch (TwitterException e) { // log.warn("Invalid tweet json -> " + rawJson, e); // return null; // } // } // } // // Path: src/main/java/tutorial/storm/trident/testutil/TestUtils.java // public class TestUtils { // public static TransactionalTridentKafkaSpout testTweetSpout(BrokerHosts hosts) { // TridentKafkaConfig kafkaConfig = new TridentKafkaConfig(hosts, "test", "storm"); // kafkaConfig.scheme = new SchemeAsMultiScheme(new StringScheme()); // return new TransactionalTridentKafkaSpout(kafkaConfig); // } // // }
import backtype.storm.Config; import backtype.storm.LocalCluster; import backtype.storm.LocalDRPC; import backtype.storm.StormSubmitter; import backtype.storm.generated.StormTopology; import backtype.storm.spout.SchemeAsMultiScheme; import backtype.storm.tuple.Fields; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import storm.kafka.BrokerHosts; import storm.kafka.KafkaConfig; import storm.kafka.StringScheme; import storm.kafka.ZkHosts; import storm.kafka.trident.TransactionalTridentKafkaSpout; import storm.kafka.trident.TridentKafkaConfig; import storm.trident.TridentState; import storm.trident.TridentTopology; import storm.trident.operation.builtin.Count; import storm.trident.operation.builtin.FirstN; import storm.trident.operation.builtin.MapGet; import storm.trident.operation.builtin.TupleCollectionGet; import storm.trident.testing.MemoryMapState; import tutorial.storm.trident.operations.ExtractFollowerClassAndContentName; import tutorial.storm.trident.operations.OnlyEnglish; import tutorial.storm.trident.operations.OnlyHashtags; import tutorial.storm.trident.operations.ParseTweet; import tutorial.storm.trident.testutil.TestUtils; import java.io.IOException;
package tutorial.storm.trident.example; /** * */ public class GlobalTop20Hashtags { public static StormTopology buildTopology(TransactionalTridentKafkaSpout spout) throws IOException { TridentTopology topology = new TridentTopology(); TridentState count = topology .newStream("tweets", spout) .each(new Fields("str"), new ParseTweet(), new Fields("text", "content", "user")) .project(new Fields("content", "user")) .each(new Fields("content"), new OnlyHashtags()) .each(new Fields("user"), new OnlyEnglish())
// Path: src/main/java/tutorial/storm/trident/operations/ExtractFollowerClassAndContentName.java // public class ExtractFollowerClassAndContentName extends BaseFunction { // @Override // public void execute(TridentTuple tuple, TridentCollector collector) { // Content content = (Content)tuple.get(0); // User user = (User)tuple.get(1); // // String followerClass = classify(user.getFollowersCount()); // // collector.emit(new Values(followerClass, content.getContentName())); // } // // private String classify(int followersCount) { // if (followersCount < 100){ // return "< 100"; // } else if (followersCount < 10*1000){ // return "< 10K"; // } else if (followersCount < 100*1000){ // return "< 100K"; // } else { // return ">= 100K"; // } // } // // } // // Path: src/main/java/tutorial/storm/trident/operations/OnlyEnglish.java // public class OnlyEnglish extends BaseFilter { // @Override // public boolean isKeep(TridentTuple tuple) { // User user = (User)tuple.get(0); // // return "en".equals(user.getLang()); // } // } // // Path: src/main/java/tutorial/storm/trident/operations/OnlyHashtags.java // public class OnlyHashtags extends BaseFilter { // @Override // public boolean isKeep(TridentTuple tuple) { // Content content = (Content)tuple.get(0); // return "hashtag".equals(content.getContentType()); // } // } // // Path: src/main/java/tutorial/storm/trident/operations/ParseTweet.java // public class ParseTweet extends BaseFunction { // private static final Logger log = LoggerFactory.getLogger(ParseTweet.class); // // private ContentExtracter extracter; // // @Override // public void execute(TridentTuple tuple, TridentCollector collector) { // if(extracter == null) extracter = new ContentExtracter(); // // String rawTweetJson = (String)tuple.get(0); // Status parsed = parse(rawTweetJson); // User user = parsed.getUser(); // // for (Content content : extracter.extract(parsed)) { // collector.emit(new Values(parsed, content, user)); // } // } // // private Status parse(String rawJson){ // try { // Status parsed = DataObjectFactory.createStatus(rawJson); // return parsed; // } catch (TwitterException e) { // log.warn("Invalid tweet json -> " + rawJson, e); // return null; // } // } // } // // Path: src/main/java/tutorial/storm/trident/testutil/TestUtils.java // public class TestUtils { // public static TransactionalTridentKafkaSpout testTweetSpout(BrokerHosts hosts) { // TridentKafkaConfig kafkaConfig = new TridentKafkaConfig(hosts, "test", "storm"); // kafkaConfig.scheme = new SchemeAsMultiScheme(new StringScheme()); // return new TransactionalTridentKafkaSpout(kafkaConfig); // } // // } // Path: src/main/java/tutorial/storm/trident/example/GlobalTop20Hashtags.java import backtype.storm.Config; import backtype.storm.LocalCluster; import backtype.storm.LocalDRPC; import backtype.storm.StormSubmitter; import backtype.storm.generated.StormTopology; import backtype.storm.spout.SchemeAsMultiScheme; import backtype.storm.tuple.Fields; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import storm.kafka.BrokerHosts; import storm.kafka.KafkaConfig; import storm.kafka.StringScheme; import storm.kafka.ZkHosts; import storm.kafka.trident.TransactionalTridentKafkaSpout; import storm.kafka.trident.TridentKafkaConfig; import storm.trident.TridentState; import storm.trident.TridentTopology; import storm.trident.operation.builtin.Count; import storm.trident.operation.builtin.FirstN; import storm.trident.operation.builtin.MapGet; import storm.trident.operation.builtin.TupleCollectionGet; import storm.trident.testing.MemoryMapState; import tutorial.storm.trident.operations.ExtractFollowerClassAndContentName; import tutorial.storm.trident.operations.OnlyEnglish; import tutorial.storm.trident.operations.OnlyHashtags; import tutorial.storm.trident.operations.ParseTweet; import tutorial.storm.trident.testutil.TestUtils; import java.io.IOException; package tutorial.storm.trident.example; /** * */ public class GlobalTop20Hashtags { public static StormTopology buildTopology(TransactionalTridentKafkaSpout spout) throws IOException { TridentTopology topology = new TridentTopology(); TridentState count = topology .newStream("tweets", spout) .each(new Fields("str"), new ParseTweet(), new Fields("text", "content", "user")) .project(new Fields("content", "user")) .each(new Fields("content"), new OnlyHashtags()) .each(new Fields("user"), new OnlyEnglish())
.each(new Fields("content", "user"), new ExtractFollowerClassAndContentName(), new Fields("followerClass", "contentName"))
eshioji/trident-tutorial
src/main/java/tutorial/storm/trident/example/GlobalTop20Hashtags.java
// Path: src/main/java/tutorial/storm/trident/operations/ExtractFollowerClassAndContentName.java // public class ExtractFollowerClassAndContentName extends BaseFunction { // @Override // public void execute(TridentTuple tuple, TridentCollector collector) { // Content content = (Content)tuple.get(0); // User user = (User)tuple.get(1); // // String followerClass = classify(user.getFollowersCount()); // // collector.emit(new Values(followerClass, content.getContentName())); // } // // private String classify(int followersCount) { // if (followersCount < 100){ // return "< 100"; // } else if (followersCount < 10*1000){ // return "< 10K"; // } else if (followersCount < 100*1000){ // return "< 100K"; // } else { // return ">= 100K"; // } // } // // } // // Path: src/main/java/tutorial/storm/trident/operations/OnlyEnglish.java // public class OnlyEnglish extends BaseFilter { // @Override // public boolean isKeep(TridentTuple tuple) { // User user = (User)tuple.get(0); // // return "en".equals(user.getLang()); // } // } // // Path: src/main/java/tutorial/storm/trident/operations/OnlyHashtags.java // public class OnlyHashtags extends BaseFilter { // @Override // public boolean isKeep(TridentTuple tuple) { // Content content = (Content)tuple.get(0); // return "hashtag".equals(content.getContentType()); // } // } // // Path: src/main/java/tutorial/storm/trident/operations/ParseTweet.java // public class ParseTweet extends BaseFunction { // private static final Logger log = LoggerFactory.getLogger(ParseTweet.class); // // private ContentExtracter extracter; // // @Override // public void execute(TridentTuple tuple, TridentCollector collector) { // if(extracter == null) extracter = new ContentExtracter(); // // String rawTweetJson = (String)tuple.get(0); // Status parsed = parse(rawTweetJson); // User user = parsed.getUser(); // // for (Content content : extracter.extract(parsed)) { // collector.emit(new Values(parsed, content, user)); // } // } // // private Status parse(String rawJson){ // try { // Status parsed = DataObjectFactory.createStatus(rawJson); // return parsed; // } catch (TwitterException e) { // log.warn("Invalid tweet json -> " + rawJson, e); // return null; // } // } // } // // Path: src/main/java/tutorial/storm/trident/testutil/TestUtils.java // public class TestUtils { // public static TransactionalTridentKafkaSpout testTweetSpout(BrokerHosts hosts) { // TridentKafkaConfig kafkaConfig = new TridentKafkaConfig(hosts, "test", "storm"); // kafkaConfig.scheme = new SchemeAsMultiScheme(new StringScheme()); // return new TransactionalTridentKafkaSpout(kafkaConfig); // } // // }
import backtype.storm.Config; import backtype.storm.LocalCluster; import backtype.storm.LocalDRPC; import backtype.storm.StormSubmitter; import backtype.storm.generated.StormTopology; import backtype.storm.spout.SchemeAsMultiScheme; import backtype.storm.tuple.Fields; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import storm.kafka.BrokerHosts; import storm.kafka.KafkaConfig; import storm.kafka.StringScheme; import storm.kafka.ZkHosts; import storm.kafka.trident.TransactionalTridentKafkaSpout; import storm.kafka.trident.TridentKafkaConfig; import storm.trident.TridentState; import storm.trident.TridentTopology; import storm.trident.operation.builtin.Count; import storm.trident.operation.builtin.FirstN; import storm.trident.operation.builtin.MapGet; import storm.trident.operation.builtin.TupleCollectionGet; import storm.trident.testing.MemoryMapState; import tutorial.storm.trident.operations.ExtractFollowerClassAndContentName; import tutorial.storm.trident.operations.OnlyEnglish; import tutorial.storm.trident.operations.OnlyHashtags; import tutorial.storm.trident.operations.ParseTweet; import tutorial.storm.trident.testutil.TestUtils; import java.io.IOException;
package tutorial.storm.trident.example; /** * */ public class GlobalTop20Hashtags { public static StormTopology buildTopology(TransactionalTridentKafkaSpout spout) throws IOException { TridentTopology topology = new TridentTopology(); TridentState count = topology .newStream("tweets", spout) .each(new Fields("str"), new ParseTweet(), new Fields("text", "content", "user")) .project(new Fields("content", "user")) .each(new Fields("content"), new OnlyHashtags()) .each(new Fields("user"), new OnlyEnglish()) .each(new Fields("content", "user"), new ExtractFollowerClassAndContentName(), new Fields("followerClass", "contentName")) .groupBy(new Fields("followerClass", "contentName")) .persistentAggregate(new MemoryMapState.Factory(), new Count(), new Fields("count")) ; topology .newDRPCStream("top_hashtags") .stateQuery(count, new TupleCollectionGet(), new Fields("followerClass", "contentName")) .stateQuery(count, new Fields("followerClass", "contentName"), new MapGet(), new Fields("count")) .aggregate(new Fields("contentName", "count"), new FirstN.FirstNSortedAgg(5,"count", true), new Fields("contentName", "count")) ; return topology.build(); } public static void main(String[] args) throws Exception { Config conf = new Config(); if (args.length == 2) { // Ready & submit the topology String name = args[0]; BrokerHosts hosts = new ZkHosts(args[1]);
// Path: src/main/java/tutorial/storm/trident/operations/ExtractFollowerClassAndContentName.java // public class ExtractFollowerClassAndContentName extends BaseFunction { // @Override // public void execute(TridentTuple tuple, TridentCollector collector) { // Content content = (Content)tuple.get(0); // User user = (User)tuple.get(1); // // String followerClass = classify(user.getFollowersCount()); // // collector.emit(new Values(followerClass, content.getContentName())); // } // // private String classify(int followersCount) { // if (followersCount < 100){ // return "< 100"; // } else if (followersCount < 10*1000){ // return "< 10K"; // } else if (followersCount < 100*1000){ // return "< 100K"; // } else { // return ">= 100K"; // } // } // // } // // Path: src/main/java/tutorial/storm/trident/operations/OnlyEnglish.java // public class OnlyEnglish extends BaseFilter { // @Override // public boolean isKeep(TridentTuple tuple) { // User user = (User)tuple.get(0); // // return "en".equals(user.getLang()); // } // } // // Path: src/main/java/tutorial/storm/trident/operations/OnlyHashtags.java // public class OnlyHashtags extends BaseFilter { // @Override // public boolean isKeep(TridentTuple tuple) { // Content content = (Content)tuple.get(0); // return "hashtag".equals(content.getContentType()); // } // } // // Path: src/main/java/tutorial/storm/trident/operations/ParseTweet.java // public class ParseTweet extends BaseFunction { // private static final Logger log = LoggerFactory.getLogger(ParseTweet.class); // // private ContentExtracter extracter; // // @Override // public void execute(TridentTuple tuple, TridentCollector collector) { // if(extracter == null) extracter = new ContentExtracter(); // // String rawTweetJson = (String)tuple.get(0); // Status parsed = parse(rawTweetJson); // User user = parsed.getUser(); // // for (Content content : extracter.extract(parsed)) { // collector.emit(new Values(parsed, content, user)); // } // } // // private Status parse(String rawJson){ // try { // Status parsed = DataObjectFactory.createStatus(rawJson); // return parsed; // } catch (TwitterException e) { // log.warn("Invalid tweet json -> " + rawJson, e); // return null; // } // } // } // // Path: src/main/java/tutorial/storm/trident/testutil/TestUtils.java // public class TestUtils { // public static TransactionalTridentKafkaSpout testTweetSpout(BrokerHosts hosts) { // TridentKafkaConfig kafkaConfig = new TridentKafkaConfig(hosts, "test", "storm"); // kafkaConfig.scheme = new SchemeAsMultiScheme(new StringScheme()); // return new TransactionalTridentKafkaSpout(kafkaConfig); // } // // } // Path: src/main/java/tutorial/storm/trident/example/GlobalTop20Hashtags.java import backtype.storm.Config; import backtype.storm.LocalCluster; import backtype.storm.LocalDRPC; import backtype.storm.StormSubmitter; import backtype.storm.generated.StormTopology; import backtype.storm.spout.SchemeAsMultiScheme; import backtype.storm.tuple.Fields; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import storm.kafka.BrokerHosts; import storm.kafka.KafkaConfig; import storm.kafka.StringScheme; import storm.kafka.ZkHosts; import storm.kafka.trident.TransactionalTridentKafkaSpout; import storm.kafka.trident.TridentKafkaConfig; import storm.trident.TridentState; import storm.trident.TridentTopology; import storm.trident.operation.builtin.Count; import storm.trident.operation.builtin.FirstN; import storm.trident.operation.builtin.MapGet; import storm.trident.operation.builtin.TupleCollectionGet; import storm.trident.testing.MemoryMapState; import tutorial.storm.trident.operations.ExtractFollowerClassAndContentName; import tutorial.storm.trident.operations.OnlyEnglish; import tutorial.storm.trident.operations.OnlyHashtags; import tutorial.storm.trident.operations.ParseTweet; import tutorial.storm.trident.testutil.TestUtils; import java.io.IOException; package tutorial.storm.trident.example; /** * */ public class GlobalTop20Hashtags { public static StormTopology buildTopology(TransactionalTridentKafkaSpout spout) throws IOException { TridentTopology topology = new TridentTopology(); TridentState count = topology .newStream("tweets", spout) .each(new Fields("str"), new ParseTweet(), new Fields("text", "content", "user")) .project(new Fields("content", "user")) .each(new Fields("content"), new OnlyHashtags()) .each(new Fields("user"), new OnlyEnglish()) .each(new Fields("content", "user"), new ExtractFollowerClassAndContentName(), new Fields("followerClass", "contentName")) .groupBy(new Fields("followerClass", "contentName")) .persistentAggregate(new MemoryMapState.Factory(), new Count(), new Fields("count")) ; topology .newDRPCStream("top_hashtags") .stateQuery(count, new TupleCollectionGet(), new Fields("followerClass", "contentName")) .stateQuery(count, new Fields("followerClass", "contentName"), new MapGet(), new Fields("count")) .aggregate(new Fields("contentName", "count"), new FirstN.FirstNSortedAgg(5,"count", true), new Fields("contentName", "count")) ; return topology.build(); } public static void main(String[] args) throws Exception { Config conf = new Config(); if (args.length == 2) { // Ready & submit the topology String name = args[0]; BrokerHosts hosts = new ZkHosts(args[1]);
TransactionalTridentKafkaSpout kafkaSpout = TestUtils.testTweetSpout(hosts);
eshioji/trident-tutorial
src/main/java/tutorial/storm/trident/Part01_BasicPrimitives.java
// Path: src/main/java/tutorial/storm/trident/operations/Print.java // public class Print extends BaseFilter { // private int partitionIndex; // private int numPartitions; // private final String name; // // public Print(){ // name = ""; // } // public Print(String name){ // this.name = name; // } // // @Override // public void prepare(Map conf, TridentOperationContext context) { // this.partitionIndex = context.getPartitionIndex(); // this.numPartitions = context.numPartitions(); // } // // // @Override // public boolean isKeep(TridentTuple tuple) { // System.err.println(String.format("%s::Partition idx: %s out of %s partitions got %s", name, partitionIndex, numPartitions, tuple.toString())); // return true; // } // } // // Path: src/main/java/tutorial/storm/trident/operations/RegexFilter.java // public class RegexFilter extends BaseFilter { // private final Pattern pattern; // // public RegexFilter(String pattern) { // this.pattern = Pattern.compile(pattern); // } // // @Override // public boolean isKeep(TridentTuple tuple) { // // String string = tuple.getString(0); // return pattern.matcher(string).matches(); // } // } // // Path: src/main/java/tutorial/storm/trident/operations/ToUpperCase.java // @SuppressWarnings("serial") // public class ToUpperCase extends BaseFunction { // // @Override // public void execute(TridentTuple tuple, TridentCollector collector) { // collector.emit(new Values(tuple.getString(0).toUpperCase())); // } // } // // Path: src/main/java/tutorial/storm/trident/testutil/FakeTweetsBatchSpout.java // @SuppressWarnings({"serial", "rawtypes"}) // public class FakeTweetsBatchSpout implements IBatchSpout { // private static final AtomicInteger seq = new AtomicInteger(); // // private int batchSize; // private FakeTweetGenerator fakeTweetGenerator; // // // public FakeTweetsBatchSpout() throws IOException { // this(5); // } // // public FakeTweetsBatchSpout(int batchSize) throws IOException { // this.batchSize = batchSize; // } // // @SuppressWarnings("unchecked") // @Override // public void open(Map conf, TopologyContext context) { // // init // System.err.println(this.getClass().getSimpleName() +":" + seq.incrementAndGet()+" opened."); // fakeTweetGenerator = new FakeTweetGenerator(); // // } // // @Override // public void emitBatch(long batchId, TridentCollector collector) { // // emit batchSize fake tweets // for (int i = 0; i < batchSize; i++) { // collector.emit(fakeTweetGenerator.getNextTweet()); // } // } // // @Override // public void ack(long batchId) { // // nothing to do here // } // // @Override // public void close() { // // nothing to do here // } // // @Override // public Map getComponentConfiguration() { // // no particular configuration here // return new Config(); // } // // @Override // public Fields getOutputFields() { // return new Fields("id", "text", "actor", "location", "date"); // } // }
import backtype.storm.Config; import backtype.storm.LocalCluster; import backtype.storm.generated.StormTopology; import backtype.storm.tuple.Fields; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import storm.trident.TridentTopology; import storm.trident.operation.builtin.Count; import storm.trident.spout.IBatchSpout; import storm.trident.testing.MemoryMapState; import tutorial.storm.trident.operations.Print; import tutorial.storm.trident.operations.RegexFilter; import tutorial.storm.trident.operations.ToUpperCase; import tutorial.storm.trident.testutil.FakeTweetsBatchSpout; import java.io.IOException;
package tutorial.storm.trident; /** * @author Enno Shioji (enno.shioji@peerindex.com) */ public class Part01_BasicPrimitives { private static final Logger log = LoggerFactory.getLogger(Part01_BasicPrimitives.class); public static void main(String[] args) throws Exception { // Storm can be run locally for testing purposes Config conf = new Config(); // conf.put(Config.TOPOLOGY_DEBUG,true); LocalCluster cluster = new LocalCluster();
// Path: src/main/java/tutorial/storm/trident/operations/Print.java // public class Print extends BaseFilter { // private int partitionIndex; // private int numPartitions; // private final String name; // // public Print(){ // name = ""; // } // public Print(String name){ // this.name = name; // } // // @Override // public void prepare(Map conf, TridentOperationContext context) { // this.partitionIndex = context.getPartitionIndex(); // this.numPartitions = context.numPartitions(); // } // // // @Override // public boolean isKeep(TridentTuple tuple) { // System.err.println(String.format("%s::Partition idx: %s out of %s partitions got %s", name, partitionIndex, numPartitions, tuple.toString())); // return true; // } // } // // Path: src/main/java/tutorial/storm/trident/operations/RegexFilter.java // public class RegexFilter extends BaseFilter { // private final Pattern pattern; // // public RegexFilter(String pattern) { // this.pattern = Pattern.compile(pattern); // } // // @Override // public boolean isKeep(TridentTuple tuple) { // // String string = tuple.getString(0); // return pattern.matcher(string).matches(); // } // } // // Path: src/main/java/tutorial/storm/trident/operations/ToUpperCase.java // @SuppressWarnings("serial") // public class ToUpperCase extends BaseFunction { // // @Override // public void execute(TridentTuple tuple, TridentCollector collector) { // collector.emit(new Values(tuple.getString(0).toUpperCase())); // } // } // // Path: src/main/java/tutorial/storm/trident/testutil/FakeTweetsBatchSpout.java // @SuppressWarnings({"serial", "rawtypes"}) // public class FakeTweetsBatchSpout implements IBatchSpout { // private static final AtomicInteger seq = new AtomicInteger(); // // private int batchSize; // private FakeTweetGenerator fakeTweetGenerator; // // // public FakeTweetsBatchSpout() throws IOException { // this(5); // } // // public FakeTweetsBatchSpout(int batchSize) throws IOException { // this.batchSize = batchSize; // } // // @SuppressWarnings("unchecked") // @Override // public void open(Map conf, TopologyContext context) { // // init // System.err.println(this.getClass().getSimpleName() +":" + seq.incrementAndGet()+" opened."); // fakeTweetGenerator = new FakeTweetGenerator(); // // } // // @Override // public void emitBatch(long batchId, TridentCollector collector) { // // emit batchSize fake tweets // for (int i = 0; i < batchSize; i++) { // collector.emit(fakeTweetGenerator.getNextTweet()); // } // } // // @Override // public void ack(long batchId) { // // nothing to do here // } // // @Override // public void close() { // // nothing to do here // } // // @Override // public Map getComponentConfiguration() { // // no particular configuration here // return new Config(); // } // // @Override // public Fields getOutputFields() { // return new Fields("id", "text", "actor", "location", "date"); // } // } // Path: src/main/java/tutorial/storm/trident/Part01_BasicPrimitives.java import backtype.storm.Config; import backtype.storm.LocalCluster; import backtype.storm.generated.StormTopology; import backtype.storm.tuple.Fields; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import storm.trident.TridentTopology; import storm.trident.operation.builtin.Count; import storm.trident.spout.IBatchSpout; import storm.trident.testing.MemoryMapState; import tutorial.storm.trident.operations.Print; import tutorial.storm.trident.operations.RegexFilter; import tutorial.storm.trident.operations.ToUpperCase; import tutorial.storm.trident.testutil.FakeTweetsBatchSpout; import java.io.IOException; package tutorial.storm.trident; /** * @author Enno Shioji (enno.shioji@peerindex.com) */ public class Part01_BasicPrimitives { private static final Logger log = LoggerFactory.getLogger(Part01_BasicPrimitives.class); public static void main(String[] args) throws Exception { // Storm can be run locally for testing purposes Config conf = new Config(); // conf.put(Config.TOPOLOGY_DEBUG,true); LocalCluster cluster = new LocalCluster();
cluster.submitTopology("basic_primitives", conf, basicPrimitives(new FakeTweetsBatchSpout()));
eshioji/trident-tutorial
src/main/java/tutorial/storm/trident/Part01_BasicPrimitives.java
// Path: src/main/java/tutorial/storm/trident/operations/Print.java // public class Print extends BaseFilter { // private int partitionIndex; // private int numPartitions; // private final String name; // // public Print(){ // name = ""; // } // public Print(String name){ // this.name = name; // } // // @Override // public void prepare(Map conf, TridentOperationContext context) { // this.partitionIndex = context.getPartitionIndex(); // this.numPartitions = context.numPartitions(); // } // // // @Override // public boolean isKeep(TridentTuple tuple) { // System.err.println(String.format("%s::Partition idx: %s out of %s partitions got %s", name, partitionIndex, numPartitions, tuple.toString())); // return true; // } // } // // Path: src/main/java/tutorial/storm/trident/operations/RegexFilter.java // public class RegexFilter extends BaseFilter { // private final Pattern pattern; // // public RegexFilter(String pattern) { // this.pattern = Pattern.compile(pattern); // } // // @Override // public boolean isKeep(TridentTuple tuple) { // // String string = tuple.getString(0); // return pattern.matcher(string).matches(); // } // } // // Path: src/main/java/tutorial/storm/trident/operations/ToUpperCase.java // @SuppressWarnings("serial") // public class ToUpperCase extends BaseFunction { // // @Override // public void execute(TridentTuple tuple, TridentCollector collector) { // collector.emit(new Values(tuple.getString(0).toUpperCase())); // } // } // // Path: src/main/java/tutorial/storm/trident/testutil/FakeTweetsBatchSpout.java // @SuppressWarnings({"serial", "rawtypes"}) // public class FakeTweetsBatchSpout implements IBatchSpout { // private static final AtomicInteger seq = new AtomicInteger(); // // private int batchSize; // private FakeTweetGenerator fakeTweetGenerator; // // // public FakeTweetsBatchSpout() throws IOException { // this(5); // } // // public FakeTweetsBatchSpout(int batchSize) throws IOException { // this.batchSize = batchSize; // } // // @SuppressWarnings("unchecked") // @Override // public void open(Map conf, TopologyContext context) { // // init // System.err.println(this.getClass().getSimpleName() +":" + seq.incrementAndGet()+" opened."); // fakeTweetGenerator = new FakeTweetGenerator(); // // } // // @Override // public void emitBatch(long batchId, TridentCollector collector) { // // emit batchSize fake tweets // for (int i = 0; i < batchSize; i++) { // collector.emit(fakeTweetGenerator.getNextTweet()); // } // } // // @Override // public void ack(long batchId) { // // nothing to do here // } // // @Override // public void close() { // // nothing to do here // } // // @Override // public Map getComponentConfiguration() { // // no particular configuration here // return new Config(); // } // // @Override // public Fields getOutputFields() { // return new Fields("id", "text", "actor", "location", "date"); // } // }
import backtype.storm.Config; import backtype.storm.LocalCluster; import backtype.storm.generated.StormTopology; import backtype.storm.tuple.Fields; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import storm.trident.TridentTopology; import storm.trident.operation.builtin.Count; import storm.trident.spout.IBatchSpout; import storm.trident.testing.MemoryMapState; import tutorial.storm.trident.operations.Print; import tutorial.storm.trident.operations.RegexFilter; import tutorial.storm.trident.operations.ToUpperCase; import tutorial.storm.trident.testutil.FakeTweetsBatchSpout; import java.io.IOException;
package tutorial.storm.trident; /** * @author Enno Shioji (enno.shioji@peerindex.com) */ public class Part01_BasicPrimitives { private static final Logger log = LoggerFactory.getLogger(Part01_BasicPrimitives.class); public static void main(String[] args) throws Exception { // Storm can be run locally for testing purposes Config conf = new Config(); // conf.put(Config.TOPOLOGY_DEBUG,true); LocalCluster cluster = new LocalCluster(); cluster.submitTopology("basic_primitives", conf, basicPrimitives(new FakeTweetsBatchSpout())); Thread.sleep(100000); } public static StormTopology basicPrimitives(IBatchSpout spout) throws IOException { // A topology is a set of streams. // A stream is a DAG of Spouts and Bolts. // (In Storm there are Spouts (data producers) and Bolts (data processors). // Spouts create Tuples and Bolts manipulate then and possibly emit new ones.) // But in Trident we operate at a higher level. // Bolts are created and connected automatically out of higher-level constructs. // Also, Spouts are "batched". TridentTopology topology = new TridentTopology(); // The "each" primitive allows us to apply either filters or functions to the stream // We always have to select the input fields. topology .newStream("filter", spout)
// Path: src/main/java/tutorial/storm/trident/operations/Print.java // public class Print extends BaseFilter { // private int partitionIndex; // private int numPartitions; // private final String name; // // public Print(){ // name = ""; // } // public Print(String name){ // this.name = name; // } // // @Override // public void prepare(Map conf, TridentOperationContext context) { // this.partitionIndex = context.getPartitionIndex(); // this.numPartitions = context.numPartitions(); // } // // // @Override // public boolean isKeep(TridentTuple tuple) { // System.err.println(String.format("%s::Partition idx: %s out of %s partitions got %s", name, partitionIndex, numPartitions, tuple.toString())); // return true; // } // } // // Path: src/main/java/tutorial/storm/trident/operations/RegexFilter.java // public class RegexFilter extends BaseFilter { // private final Pattern pattern; // // public RegexFilter(String pattern) { // this.pattern = Pattern.compile(pattern); // } // // @Override // public boolean isKeep(TridentTuple tuple) { // // String string = tuple.getString(0); // return pattern.matcher(string).matches(); // } // } // // Path: src/main/java/tutorial/storm/trident/operations/ToUpperCase.java // @SuppressWarnings("serial") // public class ToUpperCase extends BaseFunction { // // @Override // public void execute(TridentTuple tuple, TridentCollector collector) { // collector.emit(new Values(tuple.getString(0).toUpperCase())); // } // } // // Path: src/main/java/tutorial/storm/trident/testutil/FakeTweetsBatchSpout.java // @SuppressWarnings({"serial", "rawtypes"}) // public class FakeTweetsBatchSpout implements IBatchSpout { // private static final AtomicInteger seq = new AtomicInteger(); // // private int batchSize; // private FakeTweetGenerator fakeTweetGenerator; // // // public FakeTweetsBatchSpout() throws IOException { // this(5); // } // // public FakeTweetsBatchSpout(int batchSize) throws IOException { // this.batchSize = batchSize; // } // // @SuppressWarnings("unchecked") // @Override // public void open(Map conf, TopologyContext context) { // // init // System.err.println(this.getClass().getSimpleName() +":" + seq.incrementAndGet()+" opened."); // fakeTweetGenerator = new FakeTweetGenerator(); // // } // // @Override // public void emitBatch(long batchId, TridentCollector collector) { // // emit batchSize fake tweets // for (int i = 0; i < batchSize; i++) { // collector.emit(fakeTweetGenerator.getNextTweet()); // } // } // // @Override // public void ack(long batchId) { // // nothing to do here // } // // @Override // public void close() { // // nothing to do here // } // // @Override // public Map getComponentConfiguration() { // // no particular configuration here // return new Config(); // } // // @Override // public Fields getOutputFields() { // return new Fields("id", "text", "actor", "location", "date"); // } // } // Path: src/main/java/tutorial/storm/trident/Part01_BasicPrimitives.java import backtype.storm.Config; import backtype.storm.LocalCluster; import backtype.storm.generated.StormTopology; import backtype.storm.tuple.Fields; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import storm.trident.TridentTopology; import storm.trident.operation.builtin.Count; import storm.trident.spout.IBatchSpout; import storm.trident.testing.MemoryMapState; import tutorial.storm.trident.operations.Print; import tutorial.storm.trident.operations.RegexFilter; import tutorial.storm.trident.operations.ToUpperCase; import tutorial.storm.trident.testutil.FakeTweetsBatchSpout; import java.io.IOException; package tutorial.storm.trident; /** * @author Enno Shioji (enno.shioji@peerindex.com) */ public class Part01_BasicPrimitives { private static final Logger log = LoggerFactory.getLogger(Part01_BasicPrimitives.class); public static void main(String[] args) throws Exception { // Storm can be run locally for testing purposes Config conf = new Config(); // conf.put(Config.TOPOLOGY_DEBUG,true); LocalCluster cluster = new LocalCluster(); cluster.submitTopology("basic_primitives", conf, basicPrimitives(new FakeTweetsBatchSpout())); Thread.sleep(100000); } public static StormTopology basicPrimitives(IBatchSpout spout) throws IOException { // A topology is a set of streams. // A stream is a DAG of Spouts and Bolts. // (In Storm there are Spouts (data producers) and Bolts (data processors). // Spouts create Tuples and Bolts manipulate then and possibly emit new ones.) // But in Trident we operate at a higher level. // Bolts are created and connected automatically out of higher-level constructs. // Also, Spouts are "batched". TridentTopology topology = new TridentTopology(); // The "each" primitive allows us to apply either filters or functions to the stream // We always have to select the input fields. topology .newStream("filter", spout)
.each(new Fields("actor"), new RegexFilter("pere"))
eshioji/trident-tutorial
src/main/java/tutorial/storm/trident/Part01_BasicPrimitives.java
// Path: src/main/java/tutorial/storm/trident/operations/Print.java // public class Print extends BaseFilter { // private int partitionIndex; // private int numPartitions; // private final String name; // // public Print(){ // name = ""; // } // public Print(String name){ // this.name = name; // } // // @Override // public void prepare(Map conf, TridentOperationContext context) { // this.partitionIndex = context.getPartitionIndex(); // this.numPartitions = context.numPartitions(); // } // // // @Override // public boolean isKeep(TridentTuple tuple) { // System.err.println(String.format("%s::Partition idx: %s out of %s partitions got %s", name, partitionIndex, numPartitions, tuple.toString())); // return true; // } // } // // Path: src/main/java/tutorial/storm/trident/operations/RegexFilter.java // public class RegexFilter extends BaseFilter { // private final Pattern pattern; // // public RegexFilter(String pattern) { // this.pattern = Pattern.compile(pattern); // } // // @Override // public boolean isKeep(TridentTuple tuple) { // // String string = tuple.getString(0); // return pattern.matcher(string).matches(); // } // } // // Path: src/main/java/tutorial/storm/trident/operations/ToUpperCase.java // @SuppressWarnings("serial") // public class ToUpperCase extends BaseFunction { // // @Override // public void execute(TridentTuple tuple, TridentCollector collector) { // collector.emit(new Values(tuple.getString(0).toUpperCase())); // } // } // // Path: src/main/java/tutorial/storm/trident/testutil/FakeTweetsBatchSpout.java // @SuppressWarnings({"serial", "rawtypes"}) // public class FakeTweetsBatchSpout implements IBatchSpout { // private static final AtomicInteger seq = new AtomicInteger(); // // private int batchSize; // private FakeTweetGenerator fakeTweetGenerator; // // // public FakeTweetsBatchSpout() throws IOException { // this(5); // } // // public FakeTweetsBatchSpout(int batchSize) throws IOException { // this.batchSize = batchSize; // } // // @SuppressWarnings("unchecked") // @Override // public void open(Map conf, TopologyContext context) { // // init // System.err.println(this.getClass().getSimpleName() +":" + seq.incrementAndGet()+" opened."); // fakeTweetGenerator = new FakeTweetGenerator(); // // } // // @Override // public void emitBatch(long batchId, TridentCollector collector) { // // emit batchSize fake tweets // for (int i = 0; i < batchSize; i++) { // collector.emit(fakeTweetGenerator.getNextTweet()); // } // } // // @Override // public void ack(long batchId) { // // nothing to do here // } // // @Override // public void close() { // // nothing to do here // } // // @Override // public Map getComponentConfiguration() { // // no particular configuration here // return new Config(); // } // // @Override // public Fields getOutputFields() { // return new Fields("id", "text", "actor", "location", "date"); // } // }
import backtype.storm.Config; import backtype.storm.LocalCluster; import backtype.storm.generated.StormTopology; import backtype.storm.tuple.Fields; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import storm.trident.TridentTopology; import storm.trident.operation.builtin.Count; import storm.trident.spout.IBatchSpout; import storm.trident.testing.MemoryMapState; import tutorial.storm.trident.operations.Print; import tutorial.storm.trident.operations.RegexFilter; import tutorial.storm.trident.operations.ToUpperCase; import tutorial.storm.trident.testutil.FakeTweetsBatchSpout; import java.io.IOException;
package tutorial.storm.trident; /** * @author Enno Shioji (enno.shioji@peerindex.com) */ public class Part01_BasicPrimitives { private static final Logger log = LoggerFactory.getLogger(Part01_BasicPrimitives.class); public static void main(String[] args) throws Exception { // Storm can be run locally for testing purposes Config conf = new Config(); // conf.put(Config.TOPOLOGY_DEBUG,true); LocalCluster cluster = new LocalCluster(); cluster.submitTopology("basic_primitives", conf, basicPrimitives(new FakeTweetsBatchSpout())); Thread.sleep(100000); } public static StormTopology basicPrimitives(IBatchSpout spout) throws IOException { // A topology is a set of streams. // A stream is a DAG of Spouts and Bolts. // (In Storm there are Spouts (data producers) and Bolts (data processors). // Spouts create Tuples and Bolts manipulate then and possibly emit new ones.) // But in Trident we operate at a higher level. // Bolts are created and connected automatically out of higher-level constructs. // Also, Spouts are "batched". TridentTopology topology = new TridentTopology(); // The "each" primitive allows us to apply either filters or functions to the stream // We always have to select the input fields. topology .newStream("filter", spout) .each(new Fields("actor"), new RegexFilter("pere"))
// Path: src/main/java/tutorial/storm/trident/operations/Print.java // public class Print extends BaseFilter { // private int partitionIndex; // private int numPartitions; // private final String name; // // public Print(){ // name = ""; // } // public Print(String name){ // this.name = name; // } // // @Override // public void prepare(Map conf, TridentOperationContext context) { // this.partitionIndex = context.getPartitionIndex(); // this.numPartitions = context.numPartitions(); // } // // // @Override // public boolean isKeep(TridentTuple tuple) { // System.err.println(String.format("%s::Partition idx: %s out of %s partitions got %s", name, partitionIndex, numPartitions, tuple.toString())); // return true; // } // } // // Path: src/main/java/tutorial/storm/trident/operations/RegexFilter.java // public class RegexFilter extends BaseFilter { // private final Pattern pattern; // // public RegexFilter(String pattern) { // this.pattern = Pattern.compile(pattern); // } // // @Override // public boolean isKeep(TridentTuple tuple) { // // String string = tuple.getString(0); // return pattern.matcher(string).matches(); // } // } // // Path: src/main/java/tutorial/storm/trident/operations/ToUpperCase.java // @SuppressWarnings("serial") // public class ToUpperCase extends BaseFunction { // // @Override // public void execute(TridentTuple tuple, TridentCollector collector) { // collector.emit(new Values(tuple.getString(0).toUpperCase())); // } // } // // Path: src/main/java/tutorial/storm/trident/testutil/FakeTweetsBatchSpout.java // @SuppressWarnings({"serial", "rawtypes"}) // public class FakeTweetsBatchSpout implements IBatchSpout { // private static final AtomicInteger seq = new AtomicInteger(); // // private int batchSize; // private FakeTweetGenerator fakeTweetGenerator; // // // public FakeTweetsBatchSpout() throws IOException { // this(5); // } // // public FakeTweetsBatchSpout(int batchSize) throws IOException { // this.batchSize = batchSize; // } // // @SuppressWarnings("unchecked") // @Override // public void open(Map conf, TopologyContext context) { // // init // System.err.println(this.getClass().getSimpleName() +":" + seq.incrementAndGet()+" opened."); // fakeTweetGenerator = new FakeTweetGenerator(); // // } // // @Override // public void emitBatch(long batchId, TridentCollector collector) { // // emit batchSize fake tweets // for (int i = 0; i < batchSize; i++) { // collector.emit(fakeTweetGenerator.getNextTweet()); // } // } // // @Override // public void ack(long batchId) { // // nothing to do here // } // // @Override // public void close() { // // nothing to do here // } // // @Override // public Map getComponentConfiguration() { // // no particular configuration here // return new Config(); // } // // @Override // public Fields getOutputFields() { // return new Fields("id", "text", "actor", "location", "date"); // } // } // Path: src/main/java/tutorial/storm/trident/Part01_BasicPrimitives.java import backtype.storm.Config; import backtype.storm.LocalCluster; import backtype.storm.generated.StormTopology; import backtype.storm.tuple.Fields; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import storm.trident.TridentTopology; import storm.trident.operation.builtin.Count; import storm.trident.spout.IBatchSpout; import storm.trident.testing.MemoryMapState; import tutorial.storm.trident.operations.Print; import tutorial.storm.trident.operations.RegexFilter; import tutorial.storm.trident.operations.ToUpperCase; import tutorial.storm.trident.testutil.FakeTweetsBatchSpout; import java.io.IOException; package tutorial.storm.trident; /** * @author Enno Shioji (enno.shioji@peerindex.com) */ public class Part01_BasicPrimitives { private static final Logger log = LoggerFactory.getLogger(Part01_BasicPrimitives.class); public static void main(String[] args) throws Exception { // Storm can be run locally for testing purposes Config conf = new Config(); // conf.put(Config.TOPOLOGY_DEBUG,true); LocalCluster cluster = new LocalCluster(); cluster.submitTopology("basic_primitives", conf, basicPrimitives(new FakeTweetsBatchSpout())); Thread.sleep(100000); } public static StormTopology basicPrimitives(IBatchSpout spout) throws IOException { // A topology is a set of streams. // A stream is a DAG of Spouts and Bolts. // (In Storm there are Spouts (data producers) and Bolts (data processors). // Spouts create Tuples and Bolts manipulate then and possibly emit new ones.) // But in Trident we operate at a higher level. // Bolts are created and connected automatically out of higher-level constructs. // Also, Spouts are "batched". TridentTopology topology = new TridentTopology(); // The "each" primitive allows us to apply either filters or functions to the stream // We always have to select the input fields. topology .newStream("filter", spout) .each(new Fields("actor"), new RegexFilter("pere"))
.each(new Fields("text", "actor"), new Print());
eshioji/trident-tutorial
src/main/java/tutorial/storm/trident/Part01_BasicPrimitives.java
// Path: src/main/java/tutorial/storm/trident/operations/Print.java // public class Print extends BaseFilter { // private int partitionIndex; // private int numPartitions; // private final String name; // // public Print(){ // name = ""; // } // public Print(String name){ // this.name = name; // } // // @Override // public void prepare(Map conf, TridentOperationContext context) { // this.partitionIndex = context.getPartitionIndex(); // this.numPartitions = context.numPartitions(); // } // // // @Override // public boolean isKeep(TridentTuple tuple) { // System.err.println(String.format("%s::Partition idx: %s out of %s partitions got %s", name, partitionIndex, numPartitions, tuple.toString())); // return true; // } // } // // Path: src/main/java/tutorial/storm/trident/operations/RegexFilter.java // public class RegexFilter extends BaseFilter { // private final Pattern pattern; // // public RegexFilter(String pattern) { // this.pattern = Pattern.compile(pattern); // } // // @Override // public boolean isKeep(TridentTuple tuple) { // // String string = tuple.getString(0); // return pattern.matcher(string).matches(); // } // } // // Path: src/main/java/tutorial/storm/trident/operations/ToUpperCase.java // @SuppressWarnings("serial") // public class ToUpperCase extends BaseFunction { // // @Override // public void execute(TridentTuple tuple, TridentCollector collector) { // collector.emit(new Values(tuple.getString(0).toUpperCase())); // } // } // // Path: src/main/java/tutorial/storm/trident/testutil/FakeTweetsBatchSpout.java // @SuppressWarnings({"serial", "rawtypes"}) // public class FakeTweetsBatchSpout implements IBatchSpout { // private static final AtomicInteger seq = new AtomicInteger(); // // private int batchSize; // private FakeTweetGenerator fakeTweetGenerator; // // // public FakeTweetsBatchSpout() throws IOException { // this(5); // } // // public FakeTweetsBatchSpout(int batchSize) throws IOException { // this.batchSize = batchSize; // } // // @SuppressWarnings("unchecked") // @Override // public void open(Map conf, TopologyContext context) { // // init // System.err.println(this.getClass().getSimpleName() +":" + seq.incrementAndGet()+" opened."); // fakeTweetGenerator = new FakeTweetGenerator(); // // } // // @Override // public void emitBatch(long batchId, TridentCollector collector) { // // emit batchSize fake tweets // for (int i = 0; i < batchSize; i++) { // collector.emit(fakeTweetGenerator.getNextTweet()); // } // } // // @Override // public void ack(long batchId) { // // nothing to do here // } // // @Override // public void close() { // // nothing to do here // } // // @Override // public Map getComponentConfiguration() { // // no particular configuration here // return new Config(); // } // // @Override // public Fields getOutputFields() { // return new Fields("id", "text", "actor", "location", "date"); // } // }
import backtype.storm.Config; import backtype.storm.LocalCluster; import backtype.storm.generated.StormTopology; import backtype.storm.tuple.Fields; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import storm.trident.TridentTopology; import storm.trident.operation.builtin.Count; import storm.trident.spout.IBatchSpout; import storm.trident.testing.MemoryMapState; import tutorial.storm.trident.operations.Print; import tutorial.storm.trident.operations.RegexFilter; import tutorial.storm.trident.operations.ToUpperCase; import tutorial.storm.trident.testutil.FakeTweetsBatchSpout; import java.io.IOException;
package tutorial.storm.trident; /** * @author Enno Shioji (enno.shioji@peerindex.com) */ public class Part01_BasicPrimitives { private static final Logger log = LoggerFactory.getLogger(Part01_BasicPrimitives.class); public static void main(String[] args) throws Exception { // Storm can be run locally for testing purposes Config conf = new Config(); // conf.put(Config.TOPOLOGY_DEBUG,true); LocalCluster cluster = new LocalCluster(); cluster.submitTopology("basic_primitives", conf, basicPrimitives(new FakeTweetsBatchSpout())); Thread.sleep(100000); } public static StormTopology basicPrimitives(IBatchSpout spout) throws IOException { // A topology is a set of streams. // A stream is a DAG of Spouts and Bolts. // (In Storm there are Spouts (data producers) and Bolts (data processors). // Spouts create Tuples and Bolts manipulate then and possibly emit new ones.) // But in Trident we operate at a higher level. // Bolts are created and connected automatically out of higher-level constructs. // Also, Spouts are "batched". TridentTopology topology = new TridentTopology(); // The "each" primitive allows us to apply either filters or functions to the stream // We always have to select the input fields. topology .newStream("filter", spout) .each(new Fields("actor"), new RegexFilter("pere")) .each(new Fields("text", "actor"), new Print()); // Functions describe their output fields, which are always appended to the input fields. // As you see, Each operations can be chained. topology .newStream("function", spout)
// Path: src/main/java/tutorial/storm/trident/operations/Print.java // public class Print extends BaseFilter { // private int partitionIndex; // private int numPartitions; // private final String name; // // public Print(){ // name = ""; // } // public Print(String name){ // this.name = name; // } // // @Override // public void prepare(Map conf, TridentOperationContext context) { // this.partitionIndex = context.getPartitionIndex(); // this.numPartitions = context.numPartitions(); // } // // // @Override // public boolean isKeep(TridentTuple tuple) { // System.err.println(String.format("%s::Partition idx: %s out of %s partitions got %s", name, partitionIndex, numPartitions, tuple.toString())); // return true; // } // } // // Path: src/main/java/tutorial/storm/trident/operations/RegexFilter.java // public class RegexFilter extends BaseFilter { // private final Pattern pattern; // // public RegexFilter(String pattern) { // this.pattern = Pattern.compile(pattern); // } // // @Override // public boolean isKeep(TridentTuple tuple) { // // String string = tuple.getString(0); // return pattern.matcher(string).matches(); // } // } // // Path: src/main/java/tutorial/storm/trident/operations/ToUpperCase.java // @SuppressWarnings("serial") // public class ToUpperCase extends BaseFunction { // // @Override // public void execute(TridentTuple tuple, TridentCollector collector) { // collector.emit(new Values(tuple.getString(0).toUpperCase())); // } // } // // Path: src/main/java/tutorial/storm/trident/testutil/FakeTweetsBatchSpout.java // @SuppressWarnings({"serial", "rawtypes"}) // public class FakeTweetsBatchSpout implements IBatchSpout { // private static final AtomicInteger seq = new AtomicInteger(); // // private int batchSize; // private FakeTweetGenerator fakeTweetGenerator; // // // public FakeTweetsBatchSpout() throws IOException { // this(5); // } // // public FakeTweetsBatchSpout(int batchSize) throws IOException { // this.batchSize = batchSize; // } // // @SuppressWarnings("unchecked") // @Override // public void open(Map conf, TopologyContext context) { // // init // System.err.println(this.getClass().getSimpleName() +":" + seq.incrementAndGet()+" opened."); // fakeTweetGenerator = new FakeTweetGenerator(); // // } // // @Override // public void emitBatch(long batchId, TridentCollector collector) { // // emit batchSize fake tweets // for (int i = 0; i < batchSize; i++) { // collector.emit(fakeTweetGenerator.getNextTweet()); // } // } // // @Override // public void ack(long batchId) { // // nothing to do here // } // // @Override // public void close() { // // nothing to do here // } // // @Override // public Map getComponentConfiguration() { // // no particular configuration here // return new Config(); // } // // @Override // public Fields getOutputFields() { // return new Fields("id", "text", "actor", "location", "date"); // } // } // Path: src/main/java/tutorial/storm/trident/Part01_BasicPrimitives.java import backtype.storm.Config; import backtype.storm.LocalCluster; import backtype.storm.generated.StormTopology; import backtype.storm.tuple.Fields; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import storm.trident.TridentTopology; import storm.trident.operation.builtin.Count; import storm.trident.spout.IBatchSpout; import storm.trident.testing.MemoryMapState; import tutorial.storm.trident.operations.Print; import tutorial.storm.trident.operations.RegexFilter; import tutorial.storm.trident.operations.ToUpperCase; import tutorial.storm.trident.testutil.FakeTweetsBatchSpout; import java.io.IOException; package tutorial.storm.trident; /** * @author Enno Shioji (enno.shioji@peerindex.com) */ public class Part01_BasicPrimitives { private static final Logger log = LoggerFactory.getLogger(Part01_BasicPrimitives.class); public static void main(String[] args) throws Exception { // Storm can be run locally for testing purposes Config conf = new Config(); // conf.put(Config.TOPOLOGY_DEBUG,true); LocalCluster cluster = new LocalCluster(); cluster.submitTopology("basic_primitives", conf, basicPrimitives(new FakeTweetsBatchSpout())); Thread.sleep(100000); } public static StormTopology basicPrimitives(IBatchSpout spout) throws IOException { // A topology is a set of streams. // A stream is a DAG of Spouts and Bolts. // (In Storm there are Spouts (data producers) and Bolts (data processors). // Spouts create Tuples and Bolts manipulate then and possibly emit new ones.) // But in Trident we operate at a higher level. // Bolts are created and connected automatically out of higher-level constructs. // Also, Spouts are "batched". TridentTopology topology = new TridentTopology(); // The "each" primitive allows us to apply either filters or functions to the stream // We always have to select the input fields. topology .newStream("filter", spout) .each(new Fields("actor"), new RegexFilter("pere")) .each(new Fields("text", "actor"), new Print()); // Functions describe their output fields, which are always appended to the input fields. // As you see, Each operations can be chained. topology .newStream("function", spout)
.each(new Fields("text"), new ToUpperCase(), new Fields("uppercased_text"))
eshioji/trident-tutorial
src/main/java/tutorial/storm/trident/operations/OnlyUrls.java
// Path: src/main/java/tutorial/storm/trident/testutil/Content.java // public class Content { // private static final Logger log = LoggerFactory.getLogger(Content.class); // // private long tweetId; // private long userId; // private long createdAtMs; // // private String contentName; // private String contentType; // // public Content(long tweetId, long userId, long createdAtMs) { // this.tweetId = tweetId; // this.userId = userId; // this.createdAtMs = createdAtMs; // } // // public String getContentId(){ // HashFunction md5 = Hashing.md5(); // return md5.hashString(contentType + contentName).toString(); // } // // public String getContentName() { // return contentName; // } // // public void setContentName(String contentName) { // this.contentName = contentName; // } // // public void setContentType(String contentType) { // this.contentType = contentType; // } // // public long getTweetId() { // return tweetId; // } // // public void setTweetId(long tweetId) { // this.tweetId = tweetId; // } // // public long getUserId() { // return userId; // } // // public void setUserId(long userId) { // this.userId = userId; // } // // public long getCreatedAtMs() { // return createdAtMs; // } // // public void setCreatedAtMs(long createdAtMs) { // this.createdAtMs = createdAtMs; // } // // @Override // public String toString() { // return "Content{" + // "contentType='" + contentType + '\'' + // ", contentName='" + contentName + '\'' + // '}'; // } // // public String getContentType() { // return contentType; // } // }
import storm.trident.operation.BaseFilter; import storm.trident.tuple.TridentTuple; import tutorial.storm.trident.testutil.Content;
package tutorial.storm.trident.operations; /** * @author Enno Shioji (enno.shioji@peerindex.com) */ public class OnlyUrls extends BaseFilter { @Override public boolean isKeep(TridentTuple tuple) {
// Path: src/main/java/tutorial/storm/trident/testutil/Content.java // public class Content { // private static final Logger log = LoggerFactory.getLogger(Content.class); // // private long tweetId; // private long userId; // private long createdAtMs; // // private String contentName; // private String contentType; // // public Content(long tweetId, long userId, long createdAtMs) { // this.tweetId = tweetId; // this.userId = userId; // this.createdAtMs = createdAtMs; // } // // public String getContentId(){ // HashFunction md5 = Hashing.md5(); // return md5.hashString(contentType + contentName).toString(); // } // // public String getContentName() { // return contentName; // } // // public void setContentName(String contentName) { // this.contentName = contentName; // } // // public void setContentType(String contentType) { // this.contentType = contentType; // } // // public long getTweetId() { // return tweetId; // } // // public void setTweetId(long tweetId) { // this.tweetId = tweetId; // } // // public long getUserId() { // return userId; // } // // public void setUserId(long userId) { // this.userId = userId; // } // // public long getCreatedAtMs() { // return createdAtMs; // } // // public void setCreatedAtMs(long createdAtMs) { // this.createdAtMs = createdAtMs; // } // // @Override // public String toString() { // return "Content{" + // "contentType='" + contentType + '\'' + // ", contentName='" + contentName + '\'' + // '}'; // } // // public String getContentType() { // return contentType; // } // } // Path: src/main/java/tutorial/storm/trident/operations/OnlyUrls.java import storm.trident.operation.BaseFilter; import storm.trident.tuple.TridentTuple; import tutorial.storm.trident.testutil.Content; package tutorial.storm.trident.operations; /** * @author Enno Shioji (enno.shioji@peerindex.com) */ public class OnlyUrls extends BaseFilter { @Override public boolean isKeep(TridentTuple tuple) {
Content content = (Content) tuple.getValueByField("content");