file_name
stringlengths
6
86
file_path
stringlengths
45
249
content
stringlengths
47
6.26M
file_size
int64
47
6.26M
language
stringclasses
1 value
extension
stringclasses
1 value
repo_name
stringclasses
767 values
repo_stars
int64
8
14.4k
repo_forks
int64
0
1.17k
repo_open_issues
int64
0
788
repo_created_at
stringclasses
767 values
repo_pushed_at
stringclasses
767 values
PoseLandmarkTest.java
/FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/androidTest/java/hcm/ssj/PoseLandmarkTest.java
/* * LandmarkTest.java * Copyright (c) 2021 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library is free software; you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj; import org.junit.Test; import org.junit.runner.RunWith; import androidx.test.filters.SmallTest; import androidx.test.runner.AndroidJUnit4; import hcm.ssj.camera.CameraChannel; import hcm.ssj.camera.CameraSensor; import hcm.ssj.camera.NV21ToRGBDecoder; import hcm.ssj.core.Cons; import hcm.ssj.core.Pipeline; import hcm.ssj.landmark.PoseLandmarks; import hcm.ssj.test.Logger; /** * Created by Michael Dietz on 04.02.2021. */ @RunWith(AndroidJUnit4.class) @SmallTest public class PoseLandmarkTest { @Test public void testPoseLandmarks() throws Exception { // Get pipeline instance Pipeline frame = Pipeline.getInstance(); frame.options.bufferSize.set(10.0f); // Instantiate camera sensor and set options CameraSensor cameraSensor = new CameraSensor(); cameraSensor.options.cameraType.set(Cons.CameraType.FRONT_CAMERA); cameraSensor.options.width.set(640); cameraSensor.options.height.set(480); cameraSensor.options.previewFpsRangeMin.set(15); cameraSensor.options.previewFpsRangeMax.set(15); // Add sensor to the pipeline CameraChannel cameraChannel = new CameraChannel(); cameraChannel.options.sampleRate.set(10.0); frame.addSensor(cameraSensor, cameraChannel); // Set up a NV21 decoder NV21ToRGBDecoder decoder = new NV21ToRGBDecoder(); frame.addTransformer(decoder, cameraChannel); // Add pose landmarks PoseLandmarks poseLandmarks = new PoseLandmarks(); poseLandmarks.options.rotation.set(0); frame.addTransformer(poseLandmarks, decoder); Logger log = new Logger(); frame.addConsumer(log, poseLandmarks); // Start pipeline frame.start(); // Wait duration try { Thread.sleep(TestHelper.DUR_TEST_NORMAL); } catch (Exception e) { e.printStackTrace(); } // Stop pipeline frame.stop(); frame.release(); } }
3,164
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
SSIEmoVoiceTest.java
/FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/androidTest/java/hcm/ssj/SSIEmoVoiceTest.java
/* * SSIEmoVoiceTest.java * Copyright (c) 2018 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library is free software; you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj; import androidx.test.filters.SmallTest; import androidx.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import java.io.File; import hcm.ssj.audio.AudioChannel; import hcm.ssj.audio.Microphone; import hcm.ssj.core.Pipeline; import hcm.ssj.ml.ClassifierT; import hcm.ssj.ml.NaiveBayes; import hcm.ssj.mobileSSI.SSI; import hcm.ssj.mobileSSI.SSITransformer; import hcm.ssj.test.Logger; import static androidx.test.InstrumentationRegistry.getContext; /** * Tests ssi emovoice component. Uses emovoice features and a simple naive bayes model to predict * positive or negative speech. * Created by Michael Dietz on 03.12.2018. */ @RunWith(AndroidJUnit4.class) @SmallTest public class SSIEmoVoiceTest { @Test public void testEmoVoice() throws Exception { // Copy model resources File dir = getContext().getFilesDir(); String modelName = "emovoice.trainer"; TestHelper.copyAssetToFile(modelName, new File(dir, modelName)); TestHelper.copyAssetToFile("emovoice.model", new File(dir, "emovoice.model")); // Setup framework Pipeline frame = Pipeline.getInstance(); frame.options.bufferSize.set(10.0f); // Sensor Microphone microphone = new Microphone(); AudioChannel audioChannel = new AudioChannel(); audioChannel.options.sampleRate.set(8000); audioChannel.options.scale.set(true); frame.addSensor(microphone, audioChannel); // Feature transformer SSITransformer emovoiceFeatures = new SSITransformer(); emovoiceFeatures.options.name.set(SSI.TransformerName.EmoVoiceFeat); emovoiceFeatures.options.ssioptions.set(new String[]{"maj->1", "min->0"}); frame.addTransformer(emovoiceFeatures, audioChannel, 1.35); // Classifier NaiveBayes naiveBayes = new NaiveBayes(); naiveBayes.options.file.setValue(dir.getAbsolutePath() + File.separator + modelName); frame.addModel(naiveBayes); ClassifierT classifier = new ClassifierT(); classifier.setModel(naiveBayes); frame.addTransformer(classifier, emovoiceFeatures, 1.35, 0); // Logger Logger log = new Logger(); //frame.addConsumer(log, emovoiceFeatures, 1, 0); frame.addConsumer(log, classifier, 1.35, 0); // Start framework frame.start(); // Run test try { Thread.sleep(TestHelper.DUR_TEST_NORMAL); } catch (Exception e) { e.printStackTrace(); } frame.stop(); frame.release(); } }
3,730
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
BitalinoTest.java
/FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/androidTest/java/hcm/ssj/BitalinoTest.java
/* * BitalinoTest.java * Copyright (c) 2017 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library is free software; you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj; import androidx.test.filters.SmallTest; import androidx.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import hcm.ssj.bitalino.Bitalino; import hcm.ssj.bitalino.LUXChannel; import hcm.ssj.bitalino.PulseChannel; import hcm.ssj.core.Pipeline; import hcm.ssj.test.Logger; /** * Tests all channels of the BITalino sensor.<br> * Created by Ionut Damian */ @RunWith(AndroidJUnit4.class) @SmallTest public class BitalinoTest { /* @Test public void testChannels() throws Exception { // Setup Pipeline frame = Pipeline.getInstance(); frame.options.bufferSize.set(10.0f); // Sensor Bitalino sensor = new Bitalino(); sensor.options.sr.set(10); sensor.options.name.set("BITalino-17-44"); LUXChannel lux = new LUXChannel(); frame.addSensor(sensor, lux); // Logger Logger logger = new Logger(); frame.addConsumer(logger, lux, 0.1, 0); // Start framework frame.start(); // Wait duration try { Thread.sleep(TestHelper.DUR_TEST_NORMAL); } catch (Exception e) { e.printStackTrace(); } // Stop framework frame.stop(); frame.clear(); } */ @Test public void testPulseChannel() throws Exception { // Setup Pipeline pipeline = Pipeline.getInstance(); // Sensor Bitalino sensor = new Bitalino(); sensor.options.sr.set(10); sensor.options.address.set("20:18:05:28:47:08"); PulseChannel channel = new PulseChannel(); channel.options.channel.set(0); // Logger Logger logger = new Logger(); pipeline.addSensor(sensor, channel); pipeline.addConsumer(logger, channel); // Start framework pipeline.start(); // Wait duration try { Thread.sleep(TestHelper.DUR_TEST_NORMAL); } catch (Exception e) { e.printStackTrace(); } // Stop framework pipeline.stop(); pipeline.clear(); } }
3,189
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
MSBandTest.java
/FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/androidTest/java/hcm/ssj/MSBandTest.java
/* * MSBandTest.java * Copyright (c) 2017 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library is free software; you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj; import androidx.test.filters.SmallTest; import androidx.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import hcm.ssj.core.Pipeline; import hcm.ssj.msband.AccelerationChannel; import hcm.ssj.msband.AltimeterChannel; import hcm.ssj.msband.BarometerChannel; import hcm.ssj.msband.BrightnessChannel; import hcm.ssj.msband.CaloriesChannel; import hcm.ssj.msband.DistanceChannel; import hcm.ssj.msband.GSRChannel; import hcm.ssj.msband.GyroscopeChannel; import hcm.ssj.msband.HeartRateChannel; import hcm.ssj.msband.IBIChannel; import hcm.ssj.msband.MSBand; import hcm.ssj.msband.PedometerChannel; import hcm.ssj.msband.SkinTempChannel; import hcm.ssj.test.Logger; /** * Tests all channels of the MS Band.<br> * Created by Ionut Damian */ @RunWith(AndroidJUnit4.class) @SmallTest public class MSBandTest { @Test public void testChannels() throws Exception { // Setup Pipeline frame = Pipeline.getInstance(); frame.options.bufferSize.set(10.0f); // Sensor MSBand sensor = new MSBand(); frame.addConsumer(new Logger(), frame.addSensor(sensor, new DistanceChannel()), 1, 0); frame.addConsumer(new Logger(), frame.addSensor(sensor, new BarometerChannel()), 1, 0); frame.addConsumer(new Logger(), frame.addSensor(sensor, new BrightnessChannel()), 1, 0); frame.addConsumer(new Logger(), frame.addSensor(sensor, new AccelerationChannel()), 1, 0); frame.addConsumer(new Logger(), frame.addSensor(sensor, new AltimeterChannel()), 1, 0); frame.addConsumer(new Logger(), frame.addSensor(sensor, new CaloriesChannel()), 1, 0); frame.addConsumer(new Logger(), frame.addSensor(sensor, new GSRChannel()), 1, 0); frame.addConsumer(new Logger(), frame.addSensor(sensor, new GyroscopeChannel()), 1, 0); frame.addConsumer(new Logger(), frame.addSensor(sensor, new HeartRateChannel()), 1, 0); frame.addConsumer(new Logger(), frame.addSensor(sensor, new IBIChannel()), 1, 0); frame.addConsumer(new Logger(), frame.addSensor(sensor, new PedometerChannel()), 1, 0); frame.addConsumer(new Logger(), frame.addSensor(sensor, new SkinTempChannel()), 1, 0); // Start framework frame.start(); // Wait duration try { Thread.sleep(TestHelper.DUR_TEST_NORMAL); } catch (Exception e) { e.printStackTrace(); } // Stop framework frame.stop(); frame.clear(); } }
3,705
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
InceptionTest.java
/FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/androidTest/java/hcm/ssj/InceptionTest.java
/* * InceptionTest.java * Copyright (c) 2017 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library is free software; you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj; import androidx.test.filters.SmallTest; import androidx.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import java.io.File; import hcm.ssj.camera.CameraChannel; import hcm.ssj.camera.CameraSensor; import hcm.ssj.camera.ImageNormalizer; import hcm.ssj.camera.ImageResizer; import hcm.ssj.camera.NV21ToRGBDecoder; import hcm.ssj.core.Cons; import hcm.ssj.core.EventChannel; import hcm.ssj.core.Pipeline; import hcm.ssj.ml.Classifier; import hcm.ssj.ml.TensorFlow; import hcm.ssj.test.EventLogger; /** * Tests setting up, loading, and evaluating object classification * with the Inception model. * * @author Vitaly */ @RunWith(AndroidJUnit4.class) @SmallTest public class InceptionTest { @Test public void loadInceptionModel() throws Exception { String trainerName = "inception.trainer"; String trainerURL = "https://hcm-lab.de/downloads/ssj/model"; // Option parameters for camera sensor double sampleRate = 1; int width = 640; int height = 480; final float IMAGE_MEAN = 127.5f; final float IMAGE_STD = 1; final int CROP_SIZE = 224; final boolean MAINTAIN_ASPECT = true; // Get pipeline instance Pipeline frame = Pipeline.getInstance(); frame.options.bufferSize.set(10.0f); // Instantiate camera sensor and set options CameraSensor cameraSensor = new CameraSensor(); cameraSensor.options.cameraType.set(Cons.CameraType.BACK_CAMERA); cameraSensor.options.width.set(width); cameraSensor.options.height.set(height); cameraSensor.options.previewFpsRangeMin.set(15); cameraSensor.options.previewFpsRangeMax.set(15); // Add sensor to the pipeline CameraChannel cameraChannel = new CameraChannel(); cameraChannel.options.sampleRate.set(sampleRate); frame.addSensor(cameraSensor, cameraChannel); // Set up a NV21 decoder NV21ToRGBDecoder decoder = new NV21ToRGBDecoder(); frame.addTransformer(decoder, cameraChannel, 1, 0); // Add image resizer to the pipeline ImageResizer resizer = new ImageResizer(); resizer.options.maintainAspect.set(MAINTAIN_ASPECT); resizer.options.size.set(CROP_SIZE); resizer.options.rotation.set(90); frame.addTransformer(resizer, decoder, 1, 0); // Add image pixel value normalizer to the pipeline ImageNormalizer imageNormalizer = new ImageNormalizer(); imageNormalizer.options.imageMean.set(IMAGE_MEAN); imageNormalizer.options.imageStd.set(IMAGE_STD); frame.addTransformer(imageNormalizer, resizer, 1, 0); TensorFlow tensorFlow = new TensorFlow(); tensorFlow.options.file.setValue(trainerURL + File.separator + trainerName); frame.addModel(tensorFlow); // Add classifier transformer to the pipeline Classifier classifier = new Classifier(); classifier.setModel(tensorFlow); classifier.options.merge.set(false); classifier.options.bestMatchOnly.set(true); frame.addConsumer(classifier, imageNormalizer, 1, 0); // Log events EventChannel channel = classifier.getEventChannelOut(); EventLogger log = new EventLogger(); frame.registerEventListener(log, channel); // Start pipeline frame.start(); // Wait duration try { Thread.sleep(TestHelper.DUR_TEST_NORMAL); } catch (Exception e) { e.printStackTrace(); } // Stop pipeline frame.stop(); frame.release(); } }
4,642
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
SamsungTest.java
/FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/androidTest/java/hcm/ssj/SamsungTest.java
/* * PolarTest.java * Copyright (c) 2021 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library is free software; you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj; import org.junit.Test; import org.junit.runner.RunWith; import androidx.test.filters.SmallTest; import androidx.test.runner.AndroidJUnit4; import hcm.ssj.core.Pipeline; import hcm.ssj.polar.PolarECGChannel; import hcm.ssj.polar.Polar; import hcm.ssj.samsung.SamsungHRChannel; import hcm.ssj.samsung.SamsungWearable; import hcm.ssj.test.Logger; /** * Created by Michael Dietz on 08.04.2021. */ @RunWith(AndroidJUnit4.class) @SmallTest public class SamsungTest { @Test public void testSensor() throws Exception { // Setup Pipeline frame = Pipeline.getInstance(); frame.options.bufferSize.set(10.0f); SamsungWearable sensor = new SamsungWearable(); SamsungHRChannel channel = new SamsungHRChannel(); frame.addSensor(sensor, channel); Logger logger = new Logger(); frame.addConsumer(logger, channel); // Start framework frame.start(); // Wait duration try { Thread.sleep(TestHelper.DUR_TEST_NORMAL * 5); } catch (Exception e) { e.printStackTrace(); } // Stop framework frame.stop(); frame.clear(); } }
2,423
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
OpenSmileTest.java
/FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/androidTest/java/hcm/ssj/OpenSmileTest.java
/* * OpenSmileTest.java * Copyright (c) 2021 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library is free software; you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj; import android.os.Environment; import org.junit.Test; import org.junit.runner.RunWith; import java.io.File; import androidx.test.filters.SmallTest; import androidx.test.runner.AndroidJUnit4; import hcm.ssj.audio.AudioChannel; import hcm.ssj.audio.Microphone; import hcm.ssj.core.Pipeline; import hcm.ssj.core.Provider; import hcm.ssj.core.SSJException; import hcm.ssj.core.option.FilePath; import hcm.ssj.opensmile.OpenSmileFeatures; import hcm.ssj.test.Logger; /** * Created by Michael Dietz on 05.05.2021. */ @RunWith(AndroidJUnit4.class) @SmallTest public class OpenSmileTest { @Test public void testOpenSMILE() throws SSJException { // Setup Pipeline frame = Pipeline.getInstance(); frame.options.bufferSize.set(10.0f); // Sensor Microphone microphone = new Microphone(); AudioChannel audio = new AudioChannel(); audio.options.sampleRate.set(16000); audio.options.chunk.set(0.1); audio.options.scale.set(true); frame.addSensor(microphone, audio); OpenSmileFeatures openSmileFeatures = new OpenSmileFeatures(); openSmileFeatures.options.showLog.set(true); frame.addTransformer(openSmileFeatures, audio); /* OpenSmileFeatures openSmileFeatures2 = new OpenSmileFeatures(); openSmileFeatures2.options.configFile.set(new FilePath(new File(Environment.getExternalStorageDirectory(), "SSJ").getPath() + File.separator + "configs" + File.separator + "opensmile_custom.conf")); openSmileFeatures2.options.featureCount.set(3); frame.addTransformer(openSmileFeatures2, audio); */ Logger logger = new Logger(); frame.addConsumer(logger, new Provider[] {openSmileFeatures}); // Start framework frame.start(); // Wait duration try { Thread.sleep(TestHelper.DUR_TEST_NORMAL); } catch (Exception e) { e.printStackTrace(); } // Stop framework frame.stop(); frame.release(); } }
3,223
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
NetsyncTest.java
/FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/androidTest/java/hcm/ssj/NetsyncTest.java
/* * NetsyncTest.java * Copyright (c) 2017 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library is free software; you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj; import androidx.test.filters.SmallTest; import androidx.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import hcm.ssj.audio.AudioChannel; import hcm.ssj.audio.Microphone; import hcm.ssj.core.Log; import hcm.ssj.core.Pipeline; import hcm.ssj.test.Logger; @RunWith(AndroidJUnit4.class) @SmallTest public class NetsyncTest { @Test public void testListen() throws Exception { Pipeline frame = Pipeline.getInstance(); frame.options.bufferSize.set(10.0f); frame.options.sync.set(Pipeline.SyncType.CONTINUOUS); frame.options.syncPort.set(55100); frame.options.syncHost.set("192.168.0.180"); Microphone mic = new Microphone(); AudioChannel audio = new AudioChannel(); audio.options.sampleRate.set(16000); audio.options.scale.set(true); frame.addSensor(mic, audio); Logger dummy = new Logger(); dummy.options.reduceNum.set(true); frame.addConsumer(dummy, audio, 0.1, 0); /* BluetoothWriter blw = new BluetoothWriter(); blw.options.connectionType = BluetoothConnection.Type.CLIENT; blw.options.serverAddr = "60:8F:5C:F2:D0:9D"; blw.options.connectionName = "stream"; frame.addConsumer(blw, audio, 0.1, 0); FloatsEventSender fes = new FloatsEventSender(); frame.addConsumer(fes, audio, 1.0, 0); EventChannel ch = frame.registerEventChannel(fes); BluetoothEventWriter blew = new BluetoothEventWriter(); blew.options.connectionType = BluetoothConnection.Type.CLIENT; blew.options.serverAddr = "60:8F:5C:F2:D0:9D"; blew.options.connectionName = "event"; frame.registerEventListener(blew); frame.registerEventListener(blew, ch); */ frame.start(); // Wait duration try { Thread.sleep(TestHelper.DUR_TEST_LONG); } catch (Exception e) { e.printStackTrace(); } frame.stop(); Log.i("test finished"); } @Test public void testMaster() throws Exception { Pipeline frame = Pipeline.getInstance(); frame.options.bufferSize.set(10.0f); frame.options.sync.set(Pipeline.SyncType.CONTINUOUS); frame.options.syncPort.set(55100); frame.options.syncHost.set(null); //this is the syncHost /* BluetoothReader blr = new BluetoothReader(); blr.options.connectionType = BluetoothConnection.Type.SERVER; blr.options.connectionName = "stream"; BluetoothChannel data = new BluetoothChannel(); data.options.dim = 1; data.options.type = Cons.Type.FLOAT; data.options.sr = 16000; frame.addSensor(blr,data); */ Microphone mic = new Microphone(); AudioChannel audio = new AudioChannel(); audio.options.sampleRate.set(16000); audio.options.scale.set(true); frame.addSensor(mic, audio); Logger dummy = new Logger(); dummy.options.reduceNum.set(true); frame.addConsumer(dummy, audio, 0.1, 0); /* BluetoothEventReader bler = new BluetoothEventReader(); bler.options.connectionType = BluetoothConnection.Type.SERVER; bler.options.connectionName = "event"; frame.registerEventListener(bler); EventChannel ch = frame.registerEventChannel(bler); EventLogger evlog = new EventLogger(); frame.registerEventListener(evlog); frame.registerEventListener(evlog, ch); */ frame.start(); // Wait duration try { Thread.sleep(TestHelper.DUR_TEST_NORMAL); } catch (Exception e) { e.printStackTrace(); } frame.stop(); Log.i("test finished"); } }
4,872
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
EventTest.java
/FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/androidTest/java/hcm/ssj/EventTest.java
/* * EventTest.java * Copyright (c) 2017 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library is free software; you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj; import androidx.test.filters.SmallTest; import androidx.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import java.io.File; import hcm.ssj.androidSensor.AndroidSensor; import hcm.ssj.androidSensor.AndroidSensorChannel; import hcm.ssj.androidSensor.SensorType; import hcm.ssj.audio.Intensity; import hcm.ssj.core.EventChannel; import hcm.ssj.core.Pipeline; import hcm.ssj.core.Provider; import hcm.ssj.event.FloatSegmentEventSender; import hcm.ssj.event.FloatsEventSender; import hcm.ssj.event.ThresholdEventSender; import hcm.ssj.event.ValueEventSender; import hcm.ssj.file.FileReader; import hcm.ssj.file.FileReaderChannel; import hcm.ssj.ioput.SocketEventReader; import hcm.ssj.ioput.SocketEventWriter; import hcm.ssj.test.EventLogger; import static androidx.test.InstrumentationRegistry.getContext; @RunWith(AndroidJUnit4.class) @SmallTest public class EventTest { @Test public void testFloatsEventSender() throws Exception { Pipeline frame = Pipeline.getInstance(); frame.options.bufferSize.set(10.0f); AndroidSensor sensor = new AndroidSensor(); AndroidSensorChannel acc = new AndroidSensorChannel(); acc.options.sensorType.set(SensorType.ACCELEROMETER); acc.options.sampleRate.set(40); frame.addSensor(sensor, acc); FloatsEventSender evs = new FloatsEventSender(); evs.options.mean.set(true); frame.addConsumer(evs, acc, 1.0, 0); EventChannel channel = evs.getEventChannelOut(); EventLogger log = new EventLogger(); frame.registerEventListener(log, channel); frame.start(); // Wait duration try { Thread.sleep(TestHelper.DUR_TEST_NORMAL); } catch (Exception e) { e.printStackTrace(); } frame.stop(); frame.release(); } public void testThresholds() throws Exception { File dir = getContext().getFilesDir(); String fileName = "audio.stream"; File header = new File(dir, fileName); TestHelper.copyAssetToFile(fileName, header); File data = new File(dir, fileName + "~"); TestHelper.copyAssetToFile(fileName + "data", data); //android does not support "~" in asset files // Setup Pipeline frame = Pipeline.getInstance(); frame.options.bufferSize.set(10.0f); frame.options.countdown.set(0); frame.options.log.set(true); // Sensor FileReader file = new FileReader(); file.options.file.setValue(dir.getAbsolutePath() + File.separator + fileName); FileReaderChannel audio = new FileReaderChannel(); audio.options.chunk.set(0.032); audio.setWatchInterval(0); audio.setSyncInterval(0); frame.addSensor(file, audio); Intensity energy = new Intensity(); frame.addTransformer(energy, audio, 1.0, 0); ThresholdEventSender vad = new ThresholdEventSender(); vad.options.thresin.set(new float[]{50.0f}); //SPL vad.options.mindur.set(1.0); vad.options.maxdur.set(9.0); vad.options.hangin.set(3); vad.options.hangout.set(5); Provider[] vad_in = {energy}; frame.addConsumer(vad, vad_in, 1.0, 0); EventChannel vad_channel = vad.getEventChannelOut(); FloatSegmentEventSender evs = new FloatSegmentEventSender(); evs.options.mean.set(true); frame.addConsumer(evs, energy, vad_channel); EventChannel channel = evs.getEventChannelOut(); EventLogger log = new EventLogger(); frame.registerEventListener(log, channel); frame.start(); // Wait duration try { Thread.sleep(TestHelper.DUR_TEST_NORMAL); } catch (Exception e) { e.printStackTrace(); } frame.stop(); frame.release(); } @Test public void testSocketEventWriter() throws Exception { Pipeline frame = Pipeline.getInstance(); frame.options.bufferSize.set(10.0f); AndroidSensor sensor = new AndroidSensor(); AndroidSensorChannel acc = new AndroidSensorChannel(); acc.options.sensorType.set(SensorType.ACCELEROMETER); acc.options.sampleRate.set(1); frame.addSensor(sensor, acc); ValueEventSender evs = new ValueEventSender(); frame.addConsumer(evs, acc, 1.0, 0); EventChannel channel = evs.getEventChannelOut(); SocketEventWriter sew = new SocketEventWriter(); //sew.options.ip.set("192.168.2.102"); // Receiver IP sew.options.ip.set("192.168.0.237"); // Receiver IP sew.options.port.set(343); sew.options.sendAsMap.set(true); sew.options.mapKeys.set("f_accX,f_accY,f_accZ"); frame.registerEventListener(sew, channel); SocketEventReader ser = new SocketEventReader(); ser.options.ip.set("192.168.0.169"); // Phone IP ser.options.port.set(6000); ser.options.parseXmlToEvent.set(false); frame.registerEventProvider(ser); EventLogger el = new EventLogger(); frame.registerEventListener(el, ser.getEventChannelOut()); frame.start(); // Wait duration try { Thread.sleep(TestHelper.DUR_TEST_NORMAL); } catch (Exception e) { e.printStackTrace(); } frame.stop(); frame.release(); } }
6,177
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
PolarTest.java
/FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/androidTest/java/hcm/ssj/PolarTest.java
/* * PolarTest.java * Copyright (c) 2021 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library is free software; you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj; import org.junit.Test; import org.junit.runner.RunWith; import java.io.File; import androidx.test.filters.SmallTest; import androidx.test.runner.AndroidJUnit4; import hcm.ssj.core.Pipeline; import hcm.ssj.file.FileWriter; import hcm.ssj.polar.PolarACCChannel; import hcm.ssj.polar.PolarECGChannel; import hcm.ssj.polar.Polar; import hcm.ssj.polar.PolarHRChannel; import hcm.ssj.polar.PolarPPGChannel; import hcm.ssj.test.Logger; /** * Created by Michael Dietz on 08.04.2021. */ @RunWith(AndroidJUnit4.class) @SmallTest public class PolarTest { @Test public void testConnection() throws Exception { // Setup Pipeline frame = Pipeline.getInstance(); frame.options.bufferSize.set(10.0f); Polar sensor = new Polar(); /* * H10: D3:84:E5:34:76:3C * OH1: A0:9E:1A:5E:8A:A0, A0:9E:1A:93:78:3D */ sensor.options.deviceIdentifier.set("A0:9E:1A:93:78:3D"); PolarPPGChannel channel = new PolarPPGChannel(); // PolarACCChannel channel = new PolarACCChannel(); // PolarHRChannel channel = new PolarHRChannel(); //PolarECGChannel channel = new PolarECGChannel(); frame.addSensor(sensor, channel); FileWriter fw = new FileWriter(); fw.options.fileName.set("ppg"); frame.addConsumer(fw, channel); Logger polarLogger = new Logger(); frame.addConsumer(polarLogger, channel); // Start framework frame.start(); // Wait duration try { Thread.sleep(TestHelper.DUR_TEST_NORMAL * 5); } catch (Exception e) { e.printStackTrace(); } // Stop framework frame.stop(); frame.clear(); } }
2,909
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
TFLiteTest.java
/FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/androidTest/java/hcm/ssj/TFLiteTest.java
/* * TFLiteTest.java * Copyright (c) 2019 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library is free software; you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj; import org.junit.Test; import org.junit.runner.RunWith; import java.io.File; import androidx.test.filters.SmallTest; import androidx.test.runner.AndroidJUnit4; import hcm.ssj.camera.CameraChannel; import hcm.ssj.camera.CameraSensor; import hcm.ssj.camera.ImageNormalizer; import hcm.ssj.camera.ImageResizer; import hcm.ssj.camera.NV21ToRGBDecoder; import hcm.ssj.core.Cons; import hcm.ssj.core.EventChannel; import hcm.ssj.core.Pipeline; import hcm.ssj.ml.Classifier; import hcm.ssj.ml.TFLite; import hcm.ssj.ml.TensorFlow; import hcm.ssj.test.EventLogger; /** * Tests setting up, loading, and evaluating object classification * with the MobileNet model. */ @RunWith(AndroidJUnit4.class) @SmallTest public class TFLiteTest { @Test public void loadMobilenetModel() throws Exception { String trainerName = "mobilenet.trainer"; String trainerURL = "https://hcm-lab.de/downloads/ssj/model"; // Option parameters for camera sensor double sampleRate = 1; int width = 640; int height = 480; final float IMAGE_MEAN = 127.5f; final float IMAGE_STD = 127.5f; final int CROP_SIZE = 224; final boolean MAINTAIN_ASPECT = true; // Get pipeline instance Pipeline frame = Pipeline.getInstance(); frame.options.bufferSize.set(10.0f); // Instantiate camera sensor and set options CameraSensor cameraSensor = new CameraSensor(); cameraSensor.options.cameraType.set(Cons.CameraType.FRONT_CAMERA); cameraSensor.options.width.set(width); cameraSensor.options.height.set(height); cameraSensor.options.previewFpsRangeMin.set(15); cameraSensor.options.previewFpsRangeMax.set(15); // Add sensor to the pipeline CameraChannel cameraChannel = new CameraChannel(); cameraChannel.options.sampleRate.set(sampleRate); frame.addSensor(cameraSensor, cameraChannel); // Set up a NV21 decoder NV21ToRGBDecoder decoder = new NV21ToRGBDecoder(); frame.addTransformer(decoder, cameraChannel, 1, 0); // Add image resizer to the pipeline ImageResizer resizer = new ImageResizer(); resizer.options.maintainAspect.set(MAINTAIN_ASPECT); resizer.options.size.set(CROP_SIZE); resizer.options.rotation.set(270); frame.addTransformer(resizer, decoder, 1, 0); // Add image pixel value normalizer to the pipeline ImageNormalizer imageNormalizer = new ImageNormalizer(); imageNormalizer.options.imageMean.set(IMAGE_MEAN); imageNormalizer.options.imageStd.set(IMAGE_STD); frame.addTransformer(imageNormalizer, resizer, 1, 0); TFLite tfLite = new TFLite(); tfLite.options.file.setValue(trainerURL + File.separator + trainerName); frame.addModel(tfLite); // Add classifier transformer to the pipeline Classifier classifier = new Classifier(); classifier.setModel(tfLite); classifier.options.merge.set(false); classifier.options.bestMatchOnly.set(true); frame.addConsumer(classifier, imageNormalizer, 1, 0); // Log events EventChannel channel = classifier.getEventChannelOut(); EventLogger log = new EventLogger(); frame.registerEventListener(log, channel); // Start pipeline frame.start(); // Wait duration try { Thread.sleep(TestHelper.DUR_TEST_NORMAL); } catch (Exception e) { e.printStackTrace(); } // Stop pipeline frame.stop(); frame.release(); } }
4,623
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
FaceCropTest.java
/FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/androidTest/java/hcm/ssj/FaceCropTest.java
/* * FaceCropTest.java * Copyright (c) 2019 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library is free software; you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj; import org.junit.Test; import org.junit.runner.RunWith; import java.io.File; import androidx.test.filters.SmallTest; import androidx.test.runner.AndroidJUnit4; import hcm.ssj.camera.CameraChannel; import hcm.ssj.camera.CameraSensor; import hcm.ssj.camera.ImageLoaderChannel; import hcm.ssj.camera.ImageLoaderSensor; import hcm.ssj.camera.ImageNormalizer; import hcm.ssj.camera.ImageResizer; import hcm.ssj.camera.NV21ToRGBDecoder; import hcm.ssj.core.Cons; import hcm.ssj.core.EventChannel; import hcm.ssj.core.Pipeline; import hcm.ssj.core.option.FolderPath; import hcm.ssj.face.FaceCrop; import hcm.ssj.file.FileCons; import hcm.ssj.ml.Classifier; import hcm.ssj.ml.TFLite; import hcm.ssj.test.EventLogger; /** * Tests setting up, loading, and evaluating object classification * with the MobileNet model. */ @RunWith(AndroidJUnit4.class) @SmallTest public class FaceCropTest { @Test public void loadInceptionModel() throws Exception { // Option parameters for camera sensor double sampleRate = 1; int width = 640; int height = 480; int imageRotation = 270; // Get pipeline instance Pipeline frame = Pipeline.getInstance(); frame.options.bufferSize.set(10.0f); // Instantiate camera sensor and set options CameraSensor cameraSensor = new CameraSensor(); cameraSensor.options.cameraType.set(Cons.CameraType.FRONT_CAMERA); cameraSensor.options.width.set(width); cameraSensor.options.height.set(height); cameraSensor.options.previewFpsRangeMin.set(15); cameraSensor.options.previewFpsRangeMax.set(15); // Add sensor to the pipeline CameraChannel cameraChannel = new CameraChannel(); cameraChannel.options.sampleRate.set(sampleRate); frame.addSensor(cameraSensor, cameraChannel); // Set up a NV21 decoder NV21ToRGBDecoder decoder = new NV21ToRGBDecoder(); frame.addTransformer(decoder, cameraChannel, 1, 0); FaceCrop crop = new FaceCrop(); crop.options.rotation.set(imageRotation); frame.addTransformer(crop, decoder, 1, 0); // Start pipeline frame.start(); // Wait duration try { Thread.sleep(TestHelper.DUR_TEST_NORMAL); } catch (Exception e) { e.printStackTrace(); } // Stop pipeline frame.stop(); frame.release(); } }
3,586
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
BiosigTest.java
/FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/androidTest/java/hcm/ssj/BiosigTest.java
/* * BiosigTest.java * Copyright (c) 2017 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library is free software; you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj; import androidx.test.filters.SmallTest; import androidx.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import hcm.ssj.biosig.GSRArousalEstimation; import hcm.ssj.core.Log; import hcm.ssj.core.Pipeline; import hcm.ssj.empatica.Empatica; import hcm.ssj.empatica.GSRChannel; import hcm.ssj.test.Logger; /** * Created by Michael Dietz on 15.04.2015. */ @RunWith(AndroidJUnit4.class) @SmallTest public class BiosigTest { @Test public void testArousal() throws Exception { Pipeline frame = Pipeline.getInstance(); Empatica empatica = new Empatica(); GSRChannel data = new GSRChannel(); frame.addSensor(empatica, data); GSRArousalEstimation arousal = new GSRArousalEstimation(); frame.addTransformer(arousal, data, 0.25, 0); Logger dummy = new Logger(); frame.addConsumer(dummy, arousal, 0.25, 0); frame.start(); // Wait duration try { Thread.sleep(TestHelper.DUR_TEST_NORMAL); } catch (Exception e) { e.printStackTrace(); } frame.stop(); Log.i("arousal test finished"); } }
2,427
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
SvmTest.java
/FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/androidTest/java/hcm/ssj/SvmTest.java
/* * SvmTest.java * Copyright (c) 2017 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library is free software; you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj; import androidx.test.filters.SmallTest; import androidx.test.runner.AndroidJUnit4; import junit.framework.Assert; import org.junit.Test; import org.junit.runner.RunWith; import java.io.File; import hcm.ssj.androidSensor.AndroidSensor; import hcm.ssj.androidSensor.AndroidSensorChannel; import hcm.ssj.androidSensor.SensorType; import hcm.ssj.body.AccelerationFeatures; import hcm.ssj.core.Pipeline; import hcm.ssj.core.Provider; import hcm.ssj.file.FileWriter; import hcm.ssj.ml.ClassifierT; import hcm.ssj.ml.SVM; import hcm.ssj.test.Logger; import static androidx.test.InstrumentationRegistry.getContext; @RunWith(AndroidJUnit4.class) @SmallTest public class SvmTest { @Test public void testSVM() throws Exception { // Resources File dir = getContext().getFilesDir(); String modelName = "search_model.trainer"; TestHelper.copyAssetToFile(modelName, new File(dir, modelName)); TestHelper.copyAssetToFile(modelName + ".SVM.model", new File(dir, modelName + ".SVM.model")); TestHelper.copyAssetToFile(modelName + ".SVM.option", new File(dir, modelName + ".SVM.option")); String outputFileName = getClass().getSimpleName() + ".test"; File outputFile = new File(dir, outputFileName); // Setup Pipeline frame = Pipeline.getInstance(); frame.options.bufferSize.set(10.0f); // Sensor AndroidSensor accSensor = new AndroidSensor(); AndroidSensor gyrSensor = new AndroidSensor(); // Channel AndroidSensorChannel accChannel = new AndroidSensorChannel(); accChannel.options.sensorType.set(SensorType.LINEAR_ACCELERATION); accChannel.options.sampleRate.set(40); frame.addSensor(accSensor, accChannel); AndroidSensorChannel gyrChannel = new AndroidSensorChannel(); gyrChannel.options.sensorType.set(SensorType.GYROSCOPE); gyrChannel.options.sampleRate.set(40); frame.addSensor(gyrSensor, gyrChannel); // Transformer AccelerationFeatures accFeatures = new AccelerationFeatures(); frame.addTransformer(accFeatures, accChannel, 2, 2); AccelerationFeatures gyrFeatures = new AccelerationFeatures(); frame.addTransformer(gyrFeatures, gyrChannel, 2, 2); // SVM SVM svm = new SVM(); svm.options.file.setValue(dir.getAbsolutePath() + File.separator + modelName); frame.addModel(svm); ClassifierT classifier = new ClassifierT(); classifier.setModel(svm); frame.addTransformer(classifier, new Provider[]{accFeatures, gyrFeatures}, 2, 0); // Consumer Logger log = new Logger(); frame.addConsumer(log, classifier, 2, 0); FileWriter svmWriter = new FileWriter(); svmWriter.options.filePath.setValue(dir.getAbsolutePath()); svmWriter.options.fileName.set(outputFileName); frame.addConsumer(svmWriter, classifier, 2, 0); // Start framework frame.start(); // Wait duration try { Thread.sleep(TestHelper.DUR_TEST_NORMAL); } catch (Exception e) { e.printStackTrace(); } // Stop framework frame.stop(); frame.clear(); // Get data file File data = new File(dir, outputFileName + "~"); // Verify Assert.assertTrue(outputFile.length() > 100); Assert.assertTrue(data.length() > 100); if (outputFile.exists()) outputFile.delete(); if (data.exists()) data.delete(); } }
4,551
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
GATTTest.java
/FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/androidTest/java/hcm/ssj/GATTTest.java
/* * GATTTest.java * Copyright (c) 2021 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library is free software; you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj; import org.junit.Test; import org.junit.runner.RunWith; import java.util.UUID; import androidx.test.filters.SmallTest; import androidx.test.runner.AndroidJUnit4; import hcm.ssj.core.Pipeline; import hcm.ssj.core.SSJException; import hcm.ssj.ioput.GATTChannel; import hcm.ssj.ioput.GATTConnection; import hcm.ssj.ioput.GATTReader; import hcm.ssj.test.Logger; /** * Created by Michael Dietz on 27.07.2021. */ @RunWith(AndroidJUnit4.class) @SmallTest public class GATTTest { @Test public void testComponents() throws SSJException { // Setup Pipeline frame = Pipeline.getInstance(); frame.options.bufferSize.set(10.0f); GATTReader sensor = new GATTReader(); sensor.options.macAddress.set("C4:DD:57:9E:8E:EE"); GATTChannel channel = new GATTChannel(); channel.options.supportedUUID.set(GATTChannel.SupportedUUIDs.TEMPERATURE); frame.addSensor(sensor, channel); Logger logger = new Logger(); frame.addConsumer(logger, channel); frame.start(); // Wait duration try { Thread.sleep(60 * 1000); } catch (Exception e) { e.printStackTrace(); } frame.stop(); frame.clear(); } /* @Test public void testConnection() { GATTConnection connection = new GATTConnection(); connection.registerCharacteristic(UUID.fromString("00002a6e-0000-1000-8000-00805f9b34fb")); connection.registerCharacteristic(UUID.fromString("00002a6f-0000-1000-8000-00805f9b34fb")); connection.registerCharacteristic(UUID.fromString("00002a19-0000-1000-8000-00805f9b34fb")); connection.connect("C4:DD:57:9E:8E:EE"); // Wait duration try { Thread.sleep(60 * 1000); } catch (Exception e) { e.printStackTrace(); } connection.disconnect(); connection.close(); } */ }
3,087
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
AndroidSensorTest.java
/FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/androidTest/java/hcm/ssj/AndroidSensorTest.java
/* * AndroidSensorTest.java * Copyright (c) 2017 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library is free software; you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj; import android.content.Context; import android.hardware.SensorManager; import androidx.test.filters.SmallTest; import androidx.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import hcm.ssj.androidSensor.AndroidSensor; import hcm.ssj.androidSensor.AndroidSensorChannel; import hcm.ssj.androidSensor.SensorType; import hcm.ssj.core.Log; import hcm.ssj.core.Pipeline; import hcm.ssj.test.Logger; import static androidx.test.InstrumentationRegistry.getInstrumentation; /** * Tests all classes in the android sensor package.<br> * Created by Frank Gaibler on 13.08.2015. */ @RunWith(AndroidJUnit4.class) @SmallTest public class AndroidSensorTest { @Test public void testSensors() throws Exception { // Test for every sensor type for (SensorType type : SensorType.values()) { SensorManager mSensorManager = (SensorManager) getInstrumentation().getContext().getSystemService(Context.SENSOR_SERVICE); if (mSensorManager.getDefaultSensor(type.getType()) != null) { // Setup Pipeline frame = Pipeline.getInstance(); frame.options.bufferSize.set(10.0f); // Sensor AndroidSensor sensor = new AndroidSensor(); AndroidSensorChannel channel = new AndroidSensorChannel(); channel.options.sensorType.set(type); frame.addSensor(sensor, channel); // Logger Logger log = new Logger(); frame.addConsumer(log, channel, 1, 0); // Start framework frame.start(); // Wait duration try { Thread.sleep(TestHelper.DUR_TEST_SHORT); } catch (Exception e) { e.printStackTrace(); } // Stop framework frame.stop(); frame.release(); } else { Log.i(type.getName() + " not present on device"); } } } }
3,125
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
AngelSensorTest.java
/FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/androidTest/java/hcm/ssj/AngelSensorTest.java
/* * AngelSensorTest.java * Copyright (c) 2017 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library is free software; you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj; import androidx.test.filters.SmallTest; import androidx.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import hcm.ssj.angelsensor.AngelSensor; import hcm.ssj.angelsensor.BVPAngelChannel; import hcm.ssj.core.Pipeline; import hcm.ssj.test.Logger; @RunWith(AndroidJUnit4.class) @SmallTest public class AngelSensorTest { @Test public void testSensors() throws Exception { // Setup Pipeline frame = Pipeline.getInstance(); frame.options.bufferSize.set(10.0f); // Sensor AngelSensor sensor = new AngelSensor(); BVPAngelChannel sensorChannel = new BVPAngelChannel(); frame.addSensor(sensor, sensorChannel); // Logger Logger log = new Logger(); frame.addConsumer(log, sensorChannel, 1, 0); // Start framework frame.start(); // Wait duration try { Thread.sleep(TestHelper.DUR_TEST_NORMAL); } catch (Exception e) { e.printStackTrace(); } // Stop framework frame.stop(); frame.clear(); } }
2,350
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
EmpaticaTest.java
/FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/androidTest/java/hcm/ssj/EmpaticaTest.java
/* * EmpaticaTest.java * Copyright (c) 2017 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library is free software; you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj; import androidx.test.filters.SmallTest; import androidx.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import hcm.ssj.core.Log; import hcm.ssj.core.Pipeline; import hcm.ssj.empatica.AccelerationChannel; import hcm.ssj.empatica.BVPChannel; import hcm.ssj.empatica.Empatica; import hcm.ssj.empatica.GSRChannel; import hcm.ssj.empatica.IBIChannel; import hcm.ssj.empatica.TemperatureChannel; import hcm.ssj.test.Logger; /** * Created by Michael Dietz on 15.04.2015. */ @RunWith(AndroidJUnit4.class) @SmallTest public class EmpaticaTest { // Insert your API key here: String APIKEY = ""; @Test public void testAcc() throws Exception { Pipeline frame = Pipeline.getInstance(); Empatica empatica = new Empatica(); empatica.options.apiKey.set(APIKEY); AccelerationChannel acc = new AccelerationChannel(); frame.addSensor(empatica, acc); Logger dummy = new Logger(); frame.addConsumer(dummy, acc, 0.1, 0); frame.start(); // Wait duration try { Thread.sleep(TestHelper.DUR_TEST_NORMAL); } catch (Exception e) { e.printStackTrace(); } frame.stop(); Log.i("ACC test finished"); } @Test public void testGsr() throws Exception { Pipeline frame = Pipeline.getInstance(); Empatica empatica = new Empatica(); empatica.options.apiKey.set(APIKEY); GSRChannel data = new GSRChannel(); frame.addSensor(empatica, data); Logger dummy = new Logger(); frame.addConsumer(dummy, data, 0.25, 0); frame.start(); // Wait duration try { Thread.sleep(TestHelper.DUR_TEST_SHORT); } catch (Exception e) { e.printStackTrace(); } frame.stop(); Log.i("GSR test finished"); } @Test public void testIBI() throws Exception { Pipeline frame = Pipeline.getInstance(); Empatica empatica = new Empatica(); empatica.options.apiKey.set(APIKEY); IBIChannel data = new IBIChannel(); frame.addSensor(empatica, data); Logger dummy = new Logger(); frame.addConsumer(dummy, data, 0.1, 0); frame.start(); // Wait duration try { Thread.sleep(TestHelper.DUR_TEST_SHORT); } catch (Exception e) { e.printStackTrace(); } frame.stop(); Log.i("IBI test finished"); } @Test public void testTemp() throws Exception { Pipeline frame = Pipeline.getInstance(); Empatica empatica = new Empatica(); empatica.options.apiKey.set(APIKEY); TemperatureChannel data = new TemperatureChannel(); frame.addSensor(empatica, data); Logger dummy = new Logger(); frame.addConsumer(dummy, data, 0.25, 0); frame.start(); // Wait duration try { Thread.sleep(TestHelper.DUR_TEST_SHORT); } catch (Exception e) { e.printStackTrace(); } frame.stop(); Log.i("Temp test finished"); } @Test public void testBVP() throws Exception { Pipeline frame = Pipeline.getInstance(); Empatica empatica = new Empatica(); empatica.options.apiKey.set(APIKEY); BVPChannel data = new BVPChannel(); frame.addSensor(empatica, data); Logger dummy = new Logger(); frame.addConsumer(dummy, data, 0.1, 0); frame.start(); // Wait duration try { Thread.sleep(TestHelper.DUR_TEST_SHORT); } catch (Exception e) { e.printStackTrace(); } frame.stop(); Log.i("BVP test finished"); } }
4,630
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
BodyTest.java
/FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/androidTest/java/hcm/ssj/BodyTest.java
/* * BodyTest.java * Copyright (c) 2017 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library is free software; you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj; import androidx.test.filters.SmallTest; import androidx.test.runner.AndroidJUnit4; import junit.framework.Assert; import org.junit.Test; import org.junit.runner.RunWith; import java.io.File; import hcm.ssj.androidSensor.AndroidSensor; import hcm.ssj.androidSensor.AndroidSensorChannel; import hcm.ssj.androidSensor.SensorType; import hcm.ssj.body.AccelerationFeatures; import hcm.ssj.core.Pipeline; import hcm.ssj.file.FileWriter; import hcm.ssj.test.Logger; import static androidx.test.InstrumentationRegistry.getContext; @RunWith(AndroidJUnit4.class) @SmallTest public class BodyTest { @Test public void testWriting() throws Exception { // Resources File dir = getContext().getFilesDir(); String fileName = getClass().getSimpleName() + ".test"; File file = new File(dir, fileName); String fileName2 = getClass().getSimpleName() + "2.test"; File file2 = new File(dir, fileName2); // Setup Pipeline frame = Pipeline.getInstance(); frame.options.bufferSize.set(10.0f); // Sensor AndroidSensor sensor = new AndroidSensor(); // Channel AndroidSensorChannel channel = new AndroidSensorChannel(); channel.options.sensorType.set(SensorType.ACCELEROMETER); channel.options.sampleRate.set(40); frame.addSensor(sensor, channel); // Transformer AccelerationFeatures features = new AccelerationFeatures(); frame.addTransformer(features, channel, 2, 2); // Consumer Logger log = new Logger(); frame.addConsumer(log, features, 2, 0); FileWriter rawWriter = new FileWriter(); rawWriter.options.filePath.setValue(dir.getAbsolutePath()); rawWriter.options.fileName.set(fileName); frame.addConsumer(rawWriter, channel, 1, 0); FileWriter featureWriter = new FileWriter(); featureWriter.options.filePath.setValue(dir.getAbsolutePath()); featureWriter.options.fileName.set(fileName2); frame.addConsumer(featureWriter, features, 2, 0); // Start framework frame.start(); // Wait duration try { Thread.sleep(TestHelper.DUR_TEST_NORMAL); } catch (Exception e) { e.printStackTrace(); } // Stop framework frame.stop(); frame.clear(); // Get data files File data = new File(dir, fileName + "~"); File data2 = new File(dir, fileName + "~"); // Verify Assert.assertTrue(file.length() > 100); Assert.assertTrue(file2.length() > 100); Assert.assertTrue(data.length() > 100); Assert.assertTrue(data2.length() > 100); if (file.exists()) file.delete(); if (file2.exists()) file2.delete(); if (data.exists()) data.delete(); if (data2.exists()) data2.delete(); } }
3,930
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
NaiveBayesTest.java
/FileExtraction/Java_unseen/hcmlab_ssj/libssj/src/androidTest/java/hcm/ssj/NaiveBayesTest.java
/* * NaiveBayesTest.java * Copyright (c) 2017 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library is free software; you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.ssj; import androidx.test.filters.SmallTest; import androidx.test.runner.AndroidJUnit4; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import java.io.File; import java.util.Arrays; import hcm.ssj.core.Annotation; import hcm.ssj.core.Cons; import hcm.ssj.core.Log; import hcm.ssj.core.stream.Stream; import hcm.ssj.ml.NaiveBayes; import hcm.ssj.ml.NaiveBayesOld; /** * Created by Michael Dietz on 07.11.2017. */ @RunWith(AndroidJUnit4.class) @SmallTest public class NaiveBayesTest { private String trainerFileName = "activity.NaiveBayes.trainer"; private String modelPath = "/sdcard/SSJ/Creator/res"; @Test public void compareImplementations() throws Exception { // Init old model NaiveBayesOld oldImpl = new NaiveBayesOld(); oldImpl.getOptions().file.setValue(modelPath + File.separator + trainerFileName); oldImpl.setup(); oldImpl.load(); // Init new model NaiveBayes newImpl = new NaiveBayes(); newImpl.getOptions().file.setValue(modelPath + File.separator + trainerFileName); newImpl.setup(); newImpl.load(); Stream inputStream = Stream.create(1, newImpl.getInputDim().length, newImpl.getInputSr(), newImpl.getInputType()); // Fill stream for (int i = 0; i < newImpl.getInputDim().length; i++) { inputStream.ptrF()[i] = 0.5f; } float[] oldProbs = oldImpl.forward(inputStream); float[] newProbs = newImpl.forward(inputStream); Log.d("Old: " + Arrays.toString(oldProbs)); Log.d("New: " + Arrays.toString(newProbs)); Assert.assertArrayEquals("Different probabilities between old and new implementation!", oldProbs, newProbs, 1E-5f); // Train model newImpl.train(inputStream, "Stand"); newImpl.train(inputStream, "Walk"); newImpl.train(inputStream, "Jog"); float[] trainedProbs = newImpl.forward(inputStream); Log.d("Trained:" + Arrays.toString(trainedProbs)); } @Test public void batchTrainingTest() throws Exception { // Init new model NaiveBayes model = new NaiveBayes(); model.setOutputDim(2); model.setClassNames(new String[]{"a", "b"}); Stream trainStream = Stream.create(100, 1, 1, Cons.Type.FLOAT); // Fill stream for (int i = 0; i < trainStream.num / 2; i++) { trainStream.ptrF()[i] = 0.0f + (float) (Math.random() / 10f); } for (int i = trainStream.num / 2; i < trainStream.num; i++) { trainStream.ptrF()[i] = 0.9f + (float) (Math.random() / 10f); } Annotation anno = new Annotation(); anno.setClasses(model.getClassNames()); anno.addEntry(model.getClassNames()[0], 0, trainStream.num / 2 * trainStream.sr); anno.addEntry(model.getClassNames()[1], trainStream.num / 2 * trainStream.sr, trainStream.num * trainStream.sr); anno.convertToFrames(1, null, 0, 0.5); model.setup(anno.getClassArray(), trainStream.bytes, trainStream.dim, trainStream.sr, trainStream.type); //train model.train(trainStream, anno); //eval Stream testStream = Stream.create(1, 1, 1, Cons.Type.FLOAT); testStream.ptrF()[0] = 0; float[] probs = model.forward(testStream); Log.d("test for input " + testStream.ptrF()[0] + ": " + Arrays.toString(probs)); Assert.assertArrayEquals("unexpected result!", new float[]{1.0f, 0.0f}, probs, 1E-5f); testStream.ptrF()[0] = 1; probs = model.forward(testStream); Log.d("test for input " + testStream.ptrF()[0] + ": " + Arrays.toString(probs)); Assert.assertArrayEquals("unexpected result!", new float[]{0.0f, 1.0f}, probs, 1E-5f); } }
4,819
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
MainActivity.java
/FileExtraction/Java_unseen/hcmlab_ssj/demo/src/main/java/hcm/demo/MainActivity.java
/* * MainActivity.java * Copyright (c) 2018 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library is free software; you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.demo; import android.Manifest; import android.app.Activity; import android.content.pm.PackageManager; import android.content.res.AssetManager; import android.os.Build; import android.os.Bundle; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.jjoe64.graphview.GraphView; import com.thalmic.myo.Hub; import com.thalmic.myo.Myo; import hcm.ssj.core.ExceptionHandler; import hcm.ssj.core.Pipeline; import hcm.ssj.myo.Vibrate2Command; public class MainActivity extends Activity implements ExceptionHandler { private PipelineRunner _pipe = null; private String _ssj_version = null; private String _error_msg = null; private static final int REQUEST_DANGEROUS_PERMISSIONS = 108; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); _ssj_version = "SSJ v" + Pipeline.getInstance().getVersion(); TextView text = (TextView) findViewById(R.id.txt_ssj); text.setText(_ssj_version); checkPermissions(); } @Override protected void onDestroy() { if (_pipe != null && _pipe.isRunning()) _pipe.terminate(); super.onDestroy(); Log.i("LogueWorker", "destroyed"); } /** * Prevent activity from being destroyed once back button is pressed */ public void onBackPressed() { moveTaskToBack(true); } public void onStartPressed(View v) { Button btn = (Button) findViewById(R.id.btn_start); btn.setAlpha(0.5f); btn.setEnabled(false); getCacheDir().getAbsolutePath(); AssetManager am = getApplicationContext().getAssets(); getAssets(); TextView text = (TextView) findViewById(R.id.txt_ssj); if(_pipe == null || !_pipe.isRunning()) { text.setText(_ssj_version + " - starting"); GraphView graph = (GraphView) findViewById(R.id.graph); graph.removeAllSeries(); // graph.getSecondScale().removeAllSeries(); //not implemented in GraphView 4.0.1 GraphView graph2 = (GraphView) findViewById(R.id.graph2); graph2.removeAllSeries(); // graph2.getSecondScale().removeAllSeries(); //not implemented in GraphView 4.0.1 GraphView graphs[] = new GraphView[]{graph, graph2}; _pipe = new PipelineRunner(this, graphs); _pipe.setExceptionHandler(this); _pipe.start(); } else { text.setText(_ssj_version + " - stopping"); _pipe.terminate(); } } public void notifyPipeState(final boolean running) { this.runOnUiThread(new Runnable() { public void run() { Button btn = (Button) findViewById(R.id.btn_start); TextView text = (TextView) findViewById(R.id.txt_ssj); if (running) { text.setText(_ssj_version + " - running"); btn.setText(R.string.stop); btn.setEnabled(true); btn.setAlpha(1.0f); } else { text.setText(_ssj_version + " - not running"); if(_error_msg != null) { String str = text.getText() + "\nERROR: " + _error_msg; text.setText(str); } btn.setText(R.string.start); btn.setEnabled(true); btn.setAlpha(1.0f); } } }); } public void onClosePressed(View v) { finish(); } public void onDemoPressed(View v) { final Hub hub = Hub.getInstance(); Thread t1 = new Thread(new Runnable() { public void run() { if(hub.getConnectedDevices().isEmpty()) { Log.e("Logue_SSJ", "device not found"); } else { com.thalmic.myo.Myo myo = hub.getConnectedDevices().get(0); startVibrate(myo, hub); } } }); t1.start(); } private void startVibrate(Myo myo, Hub hub) { String _name = "test"; Log.i(_name, "connected"); try { Vibrate2Command vibrate2Command = new Vibrate2Command(hub); Log.i(_name, "vibrate 1..."); myo.vibrate(Myo.VibrationType.MEDIUM); Thread.sleep(3000); Log.i(_name, "vibrate 2..."); //check strength 50 vibrate2Command.vibrate(myo, 1000, (byte) 50); Thread.sleep(3000); Log.i(_name, "vibrate 3 ..."); //check strength 100 vibrate2Command.vibrate(myo, 1000, (byte) 100); Thread.sleep(3000); Log.i(_name, "vibrate 4 ..."); //check strength 100 vibrate2Command.vibrate(myo, 1000, (byte) 150); Thread.sleep(3000); Log.i(_name, "vibrate 5..."); //check strength 250 vibrate2Command.vibrate(myo, 1000, (byte) 200); Thread.sleep(3000); Log.i(_name, "vibrate 6..."); //check strength 250 vibrate2Command.vibrate(myo, 1000, (byte) 250); Thread.sleep(3000); Log.i(_name, "vibrate pattern..."); //check vibrate pattern vibrate2Command.vibrate(myo, new int[]{500, 500, 500, 500, 500, 500}, new byte[]{25, 50, 100, (byte) 150, (byte) 200, (byte) 250}); Thread.sleep(3000); } catch (Exception e) { Log.e(_name, "exception in vibrate test", e); } } @Override public void handle(final String location, final String msg, final Throwable t) { _error_msg = msg; _pipe.terminate(); //attempt to shut down framework this.runOnUiThread( new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), "Exception in Pipeline\n" + msg, Toast.LENGTH_LONG).show(); } }); } private void checkPermissions() { if (Build.VERSION.SDK_INT >= 23) { //dangerous permissions if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.BODY_SENSORS) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{ Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.BODY_SENSORS, Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_DANGEROUS_PERMISSIONS); } } } }
9,238
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
PipelineRunner.java
/FileExtraction/Java_unseen/hcmlab_ssj/demo/src/main/java/hcm/demo/PipelineRunner.java
/* * PipelineRunner.java * Copyright (c) 2018 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library is free software; you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.demo; import android.util.Log; import com.jjoe64.graphview.GraphView; import hcm.ssj.audio.AudioChannel; import hcm.ssj.audio.Microphone; import hcm.ssj.audio.Pitch; import hcm.ssj.core.ExceptionHandler; import hcm.ssj.core.Pipeline; import hcm.ssj.core.Provider; import hcm.ssj.graphic.SignalPainter; public class PipelineRunner extends Thread { private boolean _terminate = false; private Pipeline _ssj; private MainActivity _act = null; private GraphView _graphs[] = null; public PipelineRunner(MainActivity a, GraphView[] graphs) { _act = a; _graphs = graphs; if(Pipeline.isInstanced()) Pipeline.getInstance().clear(); _ssj = Pipeline.getInstance(); } public void setExceptionHandler(ExceptionHandler h) { if(_ssj == null) return; _ssj.setExceptionHandler(h); } public void run() { try { _ssj.options.bufferSize.set(10.0f); _ssj.options.countdown.set(1); _ssj.options.log.set(true); //** connection to sensors Microphone mic = new Microphone(); AudioChannel audio = new AudioChannel(); audio.options.sampleRate.set(16000); audio.options.scale.set(true); _ssj.addSensor(mic,audio); //** transform data coming from sensors Pitch pitch = new Pitch(); pitch.options.detector.set(Pitch.YIN); pitch.options.computePitchedState.set(false); pitch.options.computePitch.set(true); pitch.options.computeVoicedProb.set(false); pitch.options.computePitchEnvelope.set(false); _ssj.addTransformer(pitch, audio, 0.032, 0); //512 samples //** configure GUI //paint audio SignalPainter paint = new SignalPainter(); paint.options.manualBounds.set(true); paint.options.min.set(0.); paint.options.max.set(1.); paint.options.renderMax.set(true); paint.options.secondScaleMin.set(0.); paint.options.secondScaleMax.set(500.); paint.options.graphView.set(_graphs[0]); _ssj.addConsumer(paint, new Provider[]{audio, pitch}, 0.032, 0); } catch(Exception e) { Log.e("SSJ_Demo", "error building pipe", e); return; } Log.i("SSJ_Demo", "starting pipeline"); _ssj.start(); _act.notifyPipeState(true); while(!_terminate) { try { synchronized(this) { this.wait(); } } catch (InterruptedException e) { Log.e("pipeline", "Error", e); } } Log.i("SSJ_Demo", "stopping pipeline"); _ssj.stop(); _ssj.clear(); _act.notifyPipeState(false); } public void terminate() { _terminate = true; synchronized(this) { this.notify(); } } public boolean isRunning() { return _ssj.isRunning(); } }
4,566
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
ApplicationTest.java
/FileExtraction/Java_unseen/hcmlab_ssj/demo/src/androidTest/java/hcm/demo/ApplicationTest.java
/* * ApplicationTest.java * Copyright (c) 2017 * Authors: Ionut Damian, Michael Dietz, Frank Gaibler, Daniel Langerenken, Simon Flutura, * Vitalijs Krumins, Antonio Grieco * ***************************************************** * This file is part of the Social Signal Interpretation for Java (SSJ) framework * developed at the Lab for Human Centered Multimedia of the University of Augsburg. * * SSJ has been inspired by the SSI (http://openssi.net) framework. SSJ is not a * one-to-one port of SSI to Java, it is an approximation. Nor does SSJ pretend * to offer SSI's comprehensive functionality and performance (this is java after all). * Nevertheless, SSJ borrows a lot of programming patterns from SSI. * * This library is free software; you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this library; if not, see <http://www.gnu.org/licenses/>. */ package hcm.demo; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
1,696
Java
.java
hcmlab/ssj
31
12
1
2016-02-22T15:23:28Z
2023-06-28T11:01:08Z
PlayerChat.java
/FileExtraction/Java_unseen/handy-git_PlayerChat/src/main/java/cn/handyplus/chat/PlayerChat.java
package cn.handyplus.chat; import cn.handyplus.chat.constants.ChatConstants; import cn.handyplus.chat.hook.PlaceholderUtil; import cn.handyplus.chat.job.ClearItemJob; import cn.handyplus.chat.listener.ChatPluginMessageListener; import cn.handyplus.chat.util.ConfigUtil; import cn.handyplus.lib.InitApi; import cn.handyplus.lib.constants.BaseConstants; import cn.handyplus.lib.util.BcUtil; import cn.handyplus.lib.util.MessageUtil; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.plugin.java.JavaPlugin; /** * 主类 * * @author handy */ public class PlayerChat extends JavaPlugin { private static PlayerChat INSTANCE; public static boolean USE_PAPI; @Override public void onEnable() { INSTANCE = this; InitApi initApi = InitApi.getInstance(this); ConfigUtil.init(); // 加载PlaceholderApi this.loadPlaceholder(); // 加载主数据 initApi.initCommand("cn.handyplus.chat.command") .initListener("cn.handyplus.chat.listener") .enableSql("cn.handyplus.chat.enter") .initClickEvent("cn.handyplus.chat.listener.gui") .addMetrics(18860) .enableBc() .checkVersion(ConfigUtil.CONFIG.getBoolean(BaseConstants.IS_CHECK_UPDATE), ChatConstants.PLUGIN_VERSION_URL); ChatPluginMessageListener.getInstance().register(); // 定时任务启动 ClearItemJob.init(); MessageUtil.sendConsoleMessage(ChatColor.GREEN + "已成功载入服务器!"); MessageUtil.sendConsoleMessage(ChatColor.GREEN + "Author:handy 使用文档: https://ricedoc.handyplus.cn/wiki/PlayerChat/README/"); } @Override public void onDisable() { InitApi.disable(); BcUtil.unregisterOut(); ChatPluginMessageListener.getInstance().unregister(); } public static PlayerChat getInstance() { return INSTANCE; } /** * 加载Placeholder */ public void loadPlaceholder() { if (Bukkit.getPluginManager().getPlugin(BaseConstants.PLACEHOLDER_API) != null) { USE_PAPI = true; new PlaceholderUtil(this).register(); MessageUtil.sendConsoleMessage(ConfigUtil.LANG_CONFIG.getString("placeholderAPISucceedMsg")); return; } USE_PAPI = false; MessageUtil.sendConsoleMessage(ConfigUtil.LANG_CONFIG.getString("placeholderAPIFailureMsg")); } }
2,478
Java
.java
handy-git/PlayerChat
14
0
0
2023-06-24T06:37:49Z
2024-05-06T06:24:03Z
ItemGui.java
/FileExtraction/Java_unseen/handy-git_PlayerChat/src/main/java/cn/handyplus/chat/inventory/ItemGui.java
package cn.handyplus.chat.inventory; import cn.handyplus.chat.constants.GuiTypeEnum; import cn.handyplus.chat.enter.ChatPlayerItemEnter; import cn.handyplus.chat.hook.PlaceholderApiUtil; import cn.handyplus.chat.service.ChatPlayerItemService; import cn.handyplus.chat.util.ConfigUtil; import cn.handyplus.lib.constants.BaseConstants; import cn.handyplus.lib.core.StrUtil; import cn.handyplus.lib.inventory.HandyInventory; import cn.handyplus.lib.inventory.HandyInventoryUtil; import cn.handyplus.lib.util.ItemStackUtil; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import java.util.Optional; /** * 展示物品GUI * * @author handy */ public class ItemGui { private ItemGui() { } private final static ItemGui INSTANCE = new ItemGui(); public static ItemGui getInstance() { return INSTANCE; } /** * 创建gui * * @param player 玩家 * @param enter 物品 * @return gui */ public Inventory createGui(Player player, ChatPlayerItemEnter enter) { String title = ConfigUtil.ITEM_CONFIG.getString("title"); int size = ConfigUtil.ITEM_CONFIG.getInt("size", BaseConstants.GUI_SIZE_54); title = PlaceholderApiUtil.set(player, title); title = StrUtil.replace(title, "player", enter.getPlayerName()); HandyInventory handyInventory = new HandyInventory(GuiTypeEnum.ITEM.getType(), title, size); handyInventory.setPlayer(player); handyInventory.setId(enter.getId()); this.setInventoryDate(handyInventory); return handyInventory.getInventory(); } /** * 设置数据 * * @param handyInventory gui */ private void setInventoryDate(HandyInventory handyInventory) { // 基础设置 handyInventory.setGuiType(GuiTypeEnum.ITEM.getType()); // 1. 刷新 HandyInventoryUtil.refreshInventory(handyInventory.getInventory()); // 2.设置数据 this.setDate(handyInventory); // 3.设置功能性菜单 this.setFunctionMenu(handyInventory); } /** * 设置数据 * * @param handyInventory gui */ private void setDate(HandyInventory handyInventory) { Inventory inventory = handyInventory.getInventory(); Integer id = handyInventory.getId(); Optional<ChatPlayerItemEnter> chatPlayerItemOptional = ChatPlayerItemService.getInstance().findById(id); if (!chatPlayerItemOptional.isPresent()) { return; } ChatPlayerItemEnter chatPlayerItem = chatPlayerItemOptional.get(); ItemStack itemStack = ItemStackUtil.itemStackDeserialize(chatPlayerItem.getItem(), Material.STONE); int index = ConfigUtil.ITEM_CONFIG.getInt("index"); inventory.setItem(index, itemStack); } /** * 设置功能性菜单 * * @param handyInventory GUI */ private void setFunctionMenu(HandyInventory handyInventory) { Inventory inventory = handyInventory.getInventory(); // 关闭按钮 HandyInventoryUtil.setButton(ConfigUtil.ITEM_CONFIG, inventory, "back"); // 自定义按钮 HandyInventoryUtil.setCustomButton(ConfigUtil.ITEM_CONFIG, handyInventory, "custom"); } }
3,335
Java
.java
handy-git/PlayerChat
14
0
0
2023-06-24T06:37:49Z
2024-05-06T06:24:03Z
ChatParam.java
/FileExtraction/Java_unseen/handy-git_PlayerChat/src/main/java/cn/handyplus/chat/param/ChatParam.java
package cn.handyplus.chat.param; import lombok.Builder; import lombok.Data; import java.util.List; /** * 跨服消息 * * @author handy */ @Data @Builder public class ChatParam { /** * 渠道 */ private String channel; /** * 前缀消息 */ private String prefixText; /** * 前缀hover */ private List<String> prefixHover; /** * 前缀click */ private String prefixClick; /** * 玩家消息 */ private String playerText; /** * 玩家hover */ private List<String> playerHover; /** * 玩家click */ private String playerClick; /** * 消息 */ private String msgText; /** * 消息hover */ private List<String> msgHover; /** * 消息click */ private String msgClick; /** * 聊天消息 */ private String message; /** * 聊天内容颜色权限 */ private boolean hasColor; /** * 物品名称 */ private String itemText; /** * 物品hover */ private List<String> itemHover; /** * 物品ID */ private Integer itemId; }
1,198
Java
.java
handy-git/PlayerChat
14
0
0
2023-06-24T06:37:49Z
2024-05-06T06:24:03Z
PlayerChannelChatEventListener.java
/FileExtraction/Java_unseen/handy-git_PlayerChat/src/main/java/cn/handyplus/chat/listener/PlayerChannelChatEventListener.java
package cn.handyplus.chat.listener; import cn.handyplus.chat.core.ChatUtil; import cn.handyplus.chat.event.PlayerChannelChatEvent; import cn.handyplus.lib.annotation.HandyListener; import cn.handyplus.lib.util.BcUtil; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; /** * 玩家频道聊天 * * @author handy */ @HandyListener public class PlayerChannelChatEventListener implements Listener { /** * 频道聊天信息处理. * * @param event 事件 */ @EventHandler(priority = EventPriority.MONITOR) public void onChat(PlayerChannelChatEvent event) { if (event.isCancelled()) { return; } BcUtil.BcMessageParam bcMessageParam = event.getBcMessageParam(); // 发送本服消息 ChatUtil.sendMsg(bcMessageParam, true); // 发送BC消息 BcUtil.sendParamForward(event.getPlayer(), bcMessageParam); } }
972
Java
.java
handy-git/PlayerChat
14
0
0
2023-06-24T06:37:49Z
2024-05-06T06:24:03Z
AsyncPlayerChatEventListener.java
/FileExtraction/Java_unseen/handy-git_PlayerChat/src/main/java/cn/handyplus/chat/listener/AsyncPlayerChatEventListener.java
package cn.handyplus.chat.listener; import cn.handyplus.chat.PlayerChat; import cn.handyplus.chat.constants.ChatConstants; import cn.handyplus.chat.core.ChannelUtil; import cn.handyplus.chat.core.ChatUtil; import cn.handyplus.chat.enter.ChatPlayerItemEnter; import cn.handyplus.chat.event.PlayerChannelChatEvent; import cn.handyplus.chat.param.ChatParam; import cn.handyplus.chat.service.ChatPlayerItemService; import cn.handyplus.chat.util.ConfigUtil; import cn.handyplus.lib.annotation.HandyListener; import cn.handyplus.lib.constants.BaseConstants; import cn.handyplus.lib.core.CollUtil; import cn.handyplus.lib.core.JsonUtil; import cn.handyplus.lib.core.StrUtil; import cn.handyplus.lib.expand.adapter.HandySchedulerUtil; import cn.handyplus.lib.util.BaseUtil; import cn.handyplus.lib.util.BcUtil; import cn.handyplus.lib.util.HandyPermissionUtil; import cn.handyplus.lib.util.ItemStackUtil; import cn.handyplus.lib.util.MessageUtil; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.AsyncPlayerChatEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import java.util.Date; import java.util.List; /** * 当玩家聊天时触发这个事件 * * @author handy */ @HandyListener public class AsyncPlayerChatEventListener implements Listener { /** * 聊天信息处理. * * @param event 事件 */ @EventHandler(priority = EventPriority.HIGHEST) public void onChat(AsyncPlayerChatEvent event) { if (event.isCancelled()) { return; } Player player = event.getPlayer(); String channel = ChatConstants.PLAYER_CHAT_CHANNEL.getOrDefault(player.getUniqueId(), ChatConstants.DEFAULT); // 渠道是否开启 if (StrUtil.isEmpty(ChannelUtil.isChannelEnable(channel))) { return; } // 取消事件 event.setCancelled(true); // 聊天频率处理 if (!this.chatTimeCheck(player)) { return; } // 参数构建 BcUtil.BcMessageParam param = new BcUtil.BcMessageParam(); param.setPluginName(PlayerChat.getInstance().getName()); param.setPlayerName(player.getName()); param.setTimestamp(System.currentTimeMillis()); // 构建消息参数 ChatParam chatParam = ChatUtil.buildChatParam(player, channel); if (chatParam == null) { return; } // 内容黑名单处理 String message = this.blackListCheck(event); // 有权限进行颜色代码处理 chatParam.setMessage(ChatUtil.at(message)); chatParam.setHasColor(event.getPlayer().hasPermission("playerChat.color")); chatParam.setChannel(channel); param.setType(ChatConstants.CHAT_TYPE); param.setMessage(JsonUtil.toJson(chatParam)); // 发送事件 HandySchedulerUtil.runTask(() -> Bukkit.getServer().getPluginManager().callEvent(new PlayerChannelChatEvent(player, param))); } /** * 替换黑名单词语为* * * @param event 事件 * @return 健康消息 */ private String blackListCheck(AsyncPlayerChatEvent event) { String message = event.getMessage(); List<String> blacklist = ConfigUtil.CONFIG.getStringList("blacklist"); if (CollUtil.isNotEmpty(blacklist)) { for (String blackMsg : blacklist) { if (StrUtil.isNotEmpty(blackMsg)) { message = message.replace(blackMsg, "*"); } } } return message; } /** * 聊天时间处理 * * @param player 玩家 * @return true 可 */ private boolean chatTimeCheck(Player player) { int chatTime = HandyPermissionUtil.getReverseIntNumber(player, ConfigUtil.CONFIG, "chatTime"); if (ChatConstants.PLAYER_CHAT_TIME.containsKey(player.getUniqueId())) { long keepAlive = (System.currentTimeMillis() - ChatConstants.PLAYER_CHAT_TIME.get(player.getUniqueId())) / 1000L; if (keepAlive < chatTime) { String waitTimeMsg = BaseUtil.getLangMsg("chatTime").replace("${chatTime}", (chatTime - keepAlive) + ""); MessageUtil.sendMessage(player, waitTimeMsg); return false; } } ChatConstants.PLAYER_CHAT_TIME.put(player.getUniqueId(), System.currentTimeMillis()); return true; } /** * 展示物品处理. * * @param event 事件 */ @EventHandler(priority = EventPriority.HIGH) public void onItemChat(AsyncPlayerChatEvent event) { if (event.isCancelled()) { return; } boolean itemEnable = ConfigUtil.CHAT_CONFIG.getBoolean("item.enable"); if (!itemEnable) { return; } String format = ConfigUtil.CHAT_CONFIG.getString("item.format"); if (!event.getMessage().equals(format)) { return; } // 取消事件 event.setCancelled(true); Player player = event.getPlayer(); // 聊天频率处理 if (!this.chatTimeCheck(player)) { return; } // 获取物品参数 ItemStack itemInMainHand = ItemStackUtil.getItemInMainHand(player.getInventory()); ItemMeta itemMeta = ItemStackUtil.getItemMeta(itemInMainHand); // 存储数据 ChatPlayerItemEnter itemEnter = new ChatPlayerItemEnter(); itemEnter.setPlayerName(player.getName()); itemEnter.setPlayerUuid(player.getUniqueId().toString()); itemEnter.setVersion(BaseConstants.VERSION_ID); itemEnter.setItem(ItemStackUtil.itemStackSerialize(itemInMainHand)); itemEnter.setCreateTime(new Date()); Integer itemId = ChatPlayerItemService.getInstance().add(itemEnter); // 参数构建 BcUtil.BcMessageParam param = new BcUtil.BcMessageParam(); param.setPluginName(PlayerChat.getInstance().getName()); param.setPlayerName(player.getName()); param.setTimestamp(System.currentTimeMillis()); String channel = ChatConstants.PLAYER_CHAT_CHANNEL.getOrDefault(player.getUniqueId(), ChatConstants.DEFAULT); // 构建消息参数 ChatParam chatParam = ChatUtil.buildChatParam(player, channel); if (chatParam == null) { return; } // 内容格式 String content = ConfigUtil.CHAT_CONFIG.getString("item.content"); String itemText = StrUtil.replace(content, "item", BaseUtil.getDisplayName(itemInMainHand)); chatParam.setChannel(channel); chatParam.setItemText(itemText); chatParam.setItemHover(itemMeta.getLore()); chatParam.setItemId(itemId); param.setMessage(JsonUtil.toJson(chatParam)); param.setType(ChatConstants.ITEM_TYPE); // 发送事件 HandySchedulerUtil.runTask(() -> Bukkit.getServer().getPluginManager().callEvent(new PlayerChannelChatEvent(player, param))); } }
7,157
Java
.java
handy-git/PlayerChat
14
0
0
2023-06-24T06:37:49Z
2024-05-06T06:24:03Z
PlayerQuitEventListener.java
/FileExtraction/Java_unseen/handy-git_PlayerChat/src/main/java/cn/handyplus/chat/listener/PlayerQuitEventListener.java
package cn.handyplus.chat.listener; import cn.handyplus.chat.constants.ChatConstants; import cn.handyplus.lib.annotation.HandyListener; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerKickEvent; import org.bukkit.event.player.PlayerQuitEvent; /** * 玩家被服务器踢出事件 * 清理缓存 * * @author handy */ @HandyListener public class PlayerQuitEventListener implements Listener { /** * 玩家被服务器踢出事件. * * @param event 事件 */ @EventHandler public void onKick(PlayerKickEvent event) { removeCache(event.getPlayer()); } /** * 玩家离开服务器事件. * * @param event 事件 */ @EventHandler public void onQuit(PlayerQuitEvent event) { removeCache(event.getPlayer()); } /** * 清理缓存 * * @param player 事件 */ private void removeCache(Player player) { ChatConstants.PLAYER_CHAT_CHANNEL.remove(player.getUniqueId()); ChatConstants.PLAYER_PLUGIN_CHANNEL.remove(player.getUniqueId()); ChatConstants.PLAYER_CHAT_TIME.remove(player.getUniqueId()); } }
1,232
Java
.java
handy-git/PlayerChat
14
0
0
2023-06-24T06:37:49Z
2024-05-06T06:24:03Z
ChatPluginMessageListener.java
/FileExtraction/Java_unseen/handy-git_PlayerChat/src/main/java/cn/handyplus/chat/listener/ChatPluginMessageListener.java
package cn.handyplus.chat.listener; import cn.handyplus.chat.PlayerChat; import cn.handyplus.chat.constants.ChatConstants; import cn.handyplus.chat.core.ChatUtil; import cn.handyplus.chat.core.HornUtil; import cn.handyplus.chat.util.ConfigUtil; import cn.handyplus.lib.constants.BaseConstants; import cn.handyplus.lib.core.CollUtil; import cn.handyplus.lib.core.DateUtil; import cn.handyplus.lib.util.BcUtil; import cn.handyplus.lib.util.MessageUtil; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.plugin.messaging.PluginMessageListener; import org.jetbrains.annotations.NotNull; import java.time.temporal.ChronoUnit; import java.util.Date; import java.util.List; import java.util.Optional; /** * BC消息处理 * * @author handy */ public class ChatPluginMessageListener implements PluginMessageListener { private static final ChatPluginMessageListener INSTANCE = new ChatPluginMessageListener(); public static ChatPluginMessageListener getInstance() { return INSTANCE; } public void register() { Bukkit.getMessenger().registerIncomingPluginChannel(PlayerChat.getInstance(), BaseConstants.BUNGEE_CORD_CHANNEL, INSTANCE); } public void unregister() { Bukkit.getMessenger().unregisterIncomingPluginChannel(PlayerChat.getInstance(), BaseConstants.BUNGEE_CORD_CHANNEL, INSTANCE); } /** * 处理消息 * * @param channel 渠道 * @param player 玩家 * @param message 消息 */ @Override public void onPluginMessageReceived(@NotNull String channel,@NotNull Player player, byte[] message) { // 自定义消息处理 String server = ConfigUtil.CONFIG.getString("server"); MessageUtil.sendConsoleDebugMessage("子服:" + server + "收到消息"); Optional<BcUtil.BcMessageParam> paramOptional = BcUtil.getParamByForward(message); if (!paramOptional.isPresent()) { return; } BcUtil.BcMessageParam bcMessageParam = paramOptional.get(); // 判断时间太久的不发送 long between = DateUtil.between(new Date(bcMessageParam.getTimestamp()), new Date(), ChronoUnit.MINUTES); if (between > 1) { return; } // 群组聊天消息 if (ChatConstants.CHAT_TYPE.equals(bcMessageParam.getType()) || ChatConstants.ITEM_TYPE.equals(bcMessageParam.getType())) { ChatUtil.sendMsg(bcMessageParam, false); return; } // 获取喇叭配置 List<String> serverList = ConfigUtil.LB_CONFIG.getStringList("lb." + bcMessageParam.getType() + ".server"); if (CollUtil.isEmpty(serverList)) { MessageUtil.sendConsoleDebugMessage(bcMessageParam.getType() + "的server配置错误"); return; } // 判断是否包含该子服 if (!serverList.contains(server)) { MessageUtil.sendConsoleDebugMessage(server + "子服不发消息"); return; } // 发送消息 HornUtil.sendMsg(player, bcMessageParam); } }
3,087
Java
.java
handy-git/PlayerChat
14
0
0
2023-06-24T06:37:49Z
2024-05-06T06:24:03Z
PlayerJoinEventListener.java
/FileExtraction/Java_unseen/handy-git_PlayerChat/src/main/java/cn/handyplus/chat/listener/PlayerJoinEventListener.java
package cn.handyplus.chat.listener; import cn.handyplus.chat.constants.ChatConstants; import cn.handyplus.chat.core.ChannelUtil; import cn.handyplus.chat.enter.ChatPlayerChannelEnter; import cn.handyplus.chat.service.ChatPlayerChannelService; import cn.handyplus.chat.util.ConfigUtil; import cn.handyplus.lib.annotation.HandyListener; import cn.handyplus.lib.constants.BaseConstants; import cn.handyplus.lib.core.StrUtil; import cn.handyplus.lib.expand.adapter.HandySchedulerUtil; import cn.handyplus.lib.util.HandyHttpUtil; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import java.util.Optional; /** * 登录事件 * * @author handy */ @HandyListener public class PlayerJoinEventListener implements Listener { /** * 设置渠道 * * @param event 事件 */ @EventHandler public void onEvent(PlayerJoinEvent event) { Player player = event.getPlayer(); HandySchedulerUtil.runTaskAsynchronously(() -> { Optional<ChatPlayerChannelEnter> enterOptional = ChatPlayerChannelService.getInstance().findByUid(player.getUniqueId()); String channel = ChatConstants.DEFAULT; if (!enterOptional.isPresent()) { ChatPlayerChannelEnter enter = new ChatPlayerChannelEnter(); enter.setPlayerName(player.getName()); enter.setPlayerUuid(player.getUniqueId().toString()); enter.setChannel(ChatConstants.DEFAULT); ChatPlayerChannelService.getInstance().add(enter); } else { channel = enterOptional.get().getChannel(); } // 缓存渠道 ChatConstants.PLAYER_CHAT_CHANNEL.put(player.getUniqueId(), channel); // 判断渠道是否存在 if (StrUtil.isEmpty(ChannelUtil.isChannelEnable(channel))) { ChatPlayerChannelService.getInstance().setChannel(player.getUniqueId(), ChatConstants.DEFAULT); } }); } /** * op进入服务器发送更新提醒 * * @param event 事件 */ @EventHandler(priority = EventPriority.HIGHEST) public void onOpPlayerJoin(PlayerJoinEvent event) { // op登录发送更新提醒 if (!ConfigUtil.CONFIG.getBoolean(BaseConstants.IS_CHECK_UPDATE_TO_OP_MSG)) { return; } HandyHttpUtil.checkVersion(event.getPlayer(), ChatConstants.PLUGIN_VERSION_URL); } }
2,575
Java
.java
handy-git/PlayerChat
14
0
0
2023-06-24T06:37:49Z
2024-05-06T06:24:03Z
ItemClickEvent.java
/FileExtraction/Java_unseen/handy-git_PlayerChat/src/main/java/cn/handyplus/chat/listener/gui/ItemClickEvent.java
package cn.handyplus.chat.listener.gui; import cn.handyplus.chat.constants.GuiTypeEnum; import cn.handyplus.chat.util.ConfigUtil; import cn.handyplus.lib.core.StrUtil; import cn.handyplus.lib.expand.adapter.PlayerSchedulerUtil; import cn.handyplus.lib.inventory.HandyInventory; import cn.handyplus.lib.inventory.HandyInventoryUtil; import cn.handyplus.lib.inventory.IHandyClickEvent; import org.bukkit.entity.Player; import org.bukkit.event.inventory.InventoryClickEvent; import java.util.Map; /** * item点击事件 * * @author handy */ public class ItemClickEvent implements IHandyClickEvent { @Override public String guiType() { return GuiTypeEnum.ITEM.getType(); } @Override public boolean isAsync() { return true; } @Override public void rawSlotClick(HandyInventory handyInventory, InventoryClickEvent event) { int rawSlot = event.getRawSlot(); Player player = handyInventory.getPlayer(); // 返回按钮 if (HandyInventoryUtil.isIndex(rawSlot, ConfigUtil.ITEM_CONFIG, "back")) { handyInventory.syncClose(); return; } // 自定义菜单处理 Map<Integer, String> custom = HandyInventoryUtil.getCustomButton(ConfigUtil.ITEM_CONFIG, "custom"); String command = custom.get(rawSlot); if (StrUtil.isNotEmpty(command)) { PlayerSchedulerUtil.syncPerformReplaceCommand(player, command); } } }
1,469
Java
.java
handy-git/PlayerChat
14
0
0
2023-06-24T06:37:49Z
2024-05-06T06:24:03Z
PlayerChatCommand.java
/FileExtraction/Java_unseen/handy-git_PlayerChat/src/main/java/cn/handyplus/chat/command/PlayerChatCommand.java
package cn.handyplus.chat.command; import cn.handyplus.chat.constants.TabListEnum; import cn.handyplus.chat.util.ConfigUtil; import cn.handyplus.lib.annotation.HandyCommand; import cn.handyplus.lib.command.HandyCommandWrapper; import cn.handyplus.lib.util.BaseUtil; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.command.TabExecutor; import org.bukkit.util.StringUtil; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * 命令 * * @author handy */ @HandyCommand(name = "playerChat") public class PlayerChatCommand implements TabExecutor { private final static String PERMISSION = "playerChat.reload"; @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String label, @NotNull String[] args) { // 判断指令是否正确 if (args.length < 1) { return sendHelp(sender); } boolean rst = HandyCommandWrapper.onCommand(sender, cmd, label, args, BaseUtil.getLangMsg("noPermission")); if (!rst) { return sendHelp(sender); } return true; } @Override public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String label, @NotNull String[] args) { List<String> completions = new ArrayList<>(); List<String> commands; if (!sender.hasPermission(PERMISSION)) { commands = new ArrayList<>(); } else { commands = TabListEnum.returnList(args, args.length); } if (commands == null) { return null; } StringUtil.copyPartialMatches(args[args.length - 1].toLowerCase(), commands, completions); Collections.sort(completions); return completions; } /** * 发送帮助 * * @param sender 发送人 * @return 消息 */ private Boolean sendHelp(CommandSender sender) { if (!sender.hasPermission(PERMISSION)) { return true; } List<String> helps = ConfigUtil.LANG_CONFIG.getStringList("helps"); for (String help : helps) { sender.sendMessage(BaseUtil.replaceChatColor(help)); } return true; } }
2,320
Java
.java
handy-git/PlayerChat
14
0
0
2023-06-24T06:37:49Z
2024-05-06T06:24:03Z
GiveCommand.java
/FileExtraction/Java_unseen/handy-git_PlayerChat/src/main/java/cn/handyplus/chat/command/admin/GiveCommand.java
package cn.handyplus.chat.command.admin; import cn.handyplus.chat.enter.ChatPlayerHornEnter; import cn.handyplus.chat.service.ChatPlayerHornService; import cn.handyplus.chat.util.ConfigUtil; import cn.handyplus.lib.command.IHandyCommandEvent; import cn.handyplus.lib.util.AssertUtil; import cn.handyplus.lib.util.BaseUtil; import cn.handyplus.lib.util.MessageUtil; import org.bukkit.OfflinePlayer; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import java.util.Optional; /** * @author handy */ public class GiveCommand implements IHandyCommandEvent { @Override public String command() { return "give"; } @Override public String permission() { return "playerChat.give"; } @Override public boolean isAsync() { return true; } @Override public void onCommand(CommandSender sender, Command command, String s, String[] args) { // 参数是否正常 AssertUtil.notTrue(args.length < 4, sender, ConfigUtil.LANG_CONFIG.getString("paramFailureMsg")); String type = args[1]; String playerName = args[2]; Integer number = AssertUtil.isNumericToInt(args[3], sender, ConfigUtil.LANG_CONFIG.getString("amountFailureMsg")); OfflinePlayer offlinePlayer = BaseUtil.getOfflinePlayer(playerName); Optional<ChatPlayerHornEnter> hornPlayerEnterOpt = ChatPlayerHornService.getInstance().findByUidAndType(offlinePlayer.getUniqueId(), type); if (!hornPlayerEnterOpt.isPresent()) { ChatPlayerHornEnter hornPlayer = new ChatPlayerHornEnter(); hornPlayer.setPlayerName(offlinePlayer.getName()); hornPlayer.setPlayerUuid(offlinePlayer.getUniqueId().toString()); hornPlayer.setType(type); hornPlayer.setNumber(number); ChatPlayerHornService.getInstance().add(hornPlayer); } else { ChatPlayerHornService.getInstance().addNumber(hornPlayerEnterOpt.get().getId(), number); } MessageUtil.sendMessage(sender, ConfigUtil.LANG_CONFIG.getString("giveSucceedMsg")); } }
2,115
Java
.java
handy-git/PlayerChat
14
0
0
2023-06-24T06:37:49Z
2024-05-06T06:24:03Z
LookCommand.java
/FileExtraction/Java_unseen/handy-git_PlayerChat/src/main/java/cn/handyplus/chat/command/admin/LookCommand.java
package cn.handyplus.chat.command.admin; import cn.handyplus.chat.enter.ChatPlayerHornEnter; import cn.handyplus.chat.service.ChatPlayerHornService; import cn.handyplus.chat.util.ConfigUtil; import cn.handyplus.lib.command.IHandyCommandEvent; import cn.handyplus.lib.core.CollUtil; import cn.handyplus.lib.util.AssertUtil; import cn.handyplus.lib.util.BaseUtil; import cn.handyplus.lib.util.MessageUtil; import org.bukkit.OfflinePlayer; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * @author handy */ public class LookCommand implements IHandyCommandEvent { @Override public String command() { return "look"; } @Override public String permission() { return "playerChat.look"; } @Override public boolean isAsync() { return true; } @Override public void onCommand(CommandSender sender, Command command, String s, String[] args) { // 参数是否正常 AssertUtil.notTrue(args.length < 2, sender, ConfigUtil.LANG_CONFIG.getString("paramFailureMsg")); String playerName = args[1]; OfflinePlayer offlinePlayer = BaseUtil.getOfflinePlayer(playerName); List<ChatPlayerHornEnter> hornPlayerList = ChatPlayerHornService.getInstance().findByUid(offlinePlayer.getUniqueId()); if (CollUtil.isNotEmpty(hornPlayerList)) { Map<String, Integer> hornPlayerMap = hornPlayerList.stream().collect(Collectors.toMap(ChatPlayerHornEnter::getType, ChatPlayerHornEnter::getNumber)); for (String type : hornPlayerMap.keySet()) { MessageUtil.sendMessage(sender, playerName + "拥有 " + type + " 喇叭:" + hornPlayerMap.get(type)); } } else { MessageUtil.sendMessage(sender, ConfigUtil.LANG_CONFIG.getString("noLook", "").replace("${player}", playerName)); } } }
1,963
Java
.java
handy-git/PlayerChat
14
0
0
2023-06-24T06:37:49Z
2024-05-06T06:24:03Z
ReloadCommand.java
/FileExtraction/Java_unseen/handy-git_PlayerChat/src/main/java/cn/handyplus/chat/command/admin/ReloadCommand.java
package cn.handyplus.chat.command.admin; import cn.handyplus.chat.util.ConfigUtil; import cn.handyplus.lib.command.IHandyCommandEvent; import cn.handyplus.lib.util.MessageUtil; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; /** * 重载配置 * * @author handy */ public class ReloadCommand implements IHandyCommandEvent { @Override public String command() { return "reload"; } @Override public String permission() { return "playerChat.reload"; } @Override public boolean isAsync() { return true; } @Override public void onCommand(CommandSender sender, Command cmd, String label, String[] args) { ConfigUtil.init(); MessageUtil.sendMessage(sender, ConfigUtil.LANG_CONFIG.getString("reloadMsg")); } }
827
Java
.java
handy-git/PlayerChat
14
0
0
2023-06-24T06:37:49Z
2024-05-06T06:24:03Z
SetCommand.java
/FileExtraction/Java_unseen/handy-git_PlayerChat/src/main/java/cn/handyplus/chat/command/admin/SetCommand.java
package cn.handyplus.chat.command.admin; import cn.handyplus.chat.enter.ChatPlayerHornEnter; import cn.handyplus.chat.service.ChatPlayerHornService; import cn.handyplus.chat.util.ConfigUtil; import cn.handyplus.lib.command.IHandyCommandEvent; import cn.handyplus.lib.util.AssertUtil; import cn.handyplus.lib.util.BaseUtil; import cn.handyplus.lib.util.MessageUtil; import org.bukkit.OfflinePlayer; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import java.util.Optional; /** * @author handy */ public class SetCommand implements IHandyCommandEvent { @Override public String command() { return "set"; } @Override public String permission() { return "playerChat.set"; } @Override public boolean isAsync() { return true; } @Override public void onCommand(CommandSender sender, Command command, String s, String[] args) { // 参数是否正常 AssertUtil.notTrue(args.length < 4, sender, ConfigUtil.LANG_CONFIG.getString("paramFailureMsg")); String type = args[1]; String playerName = args[2]; Integer number = AssertUtil.isNumericToInt(args[3], sender, ConfigUtil.LANG_CONFIG.getString("amountFailureMsg")); OfflinePlayer offlinePlayer = BaseUtil.getOfflinePlayer(playerName); Optional<ChatPlayerHornEnter> hornPlayerEnterOpt = ChatPlayerHornService.getInstance().findByUidAndType(offlinePlayer.getUniqueId(), type); if (!hornPlayerEnterOpt.isPresent()) { ChatPlayerHornEnter hornPlayer = new ChatPlayerHornEnter(); hornPlayer.setPlayerName(offlinePlayer.getName()); hornPlayer.setPlayerUuid(offlinePlayer.getUniqueId().toString()); hornPlayer.setType(type); hornPlayer.setNumber(number); ChatPlayerHornService.getInstance().add(hornPlayer); } else { ChatPlayerHornService.getInstance().setNumber(hornPlayerEnterOpt.get().getId(), number); } MessageUtil.sendMessage(sender, ConfigUtil.LANG_CONFIG.getString("setSucceedMsg")); } }
2,111
Java
.java
handy-git/PlayerChat
14
0
0
2023-06-24T06:37:49Z
2024-05-06T06:24:03Z
TakeCommand.java
/FileExtraction/Java_unseen/handy-git_PlayerChat/src/main/java/cn/handyplus/chat/command/admin/TakeCommand.java
package cn.handyplus.chat.command.admin; import cn.handyplus.chat.enter.ChatPlayerHornEnter; import cn.handyplus.chat.service.ChatPlayerHornService; import cn.handyplus.chat.util.ConfigUtil; import cn.handyplus.lib.command.IHandyCommandEvent; import cn.handyplus.lib.util.AssertUtil; import cn.handyplus.lib.util.BaseUtil; import cn.handyplus.lib.util.MessageUtil; import org.bukkit.OfflinePlayer; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import java.util.Optional; /** * @author handy */ public class TakeCommand implements IHandyCommandEvent { @Override public String command() { return "take"; } @Override public String permission() { return "playerChat.take"; } @Override public boolean isAsync() { return true; } @Override public void onCommand(CommandSender sender, Command command, String s, String[] args) { // 参数是否正常 AssertUtil.notTrue(args.length < 4, sender, ConfigUtil.LANG_CONFIG.getString("paramFailureMsg")); String type = args[1]; String playerName = args[2]; Integer number = AssertUtil.isNumericToInt(args[3], sender, ConfigUtil.LANG_CONFIG.getString("amountFailureMsg")); OfflinePlayer offlinePlayer = BaseUtil.getOfflinePlayer(playerName); Optional<ChatPlayerHornEnter> hornPlayerEnterOpt = ChatPlayerHornService.getInstance().findByUidAndType(offlinePlayer.getUniqueId(), type); if (!hornPlayerEnterOpt.isPresent()) { ChatPlayerHornEnter hornPlayer = new ChatPlayerHornEnter(); hornPlayer.setPlayerName(offlinePlayer.getName()); hornPlayer.setPlayerUuid(offlinePlayer.getUniqueId().toString()); hornPlayer.setType(type); hornPlayer.setNumber(-number); ChatPlayerHornService.getInstance().add(hornPlayer); } else { ChatPlayerHornService.getInstance().subtractNumber(hornPlayerEnterOpt.get().getId(), number); } MessageUtil.sendMessage(sender, ConfigUtil.LANG_CONFIG.getString("takeSucceedMsg")); } }
2,121
Java
.java
handy-git/PlayerChat
14
0
0
2023-06-24T06:37:49Z
2024-05-06T06:24:03Z
ItemCommand.java
/FileExtraction/Java_unseen/handy-git_PlayerChat/src/main/java/cn/handyplus/chat/command/player/ItemCommand.java
package cn.handyplus.chat.command.player; import cn.handyplus.chat.enter.ChatPlayerItemEnter; import cn.handyplus.chat.inventory.ItemGui; import cn.handyplus.chat.service.ChatPlayerItemService; import cn.handyplus.chat.util.ConfigUtil; import cn.handyplus.lib.command.IHandyCommandEvent; import cn.handyplus.lib.expand.adapter.HandySchedulerUtil; import cn.handyplus.lib.util.AssertUtil; import cn.handyplus.lib.util.BaseUtil; import cn.handyplus.lib.util.MessageUtil; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import java.util.Optional; /** * 展示物品 * * @author handy */ public class ItemCommand implements IHandyCommandEvent { @Override public String command() { return "item"; } @Override public String permission() { return "playerChat.item"; } @Override public boolean isAsync() { return true; } @Override public void onCommand(CommandSender sender, Command command, String s, String[] args) { // 参数是否正常 AssertUtil.notTrue(args.length < 2, sender, ConfigUtil.LANG_CONFIG.getString("paramFailureMsg")); // 是否为玩家 Player player = AssertUtil.notPlayer(sender, BaseUtil.getMsgNotColor("noPlayerFailureMsg")); // 展示物品ID Integer itemId = AssertUtil.isNumericToInt(args[1], sender, BaseUtil.getMsgNotColor("amountFailureMsg")); Optional<ChatPlayerItemEnter> chatPlayerItemOptional = ChatPlayerItemService.getInstance().findById(itemId); if (!chatPlayerItemOptional.isPresent()) { MessageUtil.sendMessage(sender, BaseUtil.getMsgNotColor("itemNotFoundMsg")); return; } Inventory inventory = ItemGui.getInstance().createGui(player, chatPlayerItemOptional.get()); HandySchedulerUtil.runTask(() -> player.openInventory(inventory)); } }
1,965
Java
.java
handy-git/PlayerChat
14
0
0
2023-06-24T06:37:49Z
2024-05-06T06:24:03Z
ChannelCommand.java
/FileExtraction/Java_unseen/handy-git_PlayerChat/src/main/java/cn/handyplus/chat/command/player/ChannelCommand.java
package cn.handyplus.chat.command.player; import cn.handyplus.chat.constants.ChatConstants; import cn.handyplus.chat.service.ChatPlayerChannelService; import cn.handyplus.chat.util.ConfigUtil; import cn.handyplus.lib.command.IHandyCommandEvent; import cn.handyplus.lib.util.AssertUtil; import cn.handyplus.lib.util.BaseUtil; import cn.handyplus.lib.util.HandyConfigUtil; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * 切换渠道 * * @author handy */ public class ChannelCommand implements IHandyCommandEvent { @Override public String command() { return "channel"; } @Override public String permission() { return "playerChat.channel"; } @Override public boolean isAsync() { return true; } @Override public void onCommand(CommandSender sender, Command command, String s, String[] args) { // 参数是否正常 AssertUtil.notTrue(args.length < 2, sender, ConfigUtil.LANG_CONFIG.getString("paramFailureMsg")); // 是否为玩家 Player player = AssertUtil.notPlayer(sender, BaseUtil.getLangMsg("noPlayerFailureMsg")); String channel = args[1]; // 渠道存在判断 Map<String, Object> chatChannel = HandyConfigUtil.getChildMap(ConfigUtil.CHAT_CONFIG, "chat"); AssertUtil.isTrue(chatChannel.containsKey(channel), sender, "没有渠道"); // 插件注册渠道处理 List<String> pluginChannelList = ChatConstants.PLUGIN_CHANNEL.values().stream().distinct().collect(Collectors.toList()); AssertUtil.notTrue(pluginChannelList.contains(channel), sender, "无法切换到该渠道"); // 设置渠道 ChatPlayerChannelService.getInstance().setChannel(player.getUniqueId(), channel); } }
1,916
Java
.java
handy-git/PlayerChat
14
0
0
2023-06-24T06:37:49Z
2024-05-06T06:24:03Z
LbCommand.java
/FileExtraction/Java_unseen/handy-git_PlayerChat/src/main/java/cn/handyplus/chat/command/player/LbCommand.java
package cn.handyplus.chat.command.player; import cn.handyplus.chat.PlayerChat; import cn.handyplus.chat.core.HornUtil; import cn.handyplus.chat.enter.ChatPlayerHornEnter; import cn.handyplus.chat.service.ChatPlayerHornService; import cn.handyplus.chat.util.ConfigUtil; import cn.handyplus.lib.annotation.HandyCommand; import cn.handyplus.lib.core.CollUtil; import cn.handyplus.lib.util.BaseUtil; import cn.handyplus.lib.util.BcUtil; import cn.handyplus.lib.util.MessageUtil; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.command.TabExecutor; import org.bukkit.entity.Player; import org.bukkit.permissions.PermissionDefault; import org.bukkit.util.StringUtil; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; /** * 发送消息 * * @author handy */ @HandyCommand(name = "lb", permission = "playerChat.lb", PERMISSION_DEFAULT = PermissionDefault.TRUE) public class LbCommand implements TabExecutor { @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String label, @NotNull String[] args) { // 参数是否正常 if (args.length < 2) { MessageUtil.sendMessage(sender, "参数错误 /lb [喇叭类型] [消息内容]"); return true; } // 是否为玩家 if (BaseUtil.isNotPlayer(sender)) { MessageUtil.sendMessage(sender, BaseUtil.getLangMsg("noPlayerFailureMsg")); return true; } Player player = (Player) sender; // 获取类型 String type = args[0]; List<String> serverList = ConfigUtil.LB_CONFIG.getStringList("lb." + type + ".server"); if (CollUtil.isEmpty(serverList)) { MessageUtil.sendMessage(sender, "配置错误"); return true; } boolean enable = ConfigUtil.LB_CONFIG.getBoolean("lb." + type + ".enable"); if (!enable) { MessageUtil.sendMessage(player, type + " &7已经被管理员禁用"); return true; } Optional<ChatPlayerHornEnter> hornPlayerEnterOpt = ChatPlayerHornService.getInstance().findByUidAndType(player.getUniqueId(), type); if (!hornPlayerEnterOpt.isPresent()) { MessageUtil.sendMessage(player, ConfigUtil.LANG_CONFIG.getString("noHave")); return true; } ChatPlayerHornEnter hornPlayerEnter = hornPlayerEnterOpt.get(); if (hornPlayerEnter.getNumber() < 1) { MessageUtil.sendMessage(player, ConfigUtil.LANG_CONFIG.getString("noHaveNumber")); return true; } // 进行扣除 ChatPlayerHornService.getInstance().subtractNumber(hornPlayerEnter.getId(), 1); // 获取消息 StringBuilder message = new StringBuilder(); for (int i = 1; i < args.length; i++) { message.append(args[i]).append(" "); } BcUtil.BcMessageParam param = new BcUtil.BcMessageParam(); param.setPluginName(PlayerChat.getInstance().getName()); param.setType(type); param.setMessage(message.toString()); param.setTimestamp(System.currentTimeMillis()); param.setPlayerName(player.getName()); BcUtil.sendParamForward(player, param); // 发送消息 HornUtil.sendMsg(player, param); return true; } @Override public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String label, @NotNull String[] args) { List<String> completions = new ArrayList<>(); List<String> commands = null; if (args.length == 1) { commands = HornUtil.getTabTitle(); } if (commands == null) { return new ArrayList<>(); } StringUtil.copyPartialMatches(args[args.length - 1].toLowerCase(), commands, completions); Collections.sort(completions); return completions; } }
4,041
Java
.java
handy-git/PlayerChat
14
0
0
2023-06-24T06:37:49Z
2024-05-06T06:24:03Z
PlayerChatApi.java
/FileExtraction/Java_unseen/handy-git_PlayerChat/src/main/java/cn/handyplus/chat/api/PlayerChatApi.java
package cn.handyplus.chat.api; import cn.handyplus.chat.constants.ChatConstants; import cn.handyplus.chat.enter.ChatPlayerChannelEnter; import cn.handyplus.chat.service.ChatPlayerChannelService; import cn.handyplus.lib.core.CollUtil; import cn.handyplus.lib.core.StrUtil; import cn.handyplus.lib.util.BaseUtil; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.UUID; /** * API * * @author handy * @since 1.0.6 */ public class PlayerChatApi { private PlayerChatApi() { } private static class SingletonHolder { private static final PlayerChatApi INSTANCE = new PlayerChatApi(); } public static PlayerChatApi getInstance() { return PlayerChatApi.SingletonHolder.INSTANCE; } /** * 注册渠道 * * @param plugin 插件 * @param channel 渠道名 */ public void regChannel(Plugin plugin, String channel) { ChatConstants.PLUGIN_CHANNEL.put(this.getPluginChannelName(plugin, channel), plugin.getName()); } /** * 取消注册渠道 * * @param plugin 插件 * @param channel 渠道名 */ public void unRegChannel(Plugin plugin, String channel) { // 移除渠道 String pluginChannelName = this.getPluginChannelName(plugin, channel); ChatConstants.PLUGIN_CHANNEL.remove(pluginChannelName); // 查询是否有使用该渠道的 List<ChatPlayerChannelEnter> channelEnterList = ChatPlayerChannelService.getInstance().findByChannel(pluginChannelName); if (CollUtil.isEmpty(channelEnterList)) { return; } // 重新设置渠道 ChatPlayerChannelService.getInstance().setChannel(pluginChannelName, ChatConstants.DEFAULT); // 缓存渠道 for (ChatPlayerChannelEnter channelEnter : channelEnterList) { Optional<Player> playerOptional = BaseUtil.getOnlinePlayer(UUID.fromString(channelEnter.getPlayerUuid())); playerOptional.ifPresent(player -> ChatConstants.PLAYER_CHAT_CHANNEL.put(player.getUniqueId(), ChatConstants.DEFAULT)); } } /** * 注册渠道 * * @param plugin 插件 * @param channelList 渠道名集合 */ public void regChannel(Plugin plugin, List<String> channelList) { for (String channel : channelList) { regChannel(plugin, channel); } } /** * 取消注册渠道 * * @param plugin 插件 * @param channelList 渠道名集合 */ public void unRegChannel(Plugin plugin, List<String> channelList) { for (String channel : channelList) { unRegChannel(plugin, channel); } } /** * 取消注册渠道 * * @param plugin 插件 */ public void unRegChannel(Plugin plugin) { ChatConstants.PLUGIN_CHANNEL.entrySet().removeIf(entry -> entry.getValue().equals(plugin.getName())); } /** * 注册玩家监听的插件自定义的渠道 * * @param plugin 插件 * @param player 玩家 * @param channel 渠道 * @return true成功 */ public boolean regPlayerChannel(Plugin plugin, String channel, Player player) { String channelName = getPluginChannelName(plugin, channel); if (StrUtil.isEmpty(ChatConstants.PLUGIN_CHANNEL.get(channelName))) { return false; } // 设置玩家拥有的插件渠道 List<String> channelNameList = ChatConstants.PLAYER_PLUGIN_CHANNEL.getOrDefault(player.getUniqueId(), new ArrayList<>()); if (!channelNameList.contains(channelName)) { channelNameList.add(channelName); } ChatConstants.PLAYER_PLUGIN_CHANNEL.put(player.getUniqueId(), channelNameList); return true; } /** * 取消注册玩家监听的插件自定义的渠道 * * @param plugin 插件 * @param player 玩家 * @param channel 渠道 * @return true成功 */ public boolean unRegPlayerChannel(Plugin plugin, String channel, Player player) { String channelName = getPluginChannelName(plugin, channel); if (StrUtil.isEmpty(ChatConstants.PLUGIN_CHANNEL.get(channelName))) { return false; } // 取消玩家渠道 List<String> channelNameList = ChatConstants.PLAYER_PLUGIN_CHANNEL.getOrDefault(player.getUniqueId(), new ArrayList<>()); channelNameList.remove(channelName); ChatConstants.PLAYER_PLUGIN_CHANNEL.put(player.getUniqueId(), channelNameList); return true; } /** * 设置玩家正在使用的渠道 * 只能设置本插件注册的渠道 * * @param plugin 插件 * @param player 玩家 * @param channel 渠道 * @return true成功 */ public boolean setPlayerChannel(Plugin plugin, String channel, Player player) { String channelName = getPluginChannelName(plugin, channel); if (StrUtil.isEmpty(ChatConstants.PLUGIN_CHANNEL.get(channelName))) { return false; } return ChatPlayerChannelService.getInstance().setChannel(player.getUniqueId(), channelName); } /** * 设置玩家正在使用的渠道为默认 * * @param player 玩家 * @return true成功 */ public boolean setPlayerChannelToDefault(Player player) { return ChatPlayerChannelService.getInstance().setChannel(player.getUniqueId(), ChatConstants.DEFAULT); } /** * 处理渠道名称 * * @param plugin 插件 * @param channel 渠道名 * @return 渠道名称 */ private String getPluginChannelName(Plugin plugin, String channel) { return plugin.getName() + "_" + channel; } }
5,837
Java
.java
handy-git/PlayerChat
14
0
0
2023-06-24T06:37:49Z
2024-05-06T06:24:03Z
ChatPlayerChannelEnter.java
/FileExtraction/Java_unseen/handy-git_PlayerChat/src/main/java/cn/handyplus/chat/enter/ChatPlayerChannelEnter.java
package cn.handyplus.chat.enter; import cn.handyplus.lib.annotation.TableField; import cn.handyplus.lib.annotation.TableName; import cn.handyplus.lib.db.enums.IndexEnum; import lombok.Getter; import lombok.Setter; /** * 玩家渠道 * * @author handy */ @Getter @Setter @TableName(value = "chat_player_channel", comment = "玩家渠道") public class ChatPlayerChannelEnter { @TableField(value = "id", comment = "ID") private Integer id; @TableField(value = "player_name", comment = "玩家名称") private String playerName; @TableField(value = "player_uuid", comment = "玩家uuid", notNull = true, indexEnum = IndexEnum.INDEX) private String playerUuid; @TableField(value = "channel", comment = "渠道") private String channel; }
776
Java
.java
handy-git/PlayerChat
14
0
0
2023-06-24T06:37:49Z
2024-05-06T06:24:03Z
ChatPlayerItemEnter.java
/FileExtraction/Java_unseen/handy-git_PlayerChat/src/main/java/cn/handyplus/chat/enter/ChatPlayerItemEnter.java
package cn.handyplus.chat.enter; import cn.handyplus.lib.annotation.TableField; import cn.handyplus.lib.annotation.TableName; import cn.handyplus.lib.db.enums.IndexEnum; import lombok.Getter; import lombok.Setter; import java.util.Date; /** * 玩家展示 * * @author handy */ @Getter @Setter @TableName(value = "chat_player_item", comment = "玩家展示") public class ChatPlayerItemEnter { @TableField(value = "id", comment = "ID") private Integer id; @TableField(value = "player_name", comment = "玩家名称") private String playerName; @TableField(value = "player_uuid", comment = "玩家uuid", notNull = true, indexEnum = IndexEnum.INDEX) private String playerUuid; @TableField(value = "version", comment = "服务器版本") private Integer version; @TableField(value = "item", length = 20000, comment = "展示物品") private String item; @TableField(value = "create_time", comment = "创建时间") private Date createTime; }
1,000
Java
.java
handy-git/PlayerChat
14
0
0
2023-06-24T06:37:49Z
2024-05-06T06:24:03Z
ChatPlayerHornEnter.java
/FileExtraction/Java_unseen/handy-git_PlayerChat/src/main/java/cn/handyplus/chat/enter/ChatPlayerHornEnter.java
package cn.handyplus.chat.enter; import cn.handyplus.lib.annotation.TableField; import cn.handyplus.lib.annotation.TableName; import cn.handyplus.lib.db.enums.IndexEnum; import lombok.Getter; import lombok.Setter; /** * 玩家喇叭 * * @author handy */ @Getter @Setter @TableName(value = "chat_player_horn", comment = "玩家喇叭") public class ChatPlayerHornEnter { @TableField(value = "id", comment = "ID") private Integer id; @TableField(value = "player_name", comment = "玩家名称") private String playerName; @TableField(value = "player_uuid", comment = "玩家uuid", notNull = true, indexEnum = IndexEnum.INDEX) private String playerUuid; @TableField(value = "type", comment = "类型") private String type; @TableField(value = "number", comment = "数量") private Integer number; }
847
Java
.java
handy-git/PlayerChat
14
0
0
2023-06-24T06:37:49Z
2024-05-06T06:24:03Z
ChatUtil.java
/FileExtraction/Java_unseen/handy-git_PlayerChat/src/main/java/cn/handyplus/chat/core/ChatUtil.java
package cn.handyplus.chat.core; import cn.handyplus.chat.constants.ChatConstants; import cn.handyplus.chat.hook.PlaceholderApiUtil; import cn.handyplus.chat.param.ChatParam; import cn.handyplus.chat.util.ConfigUtil; import cn.handyplus.lib.core.CollUtil; import cn.handyplus.lib.core.JsonUtil; import cn.handyplus.lib.core.StrUtil; import cn.handyplus.lib.expand.adapter.HandySchedulerUtil; import cn.handyplus.lib.expand.adapter.PlayerSchedulerUtil; import cn.handyplus.lib.util.BaseUtil; import cn.handyplus.lib.util.BcUtil; import cn.handyplus.lib.util.MessageUtil; import cn.handyplus.lib.util.RgbTextUtil; import net.md_5.bungee.api.chat.BaseComponent; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Sound; import org.bukkit.entity.Player; import java.util.ArrayList; import java.util.List; import static org.bukkit.Bukkit.getServer; /** * 聊天解析工具 * * @author handy */ public class ChatUtil { /** * 解析并发送消息 * * @param msg 消息内容 * @param isConsoleMsg 打印消息 */ public static void sendMsg(BcUtil.BcMessageParam msg, boolean isConsoleMsg) { HandySchedulerUtil.runTaskAsynchronously(() -> sendTextMsg(msg, isConsoleMsg)); } /** * 解析并发送消息 * * @param param 消息内容 * @param isConsoleMsg 打印消息 */ private synchronized static void sendTextMsg(BcUtil.BcMessageParam param, boolean isConsoleMsg) { String chatParamJson = param.getMessage(); ChatParam chatParam = JsonUtil.toBean(chatParamJson, ChatParam.class); BaseComponent[] textComponent = buildMsg(chatParam, param.getType()); String channel = chatParam.getChannel(); // 渠道是否开启 if (StrUtil.isEmpty(ChannelUtil.isChannelEnable(channel))) { return; } // 根据渠道发送消息 for (Player onlinePlayer : ChannelUtil.getChannelPlayer(channel)) { MessageUtil.sendMessage(onlinePlayer, textComponent); // 如果开启艾特,发送消息 if (ChatConstants.CHAT_TYPE.equals(param.getType()) && ConfigUtil.CHAT_CONFIG.getBoolean("at.enable") && chatParam.getMessage().contains(onlinePlayer.getName())) { String sound = ConfigUtil.CHAT_CONFIG.getString("at.sound"); playSound(onlinePlayer, sound); } } // 控制台消息 if (isConsoleMsg) { StringBuilder str = new StringBuilder(); for (BaseComponent baseComponent : textComponent) { str.append(baseComponent.toLegacyText()); } getServer().getConsoleSender().sendMessage(str.toString()); } } /** * 构建消息 * * @param player 玩家 * @param channel 渠道 * @return 参数 */ public static ChatParam buildChatParam(Player player, String channel) { // 渠道是否开启 String channelEnable = ChannelUtil.isChannelEnable(channel); if (StrUtil.isEmpty(channelEnable)) { return null; } // 前缀 String prefixText = ConfigUtil.CHAT_CONFIG.getString("chat." + channelEnable + ".format.prefix.text"); List<String> prefixHover = ConfigUtil.CHAT_CONFIG.getStringList("chat." + channelEnable + ".format.prefix.hover"); String prefixClick = ConfigUtil.CHAT_CONFIG.getString("chat." + channelEnable + ".format.prefix.click"); // 玩家信息 String playerText = ConfigUtil.CHAT_CONFIG.getString("chat." + channelEnable + ".format.player.text"); List<String> playerHover = ConfigUtil.CHAT_CONFIG.getStringList("chat." + channelEnable + ".format.player.hover"); String playerClick = ConfigUtil.CHAT_CONFIG.getString("chat." + channelEnable + ".format.player.click"); // 消息 String msgText = ConfigUtil.CHAT_CONFIG.getString("chat." + channelEnable + ".format.msg.text"); List<String> msgHover = ConfigUtil.CHAT_CONFIG.getStringList("chat." + channelEnable + ".format.msg.hover"); String msgClick = ConfigUtil.CHAT_CONFIG.getString("chat." + channelEnable + ".format.msg.click"); // 解析内部变量 String channelName = ChannelUtil.getChannelName(channel); prefixText = replaceStr(player, channelName, prefixText); prefixHover = replaceStr(player, channelName, prefixHover); prefixClick = replaceStr(player, channelName, prefixClick); playerText = replaceStr(player, channelName, playerText); playerHover = replaceStr(player, channelName, playerHover); playerClick = replaceStr(player, channelName, playerClick); msgText = replaceStr(player, channelName, msgText); msgHover = replaceStr(player, channelName, msgHover); msgClick = replaceStr(player, channelName, msgClick); // 解析PAPI变量 prefixText = PlaceholderApiUtil.set(player, prefixText); prefixHover = PlaceholderApiUtil.set(player, prefixHover); prefixClick = PlaceholderApiUtil.set(player, prefixClick); playerText = PlaceholderApiUtil.set(player, playerText); playerHover = PlaceholderApiUtil.set(player, playerHover); playerClick = PlaceholderApiUtil.set(player, playerClick); msgText = PlaceholderApiUtil.set(player, msgText); msgHover = PlaceholderApiUtil.set(player, msgHover); msgClick = PlaceholderApiUtil.set(player, msgClick); // 构建参数 return ChatParam.builder().prefixText(prefixText).prefixHover(prefixHover).prefixClick(prefixClick) .playerText(playerText).playerHover(playerHover).playerClick(playerClick) .msgText(msgText).msgHover(msgHover).msgClick(msgClick).build(); } /** * 构建消息 * * @param chatParam 入参 * @param type 类型 */ public static BaseComponent[] buildMsg(ChatParam chatParam, String type) { // 加载rgb颜色 chatParam.setPrefixText(BaseUtil.replaceChatColor(chatParam.getPrefixText())); chatParam.setPrefixHover(BaseUtil.replaceChatColor(chatParam.getPrefixHover())); chatParam.setPlayerText(BaseUtil.replaceChatColor(chatParam.getPlayerText())); chatParam.setPlayerHover(BaseUtil.replaceChatColor(chatParam.getPlayerHover())); chatParam.setMsgText(BaseUtil.replaceChatColor(chatParam.getMsgText())); chatParam.setMsgHover(BaseUtil.replaceChatColor(chatParam.getMsgHover())); chatParam.setMessage(chatParam.isHasColor() ? BaseUtil.replaceChatColor(chatParam.getMessage()) : chatParam.getMessage()); // 前缀 RgbTextUtil prefixTextComponent = RgbTextUtil.getInstance().init(chatParam.getPrefixText()); prefixTextComponent.addHoverText(CollUtil.listToStr(chatParam.getPrefixHover(), "\n")); prefixTextComponent.addClickSuggestCommand(chatParam.getPrefixClick()); // 玩家 RgbTextUtil playerTextComponent = RgbTextUtil.getInstance().init(chatParam.getPlayerText()); playerTextComponent.addHoverText(CollUtil.listToStr(chatParam.getPlayerHover(), "\n")); playerTextComponent.addClickSuggestCommand(chatParam.getPlayerClick()); // 消息 RgbTextUtil msgTextComponent = RgbTextUtil.getInstance().init(chatParam.getMsgText() + chatParam.getMessage(), false); // 聊天处理 if (ChatConstants.CHAT_TYPE.equals(type)) { msgTextComponent.addHoverText(CollUtil.listToStr(chatParam.getMsgHover(), "\n")); msgTextComponent.addClickSuggestCommand(chatParam.getMsgClick()); } // 物品展示处理 if (ChatConstants.ITEM_TYPE.equals(type)) { msgTextComponent = RgbTextUtil.getInstance().init(chatParam.getMsgText() + chatParam.getItemText()); String itemHover = CollUtil.listToStr(chatParam.getItemHover(), "\n"); msgTextComponent.addHoverText(itemHover); msgTextComponent.addClickCommand("/plc item " + chatParam.getItemId()); } // 构建消息 return prefixTextComponent.addExtra(playerTextComponent.build()).addExtra(msgTextComponent.build()).build(); } /** * 解析内部变量 * * @param player 玩家 * @param channelName 渠道名称 * @param str 内容 * @return 新内容 */ private static String replaceStr(Player player, String channelName, String str) { if (StrUtil.isEmpty(str)) { return str; } return str.replace("${channel}", channelName).replace("${player}", player.getName()); } /** * 解析内部变量 * * @param player 玩家 * @param channelName 渠道名称 * @param strList 内容集合 * @return 新内容 */ private static List<String> replaceStr(Player player, String channelName, List<String> strList) { if (CollUtil.isEmpty(strList)) { return strList; } List<String> newStrList = new ArrayList<>(); for (String str : strList) { newStrList.add(replaceStr(player, channelName, str)); } return newStrList; } /** * @param message 消息 * @return 新消息 * @ 处理 * @since 1.0.9 */ public static String at(String message) { boolean enable = ConfigUtil.CHAT_CONFIG.getBoolean("at.enable"); if (!enable) { return message; } message = BaseUtil.replaceChatColor(message); for (Player onlinePlayer : Bukkit.getOnlinePlayers()) { if (message.contains("@" + onlinePlayer.getName())) { message = message.replace("@" + onlinePlayer.getName(), ChatColor.BLUE + onlinePlayer.getName() + ChatColor.WHITE); } } return message; } /** * 播放声音 * * @param player 玩家 * @param soundStr 声音 * @since 1.0.9 */ private static void playSound(Player player, String soundStr) { if (StrUtil.isEmpty(soundStr)) { return; } Sound sound; try { sound = Sound.valueOf(soundStr); } catch (Exception e) { MessageUtil.sendMessage(player, "没有 " + soundStr + " 音效"); return; } PlayerSchedulerUtil.playSound(player, sound, 1, 1); } }
10,460
Java
.java
handy-git/PlayerChat
14
0
0
2023-06-24T06:37:49Z
2024-05-06T06:24:03Z
HornUtil.java
/FileExtraction/Java_unseen/handy-git_PlayerChat/src/main/java/cn/handyplus/chat/core/HornUtil.java
package cn.handyplus.chat.core; import cn.handyplus.chat.hook.PlaceholderApiUtil; import cn.handyplus.chat.util.ConfigUtil; import cn.handyplus.lib.constants.BaseConstants; import cn.handyplus.lib.constants.VersionCheckEnum; import cn.handyplus.lib.core.StrUtil; import cn.handyplus.lib.util.BaseUtil; import cn.handyplus.lib.util.BcUtil; import cn.handyplus.lib.util.BossBarUtil; import cn.handyplus.lib.util.HandyConfigUtil; import cn.handyplus.lib.util.MessageUtil; import org.bukkit.boss.KeyedBossBar; import org.bukkit.entity.Player; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * 喇叭消息工具 * * @author handy */ public class HornUtil { /** * 发送消息 * * @param player 玩家 * @param bcMessageParam 消息 */ public static void sendMsg(Player player, BcUtil.BcMessageParam bcMessageParam) { String type = bcMessageParam.getType(); String msg = bcMessageParam.getMessage(); if (StrUtil.isEmpty(type) || StrUtil.isEmpty(msg)) { MessageUtil.sendConsoleMessage("消息错误:入参错误,type:" + type + ",msg:" + msg); return; } String rgb = ConfigUtil.LB_CONFIG.getString("lb." + type + ".rgb", ""); String name = ConfigUtil.LB_CONFIG.getString("lb." + type + ".name"); boolean message = ConfigUtil.LB_CONFIG.getBoolean("lb." + type + ".message.enable"); boolean actionbar = ConfigUtil.LB_CONFIG.getBoolean("lb." + type + ".actionbar.enable"); boolean boss = ConfigUtil.LB_CONFIG.getBoolean("lb." + type + ".boss.enable"); boolean title = ConfigUtil.LB_CONFIG.getBoolean("lb." + type + ".title"); // 解析变量 rgb = rgb.replace("${player}", bcMessageParam.getPlayerName()); rgb = PlaceholderApiUtil.set(player, rgb); // 加载rgb颜色 String msgRgb = BaseUtil.replaceChatColor(rgb + msg); if (message) { List<String> messageFormatList = ConfigUtil.LB_CONFIG.getStringList("lb." + type + ".message.format"); for (String messageFormat : messageFormatList) { MessageUtil.sendAllMessage(messageFormat.replace("${message}", msgRgb)); } } // 1.9+ 才可使用 if (actionbar && BaseConstants.VERSION_ID > VersionCheckEnum.V_1_8.getVersionId()) { String actionbarRgb = ConfigUtil.LB_CONFIG.getString("lb." + type + ".actionbar.rgb"); String actionbarRgbMsg = BaseUtil.replaceChatColor(actionbarRgb + msg); actionbarRgbMsg = PlaceholderApiUtil.set(player, actionbarRgbMsg); MessageUtil.sendAllActionbar(actionbarRgbMsg); } // 1.9+ 才可使用 if (title && BaseConstants.VERSION_ID > VersionCheckEnum.V_1_8.getVersionId()) { name = PlaceholderApiUtil.set(player, name); MessageUtil.sendAllTitle(name, msgRgb); } // 1.13+ 才可使用 if (boss && BaseConstants.VERSION_ID > VersionCheckEnum.V_1_12.getVersionId()) { KeyedBossBar bossBar = BossBarUtil.createBossBar(ConfigUtil.LB_CONFIG, "lb." + type + ".boss", msgRgb); BossBarUtil.addAllPlayer(bossBar); int time = ConfigUtil.LB_CONFIG.getInt("lb." + type + ".boss.time", 3); BossBarUtil.setProgress(bossBar.getKey(), time); BossBarUtil.removeBossBar(bossBar.getKey(), time); } } /** * 获取启动的喇叭 * * @return 喇叭列表 */ public static List<String> getTabTitle() { Map<String, String> map = HandyConfigUtil.getStringMapChild(ConfigUtil.LB_CONFIG, "lb"); List<String> list = new ArrayList<>(); for (String key : map.keySet()) { boolean enable = ConfigUtil.LB_CONFIG.getBoolean("lb." + key + ".enable"); if (!enable) { continue; } list.add(key); } return list; } }
3,978
Java
.java
handy-git/PlayerChat
14
0
0
2023-06-24T06:37:49Z
2024-05-06T06:24:03Z
ChannelUtil.java
/FileExtraction/Java_unseen/handy-git_PlayerChat/src/main/java/cn/handyplus/chat/core/ChannelUtil.java
package cn.handyplus.chat.core; import cn.handyplus.chat.constants.ChatConstants; import cn.handyplus.chat.util.ConfigUtil; import cn.handyplus.lib.core.StrUtil; import cn.handyplus.lib.util.BaseUtil; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import java.util.ArrayList; import java.util.List; /** * 渠道处理 * * @author handy * @since 1.0.6 */ public class ChannelUtil { /** * 获取渠道 * * @param channel 渠道 * @return true开启 */ public static String isChannelEnable(String channel) { // chat自带渠道 boolean chatEnable = ConfigUtil.CHAT_CONFIG.getBoolean("chat." + channel + ".enable"); if (chatEnable) { return channel; } // 第三方插件渠道 String pluginChannel = ChatConstants.PLUGIN_CHANNEL.get(channel); if (StrUtil.isEmpty(pluginChannel)) { return null; } // 第三方插件渠道是否启用 boolean pluginChannelEnable = ConfigUtil.CHAT_CONFIG.getBoolean("chat." + pluginChannel + ".enable"); if (!pluginChannelEnable) { return null; } return pluginChannel; } /** * 获取渠道名 * * @param channel 渠道 * @return channel名称 */ public static String getChannelName(String channel) { String channelEnable = isChannelEnable(channel); String pluginChannel = ConfigUtil.CHAT_CONFIG.getString("chat." + channelEnable + ".name", channelEnable); return BaseUtil.replaceChatColor(pluginChannel); } /** * 获取该渠道玩家 * * @param channel 渠道 * @return 在渠道的玩家 */ public static List<Player> getChannelPlayer(String channel) { // 默认渠道返回全部 if (ChatConstants.DEFAULT.equals(channel)) { return new ArrayList<>(Bukkit.getOnlinePlayers()); } List<Player> playerList = new ArrayList<>(); for (Player onlinePlayer : Bukkit.getOnlinePlayers()) { // 判断插件自定义渠道 List<String> channelNameList = ChatConstants.PLAYER_PLUGIN_CHANNEL.getOrDefault(onlinePlayer.getUniqueId(), new ArrayList<>()); if (channelNameList.contains(channel)) { playerList.add(onlinePlayer); continue; } // 判断是否存在对应渠道权限 if (onlinePlayer.hasPermission("playerChat.chat." + isChannelEnable(channel))) { playerList.add(onlinePlayer); } } return playerList; } }
2,627
Java
.java
handy-git/PlayerChat
14
0
0
2023-06-24T06:37:49Z
2024-05-06T06:24:03Z
ChatPlayerChannelService.java
/FileExtraction/Java_unseen/handy-git_PlayerChat/src/main/java/cn/handyplus/chat/service/ChatPlayerChannelService.java
package cn.handyplus.chat.service; import cn.handyplus.chat.constants.ChatConstants; import cn.handyplus.chat.enter.ChatPlayerChannelEnter; import cn.handyplus.lib.db.Db; import java.util.List; import java.util.Optional; import java.util.UUID; /** * 玩家渠道 * * @author handy */ public class ChatPlayerChannelService { private ChatPlayerChannelService() { } private static class SingletonHolder { private static final ChatPlayerChannelService INSTANCE = new ChatPlayerChannelService(); } public static ChatPlayerChannelService getInstance() { return SingletonHolder.INSTANCE; } /** * 新增 */ public void add(ChatPlayerChannelEnter enter) { Db.use(ChatPlayerChannelEnter.class).execution().insert(enter); } /** * 根据uid查询 * * @param playerUuid uid * @return 数据 */ public Optional<ChatPlayerChannelEnter> findByUid(UUID playerUuid) { Db<ChatPlayerChannelEnter> use = Db.use(ChatPlayerChannelEnter.class); use.where().eq(ChatPlayerChannelEnter::getPlayerUuid, playerUuid); return use.execution().selectOne(); } /** * 根据playerUuid设置渠道 * * @param playerUuid uid * @param channel 渠道 * @since 1.0.6 */ public boolean setChannel(UUID playerUuid, String channel) { Db<ChatPlayerChannelEnter> db = Db.use(ChatPlayerChannelEnter.class); db.update().set(ChatPlayerChannelEnter::getChannel, channel); db.where().eq(ChatPlayerChannelEnter::getPlayerUuid, playerUuid); int update = db.execution().update(); // 重新缓存数据 ChatConstants.PLAYER_CHAT_CHANNEL.put(playerUuid, channel); return update > 0; } /** * 根据渠道查询 * * @param channel 渠道 * @return 数据 * @since 1.0.6 */ public List<ChatPlayerChannelEnter> findByChannel(String channel) { Db<ChatPlayerChannelEnter> use = Db.use(ChatPlayerChannelEnter.class); use.where().eq(ChatPlayerChannelEnter::getChannel, channel); return use.execution().list(); } /** * 根据playerUuid设置渠道 * * @param channel 渠道 * @param newChannel 新渠道 * @since 1.0.6 */ public boolean setChannel(String channel, String newChannel) { Db<ChatPlayerChannelEnter> db = Db.use(ChatPlayerChannelEnter.class); db.update().set(ChatPlayerChannelEnter::getChannel, newChannel); db.where().eq(ChatPlayerChannelEnter::getChannel, channel); return db.execution().update() > 0; } }
2,644
Java
.java
handy-git/PlayerChat
14
0
0
2023-06-24T06:37:49Z
2024-05-06T06:24:03Z
ChatPlayerItemService.java
/FileExtraction/Java_unseen/handy-git_PlayerChat/src/main/java/cn/handyplus/chat/service/ChatPlayerItemService.java
package cn.handyplus.chat.service; import cn.handyplus.chat.enter.ChatPlayerItemEnter; import cn.handyplus.lib.core.DateUtil; import cn.handyplus.lib.db.Db; import java.util.Calendar; import java.util.Date; import java.util.Optional; /** * @author handy */ public class ChatPlayerItemService { private ChatPlayerItemService() { } private static class SingletonHolder { private static final ChatPlayerItemService INSTANCE = new ChatPlayerItemService(); } public static ChatPlayerItemService getInstance() { return ChatPlayerItemService.SingletonHolder.INSTANCE; } /** * 新增 */ public Integer add(ChatPlayerItemEnter enter) { return Db.use(ChatPlayerItemEnter.class).execution().insert(enter); } /** * 根据id查询 * * @param id id * @return 数据 */ public Optional<ChatPlayerItemEnter> findById(Integer id) { return Db.use(ChatPlayerItemEnter.class).execution().selectById(id); } /** * 清理周贡献 * * @return 清理数量 * @since 1.10.9 */ public int clearWeekData() { Db<ChatPlayerItemEnter> db = Db.use(ChatPlayerItemEnter.class); db.where().le(ChatPlayerItemEnter::getCreateTime, DateUtil.offset(new Date(), Calendar.DATE, -7)); return db.execution().delete(); } }
1,368
Java
.java
handy-git/PlayerChat
14
0
0
2023-06-24T06:37:49Z
2024-05-06T06:24:03Z
ChatPlayerHornService.java
/FileExtraction/Java_unseen/handy-git_PlayerChat/src/main/java/cn/handyplus/chat/service/ChatPlayerHornService.java
package cn.handyplus.chat.service; import cn.handyplus.chat.enter.ChatPlayerHornEnter; import cn.handyplus.lib.db.Db; import java.util.List; import java.util.Optional; import java.util.UUID; /** * 玩家喇叭 * * @author handy */ public class ChatPlayerHornService { private ChatPlayerHornService() { } private static class SingletonHolder { private static final ChatPlayerHornService INSTANCE = new ChatPlayerHornService(); } public static ChatPlayerHornService getInstance() { return SingletonHolder.INSTANCE; } /** * 新增 */ public void add(ChatPlayerHornEnter enter) { Db.use(ChatPlayerHornEnter.class).execution().insert(enter); } /** * 根据uid和类型查询 * * @param playerUuid uid * @param type 类型 * @return 数据 */ public Optional<ChatPlayerHornEnter> findByUidAndType(UUID playerUuid, String type) { Db<ChatPlayerHornEnter> use = Db.use(ChatPlayerHornEnter.class); use.where().eq(ChatPlayerHornEnter::getPlayerUuid, playerUuid) .eq(ChatPlayerHornEnter::getType, type); return use.execution().selectOne(); } /** * 根据uid查询 * * @param playerUuid uid * @return 数据 */ public List<ChatPlayerHornEnter> findByUid(UUID playerUuid) { Db<ChatPlayerHornEnter> use = Db.use(ChatPlayerHornEnter.class); use.where().eq(ChatPlayerHornEnter::getPlayerUuid, playerUuid); return use.execution().list(); } /** * 根据id 减少数量 * * @param id ID */ public void subtractNumber(Integer id, int number) { Db<ChatPlayerHornEnter> db = Db.use(ChatPlayerHornEnter.class); db.update().subtract(ChatPlayerHornEnter::getNumber, ChatPlayerHornEnter::getNumber, number); db.execution().updateById(id); } /** * 根据id 设置数量 * * @param id ID */ public void setNumber(Integer id, int number) { Db<ChatPlayerHornEnter> db = Db.use(ChatPlayerHornEnter.class); db.update().set(ChatPlayerHornEnter::getNumber, number); db.execution().updateById(id); } /** * 根据id 增加数量 * * @param id ID */ public void addNumber(Integer id, int number) { Db<ChatPlayerHornEnter> db = Db.use(ChatPlayerHornEnter.class); db.update().add(ChatPlayerHornEnter::getNumber, ChatPlayerHornEnter::getNumber, number); db.execution().updateById(id); } }
2,550
Java
.java
handy-git/PlayerChat
14
0
0
2023-06-24T06:37:49Z
2024-05-06T06:24:03Z
GuiTypeEnum.java
/FileExtraction/Java_unseen/handy-git_PlayerChat/src/main/java/cn/handyplus/chat/constants/GuiTypeEnum.java
package cn.handyplus.chat.constants; import lombok.AllArgsConstructor; import lombok.Getter; /** * gui类型 * * @author handy */ @Getter @AllArgsConstructor public enum GuiTypeEnum { /** * gui类型 */ ITEM("item"), ; private final String type; }
282
Java
.java
handy-git/PlayerChat
14
0
0
2023-06-24T06:37:49Z
2024-05-06T06:24:03Z
ChatConstants.java
/FileExtraction/Java_unseen/handy-git_PlayerChat/src/main/java/cn/handyplus/chat/constants/ChatConstants.java
package cn.handyplus.chat.constants; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; /** * 常量 * * @author handy */ public abstract class ChatConstants { /** * 检查更新网址 */ public final static String PLUGIN_VERSION_URL = "https://api.github.com/repos/handy-git/PlayerChat/releases/latest"; /** * 默认渠道 */ public final static String DEFAULT = "default"; /** * 消息类型 */ public final static String CHAT_TYPE = "RICE_CHAT"; /** * 物品类型 */ public final static String ITEM_TYPE = "RICE_ITEM"; /** * 玩家当前渠道 */ public static final Map<UUID, String> PLAYER_CHAT_CHANNEL = new HashMap<>(); /** * 插件渠道 * key 渠道 value 插件名 * * @since 1.0.6 */ public static final Map<String, String> PLUGIN_CHANNEL = new HashMap<>(); /** * 玩家注册的插件渠道 * * @since 1.0.6 */ public static final Map<UUID, List<String>> PLAYER_PLUGIN_CHANNEL = new HashMap<>(); /** * 玩家聊天冷却 * * @since 1.0.7 */ public static final Map<UUID, Long> PLAYER_CHAT_TIME = new HashMap<>(); }
1,264
Java
.java
handy-git/PlayerChat
14
0
0
2023-06-24T06:37:49Z
2024-05-06T06:24:03Z
TabListEnum.java
/FileExtraction/Java_unseen/handy-git_PlayerChat/src/main/java/cn/handyplus/chat/constants/TabListEnum.java
package cn.handyplus.chat.constants; import cn.handyplus.chat.core.HornUtil; import cn.handyplus.chat.util.ConfigUtil; import cn.handyplus.lib.util.BaseUtil; import cn.handyplus.lib.util.HandyConfigUtil; import lombok.AllArgsConstructor; import lombok.Getter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * tab提醒 * * @author handy */ @Getter @AllArgsConstructor public enum TabListEnum { /** * 第一层提醒 */ FIRST(Arrays.asList("reload", "send", "give", "take", "set", "look", "channel"), 0, null, 1), LOOK_TWO(null, 1, "look", 2), GIVE_THREE(null, 1, "give", 3), GIVE_FOUR(Collections.singletonList(BaseUtil.getLangMsg("tabHelp.number")), 1, "give", 4), TAKE_THREE(null, 1, "take", 3), TAKE_FOUR(Collections.singletonList(BaseUtil.getLangMsg("tabHelp.number")), 1, "take", 4), SET_THREE(null, 1, "set", 3), SET_FOUR(Collections.singletonList(BaseUtil.getLangMsg("tabHelp.number")), 1, "set", 4), ; /** * 返回的List */ private final List<String> list; /** * 识别的上个参数的位置 */ private final int befPos; /** * 上个参数的内容 */ private final String bef; /** * 这个参数可以出现的位置 */ private final int num; /** * 获取提醒 * * @param args 参数 * @param argsLength 参数长度 * @return 提醒 */ public static List<String> returnList(String[] args, int argsLength) { List<String> completions = new ArrayList<>(); // 渠道特殊处理 if (argsLength == 2 && ("channel".equalsIgnoreCase(args[0]))) { Map<String, Object> chatChannel = HandyConfigUtil.getChildMap(ConfigUtil.CHAT_CONFIG, "chat"); List<String> chatChannelList = new ArrayList<>(chatChannel.keySet()); List<String> pluginChannelList = ChatConstants.PLUGIN_CHANNEL.values().stream().distinct().collect(Collectors.toList()); return chatChannelList.stream().filter(s -> !pluginChannelList.contains(s)).collect(Collectors.toList()); } if (argsLength == 2 && ("give".equalsIgnoreCase(args[0]) || "take".equalsIgnoreCase(args[0]) || "set".equalsIgnoreCase(args[0]))) { return HornUtil.getTabTitle(); } for (TabListEnum tabListEnum : TabListEnum.values()) { if (tabListEnum.getBefPos() - 1 >= args.length) { continue; } if ((tabListEnum.getBef() == null || tabListEnum.getBef().equalsIgnoreCase(args[tabListEnum.getBefPos() - 1])) && tabListEnum.getNum() == argsLength) { completions = tabListEnum.getList(); } } return completions; } }
2,864
Java
.java
handy-git/PlayerChat
14
0
0
2023-06-24T06:37:49Z
2024-05-06T06:24:03Z
ConfigUtil.java
/FileExtraction/Java_unseen/handy-git_PlayerChat/src/main/java/cn/handyplus/chat/util/ConfigUtil.java
package cn.handyplus.chat.util; import cn.handyplus.lib.util.HandyConfigUtil; import org.bukkit.configuration.file.FileConfiguration; import java.util.Arrays; import java.util.Collections; /** * 配置 * * @author handy */ public class ConfigUtil { public static FileConfiguration CONFIG, LANG_CONFIG; public static FileConfiguration CHAT_CONFIG, LB_CONFIG, ITEM_CONFIG; /** * 加载全部配置 */ public static void init() { CONFIG = HandyConfigUtil.loadConfig(); LANG_CONFIG = HandyConfigUtil.loadLangConfig(CONFIG.getString("language"), true); CHAT_CONFIG = HandyConfigUtil.load("chat.yml"); LB_CONFIG = HandyConfigUtil.load("lb.yml"); ITEM_CONFIG = HandyConfigUtil.load("gui/item.yml"); upConfig(); } /** * 升级节点处理 * * @since 1.0.7 */ public static void upConfig() { // 1.0.7 添加聊天频率提醒 HandyConfigUtil.setPathIsNotContains(LANG_CONFIG, "chatTime", "&7你必须等待 &a${chatTime} &7秒后 才可以继续发言.", null, "languages/" + CONFIG.getString("language") + ".yml"); HandyConfigUtil.setPathIsNotContains(LANG_CONFIG, "itemNotFoundMsg", "&8[&c✘&8] &7展示物品超过可查看时间", null, "languages/" + CONFIG.getString("language") + ".yml"); LANG_CONFIG = HandyConfigUtil.loadLangConfig(CONFIG.getString("language"), true); // 1.0.7 添加聊天频率配置和黑名单配置 HandyConfigUtil.setPathIsNotContains(CONFIG, "blacklist", Arrays.asList("操", "草", "cao"), Collections.singletonList("黑名单,关键字替换成*"), "config.yml"); HandyConfigUtil.setPathIsNotContains(CONFIG, "chatTime.default", 0, Collections.singletonList("聊天冷却时间(单位秒)(可无限扩展和修改子节点,权限格式: playerChat.chatTime.vip1)"), "config.yml"); HandyConfigUtil.setPathIsNotContains(CONFIG, "chatTime.vip1", 0, null, "config.yml"); HandyConfigUtil.setPathIsNotContains(CONFIG, "chatTime.vip2", 0, null, "config.yml"); HandyConfigUtil.setPathIsNotContains(CONFIG, "chatTime.vip3", 0, null, "config.yml"); CONFIG = HandyConfigUtil.load("config.yml"); // 1.0.9 at功能 HandyConfigUtil.setPathIsNotContains(CHAT_CONFIG, "at.enable", true, Collections.singletonList("是否开启"), "chat.yml"); HandyConfigUtil.setPathIsNotContains(CHAT_CONFIG, "at.sound", "BLOCK_ANVIL_LAND", Collections.singletonList("音效列表 https://bukkit.windit.net/javadoc/org/bukkit/Sound.html"), "chat.yml"); // 1.1.2 展示物品支持配置格式 HandyConfigUtil.setPathIsNotContains(CHAT_CONFIG, "item.content", "&5[&a展示了一个 &6${item} &a点击查看&5]", Collections.singletonList("内容格式"), "chat.yml"); CHAT_CONFIG = HandyConfigUtil.load("chat.yml"); } }
2,873
Java
.java
handy-git/PlayerChat
14
0
0
2023-06-24T06:37:49Z
2024-05-06T06:24:03Z
ClearItemJob.java
/FileExtraction/Java_unseen/handy-git_PlayerChat/src/main/java/cn/handyplus/chat/job/ClearItemJob.java
package cn.handyplus.chat.job; import cn.handyplus.chat.service.ChatPlayerItemService; import cn.handyplus.lib.core.DateUtil; import cn.handyplus.lib.expand.adapter.HandySchedulerUtil; import cn.handyplus.lib.util.MessageUtil; import java.util.Date; import java.util.concurrent.Semaphore; /** * 清理过期数据 * * @author handy */ public class ClearItemJob { private ClearItemJob() { } private static final Semaphore CLEAR_ITEM_LOCK = new Semaphore(1); /** * 初始化定时任务 */ public static void init() { // 每12小时检查一次清理数据 HandySchedulerUtil.runTaskTimerAsynchronously(ClearItemJob::clearWeekMoney, 0, 20 * 60 * 60 * 12); } /** * 清理周贡献 * 每日 00:00 * * @since 1.10.9 */ private static void clearWeekMoney() { if (!CLEAR_ITEM_LOCK.tryAcquire()) { return; } try { Date date = new Date(); int num = ChatPlayerItemService.getInstance().clearWeekData(); MessageUtil.sendConsoleMessage("清理过期数据成功,清理时间:" + DateUtil.format(date, DateUtil.YYYY_HH) + ",本次清理:" + num + "数据"); } finally { CLEAR_ITEM_LOCK.release(); } } }
1,288
Java
.java
handy-git/PlayerChat
14
0
0
2023-06-24T06:37:49Z
2024-05-06T06:24:03Z
PlaceholderApiUtil.java
/FileExtraction/Java_unseen/handy-git_PlayerChat/src/main/java/cn/handyplus/chat/hook/PlaceholderApiUtil.java
package cn.handyplus.chat.hook; import cn.handyplus.chat.PlayerChat; import me.clip.placeholderapi.PlaceholderAPI; import org.bukkit.entity.Player; import java.util.List; /** * 变量工具类 * * @author handy */ public class PlaceholderApiUtil { /** * 替换变量 * * @param player 玩家 * @param str 字符串 * @return 新字符串 */ public static String set(Player player, String str) { if (!PlayerChat.USE_PAPI || player == null) { return str; } // 是否包含变量 if (PlaceholderAPI.containsPlaceholders(str)) { str = PlaceholderAPI.setPlaceholders(player, str); } // 双重解析,处理变量嵌套变量 if (PlaceholderAPI.containsPlaceholders(str)) { str = PlaceholderAPI.setPlaceholders(player, str); } return str; } /** * 替换变量 * * @param player 玩家 * @param strList 字符串集合 * @return 新字符串集合 */ public static List<String> set(Player player, List<String> strList) { if (!PlayerChat.USE_PAPI || player == null) { return strList; } // 解析变量 strList = PlaceholderAPI.setPlaceholders(player, strList); // 双重解析,处理变量嵌套变量 return PlaceholderAPI.setPlaceholders(player, strList); } }
1,418
Java
.java
handy-git/PlayerChat
14
0
0
2023-06-24T06:37:49Z
2024-05-06T06:24:03Z
PlaceholderUtil.java
/FileExtraction/Java_unseen/handy-git_PlayerChat/src/main/java/cn/handyplus/chat/hook/PlaceholderUtil.java
package cn.handyplus.chat.hook; import cn.handyplus.chat.PlayerChat; import cn.handyplus.chat.constants.ChatConstants; import cn.handyplus.chat.core.ChannelUtil; import cn.handyplus.chat.enter.ChatPlayerChannelEnter; import cn.handyplus.chat.enter.ChatPlayerHornEnter; import cn.handyplus.chat.service.ChatPlayerChannelService; import cn.handyplus.chat.service.ChatPlayerHornService; import cn.handyplus.lib.core.StrUtil; import me.clip.placeholderapi.expansion.PlaceholderExpansion; import org.bukkit.OfflinePlayer; import java.util.Optional; /** * 变量扩展 * * @author handy */ public class PlaceholderUtil extends PlaceholderExpansion { private final PlayerChat plugin; public PlaceholderUtil(PlayerChat plugin) { this.plugin = plugin; } /** * 变量前缀 * * @return 结果 */ @Override public String getIdentifier() { return "playerChat"; } /** * 注册变量 * * @param player 玩家 * @param placeholder 变量字符串 * @return 变量 */ @Override public String onRequest(OfflinePlayer player, String placeholder) { if (player == null) { return null; } // %playerChat_channel% if ("channel".equals(placeholder)) { String channelName = ChatConstants.PLAYER_CHAT_CHANNEL.get(player.getUniqueId()); if (StrUtil.isEmpty(channelName)) { Optional<ChatPlayerChannelEnter> enterOptional = ChatPlayerChannelService.getInstance().findByUid(player.getUniqueId()); channelName = enterOptional.isPresent() ? enterOptional.get().getChannel() : ChatConstants.DEFAULT; } return ChannelUtil.getChannelName(channelName); } // %playerChat_[类型]% Optional<ChatPlayerHornEnter> hornPlayerEnterOpt = ChatPlayerHornService.getInstance().findByUidAndType(player.getUniqueId(), placeholder); return hornPlayerEnterOpt.map(enter -> enter.getNumber().toString()).orElse("0"); } /** * 因为这是一个内部类, * 你必须重写这个方法,让PlaceholderAPI知道不要注销你的扩展类 * * @return 结果 */ @Override public boolean persist() { return true; } /** * 因为这是一个内部类,所以不需要进行这种检查 * 我们可以简单地返回{@code true} * * @return 结果 */ @Override public boolean canRegister() { return true; } /** * 作者 * * @return 结果 */ @Override public String getAuthor() { return plugin.getDescription().getAuthors().toString(); } /** * 版本 * * @return 结果 */ @Override public String getVersion() { return plugin.getDescription().getVersion(); } }
2,877
Java
.java
handy-git/PlayerChat
14
0
0
2023-06-24T06:37:49Z
2024-05-06T06:24:03Z
PlayerChannelChatEvent.java
/FileExtraction/Java_unseen/handy-git_PlayerChat/src/main/java/cn/handyplus/chat/event/PlayerChannelChatEvent.java
package cn.handyplus.chat.event; import cn.handyplus.lib.util.BcUtil; import lombok.Getter; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.event.HandlerList; import org.bukkit.event.player.PlayerEvent; import org.jetbrains.annotations.NotNull; /** * 玩家频道聊天 事件 * * @author handy * @since 1.0.0 */ public class PlayerChannelChatEvent extends PlayerEvent implements Cancellable { private static final HandlerList HANDLERS = new HandlerList(); private boolean cancel = false; /** * 获取消息内容 */ @Getter private final BcUtil.BcMessageParam bcMessageParam; @Override public @NotNull HandlerList getHandlers() { return HANDLERS; } public static HandlerList getHandlerList() { return HANDLERS; } public PlayerChannelChatEvent(Player player, BcUtil.BcMessageParam bcMessageParam) { super(player); this.bcMessageParam = bcMessageParam; } @Override public boolean isCancelled() { return cancel; } @Override public void setCancelled(boolean cancel) { this.cancel = cancel; } }
1,173
Java
.java
handy-git/PlayerChat
14
0
0
2023-06-24T06:37:49Z
2024-05-06T06:24:03Z
AbstractJSON.java
/FileExtraction/Java_unseen/mahomaps_mm-v1/src/cc/nnproject/json/AbstractJSON.java
/* Copyright (c) 2022 Arman Jussupgaliyev 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 cc.nnproject.json; public abstract class AbstractJSON { public abstract void clear(); public abstract int size(); public abstract String toString(); public abstract String build(); public final String format() { return format(0); } protected abstract String format(int l); public abstract boolean similar(Object obj); }
1,411
Java
.java
mahomaps/mm-v1
18
4
11
2023-05-01T09:07:22Z
2024-05-05T22:00:52Z
JSONString.java
/FileExtraction/Java_unseen/mahomaps_mm-v1/src/cc/nnproject/json/JSONString.java
/* Copyright (c) 2022 Arman Jussupgaliyev 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 cc.nnproject.json; class JSONString { private String str; JSONString(String s) { this.str = s; } String getString() { return str; } public String toString() { return str; } }
1,274
Java
.java
mahomaps/mm-v1
18
4
11
2023-05-01T09:07:22Z
2024-05-05T22:00:52Z
JSONException.java
/FileExtraction/Java_unseen/mahomaps_mm-v1/src/cc/nnproject/json/JSONException.java
/* Copyright (c) 2022 Arman Jussupgaliyev 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 cc.nnproject.json; public class JSONException extends RuntimeException { JSONException() { } JSONException(String string) { super(string); } public String toString() { return getMessage() == null ? "JSONException" : "JSONException: " + getMessage(); } }
1,349
Java
.java
mahomaps/mm-v1
18
4
11
2023-05-01T09:07:22Z
2024-05-05T22:00:52Z
JSON.java
/FileExtraction/Java_unseen/mahomaps_mm-v1/src/cc/nnproject/json/JSON.java
/* Copyright (c) 2022 Arman Jussupgaliyev 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 cc.nnproject.json; import java.util.Hashtable; import java.util.Vector; /** * JSON Library by nnproject.cc<br> * Usage:<p><code>JSONObject obj = JSON.getObject(str);</code> * @author Shinovon * @version 1.2 */ public final class JSON { /** * Parse all members once */ public final static boolean parse_members = false; public final static Object json_null = new Object(); public static final String FORMAT_TAB = " "; public static final Boolean TRUE = new Boolean(true); public static final Boolean FALSE = new Boolean(false); public static JSONObject getObject(String string) throws JSONException { if (string == null || string.length() <= 1) throw new JSONException("Empty string"); if (string.charAt(0) != '{') throw new JSONException("Not JSON object"); return (JSONObject) parseJSON(string); } public static JSONArray getArray(String string) throws JSONException { if (string == null || string.length() <= 1) throw new JSONException("Empty string"); if (string.charAt(0) != '[') throw new JSONException("Not JSON array"); return (JSONArray) parseJSON(string); } static Object getJSON(Object obj) throws JSONException { if (obj instanceof Hashtable) { return new JSONObject((Hashtable) obj); } else if (obj instanceof Vector) { return new JSONArray((Vector) obj); } else if (obj == null) { return json_null; } else { return obj; } } static Object parseJSON(String str) throws JSONException { if(str == null || (str = str.trim()).length() == 0) { throw new JSONException("Empty string"); } char first = str.charAt(0); int length = str.length() - 1; char last = str.charAt(length); if (first == '{' && last != '}' || first == '[' && last != ']' || first == '"' && last != '"') { throw new JSONException("Unexpected end of text"); } else if (first == '"') { // String str = str.substring(1, str.length() - 1); char[] chars = str.toCharArray(); str = null; try { int l = chars.length; StringBuffer sb = new StringBuffer(); int i = 0; // Parse string escape chars loop: { while (i < l) { char c = chars[i]; switch (c) { case '\\': { next: { replaced: { if(l < i + 1) { sb.append(c); break loop; } char c1 = chars[i + 1]; switch (c1) { case 'u': i+=2; String u = "" + chars[i++] + chars[i++] + chars[i++] + chars[i++]; sb.append((char) Integer.parseInt(u, 16)); break replaced; case 'x': i+=2; String x = "" + chars[i++] + chars[i++]; sb.append((char) Integer.parseInt(x, 16)); break replaced; case 'n': sb.append('\n'); i+=2; break replaced; case 'r': sb.append('\r'); i+=2; break replaced; case 't': sb.append('\t'); i+=2; break replaced; case 'f': sb.append('\f'); i+=2; break replaced; case 'b': sb.append('\b'); i+=2; break replaced; case '\"': case '\'': case '\\': case '/': i+=2; sb.append((char) c1); break replaced; default: break next; } } break; } sb.append(c); i++; break; } default: sb.append(c); i++; } } } str = sb.toString(); sb = null; } catch (Exception e) { } return str; } else if (first != '{' && first != '[') { if (str.equals("null")) return json_null; if (str.equals("true")) return TRUE; if (str.equals("false")) return FALSE; if(str.length() > 2 && str.charAt(0) == '0' && str.charAt(1) == 'x') { try { return new Integer(Integer.parseInt(str.substring(2), 16)); } catch (Exception e) { try { return new Long(Long.parseLong(str.substring(2), 16)); } catch (Exception e2) { } } } try { return new Integer(Integer.parseInt(str)); } catch (Exception e) { try { return new Long(Long.parseLong(str)); } catch (Exception e2) { try { return new Double(Double.parseDouble(str)); } catch (Exception e3) { } } } return str; } else { // Parse json object or array int unclosed = 0; boolean object = first == '{'; int i = 1; char nextDelimiter = object ? ':' : ','; boolean escape = false; String key = null; Object res = null; if (object) res = new Hashtable(); else res = new Vector(); for (int splIndex; i < length; i = splIndex + 1) { // skip all spaces for (; i < length - 1 && str.charAt(i) <= ' '; i++); splIndex = i; boolean quotes = false; for (; splIndex < length && (quotes || unclosed > 0 || str.charAt(splIndex) != nextDelimiter); splIndex++) { char c = str.charAt(splIndex); if (!escape) { if (c == '\\') { escape = true; } else if (c == '"') { quotes = !quotes; } } else escape = false; if (!quotes) { if (c == '{' || c == '[') { unclosed++; } else if (c == '}' || c == ']') { unclosed--; } } } if (quotes || unclosed > 0) { throw new JSONException("Corrupted JSON"); } if (object && key == null) { key = str.substring(i, splIndex); key = key.substring(1, key.length() - 1); nextDelimiter = ','; } else { Object value = str.substring(i, splIndex).trim(); if (parse_members) value = parseJSON(value.toString()); else value = new JSONString(value.toString()); if (object) { ((Hashtable) res).put(key, value); key = null; nextDelimiter = ':'; } else if (splIndex > i) ((Vector) res).addElement(value); } } return getJSON(res); } } public static boolean isNull(Object obj) { return json_null.equals(obj); } public static String escape_utf8(String s) { int len = s.length(); StringBuffer sb = new StringBuffer(); int i = 0; while (i < len) { char c = s.charAt(i); switch (c) { case '"': case '\\': sb.append("\\" + c); break; case '\b': sb.append("\\b"); break; case '\f': sb.append("\\f"); break; case '\n': sb.append("\\n"); break; case '\r': sb.append("\\r"); break; case '\t': sb.append("\\t"); break; default: if (c < 32 || c > 1103) { String u = Integer.toHexString(c); for (int z = u.length(); z < 4; z++) { u = "0" + u; } sb.append("\\u" + u); } else { sb.append(c); } } i++; } return sb.toString(); } public static double getDouble(Object o) throws JSONException { try { if (o instanceof Integer) return ((Integer) o).intValue(); if (o instanceof Long) return ((Long) o).longValue(); if (o instanceof Double) return ((Double) o).doubleValue(); } catch (Throwable e) { } throw new JSONException("Value cast failed: " + o); } public static long getLong(Object o) throws JSONException { try { if (o instanceof Integer) return ((Integer) o).longValue(); if (o instanceof Long) return ((Long) o).longValue(); if (o instanceof Double) return ((Double) o).longValue(); } catch (Throwable e) { } throw new JSONException("Value cast failed: " + o); } }
8,556
Java
.java
mahomaps/mm-v1
18
4
11
2023-05-01T09:07:22Z
2024-05-05T22:00:52Z
JSONObject.java
/FileExtraction/Java_unseen/mahomaps_mm-v1/src/cc/nnproject/json/JSONObject.java
/* Copyright (c) 2022 Arman Jussupgaliyev 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 cc.nnproject.json; import java.util.Enumeration; import java.util.Hashtable; public class JSONObject extends AbstractJSON { private Hashtable table; public JSONObject() { this.table = new Hashtable(); } public JSONObject(Hashtable table) { this.table = table; } public boolean has(String name) { return table.containsKey(name); } public Object get(String name) throws JSONException { try { if (has(name)) { Object o = table.get(name); if (o instanceof JSONString) table.put(name, o = JSON.parseJSON(o.toString())); return o; } } catch (JSONException e) { throw e; } catch (Exception e) { } throw new JSONException("No value for name: " + name); } public Object get(String name, Object def) { if(!has(name)) return def; try { return get(name); } catch (Exception e) { return def; } } public Object getNullable(String name) { return get(name, null); } public String getString(String name) throws JSONException { return get(name).toString(); } public String getString(String name, String def) { try { Object o = get(name, def); if(o == null || o instanceof String) { return (String) o; } return o.toString(); } catch (Exception e) { return def; } } public String getNullableString(String name) { return getString(name, null); } public JSONObject getObject(String name) throws JSONException { try { return (JSONObject) get(name); } catch (ClassCastException e) { throw new JSONException("Not object: " + name); } } public JSONObject getNullableObject(String name) { if(!has(name)) return null; try { return getObject(name); } catch (Exception e) { return null; } } public JSONArray getArray(String name) throws JSONException { try { return (JSONArray) get(name); } catch (ClassCastException e) { throw new JSONException("Not array: " + name); } } public JSONArray getNullableArray(String name) { if(!has(name)) return null; try { return getArray(name); } catch (Exception e) { return null; } } public int getInt(String name) throws JSONException { return (int) JSON.getLong(get(name)); } public int getInt(String name, int def) { if(!has(name)) return def; try { return getInt(name); } catch (Exception e) { return def; } } public long getLong(String name) throws JSONException { return JSON.getLong(get(name)); } public long getLong(String name, long def) { if(!has(name)) return def; try { return getLong(name); } catch (Exception e) { return def; } } public double getDouble(String name) throws JSONException { return JSON.getDouble(get(name)); } public double getDouble(String name, double def) { if(!has(name)) return def; try { return getDouble(name); } catch (Exception e) { return def; } } public boolean getBoolean(String name) throws JSONException { Object o = get(name); if(o == JSON.TRUE) return true; if(o == JSON.FALSE) return false; if(o instanceof Boolean) return ((Boolean) o).booleanValue(); if(o instanceof String) { String s = (String) o; s = s.toLowerCase(); if(s.equals("true")) return true; if(s.equals("false")) return false; } throw new JSONException("Not boolean: " + o); } public boolean getBoolean(String name, boolean def) { if(!has(name)) return def; try { return getBoolean(name); } catch (Exception e) { return def; } } public boolean isNull(String name) { return JSON.isNull(getNullable(name)); } public void put(String name, String s) { table.put(name, s); } public void put(String name, boolean b) { table.put(name, new Boolean(b)); } public void put(String name, double d) { table.put(name, new Double(d)); } public void put(String name, int i) { table.put(name, new Integer(i)); } public void put(String name, long l) { table.put(name, new Long(l)); } public void put(String name, Object obj) { table.put(name, JSON.getJSON(obj)); } public void remove(String name) { table.remove(name); } public void clear() { table.clear(); } public int size() { return table.size(); } public String toString() { return build(); } public boolean equals(Object obj) { if(this == obj || super.equals(obj)) { return true; } return similar(obj); } public boolean similar(Object obj) { if(!(obj instanceof JSONObject)) { return false; } int size = size(); if(size != ((JSONObject)obj).size()) { return false; } Enumeration keys = table.keys(); while(keys.hasMoreElements()) { String key = (String) keys.nextElement(); Object a = get(key); Object b = ((JSONObject)obj).get(key); if(a == b) { continue; } if(a == null) { return false; } if(a instanceof AbstractJSON) { if (!((AbstractJSON)a).similar(b)) { return false; } } else if(!a.equals(b)) { return false; } } return true; } public String build() { if (size() == 0) return "{}"; StringBuffer s = new StringBuffer("{"); Enumeration keys = table.keys(); while (true) { String k = keys.nextElement().toString(); s.append("\"").append(k).append("\":"); Object v = table.get(k); if (v instanceof AbstractJSON) { s.append(((AbstractJSON) v).build()); } else if (v instanceof String) { s.append("\"").append(JSON.escape_utf8((String) v)).append("\""); } else if(JSON.json_null.equals(v)) { s.append((String) null); } else { s.append(v); } if (!keys.hasMoreElements()) { break; } s.append(","); } s.append("}"); return s.toString(); } protected String format(int l) { int size = size(); if (size == 0) return "{}"; String t = ""; for (int i = 0; i < l; i++) { t = t.concat(JSON.FORMAT_TAB); } String t2 = t.concat(JSON.FORMAT_TAB); StringBuffer s = new StringBuffer("{\n"); s.append(t2); Enumeration keys = table.keys(); int i = 0; while(keys.hasMoreElements()) { String k = keys.nextElement().toString(); s.append("\"").append(k).append("\": "); Object v = null; try { v = get(k); } catch (JSONException e) { } if (v instanceof AbstractJSON) { s.append(((AbstractJSON) v).format(l + 1)); } else if (v instanceof String) { s.append("\"").append(JSON.escape_utf8((String) v)).append("\""); } else if(v == JSON.json_null) { s.append((String) null); } else { s.append(v); } i++; if (i < size) { s.append(",\n").append(t2); } } if (l > 0) { s.append("\n").append(t).append("}"); } else { s.append("\n}"); } return s.toString(); } public Enumeration keys() { return table.keys(); } public JSONArray keysAsArray() { JSONArray array = new JSONArray(); Enumeration keys = table.keys(); while(keys.hasMoreElements()) { array.add(keys.nextElement()); } return array; } }
8,089
Java
.java
mahomaps/mm-v1
18
4
11
2023-05-01T09:07:22Z
2024-05-05T22:00:52Z
JSONArray.java
/FileExtraction/Java_unseen/mahomaps_mm-v1/src/cc/nnproject/json/JSONArray.java
/* Copyright (c) 2022 Arman Jussupgaliyev 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 cc.nnproject.json; import java.util.Enumeration; import java.util.Vector; public class JSONArray extends AbstractJSON { private Vector vector; public JSONArray() { this.vector = new Vector(); } public JSONArray(Vector vector) { this.vector = vector; } public Object get(int index) throws JSONException { try { if(index >= 0 && index < vector.size()) { Object o = vector.elementAt(index); if (o instanceof JSONString) { vector.setElementAt(o = JSON.parseJSON(o.toString()), index); } return o; } } catch (Exception e) { } throw new JSONException("No value at " + index); } public Object get(int index, Object def) { try { return get(index); } catch (Exception e) { return def; } } public Object getNullable(int index) { return get(index, null); } public String getString(int index) throws JSONException { return get(index).toString(); } public String getString(int index, String def) { try { return get(index).toString(); } catch (Exception e) { return def; } } public JSONObject getObject(int index) throws JSONException { try { return (JSONObject) get(index); } catch (ClassCastException e) { throw new JSONException("Not object at " + index); } } public JSONObject getNullableObject(int index) { try { return getObject(index); } catch (Exception e) { return null; } } public JSONArray getArray(int index) throws JSONException { try { return (JSONArray) get(index); } catch (ClassCastException e) { throw new JSONException("Not array at " + index); } } public JSONArray getNullableArray(int index) { try { return getArray(index); } catch (Exception e) { return null; } } public int getInt(int index) throws JSONException { return (int) JSON.getLong(get(index)); } public int getInt(int index, int def) { try { return getInt(index); } catch (Exception e) { return def; } } public long getLong(int index) throws JSONException { return JSON.getLong(get(index)); } public long getLong(int index, long def) { try { return getLong(index); } catch (Exception e) { return def; } } public double getDouble(int index) throws JSONException { return JSON.getDouble(get(index)); } public double getDouble(int index, double def) { try { return getDouble(index); } catch (Exception e) { return def; } } public boolean getBoolean(int index) throws JSONException { Object o = get(index); if(o == JSON.TRUE) return true; if(o == JSON.FALSE) return false; if(o instanceof Boolean) return ((Boolean) o).booleanValue(); if(o instanceof String) { String s = (String) o; s = s.toLowerCase(); if(s.equals("true")) return true; if(s.equals("false")) return false; } throw new JSONException("Not boolean: " + o + " (" + index + ")"); } public boolean getBoolean(int index, boolean def) { try { return getBoolean(index); } catch (Exception e) { return def; } } public boolean isNull(int index) { return JSON.isNull(getNullable(index)); } public void add(String s) { vector.addElement(s); } public void add(boolean b) { vector.addElement(new Boolean(b)); } public void add(double d) { vector.addElement(Double.toString(d)); } public void add(int i) { vector.addElement(Integer.toString(i)); } public void add(long l) { vector.addElement(Long.toString(l)); } public void add(Object obj) { vector.addElement(JSON.getJSON(obj)); } public void set(int idx, String s) { vector.setElementAt(s, idx); } public void set(int idx, boolean b) { vector.setElementAt(new Boolean(b), idx); } public void set(int idx, double d) { vector.setElementAt(Double.toString(d), idx); } public void set(int idx, int i) { vector.setElementAt(Integer.toString(i), idx); } public void set(int idx, long l) { vector.setElementAt(Long.toString(l), idx); } public void set(int idx, Object obj) { vector.setElementAt(JSON.getJSON(obj), idx); } public void put(int idx, String s) { vector.insertElementAt(s, idx); } public void put(int idx, boolean b) { vector.insertElementAt(new Boolean(b), idx); } public void put(int idx, double d) { vector.insertElementAt(Double.toString(d), idx); } public void put(int idx, int i) { vector.insertElementAt(Integer.toString(i), idx); } public void put(int idx, long l) { vector.insertElementAt(Long.toString(l), idx); } public void put(int idx, Object obj) { vector.insertElementAt(JSON.getJSON(obj), idx); } public void remove(int idx) { vector.removeElementAt(idx); } public void clear() { vector.removeAllElements(); } public int size() { return vector.size(); } public String toString() { return build(); } public boolean equals(Object obj) { if(this == obj || super.equals(obj)) { return true; } return similar(obj); } public boolean similar(Object obj) { if(!(obj instanceof JSONArray)) { return false; } int size = size(); if(size != ((JSONArray)obj).size()) { return false; } for(int i = 0; i < size; i++) { Object a = get(i); Object b = ((JSONArray)obj).get(i); if(a == b) { continue; } if(a == null) { return false; } if(a instanceof AbstractJSON) { if (!((AbstractJSON)a).similar(b)) { return false; } } else if(!a.equals(b)) { return false; } } return true; } public String build() { int size = size(); if (size == 0) return "[]"; StringBuffer s = new StringBuffer("["); int i = 0; while (i < size) { Object v = vector.elementAt(i); if (v instanceof AbstractJSON) { s.append(((AbstractJSON) v).build()); } else if (v instanceof String) { s.append("\"").append(JSON.escape_utf8((String) v)).append("\""); } else if(JSON.json_null.equals(v)) { s.append((String) null); } else { s.append(String.valueOf(v)); } i++; if (i < size) { s.append(","); } } s.append("]"); return s.toString(); } protected String format(int l) { int size = size(); if (size == 0) return "[]"; String t = ""; for (int i = 0; i < l; i++) { t = t.concat(JSON.FORMAT_TAB); } String t2 = t.concat(JSON.FORMAT_TAB); StringBuffer s = new StringBuffer("[\n"); s.append(t2); for (int i = 0; i < size; ) { Object v = null; try { v = get(i); } catch (JSONException e) { } if (v instanceof AbstractJSON) { s.append(((AbstractJSON) v).format(l + 1)); } else if (v instanceof String) { s.append("\"").append(JSON.escape_utf8((String) v)).append("\""); } else if(v == JSON.json_null) { s.append((String) null); } else { s.append(v); } i++; if (i < size()) { s.append(",\n").append(t2); } } if (l > 0) { s.append("\n").append(t).append("]"); } else { s.append("\n]"); } return s.toString(); } public Enumeration elements() { return new Enumeration() { int i = 0; public boolean hasMoreElements() { return i < vector.size(); } public Object nextElement() { try { return get(i++); } catch (Exception e) { return null; } } }; } public void copyInto(Object[] arr, int offset, int length) { int i = offset; int j = 0; while(i < arr.length && j < length && j < size()) { Object o = get(j++); if(o == JSON.json_null) o = null; arr[i++] = o; } } }
8,650
Java
.java
mahomaps/mm-v1
18
4
11
2023-05-01T09:07:22Z
2024-05-05T22:00:52Z
ImageFxUtils.java
/FileExtraction/Java_unseen/mahomaps_mm-v1/src/tube42/lib/imagelib/ImageFxUtils.java
/* * This file is a part of the TUBE42 imagelib, released under the LGPL license. * * Development page: https://github.com/tube42/imagelib * License: http://www.gnu.org/copyleft/lesser.html */ package tube42.lib.imagelib; import javax.microedition.lcdui.*; /** * This class contains some simple image effects */ public final class ImageFxUtils { /** * my generic filter function * * override _one_ of these function to work on a line or a single pixel */ public abstract static class ImageFilter { public void apply(int[][] pixels, int[] output, int offset, int count, int y) { for (int i = 0; i < count; i++) output[i] = apply(pixels, offset + i, i, y); } public int apply(int[][] pixels, int offset, int x, int y) { return 0; } } /** * my generic pixel modifier. override _one_ of these function to work on a line * or a single pixel */ public abstract static class PixelModifier { public void apply(int[] pixel, int[] output, int count, int y) { for (int i = 0; i < count; i++) output[i] = apply(pixel[i], i, y); } public int apply(int pixel, int x, int y) { return pixel; } } // --------------------------------------------- /** * apply filter of size filter_w * filter_h to the image. * * This function will process one line at a time */ public static Image applyFilter(Image image, int filter_w, int filter_h, ImageFilter filter) { // 0. sanity check: filter dimensions must be odd if ((filter_w & filter_h & 1) == 0) return null; // boolean haxory ftw int fw2 = filter_w / 2; int fh2 = filter_h / 2; // 1. allocate needed buffers & output image final int w = image.getWidth(); final int h = image.getHeight(); final int scanlength = w + filter_w; Image ret = Image.createImage(w, h); Graphics g = ret.getGraphics(); int[] buffer_out = new int[w]; int[][] buffer_in = new int[filter_h][]; for (int i = 0; i < buffer_in.length; i++) buffer_in[i] = new int[scanlength]; int next_line = 0; // 2. get initial pixels and empty surroundings for (int i = 0; i < filter_h; i++) { for (int j = 0; j < scanlength; j++) buffer_in[i][j] = 0; if (i >= fh2) image.getRGB(buffer_in[i], fw2, w, 0, next_line++, w, 1); } // 3. for each row, compute new line, write it to image and then get the next // line for (int y = 0; y < h; y++) { filter.apply(buffer_in, buffer_out, fw2, w, y); g.drawRGB(buffer_out, 0, w, 0, y, w, 1, true); // buffer rotation instead of copying int[] tmp = buffer_in[0]; for (int i = 1; i < filter_h; i++) buffer_in[i - 1] = buffer_in[i]; buffer_in[filter_h - 1] = tmp; // and add the next line (if any) if (next_line < h) image.getRGB(tmp, fw2, w, 0, next_line++, w, 1); else for (int i = 0; i < scanlength; i++) tmp[i] = 0; } return ret; } // --------------------------------------------- /** * apply 2D filter * * NOTE: this function is currently quite slow! * */ public static Image applyFilter(Image image, final int[][] multiplier, final int divider) { final int w = multiplier[0].length; final int h = multiplier.length; return applyFilter(image, w, h, new ImageFxUtils.ImageFilter() { public void apply(int[][] pixels, int[] output, int offset, int count, int y_) { for (int i = 0; i < count; i++) { int sum_a = 0, sum_r = 0, sum_g = 0, sum_b = 0; // TODO 1: speed up computation by using the SIMD trick here // TODO 2: speed up computation by extracting each point only once? for (int y = 0; y < h; y++) { final int[] line = pixels[y]; final int[] mul = multiplier[y]; for (int x = 0; x < w; x++) { sum_a += mul[x] * ((line[x + i] >> 24) & 0xFF); sum_r += mul[x] * ((line[x + i] >> 16) & 0xFF); sum_g += mul[x] * ((line[x + i] >> 8) & 0xFF); sum_b += mul[x] * ((line[x + i] >> 0) & 0xFF); } } output[i] = Math.min(255, Math.max(0, sum_a / divider)) << 24 | Math.min(255, Math.max(0, sum_r / divider)) << 16 | Math.min(255, Math.max(0, sum_g / divider)) << 8 | Math.min(255, Math.max(0, sum_b / divider)); } } }); } /** * apply pixel modifier to the image. This function also demonstrates use of * in-place image modification which consumes less memory. * */ public static Image applyModifier(Image image, PixelModifier modifier) { return applyModifier(image, modifier, false); } public static Image applyModifier(Image image, PixelModifier modifier, boolean modify_original) { // 1. allocate needed buffers final int w = image.getWidth(); final int h = image.getHeight(); int[] buffer1 = new int[w]; int[] buffer2 = new int[w]; // 2. get image for in-place modification or create new Image ret = modify_original ? image : Image.createImage(w, h); Graphics g = ret.getGraphics(); // 3. for each row, get the pixels for (int y = 0; y < h; y++) { image.getRGB(buffer1, 0, w, 0, y, w, 1); modifier.apply(buffer1, buffer2, w, y); g.drawRGB(buffer2, 0, w, 0, y, w, 1, true); } return ret; } // -------------------------------------- /** * transform the components in each pixel according to the transfrom tables. * * If a table is null, the original value will be used */ public static Image transformARGB(Image image, byte[] ta, byte[] tr, byte[] tg, byte[] tb) { // 1. get blended image: int w = image.getWidth(); int h = image.getHeight(); int[] buffer = new int[w * h]; image.getRGB(buffer, 0, w, 0, 0, w, h); image = null; // not needed anymore int[] tmp = new int[256]; // apply A, R, G and B tables when available if (ta != null) { for (int i = 0; i < 256; i++) tmp[i] = (((int) ta[i]) & 0xFF) << 24; for (int i = 0; i < buffer.length; i++) buffer[i] = (buffer[i] & 0x00FFFFFF) | tmp[(buffer[i] >> 24) & 0xFF]; } if (tr != null) { for (int i = 0; i < 256; i++) tmp[i] = (((int) tr[i]) & 0xFF) << 16; for (int i = 0; i < buffer.length; i++) buffer[i] = (buffer[i] & 0xFF00FFFF) | tmp[(buffer[i] >> 16) & 0xFF]; } if (tg != null) { for (int i = 0; i < 256; i++) tmp[i] = (((int) tg[i]) & 0xFF) << 8; for (int i = 0; i < buffer.length; i++) buffer[i] = (buffer[i] & 0xFFFF00FF) | tmp[(buffer[i] >> 8) & 0xFF]; } if (tb != null) { for (int i = 0; i < 256; i++) tmp[i] = (((int) tb[i]) & 0xFF) << 0; for (int i = 0; i < buffer.length; i++) buffer[i] = (buffer[i] & 0xFFFFFF00) | tmp[(buffer[i] >> 0) & 0xFF]; } return Image.createRGBImage(buffer, w, h, true); } /* * Image transform colors by adding a delta to the linear mapping */ public static Image transformARGB(Image image, int delta_alpha, int delta_red, int delta_green, int delta_blue) { // build transformation tables byte[] ta = new byte[256]; byte[] tr = new byte[256]; byte[] tg = new byte[256]; byte[] tb = new byte[256]; for (int i = 0; i < 256; i++) { ta[i] = (byte) Math.min(255, Math.max(0, i + delta_alpha)); tr[i] = (byte) Math.min(255, Math.max(0, i + delta_red)); tg[i] = (byte) Math.min(255, Math.max(0, i + delta_green)); tb[i] = (byte) Math.min(255, Math.max(0, i + delta_blue)); } // now, transform it according to the tables return transformARGB(image, ta, tr, tg, tb); } }
7,335
Java
.java
mahomaps/mm-v1
18
4
11
2023-05-01T09:07:22Z
2024-05-05T22:00:52Z
ColorUtils.java
/FileExtraction/Java_unseen/mahomaps_mm-v1/src/tube42/lib/imagelib/ColorUtils.java
/* * This file is a part of the TUBE42 imagelib, released under the LGPL license. * * Development page: https://github.com/tube42/imagelib * License: http://www.gnu.org/copyleft/lesser.html */ package tube42.lib.imagelib; /** * This class contains some functions * that are common during color manipulation */ public final class ColorUtils { public static final int blend(final int c1, final int c2, final int value256) { final int v1 = value256 & 0xFF; final int c2_RB = c2 & 0x00FF00FF; final int c2_AG_org = c2 & 0xFF00FF00; return ((c2_AG_org + ((((c1 >>> 8) & 0x00FF00FF) - ((c2_AG_org) >>> 8)) * v1)) & 0xFF00FF00) | ((c2_RB + ((((c1 & 0x00FF00FF) - c2_RB) * v1) >> 8)) & 0x00FF00FF); } public static int darker(int c) { int a = (c >> 24) & 0xFF; int r = (c >> 16) & 0xFF; int g = (c >> 8) & 0xFF; int b = (c >> 0) & 0xFF; r = (r * 15) >> 4; g = (g * 15) >> 4; b = (b * 15) >> 4; return (a << 24) | (r << 16) | (g << 8) | b; } public static int lighter(int c) { int a = (c >> 24) & 0xFF; int r = (c >> 16) & 0xFF; int g = (c >> 8) & 0xFF; int b = (c >> 0) & 0xFF; r = Math.max(1, Math.min(255, (r * 17) >> 4)); g = Math.max(1, Math.min(255, (g * 17) >> 4)); b = Math.max(1, Math.min(255, (b * 17) >> 4)); return (a << 24) | (r << 16) | (g << 8) | b; } // ---------------------------------------------- public static int mix(int c1, int c2) { // return blend(c1, c2, 0x7f); int c_RB = (((c1 & 0x00FF00FF) + (c2 & 0x00FF00FF)) >> 1) & 0x00FF00FF; int c_AG = (((c1 & 0xFF00FF00) >>> 1) + ((c2 & 0xFF00FF00) >>> 1)) & 0xFF00FF00; return c_RB | c_AG; } public static int mix(int c1, int c2, int c3, int c4) { // return blend(c1, c2, 0x7f); int c_RB = ( ((c1 & 0x00FF00FF) + (c2 & 0x00FF00FF) + (c3 & 0x00FF00FF) + (c4 & 0x00FF00FF)) >> 2 ) & 0x00FF00FF; int c_AG = ( ((c1 & 0xFF00FF00) >>> 2) + ((c2 & 0xFF00FF00) >>> 2) + ((c3 & 0xFF00FF00) >>> 2) + ((c4 & 0xFF00FF00) >>> 2) ) & 0xFF00FF00; return c_RB | c_AG; } // -------------------------------------- // colorspace conversion functions /* * ARGB_8 to A_8 + YCbCr_8 * * (CCIR Recommendation 601, normalized to 0-255) */ public final static void ARGB2AYCbCr(int argb, int [] result) { int a = argb >>> 24; int r = (argb >> 16) & 0xFF; int g = (argb >> 8) & 0xFF; int b = argb & 0xFF; result[0] = a; result[1] = ( r * 77 + g * 150 + b * 29) >> 8; result[2] = (0x8000 - r * 43 - g * 85 + b * 128) >> 8; result[3] = (0x8000 + r * 128 - g * 107 - b * 21) >> 8; } /* * A_8 + YCbCr_8 to ARGB_8 * * (CCIR Recommendation 601, normalized to 0-255) * * NOTE: the current implmentation is very inefficient! */ public final static int AYCbCr2ARGB(int [] components) { int Y8 = components[1] << 8; // XXX: I can't figure out why these number don't map to 0-255, hence the min/max for now :( int r = Math.max(0, Math.min(255, (Y8 + (components[3]-128) * 359) >> 8)); int g = Math.max(0, Math.min(255, (Y8 - (components[3]-128) * 183 - (components[2]-128) * 88) >> 8)); int b = Math.max(0, Math.min(255, (Y8 + (components[2]-128) * 454) >> 8)); return (components[0] << 24) | (r << 16) | (g << 8) | b; } }
3,899
Java
.java
mahomaps/mm-v1
18
4
11
2023-05-01T09:07:22Z
2024-05-05T22:00:52Z
ImageAnalysisUtils.java
/FileExtraction/Java_unseen/mahomaps_mm-v1/src/tube42/lib/imagelib/ImageAnalysisUtils.java
/* * This file is a part of the TUBE42 imagelib, released under the LGPL license. * * Development page: https://github.com/tube42/imagelib * License: http://www.gnu.org/copyleft/lesser.html */ package tube42.lib.imagelib; import javax.microedition.lcdui.*; /** * This class contains some functions * for image analysis */ public final class ImageAnalysisUtils { /** * Create a histogram over the ARGB component distribution. * * Note that this function returns pixel counters, so * the accumulative total for each component is w * h, not 1.0 */ public static int [][] getARGBHistogram(Image image) { int w = image.getWidth(); int h = image.getHeight(); return getARGBHistogram(image, 0, 0, w, h); } /** * Create a histogram over the ARGB component distribution * of selected parts in an image. * * Note that this function returns pixel counters, so * the accumulative total for each component is w * h, not 1.0 */ public static int [][] getARGBHistogram(Image image, int x, int y, int w, int h) { // 1. create initial empty histogram int [][]ret = new int[4][]; for(int i = 0; i < ret.length; i++) { ret[i] = new int[256]; for(int j = 0; j < 256; j++) ret[i][j] = 0; } // 2. build histogram int [] buffer = new int[w]; for(int i = 0; i < h; i++) { image.getRGB(buffer, 0, w, 0, i, w, 1); for(int j = 0; j < w; j++) { int c = buffer[j]; ret[0][(c >> 24) & 0xFF]++; ret[1][(c >> 16) & 0xFF]++; ret[2][(c >> 8) & 0xFF]++; ret[3][(c >> 0) & 0xFF]++; } } // 3. and we are done return ret; } }
1,922
Java
.java
mahomaps/mm-v1
18
4
11
2023-05-01T09:07:22Z
2024-05-05T22:00:52Z
ImageUtils.java
/FileExtraction/Java_unseen/mahomaps_mm-v1/src/tube42/lib/imagelib/ImageUtils.java
/* * This file is a part of the TUBE42 imagelib, released under the LGPL license. * * Development page: https://github.com/tube42/imagelib * License: http://www.gnu.org/copyleft/lesser.html */ package tube42.lib.imagelib; import javax.microedition.lcdui.*; /** * This class contains some functions * that are common during image manipulation * * * In a perfect world, you wouldnt need this class since * JSR-234 would do the same work faster and better :( * */ public final class ImageUtils { /** * move user image to hardware memory if available. * * NOTE: when in GPU memory, image is immutable and * you cannot call Image.getGraphics() */ public static Image moveToGPU(Image img) { return Image.createImage(img); } /** * Move image to CPU memory. */ public static Image moveToCPU(Image img) { Image ret = Image.createImage(img.getWidth(), img.getHeight()); Graphics g = ret.getGraphics(); g.drawImage(img, 0, 0, 0); return ret; } // --------------------------------------------- /** * blend two images: */ public static Image blend(Image img1, Image img2, int value256) { // 0. no change? if(value256 == 0xFF) return img1; if(value256 == 0x00) return img2; // 1. get blended image: int w1 = img1.getWidth(); int h1 = img1.getHeight(); int w2 = img2.getWidth(); int h2 = img2.getHeight(); int w0 = Math.min(w1, w2); int h0 = Math.min(h1, h2); int [] data = new int[w0 * h0]; int [] b1 = new int[w0]; int [] b2 = new int[w0]; value256 &= 0xFF; for(int offset = 0, i = 0; i < h0; i++) { img1.getRGB( b1, 0, w1, 0, i, w0, 1); // get one line from each img2.getRGB( b2, 0, w2, 0, i, w0, 1); for(int j = 0; j < w0; j++) // blend all pixels data[offset ++] = ColorUtils.blend( b1[j], b2[j], value256); } Image tmp = Image.createRGBImage(data, w0, h0, true); data = null; // can this help GC at this point? return tmp; } /** * reduce image dimension to half */ public static Image halve(Image org) { int w1 = org.getWidth(); int h1 = org.getHeight(); int w2 = w1 / 2; int h2 = h1 / 2; int [] data = new int[w2 * h2]; int [] buffer = new int[w1 * 2]; for(int offset = 0, i = 0; i < h2; i++) { org.getRGB( buffer, 0, w1, 0, i * 2, w1, 2); // get two lines from the original int o1 = 0, o2 = 1; int o3 = w1, o4 = w1 + 1; for(int j = 0; j < w2; j++) { data[offset ++] = ColorUtils.mix( buffer[o1], buffer[o2], buffer[o3], buffer[o4]); o1 += 2; o2 += 2; o3 += 2; o4 += 2; } } Image tmp = Image.createRGBImage(data, w2, h2, true); data = null; // can this help GC at this point? return tmp; } // ------------------------------------------------- /** * this will remove the alpha component and add * a background to non-opaque pixels */ public static Image setBackground(Image src, int color) { int w = src.getWidth(); int h = src.getHeight(); int [] buffer = new int[w]; Image ret = Image.createImage(w, h); Graphics g = ret.getGraphics(); // make sure background has no alpha color |= 0xFF000000; for(int y = 0; y < h; y++) { src.getRGB(buffer, 0, w, 0, y, w, 1); for(int x = 0; x < w; x++) { int alpha = (buffer[x] >> 24) & 0xFF; if(alpha != 0xFF) buffer[x] = ColorUtils.blend(buffer[x], color, alpha) | 0xFF000000; } g.drawRGB(buffer, 0, w, 0, y, w, 1, true); } return ret; } // ------------------------------------------------- /** * crop an image: */ public static Image crop(Image src_i, int x0, int y0, int x1, int y1) { if(x0 > x1) { int tmp = x0; x0 = x1; x1 = tmp; } if(y0 > y1) { int tmp = y0; y0 = y1; y1 = tmp; } Image ret = Image.createImage(x1 - x0 + 1, y1 - y0 + 1); Graphics g = ret.getGraphics(); g.drawImage(src_i, -x0, -y0, 0); return ret; } /** * resize an image: */ public static Image resize(Image src_i, int size_w, int size_h, boolean filter, boolean mipmap) { // set source size int w = src_i.getWidth(); int h = src_i.getHeight(); // no change?? if(size_w == w && size_h == h) return src_i; // scale only after mip-mapping? if(mipmap) { while(w > size_w *2 && h > size_h * 2) { src_i = halve(src_i); w /= 2; h /= 2; } } int [] dst = new int[size_w * size_h]; if(filter) resize_rgb_filtered(src_i, dst, w, h, size_w, size_h); else resize_rgb_unfiltered(src_i, dst, w, h, size_w, size_h); // not needed anymore src_i = null; return Image.createRGBImage(dst, size_w, size_h, true); } // ------------------------------------------------ private static final void resize_rgb_unfiltered(Image src_i, int [] dst, int w0, int h0, int w1, int h1) { int [] buffer = new int[w0]; // scale with no filtering int index1 = 0; int index0_y = 0; for(int y = 0; y < h1; y++) { int y_ = index0_y / h1; int index0_x = 0; src_i.getRGB(buffer, 0, w0, 0, y_, w0, 1); for(int x = 0; x < w1; x++) { int x_ = index0_x / w1; dst[index1++] = buffer[x_]; // for next pixel index0_x += w0; } // For next line index0_y += h0; } } private static final void resize_rgb_filtered(Image src_i, int[] dst, int w0, int h0, int w1, int h1) { int[] buffer1 = new int[w0]; int[] buffer2 = new int[w0]; // UNOPTIMIZED bilinear filtering: // // The pixel position is defined by y_a and y_b, // which are 24.8 fixed point numbers // // for bilinear interpolation, we use y_a1 <= y_a <= y_b1 // and x_a1 <= x_a <= x_b1, with y_d and x_d defining how long // from x/y_b1 we are. // // since we are resizing one line at a time, we will at most // need two lines from the source image (y_a1 and y_b1). // this will save us some memory but will make the algorithm // noticeably slower for (int index1 = 0, y = 0; y < h1; y++) { final int y_a = ((y * h0) << 8) / h1; final int y_a1 = y_a >> 8; int y_d = y_a & 0xFF; int y_b1 = y_a1 + 1; if (y_b1 >= h0) { y_b1 = h0 - 1; y_d = 0; } // get the two affected lines: src_i.getRGB(buffer1, 0, w0, 0, y_a1, w0, 1); if (y_d != 0) src_i.getRGB(buffer2, 0, w0, 0, y_b1, w0, 1); for (int x = 0; x < w1; x++) { // get this and the next point int x_a = ((x * w0) << 8) / w1; int x_a1 = x_a >> 8; int x_d = x_a & 0xFF; int x_b1 = x_a1 + 1; if (x_b1 >= w0) { x_b1 = w0 - 1; x_d = 0; } // interpolate in x int c12, c34; int c1 = buffer1[x_a1]; int c3 = buffer1[x_b1]; // interpolate in y: if (y_d == 0) { c12 = c1; c34 = c3; } else { int c2 = buffer2[x_a1]; int c4 = buffer2[x_b1]; final int v1 = y_d & 0xFF; final int a_c2_RB = c1 & 0x00FF00FF; final int a_c2_AG_org = c1 & 0xFF00FF00; final int b_c2_RB = c3 & 0x00FF00FF; final int b_c2_AG_org = c3 & 0xFF00FF00; c12 = (a_c2_AG_org + ((((c2 >>> 8) & 0x00FF00FF) - (a_c2_AG_org >>> 8)) * v1)) & 0xFF00FF00 | (a_c2_RB + ((((c2 & 0x00FF00FF) - a_c2_RB) * v1) >> 8)) & 0x00FF00FF; c34 = (b_c2_AG_org + ((((c4 >>> 8) & 0x00FF00FF) - (b_c2_AG_org >>> 8)) * v1)) & 0xFF00FF00 | (b_c2_RB + ((((c4 & 0x00FF00FF) - b_c2_RB) * v1) >> 8)) & 0x00FF00FF; } // final result final int v1 = x_d & 0xFF; final int c2_RB = c12 & 0x00FF00FF; final int c2_AG_org = c12 & 0xFF00FF00; dst[index1++] = (c2_AG_org + ((((c34 >>> 8) & 0x00FF00FF) - (c2_AG_org >>> 8)) * v1)) & 0xFF00FF00 | (c2_RB + ((((c34 & 0x00FF00FF) - c2_RB) * v1) >> 8)) & 0x00FF00FF; } } } }
9,238
Java
.java
mahomaps/mm-v1
18
4
11
2023-05-01T09:07:22Z
2024-05-05T22:00:52Z
FpsLimiter.java
/FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/FpsLimiter.java
package mahomaps; public final class FpsLimiter extends Gate { private long time; public FpsLimiter() { super(true); } public void Begin() { time = System.currentTimeMillis(); } public void End(int timeout) throws InterruptedException { int delay = timeout - (int) (System.currentTimeMillis() - time); if (delay <= 0) return; super.Pass(delay); } }
375
Java
.java
mahomaps/mm-v1
18
4
11
2023-05-01T09:07:22Z
2024-05-05T22:00:52Z
Gate.java
/FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/Gate.java
package mahomaps; public class Gate { private volatile boolean pass; private final Object lock = new Object(); /** * Создаёт гейт. * * @param initState True, если 1 ближайший проход потока должен быть разрешён. */ public Gate(boolean initState) { pass = initState; } /** * Проходит гейт. Если прохождение было разрешено вызовом {@link #Reset()}, * метод возвращается. Если гейт заблокирован, ожидает ближайшего вызова * {@link #Reset()}. * * @throws InterruptedException Ожидание прервано. */ public void Pass() throws InterruptedException { synchronized (lock) { if (!pass) { lock.wait(); } pass = false; } } /** * Проходит гейт. Если прохождение было разрешено вызовом {@link #Reset()}, * метод возвращается. Если гейт заблокирован, ожидает ближайшего вызова * {@link #Reset()} до таймаута. * * @throws InterruptedException Ожидание прервано. */ public void Pass(int timeout) throws InterruptedException { synchronized (lock) { if (!pass) { lock.wait(timeout); } pass = false; } } /** * Запрещает потоку прохождение через гейт, если оно было разрешено вызовом * {@link #Reset()}. */ public void Set() { synchronized (lock) { pass = false; } } /** * Разрешает ожидающему потоку пройти гейт. Если поток ещё не достиг гейта, ему * будет разрешено пройти 1 раз в будущем. После прохождения потока гейт будет * заблокирован до следующего вызова {@link #Reset()}. */ public void Reset() { synchronized (lock) { pass = true; lock.notify(); } } }
2,091
Java
.java
mahomaps/mm-v1
18
4
11
2023-05-01T09:07:22Z
2024-05-05T22:00:52Z
MahoMapsApp.java
/FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/MahoMapsApp.java
package mahomaps; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Vector; import javax.microedition.io.ConnectionNotFoundException; import javax.microedition.lcdui.Alert; import javax.microedition.lcdui.Choice; import javax.microedition.lcdui.ChoiceGroup; import javax.microedition.lcdui.Command; import javax.microedition.lcdui.CommandListener; import javax.microedition.lcdui.Display; import javax.microedition.lcdui.Displayable; import javax.microedition.lcdui.Form; import javax.microedition.lcdui.Item; import javax.microedition.lcdui.StringItem; import javax.microedition.midlet.MIDlet; import mahomaps.api.YmapsApi; import mahomaps.map.TilesProvider; import mahomaps.overlays.OverlaysManager; import mahomaps.route.RouteTracker; import mahomaps.screens.MapCanvas; import mahomaps.screens.MenuScreen; import mahomaps.screens.SearchScreen; import mahomaps.screens.Splash; public class MahoMapsApp extends MIDlet implements Runnable, CommandListener { // globals public static Display display; public static Thread thread; public static TilesProvider tiles; private static MapCanvas canvas; private static MenuScreen menu; private static MahoMapsApp midlet; public static SearchScreen lastSearch; public static RouteTracker route; public static final YmapsApi api = new YmapsApi(); // locale public static String[] text; // info cache public static final String platform; public static final boolean bb; public static String version; public static String commit; public static boolean paused; private ChoiceGroup lang, bbNet; // commands public static Command exit; public static Command back; public static Command ok; public static Command rms; public static Command openLink; public static Command reset; public static Command no; public static Command yes; public static Command toMap; static { platform = System.getProperty("microedition.platform"); if (platform == null) { bb = false; } else { bb = platform.toLowerCase().indexOf("blackberry") != -1; } } public MahoMapsApp() { display = Display.getDisplay(this); } protected void startApp() { paused = false; if (thread == null) { version = getAppProperty("MIDlet-Version"); commit = getAppProperty("Commit"); midlet = this; Settings.Read(); if (Settings.firstLaunch) { processFirstLaunch(); return; } thread = new Thread(this, "Init & repaint thread"); thread.start(); } } private void processFirstLaunch() { if (lang != null) return; // do not translate anything here Form f = new Form("Setup"); lang = new ChoiceGroup("Language", Choice.EXCLUSIVE, new String[] { "Russian", "English", "French", "Arabic" }, null); bbNet = new ChoiceGroup("Network", Choice.EXCLUSIVE, new String[] { "Cellular", "Wi-Fi" }, null); f.append(lang); if (bb) { f.append(bbNet); } f.addCommand(ok); f.setCommandListener(this); BringSubScreen(f); return; } protected void destroyApp(boolean arg0) { if (thread != null) thread.interrupt(); if (tiles != null) tiles.Stop(); if (canvas != null) canvas.dispose(); } protected void pauseApp() { paused = true; } public void run() { try { BringSubScreen(new Splash()); } catch (Throwable t) { // just in case } try { tiles = new TilesProvider(Settings.GetLangString()); // wrong lang in settings } catch (RuntimeException e) { Form f = new Form(MahoMapsApp.text[88], new Item[] { new StringItem(MahoMapsApp.text[91], MahoMapsApp.text[92]) }); f.addCommand(exit); f.setCommandListener(this); BringSubScreen(f); thread = null; return; } if (!TryInitFSCache(true)) { // catch(Throwable) inside thread = null; return; } api.TryRead(); // catch(Throwable) inside try { if (api.token == null) api.RefreshToken(); } catch (Throwable e) { // network or OOM errors } try { menu = new MenuScreen(tiles); // nothing to fail canvas = new MapCanvas(tiles); // hz tiles.Start(); // OOM BringMap(); // jic } catch (Throwable t) { Form f = new Form(MahoMapsApp.text[88], new Item[] { new StringItem(MahoMapsApp.text[122], t.toString()) }); f.addCommand(exit); f.setCommandListener(this); BringSubScreen(f); thread = null; return; } try { (new UpdateCheckThread()).start(); } catch (Throwable t) { // OOM } try { canvas.run(); } catch (InterruptedException e) { } catch (Throwable t) { Form f = new Form(MahoMapsApp.text[88], new Item[] { new StringItem(MahoMapsApp.text[123], t.toString()) }); f.addCommand(exit); f.setCommandListener(this); BringSubScreen(f); } thread = null; } public static String getAppropCachePath() { String loc = null; if (IsKemulator()) { loc = "file:///root/ym/"; } else if (IsJ2MEL()) { loc = "file:///C:/MahoMaps/"; } else { loc = fixPath(System.getProperty("fileconn.dir.private"), null); if (loc == null) loc = fixPath(System.getProperty("fileconn.dir.photos"), "MahoMaps/"); if (loc == null) loc = "file:///C:/MahoMaps/"; } return loc; } private static String fixPath(String loc, String suf) { if (loc == null) return null; if (loc.charAt(loc.length() - 1) != '/') loc = loc + "/"; if (suf != null) loc = loc + suf; return loc; } /** * Запускает кэш с файловой. * * @param allowSwitch True, если предоставляется возможность использовать RMS. * Это перезапустит приложение. * @return False, если инициализировать не удалось. */ public static boolean TryInitFSCache(boolean allowSwitch) { try { if (Settings.cacheMode == Settings.CACHE_FS) tiles.InitFSCache(getAppropCachePath()); return true; } catch (Throwable e) { e.printStackTrace(); Form f = new Form(MahoMapsApp.text[88], new Item[] { new StringItem(MahoMapsApp.text[89], MahoMapsApp.text[90] + " " + getAppropCachePath()), new StringItem(e.getClass().getName(), e.getMessage()) }); f.addCommand(exit); if (allowSwitch) f.addCommand(rms); f.setCommandListener(midlet); BringSubScreen(f); return false; } } public static void BringSubScreen(Displayable screen) { display.setCurrent(screen); } public static void BringSubScreen(Alert a, Displayable screen) { display.setCurrent(a, screen); } public static void BringMap() { display.setCurrent(canvas); } public static void BringMenu() { display.setCurrent(menu); } public static MapCanvas GetCanvas() { return canvas; } public static OverlaysManager Overlays() { return canvas.overlays; } public static void open(String link) { try { midlet.platformRequest(link); } catch (ConnectionNotFoundException e) { } } public static void Exit() { midlet.destroyApp(true); midlet.notifyDestroyed(); } private final static double E = 2.71828182845904523536028d; public static double ln(double n) { int a = 0, b; double c, d, e, f; if (n < 0) c = Double.NaN; else if (n != 0) { for (; (d = n / E) > 1; ++a, n = d) ; for (; (d = n * E) < 1; --a, n = d) ; d = 1d / (n - 1); d = d + d + 1; e = d * d; c = 0; f = 1; for (b = 1; c + 0.00000001d < (c += 1d / (b * f)); b += 2) { f *= e; } c *= 2 / d; } else c = Double.NEGATIVE_INFINITY; return a + c; } public static boolean IsKemulator() { try { Class.forName("emulator.custom.CustomMethod"); return true; } catch (Exception e) { return false; } } public static boolean IsJ2MEL() { try { Class.forName("javax.microedition.shell.MicroActivity"); return true; } catch (Exception e) { return false; } } // called in settings load public static void LoadLocale(String name) { text = splitFull(getStringFromJAR("/" + name + ".txt"), '\n'); if (text == null) throw new RuntimeException("Lang is not loaded"); if (text.length != 169) throw new RuntimeException("Lang is outdated"); for (int i = 0; i < text.length; i++) { if (text[i].endsWith("\r")) { text[i] = text[i].substring(0, text[i].length() - 1); } } exit = new Command(text[0], Command.EXIT, 0); back = new Command(text[1], Command.BACK, 1); ok = new Command(text[2], Command.OK, 0); rms = new Command(text[3], Command.OK, 0); openLink = new Command(text[4], Command.ITEM, 0); reset = new Command(text[5], Command.ITEM, 0); no = new Command(text[6], Command.CANCEL, 1); yes = new Command(text[7], Command.OK, 0); toMap = new Command(text[8], Command.SCREEN, 0); } public static double pow(double a, double b) { boolean gt1 = (Math.sqrt((a - 1) * (a - 1)) <= 1) ? false : true; int oc = -1, iter = 30; double p = a, x, x2, sumX, sumY; if ((b - Math.floor(b)) == 0) { for (int i = 1; i < b; i++) p *= a; return p; } x = (gt1) ? (a / (a - 1)) : (a - 1); sumX = (gt1) ? (1 / x) : x; for (int i = 2; i < iter; i++) { p = x; for (int j = 1; j < i; j++) p *= x; double xTemp = (gt1) ? (1 / (i * p)) : (p / i); sumX = (gt1) ? (sumX + xTemp) : (sumX + (xTemp * oc)); oc *= -1; } x2 = b * sumX; sumY = 1 + x2; for (int i = 2; i <= iter; i++) { p = x2; for (int j = 1; j < i; j++) p *= x2; int yTemp = 2; for (int j = i; j > 2; j--) yTemp *= j; sumY += p / yTemp; } return sumY; } /** * * @param a Cos value [-1; 1] * @return Angle in radians. */ public static double acos(double a) { final double epsilon = 1.0E-14; double x = a; do { x -= (Math.sin(x) - a) / Math.cos(x); } while (Math.abs(Math.sin(x) - a) > epsilon); // returned angle is in radians return -1 * (x - Math.PI / 2); } public void commandAction(Command c, Displayable d) { if (c == exit) { Exit(); } else if (c == rms) { Settings.cacheMode = Settings.CACHE_RMS; Settings.Save(); startApp(); } else if (c == ok) { if (thread != null) throw new IllegalStateException("First-run setup can't be finished if app is running!"); int selLang = lang.getSelectedIndex(); Settings.uiLang = selLang; if (selLang == 1 || selLang == 2) { // english api for english/french UI Settings.apiLang = 1; } if (bb) Settings.bbWifi = bbNet.getSelectedIndex() == 1; Settings.firstLaunch = false; Settings.Save(); bbNet = null; lang = null; startApp(); } } public static String getConnectionParams() { if (!bb || !Settings.bbWifi) { return ""; } return ";deviceside=true;interface=wifi"; } public static final String getStringFromJAR(String path) { try { StringBuffer sb = new StringBuffer(); char[] chars = new char[1024]; InputStream stream = MahoMapsApp.class.getResourceAsStream(path); if (stream == null) return null; InputStreamReader isr; isr = new InputStreamReader(stream, "UTF-8"); while (true) { int c = isr.read(chars); if (c == -1) break; sb.append(chars, 0, c); } isr.close(); return sb.toString(); } catch (IOException e) { e.printStackTrace(); return null; } } public static String[] splitFull(String str, char c) { if (str == null) return null; Vector v = new Vector(64, 16); int lle = 0; while (true) { int nle = str.indexOf(c, lle); if (nle == -1) { v.addElement(str.substring(lle, str.length())); break; } v.addElement(str.substring(lle, nle)); lle = nle + 1; } String[] a = new String[v.size()]; v.copyInto(a); v.removeAllElements(); v.trimToSize(); v = null; return a; } }
11,674
Java
.java
mahomaps/mm-v1
18
4
11
2023-05-01T09:07:22Z
2024-05-05T22:00:52Z
UpdateCheckThread.java
/FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/UpdateCheckThread.java
package mahomaps; import java.io.ByteArrayOutputStream; import java.io.InputStream; import javax.microedition.io.Connector; import javax.microedition.io.HttpConnection; import cc.nnproject.json.*; import mahomaps.api.YmapsApiBase; import mahomaps.screens.UpdateScreen; public class UpdateCheckThread extends Thread { public UpdateCheckThread() { super("Update check"); } public void run() { String dev = MahoMapsApp.platform; String os = System.getProperty("os.name"); String osver = System.getProperty("os.version"); String sejp = System.getProperty("com.sonyericsson.java.platform"); if (MahoMapsApp.IsKemulator()) { dev += "|KEmulator"; String kemV = System.getProperty("kemulator.mod.version"); if (kemV != null) dev += "/nnmod" + kemV; } try { Class.forName("javax.microedition.shell.MicroActivity"); dev += "|J2MELoader"; } catch (Exception e) { } if (os != null) { dev += "|o:" + os; } if (osver != null) { dev += "|v:" + osver; } if (sejp != null) { dev += "|s:" + sejp; } boolean hasGeo = false; try { Class.forName("javax.microedition.location.LocationProvider"); hasGeo = true; } catch (Exception e) { } String url = "http://nnp.nnchan.ru:80/mahomaps/check.php?v=1." + MahoMapsApp.version + "&gt=" + Settings.geoLook + "&geo=" + (hasGeo ? 1 : 0) + "&uf=" + Settings.usageFlags + "&device=" + YmapsApiBase.EncodeUrl(dev); System.out.println("GET " + url); HttpConnection hc = null; InputStream is = null; ByteArrayOutputStream o = new ByteArrayOutputStream(); try { hc = (HttpConnection) Connector.open(url + MahoMapsApp.getConnectionParams()); hc.setRequestMethod("GET"); int r = hc.getResponseCode(); is = hc.openInputStream(); byte[] buf = new byte[256]; int len; while ((len = is.read(buf)) != -1) { o.write(buf, 0, len); } Settings.usageFlags = 0; Settings.Save(); String str = new String(o.toByteArray(), "UTF-8"); o.close(); if (r == 200) { JSONObject j = JSON.getObject(str); String uurl = j.getString("url", null); String utext = j.getString("text", null); if (uurl != null || utext != null) { MahoMapsApp.BringSubScreen(new UpdateScreen(utext, uurl)); } } } catch (Exception e) { e.printStackTrace(); } finally { try { if (is != null) is.close(); if (hc != null) hc.close(); } catch (Exception e) { } } } }
2,435
Java
.java
mahomaps/mm-v1
18
4
11
2023-05-01T09:07:22Z
2024-05-05T22:00:52Z
Settings.java
/FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/Settings.java
package mahomaps; import javax.microedition.rms.RecordStore; import cc.nnproject.json.*; import mahomaps.map.MapState; public class Settings { private static final String RMS_NAME = "mm_v1_prefs"; private static final String POS_RMS_NAME = "mm_v1_state"; private Settings() { } public static boolean drawDebugInfo = false; public static int focusZoom = 16; public static int geoLook = 0; public static int showGeo = 1; public static boolean allowDownload = true; public static int cacheMode = 1; public static boolean proxyTiles = false; public static boolean proxyApi = false; public static int uiSize = 0; public static int apiLang = 0; public static int uiLang = 0; public static boolean bbWifi; public static boolean firstLaunch = true; public static int map; /** * Reads "fallback" tile (scaled up) before downloading it. */ public static boolean readCachedBeforeDownloading = false; public static String proxyServer = "http://nnp.nnchan.ru:80/mahoproxy.php?u="; public static final int CACHE_FS = 1; public static final int CACHE_RMS = 2; public static final int CACHE_DISABLED = 0; /** * Telemetry flags * <ul> * <li>1 - about screen * <li>2 - others screen * <li>4 - settings screen * <li>8 - geolocation * <li>16 - search * <li>32 - route build by foot * <li>64 - route build by auto * <li>128 - route build by PT * <li>256 - route follow * <li>512 - route details * </ul> */ public static int usageFlags = 0; public static synchronized void PushUsageFlag(int flag) { usageFlags |= flag; Save(); } /** * Читает настройки приложения. Вызывает загрузку локализации. * * @return False, если чтение неудачно. */ public static synchronized boolean Read() { try { RecordStore r = RecordStore.openRecordStore(RMS_NAME, true); byte[] d = null; if (r.getNumRecords() > 0) { d = r.getRecord(1); } r.closeRecordStore(); // parse if (d == null) { ApplyOptimal(); return true; } JSONObject j = JSON.getObject(new String(d)); drawDebugInfo = j.getBoolean("tile_info", false); focusZoom = j.getInt("focus_zoom", 16); geoLook = j.getInt("geo_look", 0); showGeo = j.getInt("show_geo", 1); allowDownload = j.getBoolean("online", true); cacheMode = j.getInt("cache", 1); proxyTiles = j.getBoolean("proxy_tiles"); proxyApi = j.getBoolean("proxy_api"); proxyServer = j.getString("proxy_server", proxyServer); uiSize = j.getInt("ui_size", 0); apiLang = j.getInt("lang", 0); uiLang = j.getInt("ui_lang", 0); bbWifi = j.getBoolean("bb_wifi", false); firstLaunch = j.getBoolean("1", true); usageFlags = j.getInt("tm", 0); map = j.getInt("map", 0); readCachedBeforeDownloading = j.getBoolean("upscale", false); return true; } catch (Throwable e) { e.printStackTrace(); ApplyOptimal(); return false; } finally { try { MahoMapsApp.LoadLocale(GetUiLangFile()); } catch (Exception e) { MahoMapsApp.LoadLocale(new String(new char[] { 'r', 'u' })); } } } private static void ApplyOptimal() { if (MahoMapsApp.IsKemulator()) { proxyApi = false; proxyTiles = false; } else { proxyTiles = proxyApi = MahoMapsApp.platform == null || MahoMapsApp.platform.indexOf("platform_version=5.") == -1 || MahoMapsApp.platform.indexOf("platform_version=5.0") != -1; } } public static String Serialize() { JSONObject j = new JSONObject(); j.put("tile_info", drawDebugInfo); j.put("focus_zoom", focusZoom); j.put("geo_look", geoLook); j.put("show_geo", showGeo); j.put("online", allowDownload); j.put("cache", cacheMode); j.put("proxy_tiles", proxyTiles); j.put("proxy_api", proxyApi); j.put("proxy_server", proxyServer); j.put("ui_size", uiSize); j.put("lang", apiLang); j.put("ui_lang", uiLang); j.put("bb_wifi", bbWifi); j.put("1", firstLaunch); j.put("tm", usageFlags); j.put("map", map); j.put("upscale", readCachedBeforeDownloading); return j.toString(); } public static synchronized void Save() { try { byte[] d = Serialize().getBytes(); RecordStore r = RecordStore.openRecordStore(RMS_NAME, true); if (r.getNumRecords() == 0) { r.addRecord(new byte[1], 0, 1); } r.setRecord(1, d, 0, d.length); r.closeRecordStore(); } catch (Exception e) { e.printStackTrace(); } } public static MapState ReadStateOrDefault() { try { RecordStore r = RecordStore.openRecordStore(POS_RMS_NAME, true); byte[] d = null; if (r.getNumRecords() > 0) { d = r.getRecord(1); } r.closeRecordStore(); if (d != null) { return MapState.Decode(new String(d)); } } catch (Throwable e) { e.printStackTrace(); } return MapState.Default(); } public static void SaveState(MapState ms) { try { byte[] d = ms.Encode().getBytes(); RecordStore r = RecordStore.openRecordStore(POS_RMS_NAME, true); if (r.getNumRecords() == 0) r.addRecord(new byte[1], 0, 1); r.setRecord(1, d, 0, d.length); r.closeRecordStore(); } catch (Exception e) { e.printStackTrace(); } } /** * Gets language string for use in API requests. */ public static String GetLangString() { switch (apiLang) { case 0: return new String(new char[] { 'r', 'u', '_', 'R', 'U' }); case 1: return new String(new char[] { 'e', 'n', '_', 'U', 'S' }); case 2: return new String(new char[] { 't', 'r', '_', 'T', 'R' }); default: throw new IndexOutOfBoundsException("Unknown language code!"); } } /** * Gets language string for localisation files. */ public static String GetUiLangFile() { switch (uiLang) { case 0: default: return new String(new char[] { 'r', 'u' }); case 1: return new String(new char[] { 'e', 'n' }); case 2: return new String(new char[] { 'f', 'r' }); case 3: return new String(new char[] { 'a', 'r' }); } } }
5,940
Java
.java
mahomaps/mm-v1
18
4
11
2023-05-01T09:07:22Z
2024-05-05T22:00:52Z
CacheFailedOverlay.java
/FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/overlays/CacheFailedOverlay.java
package mahomaps.overlays; import java.util.Vector; import mahomaps.MahoMapsApp; import mahomaps.map.Geopoint; import mahomaps.ui.Button; import mahomaps.ui.ColumnsContainer; import mahomaps.ui.FillFlowContainer; import mahomaps.ui.IButtonHandler; import mahomaps.ui.SimpleText; import mahomaps.ui.UIElement; public class CacheFailedOverlay extends MapOverlay implements IButtonHandler { public CacheFailedOverlay() { content = new FillFlowContainer( new UIElement[] { new SimpleText(MahoMapsApp.text[124]), new SimpleText(MahoMapsApp.text[125]), new ColumnsContainer(new UIElement[] { new Button(MahoMapsApp.text[38], 0, this) }) }); } public String GetId() { return "cache_fail"; } public Vector GetPoints() { return EMPTY_VECTOR; } public boolean OnPointTap(Geopoint p) { return false; } public void OnButtonTap(UIElement sender, int uid) { switch (uid) { case 0: Close(); break; } } }
939
Java
.java
mahomaps/mm-v1
18
4
11
2023-05-01T09:07:22Z
2024-05-05T22:00:52Z
TileDownloadForbiddenOverlay.java
/FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/overlays/TileDownloadForbiddenOverlay.java
package mahomaps.overlays; import java.util.Vector; import mahomaps.MahoMapsApp; import mahomaps.map.Geopoint; import mahomaps.screens.SettingsScreen; import mahomaps.ui.Button; import mahomaps.ui.ColumnsContainer; import mahomaps.ui.FillFlowContainer; import mahomaps.ui.IButtonHandler; import mahomaps.ui.SimpleText; import mahomaps.ui.UIElement; public class TileDownloadForbiddenOverlay extends MapOverlay implements IButtonHandler { public TileDownloadForbiddenOverlay() { content = new FillFlowContainer(new UIElement[] { new SimpleText(MahoMapsApp.text[42]), new SimpleText(MahoMapsApp.text[43]), new ColumnsContainer(new UIElement[] { new Button(MahoMapsApp.text[41], 1, this), new Button(MahoMapsApp.text[38], 0, this) }) }); } public String GetId() { return "no_network"; } public Vector GetPoints() { return EMPTY_VECTOR; } public boolean OnPointTap(Geopoint p) { return false; } public void OnButtonTap(UIElement sender, int uid) { switch (uid) { case 0: Close(); break; case 1: MahoMapsApp.BringSubScreen(new SettingsScreen()); Close(); break; } } }
1,122
Java
.java
mahomaps/mm-v1
18
4
11
2023-05-01T09:07:22Z
2024-05-05T22:00:52Z
TileCacheForbiddenOverlay.java
/FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/overlays/TileCacheForbiddenOverlay.java
package mahomaps.overlays; import java.util.Vector; import mahomaps.MahoMapsApp; import mahomaps.map.Geopoint; import mahomaps.screens.SettingsScreen; import mahomaps.ui.Button; import mahomaps.ui.ColumnsContainer; import mahomaps.ui.FillFlowContainer; import mahomaps.ui.IButtonHandler; import mahomaps.ui.SimpleText; import mahomaps.ui.UIElement; public class TileCacheForbiddenOverlay extends MapOverlay implements IButtonHandler { public TileCacheForbiddenOverlay() { content = new FillFlowContainer(new UIElement[] { new SimpleText(MahoMapsApp.text[44]), new SimpleText(MahoMapsApp.text[45]), new ColumnsContainer(new UIElement[] { new Button(MahoMapsApp.text[41], 1, this), new Button(MahoMapsApp.text[38], 0, this) }) }); } public String GetId() { return "no_network"; } public Vector GetPoints() { return EMPTY_VECTOR; } public boolean OnPointTap(Geopoint p) { return false; } public void OnButtonTap(UIElement sender, int uid) { switch (uid) { case 0: Close(); break; case 1: MahoMapsApp.BringSubScreen(new SettingsScreen()); Close(); break; } } }
1,115
Java
.java
mahomaps/mm-v1
18
4
11
2023-05-01T09:07:22Z
2024-05-05T22:00:52Z
RouteFollowOverlay.java
/FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/overlays/RouteFollowOverlay.java
package mahomaps.overlays; import java.util.Vector; import javax.microedition.lcdui.Alert; import javax.microedition.lcdui.AlertType; import javax.microedition.lcdui.Command; import javax.microedition.lcdui.CommandListener; import javax.microedition.lcdui.Displayable; import mahomaps.MahoMapsApp; import mahomaps.map.Geopoint; import mahomaps.ui.Button; import mahomaps.ui.FillFlowContainer; import mahomaps.ui.IButtonHandler; import mahomaps.ui.UIElement; public class RouteFollowOverlay extends MapOverlay implements IButtonHandler, CommandListener { final Vector v = new Vector(); private Geopoint a; private Geopoint b; public RouteFollowOverlay(Geopoint a, Geopoint b) { this.a = a; this.b = b; content = new FillFlowContainer(new UIElement[] { new Button(MahoMapsApp.text[32], 0, this) }); ShowPoint(null); } public void ShowPoint(Geopoint p) { v.removeAllElements(); v.addElement(a); v.addElement(b); if (p != null) v.addElement(p); } public String GetId() { return RouteBuildOverlay.ID; } public Vector GetPoints() { return v; } public boolean OnPointTap(Geopoint p) { return false; } public void OnButtonTap(UIElement sender, int uid) { if (uid == 0) { Alert a1 = new Alert("MahoMaps v1", MahoMapsApp.text[112], null, AlertType.WARNING); a1.setTimeout(Alert.FOREVER); a1.addCommand(MahoMapsApp.yes); a1.addCommand(MahoMapsApp.no); a1.setCommandListener(this); MahoMapsApp.BringSubScreen(a1); } } public void commandAction(Command c, Displayable d) { if (c == MahoMapsApp.yes) { MahoMapsApp.GetCanvas().line = null; MahoMapsApp.route.ReleaseGeolocation(); MahoMapsApp.route = null; Close(); } MahoMapsApp.BringMap(); } }
1,725
Java
.java
mahomaps/mm-v1
18
4
11
2023-05-01T09:07:22Z
2024-05-05T22:00:52Z
RouteOverlay.java
/FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/overlays/RouteOverlay.java
package mahomaps.overlays; import java.io.IOException; import java.util.Vector; import javax.microedition.lcdui.Alert; import javax.microedition.lcdui.AlertType; import javax.microedition.lcdui.Command; import javax.microedition.lcdui.CommandListener; import javax.microedition.lcdui.Displayable; import javax.microedition.lcdui.Form; import javax.microedition.lcdui.Item; import mahomaps.MahoMapsApp; import mahomaps.Settings; import mahomaps.api.Http403Exception; import mahomaps.api.YmapsApi; import mahomaps.map.Geopoint; import mahomaps.map.Line; import mahomaps.route.Route; import mahomaps.route.RouteSegment; import mahomaps.route.RouteTracker; import mahomaps.screens.MapCanvas; import mahomaps.ui.Button; import mahomaps.ui.ColumnsContainer; import mahomaps.ui.FillFlowContainer; import mahomaps.ui.IButtonHandler; import mahomaps.ui.SimpleText; import mahomaps.ui.UIElement; public class RouteOverlay extends MapOverlay implements Runnable, IButtonHandler, CommandListener { final Vector v = new Vector(); private Geopoint a; private Geopoint b; private final int method; Route route; private boolean anchorsShown = false; public RouteOverlay(Geopoint a, Geopoint b, int method) { this.a = a; this.b = b; this.method = method; ShowAB(); content = new FillFlowContainer(new UIElement[] { new SimpleText(MahoMapsApp.text[134]) }); Thread th = new Thread(this, "Route api request"); th.start(); } public String GetId() { return RouteBuildOverlay.ID; } public Vector GetPoints() { return v; } public boolean OnPointTap(Geopoint p) { return false; } public void run() { try { route = new Route(MahoMapsApp.api.Route(a, b, method)); LoadRoute(); } catch (IOException e) { content = new FillFlowContainer(new UIElement[] { new SimpleText(MahoMapsApp.text[111]), new Button(MahoMapsApp.text[37], 2, this), new Button(MahoMapsApp.text[38], 0, this) }); } catch (Http403Exception e) { content = new FillFlowContainer( new UIElement[] { new SimpleText(MahoMapsApp.text[135]), new SimpleText(MahoMapsApp.text[136]), new Button(MahoMapsApp.text[37], 2, this), new Button(MahoMapsApp.text[38], 0, this) }); } catch (Exception e) { e.printStackTrace(); content = new FillFlowContainer(new UIElement[] { new SimpleText(MahoMapsApp.text[120]), new SimpleText(e.getClass().getName()), new Button(MahoMapsApp.text[38], 1, this) }); } catch (OutOfMemoryError e) { content = new FillFlowContainer(new UIElement[] { new SimpleText(MahoMapsApp.text[121]), new Button(MahoMapsApp.text[38], 1, this) }); } finally { InvalidateSize(); } } public void LoadRoute() { // route field must be non-null here! ColumnsContainer cols = new ColumnsContainer(new UIElement[] { new Button(MahoMapsApp.text[113], 3, this), new Button(MahoMapsApp.text[114], 4, this) }); content = new FillFlowContainer( new UIElement[] { new SimpleText(Type(method)), new SimpleText(route.distance + ", " + route.time), new Button(MahoMapsApp.text[115], 5, this), cols, new Button(MahoMapsApp.text[38], 0, this) }); MahoMapsApp.GetCanvas().line = new Line(a, route.points); } public void ShowAB() { v.removeAllElements(); v.addElement(a); v.addElement(b); } public void ShowAnchors() { v.removeAllElements(); RouteSegment[] sgs = route.segments; for (int i = 0; i < sgs.length; i++) { Geopoint p = sgs[i].GetAnchor(); if (p != null) v.addElement(p); } v.addElement(a); v.addElement(b); } public void OnButtonTap(UIElement sender, int uid) { switch (uid) { case 0: { Alert a1 = new Alert("MahoMaps v1", MahoMapsApp.text[112], null, AlertType.WARNING); a1.setTimeout(Alert.FOREVER); a1.addCommand(MahoMapsApp.yes); a1.addCommand(MahoMapsApp.no); a1.setCommandListener(this); MahoMapsApp.BringSubScreen(a1); break; } case 1: // close after error Close(); break; case 2: RouteBuildOverlay rbo = RouteBuildOverlay.Get(); rbo.SetA(a); rbo.SetB(b); break; case 3: if (route != null) { Form f = new Form(MahoMapsApp.text[116]); for (int i = 0; i < route.segments.length; i++) { Item[] items = route.segments[i].ToLcdui(); for (int j = 0; j < items.length; j++) { items[j].setLayout(Item.LAYOUT_NEWLINE_AFTER | Item.LAYOUT_NEWLINE_BEFORE); f.append(items[j]); } } f.addCommand(MahoMapsApp.back); f.setCommandListener(this); MahoMapsApp.BringSubScreen(f); Settings.PushUsageFlag(512); } break; case 4: if (anchorsShown) { ShowAB(); } else { ShowAnchors(); } anchorsShown = !anchorsShown; break; case 5: MapCanvas mc = MahoMapsApp.GetCanvas(); if (mc.geo != null && mc.geo.DrawPoint()) { try { RouteFollowOverlay rfo = new RouteFollowOverlay(a, b); MahoMapsApp.GetCanvas().overlays.PushOverlay(rfo); RouteTracker rt = new RouteTracker(route, rfo); rt.SpoofGeolocation(MahoMapsApp.GetCanvas()); MahoMapsApp.route = rt; UIElement.Deselect(); Settings.PushUsageFlag(256); } catch (IOException e) { e.printStackTrace(); } } else { Alert a1 = new Alert("MahoMaps v1", MahoMapsApp.text[119], null, AlertType.WARNING); a1.setTimeout(Alert.FOREVER); MahoMapsApp.BringSubScreen(a1, mc); } break; } } private static String Type(int t) { switch (t) { case YmapsApi.ROUTE_AUTO: return MahoMapsApp.text[126]; case YmapsApi.ROUTE_BYFOOT: return MahoMapsApp.text[127]; case YmapsApi.ROUTE_TRANSPORT: return MahoMapsApp.text[144]; } return ""; } public void commandAction(Command c, Displayable d) { if (c == MahoMapsApp.yes) { MahoMapsApp.GetCanvas().line = null; Close(); } MahoMapsApp.BringMap(); } }
5,772
Java
.java
mahomaps/mm-v1
18
4
11
2023-05-01T09:07:22Z
2024-05-05T22:00:52Z
SelectOverlay.java
/FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/overlays/SelectOverlay.java
package mahomaps.overlays; import java.util.Vector; import mahomaps.MahoMapsApp; import mahomaps.map.Geopoint; import mahomaps.screens.BookmarksScreen; import mahomaps.screens.SearchLoader; import mahomaps.ui.Button; import mahomaps.ui.ColumnsContainer; import mahomaps.ui.FillFlowContainer; import mahomaps.ui.IButtonHandler; import mahomaps.ui.SimpleText; import mahomaps.ui.UIElement; public class SelectOverlay extends MapOverlay implements IButtonHandler { public static final String ID = "selection"; private final Geopoint selection; private final Vector v = new Vector(1); public SelectOverlay(final Geopoint p) { selection = new Geopoint(p.lat, p.lon); selection.type = Geopoint.POI_SELECT; selection.color = Geopoint.COLOR_RED; v.addElement(selection); content = new FillFlowContainer(new UIElement[] { new SimpleText(p.toString()), new Button(MahoMapsApp.text[103], 1, this), new Button(MahoMapsApp.text[137], 4, this), new ColumnsContainer(new UIElement[] { new Button(MahoMapsApp.text[104], 2, this), new Button(MahoMapsApp.text[105], 3, this) }), new Button(MahoMapsApp.text[38], 0, this) }); } public String GetId() { return ID; } public Vector GetPoints() { return v; } public boolean OnPointTap(Geopoint p) { return false; } public void OnButtonTap(UIElement sender, int uid) { switch (uid) { case 0: Close(); break; case 1: if (MahoMapsApp.GetCanvas().CheckApiAcsess()) { Close(); MahoMapsApp.BringSubScreen(new SearchLoader(selection.toString(), selection)); } break; case 2: Close(); RouteBuildOverlay.Get().SetA(selection); break; case 3: Close(); RouteBuildOverlay.Get().SetB(selection); break; case 4: BookmarksScreen.BeginAdd(selection, null); break; } } }
1,801
Java
.java
mahomaps/mm-v1
18
4
11
2023-05-01T09:07:22Z
2024-05-05T22:00:52Z
MapOverlay.java
/FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/overlays/MapOverlay.java
package mahomaps.overlays; import java.util.Vector; import javax.microedition.lcdui.Graphics; import mahomaps.MahoMapsApp; import mahomaps.map.Geopoint; import mahomaps.ui.UIComposite; import mahomaps.ui.UIElement; public abstract class MapOverlay extends UIElement { public static final int OVERLAY_BG = 0x1E1E1E; protected final static Vector EMPTY_VECTOR = new Vector(); public abstract String GetId(); public abstract Vector GetPoints(); /** * Обрабатывает нажатие на точку оверлея. * * @param p Точка. * @return False, если нажатие нужно проигнорировать. */ public abstract boolean OnPointTap(Geopoint p); public UIComposite content; public void Paint(Graphics g, int x, int y, int w, int h) { if (content == null) return; g.setColor(OVERLAY_BG); g.fillRoundRect(x, y, w, H + 6, 10, 10); content.Paint(g, x + 3, y + 3, w - 6, 0); H = content.H; } protected void Close() { MahoMapsApp.Overlays().CloseOverlay(this); } protected void InvalidateSize() { MahoMapsApp.Overlays().InvalidateOverlayHeight(this); } }
1,136
Java
.java
mahomaps/mm-v1
18
4
11
2023-05-01T09:07:22Z
2024-05-05T22:00:52Z
NoApiTokenOverlay.java
/FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/overlays/NoApiTokenOverlay.java
package mahomaps.overlays; import java.util.Vector; import mahomaps.MahoMapsApp; import mahomaps.map.Geopoint; import mahomaps.screens.APIReconnectForm; import mahomaps.ui.Button; import mahomaps.ui.ColumnsContainer; import mahomaps.ui.FillFlowContainer; import mahomaps.ui.IButtonHandler; import mahomaps.ui.SimpleText; import mahomaps.ui.UIElement; public class NoApiTokenOverlay extends MapOverlay implements IButtonHandler { public NoApiTokenOverlay() { content = new FillFlowContainer(new UIElement[] { new SimpleText(MahoMapsApp.text[39]), new SimpleText(MahoMapsApp.text[40]), new ColumnsContainer(new UIElement[] { new Button(MahoMapsApp.text[37], 1, this), new Button(MahoMapsApp.text[38], 0, this) }) }); } public String GetId() { return "no_token"; } public Vector GetPoints() { return EMPTY_VECTOR; } public boolean OnPointTap(Geopoint p) { return false; } public void OnButtonTap(UIElement sender, int uid) { switch (uid) { case 0: Close(); break; case 1: MahoMapsApp.BringSubScreen(new APIReconnectForm()); Close(); break; } } }
1,104
Java
.java
mahomaps/mm-v1
18
4
11
2023-05-01T09:07:22Z
2024-05-05T22:00:52Z
RouteBuildOverlay.java
/FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/overlays/RouteBuildOverlay.java
package mahomaps.overlays; import java.util.Vector; import javax.microedition.lcdui.Alert; import javax.microedition.lcdui.AlertType; import mahomaps.MahoMapsApp; import mahomaps.Settings; import mahomaps.api.YmapsApi; import mahomaps.map.Geopoint; import mahomaps.screens.MapCanvas; import mahomaps.ui.Button; import mahomaps.ui.ColumnsContainer; import mahomaps.ui.FillFlowContainer; import mahomaps.ui.IButtonHandler; import mahomaps.ui.SimpleText; import mahomaps.ui.UIElement; public class RouteBuildOverlay extends MapOverlay implements IButtonHandler { public static final String ID = "route"; private final Vector v = new Vector(); private Geopoint a, b; public RouteBuildOverlay() { Update(); } private void Update() { v.removeAllElements(); if (a != null && b != null) { v.addElement(a); v.addElement(b); content = new FillFlowContainer(new UIElement[] { new ColumnsContainer(new UIElement[] { new Button(MahoMapsApp.text[126], 1, this), new Button(MahoMapsApp.text[127], 2, this), new Button(MahoMapsApp.text[128], 3, this) }), new Button(MahoMapsApp.text[118], 0, this) }); } else if (a == null && b == null) { content = new FillFlowContainer(new UIElement[] { new SimpleText(MahoMapsApp.text[129]), new Button(MahoMapsApp.text[118], 0, this) }); } else { String s; Button bt; if (b == null) { s = MahoMapsApp.text[131]; bt = new Button(MahoMapsApp.text[133], 10, this); v.addElement(a); } else { s = MahoMapsApp.text[130]; bt = new Button(MahoMapsApp.text[132], 11, this); v.addElement(b); } content = new FillFlowContainer(new UIElement[] { new SimpleText(s), bt, new Button(MahoMapsApp.text[118], 0, this) }); } } public void SetA(Geopoint p) { a = new Geopoint(p.lat, p.lon); a.type = Geopoint.ROUTE_A; Update(); InvalidateSize(); } public void SetB(Geopoint p) { b = new Geopoint(p.lat, p.lon); b.type = Geopoint.ROUTE_B; Update(); InvalidateSize(); } public static RouteBuildOverlay Get() { MapOverlay mo = MahoMapsApp.Overlays().GetOverlay(ID); if (mo != null) { if (mo instanceof RouteBuildOverlay) { return (RouteBuildOverlay) mo; } } RouteBuildOverlay o = new RouteBuildOverlay(); MahoMapsApp.Overlays().PushOverlay(o); return o; } private static void NotifyNoGeo() { Alert a = new Alert(MahoMapsApp.text[116], MahoMapsApp.text[117], null, AlertType.WARNING); a.setTimeout(4000); MahoMapsApp.BringSubScreen(a, MahoMapsApp.GetCanvas()); } public String GetId() { return ID; } public Vector GetPoints() { return v; } public boolean OnPointTap(Geopoint p) { return false; } public void OnButtonTap(UIElement sender, int uid) { MapCanvas m = MahoMapsApp.GetCanvas(); if (uid == 0) { Close(); return; } if (uid == 10) { if (m.geo.DrawPoint()) { SetB(m.geolocation); } else { NotifyNoGeo(); } return; } if (uid == 11) { if (m.geo.DrawPoint()) { SetA(m.geolocation); } else { NotifyNoGeo(); } return; } if (a == null || b == null) return; if (!MahoMapsApp.GetCanvas().CheckApiAcsess()) return; int method = 0; switch (uid) { case 1: Settings.PushUsageFlag(64); method = YmapsApi.ROUTE_AUTO; break; case 2: Settings.PushUsageFlag(32); method = YmapsApi.ROUTE_BYFOOT; break; case 3: Settings.PushUsageFlag(128); method = YmapsApi.ROUTE_TRANSPORT; break; } MahoMapsApp.Overlays().PushOverlay(new RouteOverlay(a, b, method)); } }
3,528
Java
.java
mahomaps/mm-v1
18
4
11
2023-05-01T09:07:22Z
2024-05-05T22:00:52Z
SearchOverlay.java
/FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/overlays/SearchOverlay.java
package mahomaps.overlays; import java.util.Vector; import cc.nnproject.json.*; import mahomaps.MahoMapsApp; import mahomaps.map.Geopoint; import mahomaps.map.MapState; import mahomaps.screens.BookmarksScreen; import mahomaps.screens.SearchResultScreen; import mahomaps.screens.SearchScreen; import mahomaps.ui.Button; import mahomaps.ui.ColumnsContainer; import mahomaps.ui.FillFlowContainer; import mahomaps.ui.IButtonHandler; import mahomaps.ui.SimpleText; import mahomaps.ui.UIElement; public class SearchOverlay extends MapOverlay implements IButtonHandler { public static final String ID = "search"; private final String query; private final JSONArray results; private Vector points; private Geopoint selected = null; private SearchScreen list; public SearchOverlay(Geopoint around, String query, JSONArray results, SearchScreen list) { this.query = query; this.results = results; this.list = list; SetNullSelection(); } public void SetNullSelection() { selected = null; points = new Vector(); for (int i = 0; i < results.size(); i++) { JSONArray point1 = results.getObject(i).getObject("geometry").getArray("coordinates"); Geopoint gp = new Geopoint(point1.getDouble(1), point1.getDouble(0)); gp.type = Geopoint.POI_SEARCH; gp.color = Geopoint.COLOR_GREEN; gp.object = results.getObject(i); points.addElement(gp); } content = new FillFlowContainer(new UIElement[] { new SimpleText(query), new SimpleText(MahoMapsApp.text[108] + ": " + results.size()), new SimpleText(MahoMapsApp.text[107]), new ColumnsContainer(new UIElement[] { new Button(MahoMapsApp.text[106], 1, this), new Button(MahoMapsApp.text[38], 0, this) }) }); InvalidateSize(); } private void SetSelection(Geopoint p) { selected = p; for (int i = 0; i < points.size(); i++) { Geopoint pp = (Geopoint) points.elementAt(i); if (pp == p) { points.removeElementAt(i); i--; pp.color = Geopoint.COLOR_RED; } else { pp.color = Geopoint.COLOR_GRAY; } } points.addElement(p); JSONObject data = ((JSONObject) p.object).getObject("properties"); content = new FillFlowContainer(new UIElement[] { new SimpleText(data.getNullableString("name")), new SimpleText(data.getString("description", "")), new ColumnsContainer(new UIElement[] { new Button(MahoMapsApp.text[109], 2, this), new Button(MahoMapsApp.text[110], 3, this) }), new ColumnsContainer(new UIElement[] { new Button(MahoMapsApp.text[104], 4, this), new Button(MahoMapsApp.text[105], 5, this) }), new ColumnsContainer(new UIElement[] { new Button(MahoMapsApp.text[137], 7, this), new Button(MahoMapsApp.text[1], 6, this) }), }); InvalidateSize(); } public void SetSelection(JSONObject obj) { for (int i = 0; i < points.size(); i++) { Geopoint p = (Geopoint) points.elementAt(i); if (p.object == obj) { SetSelection(p); return; } } } public String GetId() { return ID; } public Vector GetPoints() { return points; } public boolean OnPointTap(Geopoint p) { if (p.color == Geopoint.COLOR_RED || p.object == null) return false; SetSelection(p); return true; } public void OnButtonTap(UIElement sender, int uid) { switch (uid) { case 0: SearchScreen.ResetSearch(); Close(); break; case 1: MahoMapsApp.BringSubScreen(list); break; case 2: MahoMapsApp.BringSubScreen(new SearchResultScreen((JSONObject) selected.object, this)); break; case 3: MahoMapsApp.GetCanvas().state = MapState.FocusAt(selected); break; case 4: SearchScreen.ResetSearch(); Close(); RouteBuildOverlay.Get().SetA(selected); break; case 5: SearchScreen.ResetSearch(); Close(); RouteBuildOverlay.Get().SetB(selected); break; case 6: SetNullSelection(); break; case 7: BookmarksScreen.BeginAdd(selected, ((JSONObject) selected.object).getObject("properties").getNullableString("name")); break; } } }
3,968
Java
.java
mahomaps/mm-v1
18
4
11
2023-05-01T09:07:22Z
2024-05-05T22:00:52Z
OverlaysManager.java
/FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/overlays/OverlaysManager.java
package mahomaps.overlays; import java.util.Vector; import javax.microedition.lcdui.Graphics; import javax.microedition.lcdui.Image; import mahomaps.map.Geopoint; import mahomaps.map.MapState; import mahomaps.screens.MapCanvas; public final class OverlaysManager { public final static int OVERLAYS_SPACING = 11; private final Vector overlays = new Vector(); private final MapCanvas map; public int overlaysH; private final Image dummyBuffer = Image.createImage(1, 1); public OverlaysManager(MapCanvas map) { this.map = map; } public void DrawMap(Graphics g, MapState ms) { for (int i = 0; i < overlays.size(); i++) { Vector points = ((MapOverlay) overlays.elementAt(i)).GetPoints(); int s = points.size(); for (int j = 0; j < s; j++) { ((Geopoint) points.elementAt(j)).paint(g, ms); } } } public void Draw(Graphics g, int w, int h) { int y = h - overlaysH; int oh = 0; for (int i = 0; i < overlays.size(); i++) { MapOverlay mo = (MapOverlay) overlays.elementAt(i); try { mo.Paint(g, 5, y, w - 10, h); } catch (Exception e) { throw new RuntimeException("Failed to paint overlay #" + i + " " + e.toString()); } y += mo.H + OVERLAYS_SPACING; oh += mo.H + OVERLAYS_SPACING; } overlaysH = oh; } public boolean OnGeopointTap(int x, int y) { synchronized (overlays) { for (int i = 0; i < overlays.size(); i++) { MapOverlay mo = (MapOverlay) overlays.elementAt(i); Vector points = mo.GetPoints(); int s = points.size(); for (int j = 0; j < s; j++) { Geopoint p = (Geopoint) points.elementAt(j); if (p.isTouched(map, map.state, x, y)) { if (mo.OnPointTap(p)) { return true; } } } } } return false; } public void CloseOverlay(MapOverlay o) { CloseOverlay(o.GetId()); } public void CloseOverlay(String id) { synchronized (overlays) { for (int i = overlays.size() - 1; i >= 0; i--) { if (((MapOverlay) overlays.elementAt(i)).GetId().equals(id)) overlays.removeElementAt(i); } RecalcOverlaysHeight(); } map.requestRepaint(); } public void PushOverlay(MapOverlay o) { synchronized (overlays) { CloseOverlay(o.GetId()); o.Paint(dummyBuffer.getGraphics(), 0, 0, map.getWidth(), map.getHeight()); overlays.addElement(o); RecalcOverlaysHeight(); } } public void RecalcOverlaysHeight() { int oh = 0; for (int i = 0; i < overlays.size(); i++) { MapOverlay mo = (MapOverlay) overlays.elementAt(i); oh += mo.H + OVERLAYS_SPACING; } overlaysH = oh; } public void InvalidateOverlayHeight(MapOverlay o) { synchronized (overlays) { o.Paint(dummyBuffer.getGraphics(), 0, 0, map.getWidth(), map.getHeight()); RecalcOverlaysHeight(); } map.requestRepaint(); } public MapOverlay GetOverlay(String id) { synchronized (overlays) { for (int i = overlays.size() - 1; i >= 0; i--) { MapOverlay mo = (MapOverlay) overlays.elementAt(i); if (mo.GetId().equals(id)) return mo; } return null; } } }
3,020
Java
.java
mahomaps/mm-v1
18
4
11
2023-05-01T09:07:22Z
2024-05-05T22:00:52Z
WalkingSegment.java
/FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/route/WalkingSegment.java
package mahomaps.route; import mahomaps.MahoMapsApp; import mahomaps.map.Geopoint; public class WalkingSegment extends RouteSegment { private final String descr; private final int dist; private final Geopoint anchor; public WalkingSegment(String descr, int dist, int sv, Geopoint anchor) { super(sv); this.descr = descr; this.dist = dist; this.anchor = new Geopoint(anchor.lat, anchor.lon); this.anchor.type = Geopoint.POI_MARK; this.anchor.color = Geopoint.COLOR_BLUE; } public int GetDistance() { return dist; } public int GetIcon() { return ICON_WALK; } public String GetType() { return MahoMapsApp.text[127]; } public String GetDescription() { return descr; } public String GetAction() { return MahoMapsApp.text[147]; } public Geopoint GetAnchor() { return anchor; } }
824
Java
.java
mahomaps/mm-v1
18
4
11
2023-05-01T09:07:22Z
2024-05-05T22:00:52Z
Route.java
/FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/route/Route.java
package mahomaps.route; import cc.nnproject.json.*; import mahomaps.map.Geopoint; public class Route { public Geopoint[] points; public RouteSegment[] segments; public String time; public String distance = "Unknown"; public Route(JSONObject route) { JSONObject props = route.getObject("properties"); JSONObject meta = props.getObject("PathMetaData"); time = meta.getObject("Duration").getString("text"); JSONObject dist = meta.getNullableObject("Distance"); if (dist == null) dist = meta.getObject("WalkingDistance"); if (dist != null) distance = dist.getString("text"); points = RouteDecoder.DecodeRoutePath(props.getString("encodedCoordinates")); segments = RouteDecoder.DecodeSegments(route.getArray("features"), points); } }
763
Java
.java
mahomaps/mm-v1
18
4
11
2023-05-01T09:07:22Z
2024-05-05T22:00:52Z
UnknownSegment.java
/FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/route/UnknownSegment.java
package mahomaps.route; import mahomaps.MahoMapsApp; public final class UnknownSegment extends RouteSegment { protected UnknownSegment(int sv) { super(sv); } public int GetDistance() { return 0; } public int GetIcon() { return NO_ICON; } public String GetType() { return MahoMapsApp.text[146]; } public String GetDescription() { return MahoMapsApp.text[146]; } public String GetAction() { return MahoMapsApp.text[146]; } }
456
Java
.java
mahomaps/mm-v1
18
4
11
2023-05-01T09:07:22Z
2024-05-05T22:00:52Z
RailwaySegment.java
/FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/route/RailwaySegment.java
package mahomaps.route; import mahomaps.MahoMapsApp; import mahomaps.map.Geopoint; public class RailwaySegment extends TransportSegment { public RailwaySegment(String descr, int sv, Geopoint a) { super(descr, sv, a); } public String GetType() { return MahoMapsApp.text[139]; } public int GetIcon() { return ICON_SUBURBAN; } }
344
Java
.java
mahomaps/mm-v1
18
4
11
2023-05-01T09:07:22Z
2024-05-05T22:00:52Z
TrackerOverlayState.java
/FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/route/TrackerOverlayState.java
package mahomaps.route; public class TrackerOverlayState { public final int icon; public final float angle; public final String line1; public final String line2; public final String line3; public TrackerOverlayState(int icon, float angle, String line1, String line2, String line3) { if (line1 == null) throw new NullPointerException(); if (line2 == null) throw new NullPointerException(); if (line3 == null) throw new NullPointerException(); this.icon = icon; this.angle = angle; this.line1 = line1; this.line2 = line2; this.line3 = line3; } }
578
Java
.java
mahomaps/mm-v1
18
4
11
2023-05-01T09:07:22Z
2024-05-05T22:00:52Z
TransportSegment.java
/FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/route/TransportSegment.java
package mahomaps.route; import mahomaps.MahoMapsApp; import mahomaps.map.Geopoint; public class TransportSegment extends RouteSegment { private String descr; private final Geopoint anchor; public TransportSegment(String descr, int sv, Geopoint anchor) { super(sv); this.descr = descr; this.anchor = new Geopoint(anchor.lat, anchor.lon); this.anchor.type = Geopoint.POI_MARK; this.anchor.color = Geopoint.COLOR_BLUE; } public int GetDistance() { return 0; } public int GetIcon() { return ICON_BUS; } public String GetType() { return MahoMapsApp.text[144]; } public String GetDescription() { return descr; } public String GetAction() { return MahoMapsApp.text[145]; } public Geopoint GetAnchor() { return anchor; } }
763
Java
.java
mahomaps/mm-v1
18
4
11
2023-05-01T09:07:22Z
2024-05-05T22:00:52Z
RouteTracker.java
/FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/route/RouteTracker.java
package mahomaps.route; import java.io.IOException; import javax.microedition.lcdui.Font; import javax.microedition.lcdui.Graphics; import javax.microedition.lcdui.Image; import mahomaps.MahoMapsApp; import mahomaps.map.GeoUpdateThread; import mahomaps.map.Geopoint; import mahomaps.map.MapState; import mahomaps.overlays.MapOverlay; import mahomaps.overlays.RouteFollowOverlay; import mahomaps.screens.MapCanvas; public class RouteTracker { final Image icons; public final RouteFollowOverlay overlay; Geopoint trueGeolocation = null; GeoUpdateThread geoProvider = null; Geopoint extrapolatedGeolocation = null; private final Geopoint[] vertex; private final float[] lineLengths; private final RouteSegment[] segments; int currentSegment; int currentVertex; boolean anchorTouched; boolean trackingLost; private long lastUpdateTime = 0; private int lastUpdateNumber; // look at https://t.me/nnmidletschat/13309 for details private double lat1, lon1, lat2, lon2, lat3, lon3, timeDelta12; static final int ANCHOR_TRIGGER_DIST = 20; static final int REATTACH_DIST = 50; // drawing temps private TrackerOverlayState tos = new TrackerOverlayState(RouteSegment.NO_ICON, 0, "", "Начинаем маршрут...", ""); private MapCanvas map; public RouteTracker(Route r, RouteFollowOverlay o) throws IOException { this.overlay = o; vertex = r.points; segments = r.segments; currentSegment = -2; lineLengths = new float[vertex.length - 1]; for (int i = 0; i < lineLengths.length; i++) { lineLengths[i] = Distance(vertex[i], vertex[i + 1]); } icons = Image.createImage("/navigator50.png"); } public void SpoofGeolocation(MapCanvas m) { map = m; geoProvider = map.geo; trueGeolocation = map.geolocation; extrapolatedGeolocation = new Geopoint(trueGeolocation.lat, trueGeolocation.lon); extrapolatedGeolocation.type = Geopoint.LOCATION; extrapolatedGeolocation.color = Geopoint.COLOR_RED; map.geolocation = extrapolatedGeolocation; } // sync to avoid detaching during update public synchronized void ReleaseGeolocation() { map.geolocation = trueGeolocation; trueGeolocation = null; extrapolatedGeolocation = null; map = null; geoProvider = null; } /** * Call this every frame to make tracker work. */ public synchronized void Update() { if (map == null) { // we are detached from map return; } if (lastUpdateTime == 0) { // init lastUpdateNumber = geoProvider.updateCount; lastUpdateTime = System.currentTimeMillis(); lat1 = lat2 = lat3 = trueGeolocation.lat; lon1 = lon2 = lon3 = trueGeolocation.lon; } else { if (lastUpdateNumber != geoProvider.updateCount) ProcessGeoUpdate(); ProcessGeo(); } MapState ms = MapState.FocusAt(extrapolatedGeolocation, map.state.zoom); map.state = ms; map.line.drawFrom = currentVertex - 1; if (currentSegment == -2) { // first update currentVertex = 0; if (distTo(vertex[0]) < ANCHOR_TRIGGER_DIST) { currentSegment = 0; } else { currentSegment = -1; } } if (currentSegment == -1) { // route start is not reached ProcessRouteEntering(); } else if (currentSegment < segments.length) { // route is follown ProcessRegularSegment(); } else { // route ended tos = new TrackerOverlayState(RouteSegment.ICON_FINISH, 0, "", MahoMapsApp.text[140], ""); overlay.ShowPoint(null); } } private void ProcessGeoUpdate() { final long now = System.currentTimeMillis(); timeDelta12 = (now - lastUpdateTime) / 1000d; lat1 = lat2; lon1 = lon2; lat2 = trueGeolocation.lat; lon2 = trueGeolocation.lon; lat3 = extrapolatedGeolocation.lat; lon3 = extrapolatedGeolocation.lon; lastUpdateTime = now; lastUpdateNumber = geoProvider.updateCount; } private void ProcessGeo() { final long now = System.currentTimeMillis(); final double delta = (now - lastUpdateTime) / 1000d; double prg = (delta / timeDelta12) + 1d; if (prg > 2d) prg = 2d; double tlon = lerp(lon1, lon2, prg); double tlat = lerp(lat1, lat2, prg); if (delta < 1d) { tlon = lerp(lon3, tlon, delta); tlat = lerp(lat3, tlat, delta); } extrapolatedGeolocation.lat = tlat; extrapolatedGeolocation.lon = tlon; } private static double lerp(double a, double b, double f) { return a * (1.0 - f) + (b * f); } private void ProcessRouteEntering() { final double d = GetDistanceToSegment(vertex[0], vertex[1], extrapolatedGeolocation); final RouteSegment rs = segments[0]; tos = new TrackerOverlayState(rs.GetIcon(), getSegmentAngle(rs), MahoMapsApp.text[143], "Осталось " + ((int) d) + "м", rs.GetDescription()); overlay.ShowPoint(rs.GetAnchor()); if (TryReattach()) { // segment/vertex are set, do nothing } } private void ProcessRegularSegment() { if (trackingLost) { if (!TryReattach()) { // if could not reattach, we are off route and nothing to process return; } trackingLost = false; map.line.drawFrom = currentVertex - 1; map.line.Invalidate(); // voice returning to route // processing our segment as usual } RouteSegment s = segments[currentSegment]; RouteSegment ns; int ev; String na; if (currentSegment == segments.length - 1) { ns = null; ev = vertex.length - 1; na = MahoMapsApp.text[141]; } else { ns = segments[currentSegment + 1]; ev = ns.segmentStartVertex; na = ns.GetAction(); } float d = distTo(vertex[ev]); if (d < 200) { final String dist = "Через " + ((int) d) + "м"; final String info = ns == null ? "" : getCurrentSegmentInfo(ns); final int icon = ns == null ? RouteSegment.ICON_FINISH : ns.GetIcon(); tos = new TrackerOverlayState(icon, getSegmentAngle(ns), dist, na, info); } else { final String info = getCurrentSegmentInfo(s); final String dist = "Осталось " + ((int) d) + "м"; tos = new TrackerOverlayState(s.GetIcon(), 0f, info, dist, na); } { double distToThis = GetDistanceToSegment(vertex[currentVertex], vertex[currentVertex + 1], extrapolatedGeolocation); double distToNext = GetDistanceToSegment(vertex[currentVertex + 1], vertex[currentVertex + 2], extrapolatedGeolocation); if (distToNext < ANCHOR_TRIGGER_DIST) { // we are close enough to next line currentVertex++; map.line.drawFrom = currentVertex - 1; map.line.Invalidate(); } else if (distToThis < REATTACH_DIST) { // everything is okay, we are moving along the line // do nothing } else { // tracking is lost! Reattaching. if (TryReattach()) { map.line.drawFrom = currentVertex - 1; map.line.Invalidate(); // sucseed. } else { trackingLost = true; tos = new TrackerOverlayState(RouteSegment.ICON_WALK, 0, "", MahoMapsApp.text[142], ""); overlay.ShowPoint(null); } } } if (anchorTouched) { if (GetDistanceToSegment(vertex[ev - 1], vertex[ev], extrapolatedGeolocation) > ANCHOR_TRIGGER_DIST) { currentSegment++; anchorTouched = false; } } else if (d < ANCHOR_TRIGGER_DIST) { anchorTouched = true; // voice the action } overlay.ShowPoint(ns == null ? null : ns.GetAnchor()); } /** * Пытается присоединиться к сегменту линии маршрута. Текущий сегмент/вершина в * случае успеха будут изменены на подходящие. * * @return True, если удалось. */ private boolean TryReattach() { int found = -1; for (int i = Math.max(currentVertex - 5, 0); i < vertex.length - 1; i++) { double dist = GetDistanceToSegment(vertex[i], vertex[i + 1], extrapolatedGeolocation); if (dist < REATTACH_DIST) { found = i; break; } } if (found == -1) return false; currentVertex = found; for (int i = segments.length - 1; i >= 0; i--) { int sv = segments[i].segmentStartVertex; if (currentVertex >= sv) { currentSegment = i; break; } } return true; } /** * Call this every frame after {@link #Update()} to draw tracker. May fail due * to corrupted state object. */ public void Draw(Graphics g, int w) { try { drawInternal(g, w); } catch (RuntimeException e) { e.printStackTrace(); throw new RuntimeException("Failed to redraw route tracker: " + e.toString()); } } private final void drawInternal(Graphics g, int w) { Font f = Font.getFont(0, 0, 8); int fh = f.getHeight(); g.setFont(f); // bg g.setColor(MapOverlay.OVERLAY_BG); g.fillRoundRect(5, 5, w - 10, fh * 3 + 10, 10, 10); // text int x = tos.icon == RouteSegment.NO_ICON ? 10 : (10 + 5 + 50); g.setColor(-1); g.drawString(tos.line1, x, 10, 0); g.drawString(tos.line2, x, 10 + fh, 0); g.drawString(tos.line3, x, 10 + fh + fh, 0); // icons int cx = 10 + 25; int cy = 10 + fh + fh / 2; if (tos.icon == RouteSegment.MANEUVER_ANGLE) { g.setColor(-1); final int THICK = 6; final int ARROW = 9; g.fillRoundRect(cx - THICK / 2, cy - THICK / 2, THICK, 25 + THICK / 2, THICK, THICK); float sin = (float) Math.sin(Math.toRadians(tos.angle)); float cos = (float) Math.cos(Math.toRadians(tos.angle)); { // якоря int x25 = (int) (sin * 25); int y25 = (int) (cos * 25); final float x25t = (sin * (25 - ARROW)); final float y25t = (cos * (25 - ARROW)); // оффсеты для линии float ldx = (cos * (THICK / 2)); float ldy = (-sin * (THICK / 2)); float adx = (cos * ARROW); float ady = (-sin * ARROW); // стрелка int xAl = (int) (cx - x25t - adx); int yAl = (int) (cy - y25t - ady); int xAr = (int) (cx - x25t + adx); int yAr = (int) (cy - y25t + ady); // углы линии int lfblx = (int) (cx - ldx); int lfbly = (int) (cy - ldy); int lfbrx = (int) (cx + ldx); int lfbry = (int) (cy + ldy); int lftlx = (int) (cx - x25t - ldx); int lftly = (int) (cy - y25t - ldy); int lftrx = (int) (cx - x25t + ldx); int lftry = (int) (cy - y25t + ldy); g.fillTriangle(lfblx, lfbly, lfbrx, lfbry, lftlx, lftly); g.fillTriangle(lftrx, lftry, lfbrx, lfbry, lftlx, lftly); g.fillTriangle(cx - x25, cy - y25, xAl, yAl, xAr, yAr); } } else if (tos.icon != RouteSegment.NO_ICON) { g.drawRegion(icons, (tos.icon - 1) * 50, 0, 50, 50, 0, cx, cy, Graphics.VCENTER | Graphics.HCENTER); } } private static String getCurrentSegmentInfo(RouteSegment rs) { if (rs instanceof AutoSegment) { AutoSegment as = (AutoSegment) rs; if (as.street.length() > 0) { return as.street + "; " + as.dist + "м"; } return "Дорога " + as.dist + "м"; } return rs.GetDescription(); } /** * @return Null if rs was null, segment action angle if it's auto, 0 if not. */ private static float getSegmentAngle(RouteSegment rs) { if (rs == null) return 0f; if (rs instanceof AutoSegment) { AutoSegment as = (AutoSegment) rs; return (float) as.angle; } return 0f; } private float distTo(Geopoint p) { return Distance(extrapolatedGeolocation, p); } public static float Distance(Geopoint a, Geopoint b) { double alat = Math.toRadians(a.lat); double alon = Math.toRadians(a.lon); double blat = Math.toRadians(b.lat); double blon = Math.toRadians(b.lon); double cosd = Math.sin(alat) * Math.sin(blat) + Math.cos(alat) * Math.cos(blat) * Math.cos(alon - blon); double d = MahoMapsApp.acos(cosd); // return d; return (float) (d * 6371000D); } public static double GetDistanceToSegment(Geopoint a, Geopoint b, Geopoint point) { double degDist = GetDistanceToSegment(a.lon, a.lat, b.lon, b.lat, point.lon, point.lat); Geopoint p = new Geopoint(point.lat + degDist, point.lon); return Distance(point, p); } public static double GetDistanceToSegment(double ax, double ay, double bx, double by, double x, double y) { double ak = Math.sqrt((x - ax) * (x - ax) + (y - ay) * (y - ay)); double kb = Math.sqrt((x - bx) * (x - bx) + (y - by) * (y - by)); double ab = Math.sqrt((ax - bx) * (ax - bx) + (ay - by) * (ay - by)); // скалярное произведение векторов double mulScalarAKAB = (x - ax) * (bx - ax) + (y - ay) * (by - ay); double mulScalarBKAB = (x - bx) * (-bx + ax) + (y - by) * (-by + ay); if (ab == 0) return ak; else if (mulScalarAKAB >= 0 && mulScalarBKAB >= 0) { double p = (ak + kb + ab) / 2.0; double s = Math.sqrt(Math.abs((p * (p - ak) * (p - kb) * (p - ab)))); return (2.0 * s) / ab; } else if (mulScalarAKAB < 0 || mulScalarBKAB < 0) { return Math.min(ak, kb); } else return 0; } }
12,594
Java
.java
mahomaps/mm-v1
18
4
11
2023-05-01T09:07:22Z
2024-05-05T22:00:52Z
RouteSegment.java
/FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/route/RouteSegment.java
package mahomaps.route; import javax.microedition.lcdui.Item; import javax.microedition.lcdui.StringItem; import mahomaps.map.Geopoint; public abstract class RouteSegment { protected RouteSegment(int sv) { segmentStartVertex = sv; } /** * Index of line's vertex, where this segment starts. */ public final int segmentStartVertex; /** * @return May return a geopoint to show it as maneuver on map. */ public Geopoint GetAnchor() { return null; } /** * @return Дистанция сегмента в метрах. */ public abstract int GetDistance(); public abstract int GetIcon(); public abstract String GetType(); /** * Описание сегмента. Может быть null. * * @return Описание сегмента. */ public abstract String GetDescription(); public abstract String GetAction(); /** * Получает один элемент LCDUI, которым можно отобразить сегмент. Этот метод не * вызывается напрямую, его использует {@link #ToLcdui()}, не переопределяйте * его. * * @return Элемент, представляющий сегмент. */ public Item ToLcduiSingle() { return new StringItem(GetType(), GetDescription()); } /** * Возвращает элементы, отображающие сегмент. Если не переопределён, возвращает * 1 элемент возвращённый методом {@link #ToLcduiSingle()}. * * @return Элементы, представляющий сегмент. */ public Item[] ToLcdui() { return new Item[] { ToLcduiSingle() }; } public static final int MANEUVER_ANGLE = -1; public static final int NO_ICON = 0; public static final int ICON_WALK = 1; public static final int ICON_BUS = 2; public static final int ICON_METRO = 3; public static final int ICON_SUBURBAN = 4; public static final int ICON_FINISH = 5; }
2,002
Java
.java
mahomaps/mm-v1
18
4
11
2023-05-01T09:07:22Z
2024-05-05T22:00:52Z
RouteDecoder.java
/FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/route/RouteDecoder.java
package mahomaps.route; import java.util.Stack; import cc.nnproject.json.*; import mahomaps.map.Geopoint; public class RouteDecoder { private static final byte[] DECODE_ALPHABET = { -9, -9, -9, -9, -9, -9, -9, -9, -9, -5, -5, -9, -9, -5, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -5, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, 62, -9, -9, -9, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -9, -9, -9, -1, -9, -9, -9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -9, -9, -9, -9, -9, -9, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -9, -9, -9, -9 }; public static byte[] Base64ToBlob(String s) { if (s == null) { return null; } byte[] source = s.getBytes(); int len34 = source.length * 3 / 4; byte[] outBuff = new byte[len34]; int outBuffPosn = 0; byte[] b4 = new byte[4]; int b4Posn = 0; int i = 0; byte sbiCrop = 0; byte sbiDecode = 0; for (i = 0; i < source.length; i++) { sbiCrop = (byte) (source[i] & 0x7F); sbiDecode = DECODE_ALPHABET[sbiCrop]; if (sbiDecode >= -5) { if (sbiDecode >= -1) { b4[(b4Posn++)] = sbiCrop; if (b4Posn > 3) { outBuffPosn += decode4to3(b4, 0, outBuff, outBuffPosn); b4Posn = 0; if (sbiCrop == 61) { break; } } } } else { return null; } } if (outBuffPosn == 0) { return null; } byte[] out = new byte[outBuffPosn]; System.arraycopy(outBuff, 0, out, 0, outBuffPosn); return out; } private static int decode4to3(byte[] source, int srcOffset, byte[] destination, int destOffset) { if (source[(srcOffset + 2)] == 61) { int outBuff = (DECODE_ALPHABET[source[srcOffset]] & 0xFF) << 18 | (DECODE_ALPHABET[source[(srcOffset + 1)]] & 0xFF) << 12; destination[destOffset] = ((byte) (outBuff >>> 16)); return 1; } if (source[(srcOffset + 3)] == 61) { int outBuff = (DECODE_ALPHABET[source[srcOffset]] & 0xFF) << 18 | (DECODE_ALPHABET[source[(srcOffset + 1)]] & 0xFF) << 12 | (DECODE_ALPHABET[source[(srcOffset + 2)]] & 0xFF) << 6; destination[destOffset] = ((byte) (outBuff >>> 16)); destination[(destOffset + 1)] = ((byte) (outBuff >>> 8)); return 2; } try { int outBuff = (DECODE_ALPHABET[source[srcOffset]] & 0xFF) << 18 | (DECODE_ALPHABET[source[(srcOffset + 1)]] & 0xFF) << 12 | (DECODE_ALPHABET[source[(srcOffset + 2)]] & 0xFF) << 6 | DECODE_ALPHABET[source[(srcOffset + 3)]] & 0xFF; destination[destOffset] = ((byte) (outBuff >> 16)); destination[(destOffset + 1)] = ((byte) (outBuff >> 8)); destination[(destOffset + 2)] = ((byte) outBuff); return 3; } catch (Exception e) { } return -1; } public static Geopoint[] DecodeRoutePath(final String data) { double o = 1000000d; byte[] t = Base64ToBlob(data.replace('-', '+').replace('_', '/')); Stack stack = new Stack(); double[] n = new double[2]; for (int i = 0; i < t.length; i += 8) { int c1 = 0; int c2 = 0; for (int j = 0; j < 4; j++) { if (i + j < t.length) c1 |= (t[i + j] & 0xFF) << (8 * j); else c1 |= 255 << (8 * j); if (i + j + 4 < t.length) c2 |= (t[i + j + 4] & 0xFF) << (8 * j); else c2 |= 255 << (8 * j); } double d1 = c1 / o; double d2 = c2 / o; double[] l = new double[] { d1 + n[0], d2 + n[1] }; n = l; Geopoint g = new Geopoint(l[1], l[0]); g.type = Geopoint.ROUTE_VERTEX; stack.push(g); } Geopoint[] arr = new Geopoint[stack.size()]; stack.copyInto(arr); System.out.println("Route points count: " + arr.length); return arr; } public static RouteSegment[] DecodeSegments(JSONArray j, Geopoint[] line) { RouteSegment[] arr = new RouteSegment[j.size()]; for (int i = 0; i < arr.length; i++) { final JSONObject js = j.getObject(i); final JSONObject props = js.getObject("properties"); int sv = -1; { JSONObject gm = js.getNullableObject("geometry"); if (gm != null) { JSONArray gms = gm.getNullableArray("geometries"); if (gms != null) { sv = gms.getObject(0).getInt("lodIndex", -1); } } if (sv == -1) { JSONArray ftrs = js.getNullableArray("features"); if (ftrs != null) { gm = ftrs.getObject(0).getNullableObject("geometry"); if (gm != null) { sv = gm.getInt("lodIndex", -1); } } } if (sv == -1) throw new IllegalArgumentException(); } final JSONObject segmd = props.getObject("SegmentMetaData"); final String descr = segmd.getString("text"); int dist = 0; { JSONObject dj = segmd.getNullableObject("Distance"); String v = null; if (dj != null) v = dj.getNullableString("value"); if (v != null) dist = (int) Double.parseDouble(v); } if (segmd.getBoolean("Walk", false)) { arr[i] = new WalkingSegment(descr, dist, sv, line[sv]); continue; } JSONArray tr = segmd.getNullableArray("Transports"); if (tr != null && tr.size() > 0) { String trt = tr.getObject(0).getString("type"); if (trt.equals("suburban")) { arr[i] = new RailwaySegment(descr, sv, line[sv]); } else if (trt.equals("underground")) { arr[i] = new MetroSegment(descr, sv, line[sv]); } else { arr[i] = new TransportSegment(descr, sv, line[sv]); } continue; } JSONObject action = segmd.getNullableObject("Action"); if (action != null) { String actionKey = action.getString("value"); String actionText = action.getString("text"); String street = segmd.getString("street", ""); int angle = (int) segmd.getDouble("angle", 0); JSONObject durObj = segmd.getNullableObject("Duration"); int dur = durObj == null ? 0 : (int) durObj.getDouble("value", 0); arr[i] = new AutoSegment(descr, street, dist, angle, dur, actionKey, actionText, sv, line[sv]); continue; } arr[i] = new UnknownSegment(sv); } return arr; } }
5,974
Java
.java
mahomaps/mm-v1
18
4
11
2023-05-01T09:07:22Z
2024-05-05T22:00:52Z
AutoSegment.java
/FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/route/AutoSegment.java
package mahomaps.route; import mahomaps.MahoMapsApp; import mahomaps.map.Geopoint; public class AutoSegment extends RouteSegment { public final String descr; public final int dist; public final double angle; public final int duration; public final String actionKey; public final Geopoint actionPoint; public final String street; public final String actionText; public AutoSegment(String descr, String street, int dist, double angle, int duration, String actionKey, String actionText, int actionVertex, Geopoint actionPoint) { super(actionVertex); this.descr = descr; this.street = street; this.dist = dist; this.angle = angle; this.duration = duration; this.actionKey = actionKey; if (actionText == null || actionText.length() == 0) { this.actionText = ""; } else { this.actionText = Character.toUpperCase(actionText.charAt(0)) + actionText.substring(1); } this.actionPoint = new Geopoint(actionPoint.lat, actionPoint.lon); this.actionPoint.type = Geopoint.POI_MARK; this.actionPoint.color = Geopoint.COLOR_BLUE; } public Geopoint GetAnchor() { return actionPoint; } public int GetDistance() { return dist; } public int GetIcon() { return MANEUVER_ANGLE; } public String GetType() { return MahoMapsApp.text[126]; } public String GetDescription() { return descr + ", " + dist + "m"; } public String GetAction() { return actionText; } }
1,415
Java
.java
mahomaps/mm-v1
18
4
11
2023-05-01T09:07:22Z
2024-05-05T22:00:52Z
MetroSegment.java
/FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/route/MetroSegment.java
package mahomaps.route; import mahomaps.MahoMapsApp; import mahomaps.map.Geopoint; public class MetroSegment extends TransportSegment { public MetroSegment(String descr, int sv, Geopoint a) { super(descr, sv, a); } public String GetType() { return MahoMapsApp.text[138]; } public int GetIcon() { return ICON_METRO; } }
336
Java
.java
mahomaps/mm-v1
18
4
11
2023-05-01T09:07:22Z
2024-05-05T22:00:52Z
GeoUpdateThread.java
/FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/map/GeoUpdateThread.java
package mahomaps.map; import java.util.Vector; import javax.microedition.location.Coordinates; import javax.microedition.location.Location; import javax.microedition.location.LocationListener; import javax.microedition.location.LocationProvider; import mahomaps.MahoMapsApp; import mahomaps.screens.MapCanvas; public class GeoUpdateThread extends Thread { /** * Точка геопозиции. */ final Geopoint positionPoint; /** * Состояние получения геопозиции. Одно из state-значений. */ public int state; private LocationAPI locationAPI; public boolean loop = true; public long lastUpdateTime = System.currentTimeMillis(); public String method = null; public int sattelites = -1; public int totalSattelitesInView = -1; public int updateCount; private Object lock = new Object(); public boolean vibrated; public GeoUpdateThread(Geopoint positionPoint, MapCanvas map) { super("Geo update"); this.positionPoint = positionPoint; } public void run() { try { Class.forName("javax.microedition.location.LocationProvider"); try { locationAPI = new LocationAPI(); } catch (Exception e) { state = e.toString().indexOf("LocationException") != -1 ? STATE_UNAVAILABLE : STATE_UNSUPPORTED; e.printStackTrace(); } } catch (Throwable e) { state = STATE_UNSUPPORTED; System.out.println("Location api is not supported"); e.printStackTrace(); return; } if (locationAPI == null) { try { while (true) { synchronized (lock) { lock.wait(); } run(); } } catch (Exception e) { } return; } positionPoint.lat = 0; positionPoint.lon = 0; state = STATE_PENDING; double[] coordinates = locationAPI.getLastKnownCoordinates(); if (coordinates != null && coordinates[0] != 0 && coordinates[1] != 0) { positionPoint.lat = coordinates[0]; positionPoint.lon = coordinates[1]; positionPoint.color = Geopoint.COLOR_GRAY; state = STATE_OK_PENDING; lastUpdateTime = System.currentTimeMillis(); } locationAPI.setupListener(); try { while (true) { synchronized (lock) { lock.wait(); } locationAPI.resetProvider(); } } catch (Exception e) { } } public void restart() { synchronized (lock) { lock.notify(); } } static String[] split(String str, char d) { int i = str.indexOf(d); if (i == -1) return new String[] { str }; Vector v = new Vector(); v.addElement(str.substring(0, i)); while (i != -1) { str = str.substring(i + 1); if ((i = str.indexOf(d)) != -1) v.addElement(str.substring(0, i)); i = str.indexOf(d); } v.addElement(str); String[] r = new String[v.size()]; v.copyInto(r); return r; } public void Dispose() { loop = false; interrupt(); } /** * Рисовать точку? */ public boolean DrawPoint() { if (positionPoint.lat == 0 && positionPoint.lon == 0) return false; if (state == STATE_OK_PENDING || state == STATE_OK || state == STATE_ERROR) return true; return false; } /** * Гео не поддерживается устройством. */ public final static int STATE_UNSUPPORTED = 5; /** * К гео запрещён доступ, либо оно отключено. */ public final static int STATE_UNAVAILABLE = 4; /** * Геопозиция доступна, однако получить её не удалось. */ public final static int STATE_ERROR = 3; /** * Геопозиция определяется, но ещё не известна. */ public final static int STATE_PENDING = 0; /** * Геопозиция уже примерно известна, но ещё определяется. */ public final static int STATE_OK_PENDING = 1; /** * Геопозиция известна. */ public final static int STATE_OK = 2; public final static int[] states = new int[] { 93, 93, 94, 88, 95, 96 }; // для безопасных вызовов class LocationAPI { public LocationProvider locationProvider; public LocationAPI() throws Exception { locationProvider = LocationProvider.getInstance(null); } public double[] getLastKnownCoordinates() { Location location = LocationProvider.getLastKnownLocation(); if (location == null || !location.isValid()) return null; Coordinates coordinates = location.getQualifiedCoordinates(); if (coordinates == null) return null; return new double[] { coordinates.getLatitude(), coordinates.getLongitude() }; } public void setupListener() { locationProvider.setLocationListener(new LocationAPIListener(), 5, 5, 5); } public void resetProvider() throws Exception { System.out.println("resetProvider"); Thread.sleep(5000); LocationProvider old = locationProvider; try { locationProvider = LocationProvider.getInstance(null); old.setLocationListener(null, 0, 0, 0); setupListener(); } catch (Exception e) { e.printStackTrace(); } } class LocationAPIListener implements LocationListener { public void locationUpdated(LocationProvider provider, Location location) { // определение кол-ва спутников satellites: { // парамы из патча для symbian^3 https://github.com/shinovon/Symbian3JSR179Mod try { String s1 = location.getExtraInfo("satelliteNumInView"); String s2 = location.getExtraInfo("satelliteNumUsed"); if (s1 != null && s2 != null) { totalSattelitesInView = Integer.parseInt(s1); sattelites = Integer.parseInt(s2); break satellites; } } catch (Exception e) {} // парс сырых nmea данных String nmea = location.getExtraInfo("application/X-jsr179-location-nmea"); if (nmea != null) { String[] sequence = split(nmea, '$'); int s1 = -1; int s2 = -1; for (int i = sequence.length - 1; i >= 0; i--) { String s = sequence[i]; if (s.indexOf('*') != -1) s = s.substring(0, s.lastIndexOf('*')); String[] sentence = split(s, ','); if (sentence[0].endsWith("GGA")) { try { s1 = Integer.parseInt(sentence[7]); } catch (Exception e) { s1 = -1; } s2 = Math.max(s2, s1); } else if (sentence[0].endsWith("GSV")) { try { s2 = Math.max(s2, Integer.parseInt(sentence[3])); } catch (Exception e) { } } } sattelites = s1; totalSattelitesInView = s2; } else { totalSattelitesInView = sattelites = -1; } } String s = ""; int t = location.getLocationMethod(); if ((t & Location.MTE_SATELLITE) == Location.MTE_SATELLITE) { s = "GPS"; } if ((t & Location.MTE_TIMEDIFFERENCE) == Location.MTE_TIMEDIFFERENCE) { s += "TD"; } if ((t & Location.MTE_TIMEOFARRIVAL) == Location.MTE_TIMEOFARRIVAL) { s += "TOA"; } if ((t & Location.MTE_CELLID) == Location.MTE_CELLID) { s += "CID"; } if ((t & Location.MTE_SHORTRANGE) == Location.MTE_SHORTRANGE) { s += "SR"; } if ((t & Location.MTE_ANGLEOFARRIVAL) == Location.MTE_ANGLEOFARRIVAL) { s += "AOA"; } if ((t & Location.MTA_ASSISTED) == Location.MTA_ASSISTED) { s = "A" + s; } else if ((t & Location.MTA_UNASSISTED) == Location.MTA_UNASSISTED) { s = "U" + s; } if ((t & Location.MTY_TERMINALBASED) == Location.MTY_TERMINALBASED) { s = "TB " + s; } if ((t & Location.MTY_NETWORKBASED) == Location.MTY_NETWORKBASED) { s = "NB " + s; } method = s.length() == 0 ? null : s; if (location.isValid()) { Coordinates coordinates = location.getQualifiedCoordinates(); if (coordinates.getLatitude() != 0 && coordinates.getLongitude() != 0) { if (!vibrated) { try { MahoMapsApp.display.vibrate(100); } catch (Exception e) { } vibrated = true; } positionPoint.lat = coordinates.getLatitude(); positionPoint.lon = coordinates.getLongitude(); positionPoint.color = Geopoint.COLOR_RED; state = STATE_OK; lastUpdateTime = location.getTimestamp(); MahoMapsApp.GetCanvas().requestRepaint(); } else { state = STATE_UNAVAILABLE; } } updateCount++; } public void providerStateChanged(LocationProvider provider, int newState) { if (newState != LocationProvider.AVAILABLE) { state = STATE_OK_PENDING; } // на случай если изменился провайдер if (newState == LocationProvider.OUT_OF_SERVICE) { restart(); } } } } }
8,630
Java
.java
mahomaps/mm-v1
18
4
11
2023-05-01T09:07:22Z
2024-05-05T22:00:52Z
Geopoint.java
/FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/map/Geopoint.java
package mahomaps.map; import java.io.IOException; import javax.microedition.lcdui.Graphics; import javax.microedition.lcdui.Image; import mahomaps.MahoMapsApp; import mahomaps.Settings; import mahomaps.screens.MapCanvas; public class Geopoint { /** * Градусы от экватора на север (вертикаль) */ public double lat; /** * Градусы по экватору (горизонталь) */ public double lon; public int type; public int color; public Object object; public static Image locationIcons; public static Image commonPs; public static Image route; static { try { locationIcons = Image.createImage("/geo40.png"); commonPs = Image.createImage("/points40.png"); route = Image.createImage("/route40.png"); } catch (IOException e) { e.printStackTrace(); } } public Geopoint(double lat, double lon) { this.lat = lat; this.lon = lon; } public int GetScreenX(MapState ms) { int tilesCount = 1 << ms.zoom; double tile = (tilesCount * (lon + 180d)) / 360d; tile -= ms.tileX; tile *= 256; tile += ms.xOffset; return (int) tile; } public int GetScreenY(MapState ms) { return GetY(ms.zoom, ms.tileY, ms.yOffset); } public int GetY(int zoom, int tileY, int yOffset) { double latR = lat * Math.PI / 180d; double tg = Math.tan(latR / 2 + Math.PI / 4); double linear = MahoMapsApp.ln(tg * CalcLatCorr(latR)); double linearLocal = linear * LAT_COEF; // [-128; 128] double linearAbs = 128 - linearLocal; // [0; 256] int tilesCount = 1 << zoom; double py = (tilesCount * linearAbs) - (tileY * 256) + yOffset; return (int) py; } private static double CalcLatCorr(double latR) { double base = (1 - EL_CORR * Math.sin(latR)) / (1 + EL_CORR * Math.sin(latR)); return MahoMapsApp.pow(base, (EL_CORR / 2)); } public boolean IsValid() { return Math.abs(lat) <= 85 && Math.abs(lon) < 180; } public void paint(Graphics g, MapState ms) { int px = GetScreenX(ms); int py = GetScreenY(ms); int s; switch (type) { case POI_SELECT: s = commonPs.getWidth() / 4; g.drawRegion(commonPs, s * color, 80, s, 40, 0, px, py, Graphics.BOTTOM | Graphics.HCENTER); break; case POI_MARK: s = commonPs.getWidth() / 4; g.drawRegion(commonPs, s * color, 40, s, 40, 0, px, py, Graphics.BOTTOM | Graphics.HCENTER); break; case POI_SEARCH: s = commonPs.getWidth() / 4; g.drawRegion(commonPs, s * color, 0, s, 40, 0, px, py, Graphics.BOTTOM | Graphics.HCENTER); break; case LOCATION: s = locationIcons.getWidth() / 2; g.drawRegion(locationIcons, color == 0 ? 0 : s, s * Settings.geoLook, s, s, 0, px, py, Graphics.VCENTER | Graphics.HCENTER); break; case ROUTE_A: g.drawRegion(route, 0, 0, route.getWidth() / 3, route.getHeight(), 0, px, py, Graphics.BOTTOM | Graphics.HCENTER); break; case ROUTE_B: s = route.getWidth() / 3; g.drawRegion(route, s, 0, s, route.getHeight(), 0, px, py, Graphics.BOTTOM | Graphics.HCENTER); break; case ROUTE_C: s = route.getWidth() / 3; g.drawRegion(route, s * 2, 0, s, route.getHeight(), 0, px, py, Graphics.BOTTOM | Graphics.HCENTER); break; case ROUTE_VERTEX: g.setColor(0xff0000); g.fillRect(px - 2, py - 2, 4, 4); } } public boolean isTouched(MapCanvas map, MapState ms, int x, int y) { x -= map.getWidth() / 2; y -= map.getHeight() / 2; if (Math.abs(GetScreenX(ms) - x) < 14) { int py = GetScreenY(ms); if (y > py) return false; if (y > py - 40) return true; } return false; } public String[] GetRounded() { boolean latS = lat >= 0; double latF = Math.abs(lat) % 1; int latD = (int) (Math.abs(lat) - latF); String latFS = String.valueOf(latF).substring(1); if (latFS.length() > 7) latFS = latFS.substring(0, 7); boolean lonS = lon >= 0; double lonF = Math.abs(lon) % 1; int lonD = (int) (Math.abs(lon) - lonF); String lonFS = String.valueOf(lonF).substring(1); if (lonFS.length() > 7) lonFS = lonFS.substring(0, 7); StringBuffer sb = new StringBuffer(); String[] r = new String[2]; if (!latS) sb.append('-'); sb.append(latD); sb.append(latFS); r[0] = sb.toString(); sb.setLength(0); if (!lonS) sb.append('-'); sb.append(lonD); sb.append(lonFS); r[1] = sb.toString(); return r; } public String toString() { String[] r = GetRounded(); return r[0] + " " + r[1]; } /** * Получает точку на экране по координатам экрана. * * @param ms Состояние карты. * @param x X относительно центра (центр = 0) * @param y Y относительно центра (центр = 0) * @return Точка. */ public static Geopoint GetAtCoords(MapState ms, int x, int y) { ms = ms.Clone(); int tilesCount = 1 << ms.zoom; double dx = x; dx -= ms.xOffset; dx /= 256; dx += ms.tileX; dx *= 360d; dx /= tilesCount; double lon = dx - 180d; Geopoint g = new Geopoint(0, lon); double step = 60d; while (true) { double or = g.lat; if (Math.abs(or) > 91d) { g.lat = or > 0 ? 90 : -90; return g; } int zero = Math.abs(g.GetScreenY(ms) - y); if (zero <= 2) break; g.lat = or + step; int plus = Math.abs(g.GetScreenY(ms) - y); g.lat = or - step; int minus = Math.abs(g.GetScreenY(ms) - y); if (zero < Math.min(minus, plus)) { g.lat = or; } else if (minus < plus) { g.lat = or - step; } else { g.lat = or + step; } step /= 2d; if (step < 0.000001d) { System.out.println("Step too small, bumping"); step = 0.05d; } } return g; } public static final int COLOR_RED = 0; public static final int COLOR_GREEN = 1; public static final int COLOR_GRAY = 2; public static final int COLOR_BLUE = 3; /** * Shevron mark. Usually means manually selected objects. */ public static final int POI_SELECT = 0; /** * Exclamation mark. Usually means additional POIs around object. */ public static final int POI_MARK = 1; /** * Search mark. Search results. */ public static final int POI_SEARCH = 2; public static final int LOCATION = 3; public static final int ROUTE_A = 4; public static final int ROUTE_B = 5; public static final int ROUTE_C = 6; public static final int ROUTE_VERTEX = 7; public static final double PI = 3.14159265358979323846; public static final double LAT_COEF = 40.74366567247929d; public static final double EL_CORR = 0.0818191909289069d; }
6,485
Java
.java
mahomaps/mm-v1
18
4
11
2023-05-01T09:07:22Z
2024-05-05T22:00:52Z
TileCache.java
/FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/map/TileCache.java
package mahomaps.map; import javax.microedition.lcdui.Font; import javax.microedition.lcdui.Graphics; import javax.microedition.lcdui.Image; import mahomaps.MahoMapsApp; import mahomaps.Settings; public class TileCache extends TileId { public Image img; public volatile int state = 0; public volatile int unuseCount; public TileCache(int x, int y, int zoom, int map) { super(x, y, zoom, map); } public TileCache(TileId id) { super(id.x, id.y, id.zoom, id.map); } public boolean is(TileId id) { return id.x == x && id.y == y && id.zoom == zoom && id.map == map; } public void paint(Graphics g, int tx, int ty) { Font f = Font.getFont(0, 0, 8); int vo = f.getHeight(); g.setFont(f); Image i = img; if (i != null) { g.drawImage(i, tx, ty, 0); } if (state == STATE_READY) { if (i == null) // wtf!? throw new NullPointerException("Corrupted tile state!"); g.setColor(0, 0, 255); } else { int ax = tx + 128; int ay = ty + 128 - (vo / 2); g.setGrayScale(255); g.drawString(GetState(), ax + 1, ay + 1, Graphics.TOP | Graphics.HCENTER); g.drawString(GetState(), ax - 1, ay + 1, Graphics.TOP | Graphics.HCENTER); g.drawString(GetState(), ax + 1, ay - 1, Graphics.TOP | Graphics.HCENTER); g.drawString(GetState(), ax - 1, ay - 1, Graphics.TOP | Graphics.HCENTER); g.setGrayScale(0); g.drawString(GetState(), ax, ay, Graphics.TOP | Graphics.HCENTER); } if (Settings.drawDebugInfo) { g.drawRect(tx, ty, 255, 255); g.fillRect(tx + 125, ty + 63, 6, 2); g.fillRect(tx + 127, ty + 61, 2, 6); g.fillRect(tx + 125, ty + 127, 6, 2); g.fillRect(tx + 127, ty + 125, 2, 6); g.fillRect(tx + 125, ty + 191, 6, 2); g.fillRect(tx + 127, ty + 189, 2, 6); g.drawString("x=" + this.x + " y=" + this.y, tx + 1, ty + 1, 0); } } public String GetState() { if (state < 0) return ""; if (state > STATE_MISSING) return ""; return MahoMapsApp.text[STATE_DESCRIPTION[state]]; } public static final int[] STATE_DESCRIPTION = new int[] { 97, 98, 99, 100, 94, 88, 101, 102 }; public static final int STATE_CACHE_PENDING = 0; public static final int STATE_CACHE_LOADING = 1; public static final int STATE_SERVER_PENDING = 2; public static final int STATE_SERVER_LOADING = 3; public static final int STATE_READY = 4; public static final int STATE_ERROR = 5; public static final int STATE_UNLOADED = 6; public static final int STATE_MISSING = 7; }
2,443
Java
.java
mahomaps/mm-v1
18
4
11
2023-05-01T09:07:22Z
2024-05-05T22:00:52Z
Rect.java
/FileExtraction/Java_unseen/mahomaps_mm-v1/src/mahomaps/map/Rect.java
package mahomaps.map; public class Rect { public int x, y, w, h; public Rect(int x, int y, int w, int h) { this.x = x; this.y = y; this.w = w; this.h = h; } public boolean contains(int px, int py) { return px > x && px < x + w && py > y && py < y + h; } public boolean containsBoth(int px1, int py1, int px2, int py2) { return contains(px1, py1) && contains(px2, py2); } }
396
Java
.java
mahomaps/mm-v1
18
4
11
2023-05-01T09:07:22Z
2024-05-05T22:00:52Z