repo_name
stringlengths 7
104
| file_path
stringlengths 13
198
| context
stringlengths 67
7.15k
| import_statement
stringlengths 16
4.43k
| code
stringlengths 40
6.98k
| prompt
stringlengths 227
8.27k
| next_line
stringlengths 8
795
|
---|---|---|---|---|---|---|
Audiveris/omr-dataset-tools | src/main/java/org/audiveris/omrdataset/train/AppPaths.java | // Path: src/main/java/org/audiveris/omrdataset/Main.java
// public class Main
// {
// //~ Static fields/initializers -----------------------------------------------------------------
//
// private static final Logger logger = LoggerFactory.getLogger(Main.class);
//
// /** CLI Parameters. */
// public static CLI cli;
//
// //~ Methods ------------------------------------------------------------------------------------
// public static void main (String[] args)
// throws Exception
// {
// cli = CLI.create(args);
//
// if (cli.help) {
// return; // Help has been printed by CLI itself
// }
//
// if (cli.outputFolder == null) {
// logger.warn("Output location not specified, please use -output option");
//
// return;
// }
//
// if (cli.names) {
// OmrShapes.printOmrShapes();
// }
//
// if (cli.clean) {
// new Clean().process();
// }
//
// if (cli.features) {
// // Extract features
// new Features().process();
// }
//
// if (cli.subimages) {
// // Extract subimages for visual check (not mandatory)
// new SubImages().process();
// }
//
// if (cli.training) {
// // Train the classifier
// new Training().process();
// }
// }
// }
//
// Path: src/main/java/org/audiveris/omrdataset/classifier/Context.java
// public static final String DIMS_NAME = "dims.dat";
//
// Path: src/main/java/org/audiveris/omrdataset/classifier/Context.java
// public static final String MODEL_NAME = "patch-classifier.zip";
//
// Path: src/main/java/org/audiveris/omrdataset/train/App.java
// public abstract class App
// {
// //~ Static fields/initializers -----------------------------------------------------------------
//
// private static final Logger logger = LoggerFactory.getLogger(App.class);
//
// /** Abscissa margin around a None symbol location. */
// public static final int NONE_X_MARGIN = (int) Math.rint(INTERLINE * 0.5);
//
// /** Ordinate margin around a None symbol location. */
// public static final int NONE_Y_MARGIN = (int) Math.rint(INTERLINE * 0.5);
//
// /** Ratio of None symbols created versus valid symbols found in page: {@value}. */
// public static final double NONE_RATIO = 0.2; // 1.0;
//
// /** Format for output images (sub-images and control-images): {@value}. */
// public static final String OUTPUT_IMAGES_FORMAT = "png";
//
// /** File extension for output images: {@value}. */
// public static final String OUTPUT_IMAGES_EXT = "." + OUTPUT_IMAGES_FORMAT;
//
// /** File extension for page info: {@value}. */
// public static final String INFO_EXT = ".xml";
//
// /** Folder name for control-images: {@value}. */
// public static final String CONTROL_IMAGES_NAME = "control-images";
//
// /** Folder name for sub-images: {@value}. */
// public static final String SUB_IMAGES_NAME = "sub-images";
//
// /** Folder name for mistakes: {@value}. */
// public static final String MISTAKES_NAME = "mistakes";
//
// /** File name for features: {@value}. */
// public static final String FEATURES_NAME = "features.csv";
//
// /** FIle name for journal: {@value}. */
// public static final String JOURNAL_NAME = "journal.csv";
//
// /** File name for sheets: {@value}. */
// public static final String SHEETS_NAME = "sheets.csv";
//
// /** File name for pixel standards: {@value}. */
// public static final String PIXELS_NAME = "pixels.dat";
// }
| import org.audiveris.omrdataset.Main;
import static org.audiveris.omrdataset.classifier.Context.DIMS_NAME;
import static org.audiveris.omrdataset.classifier.Context.MODEL_NAME;
import static org.audiveris.omrdataset.train.App.*;
import java.nio.file.Path;
import java.nio.file.Paths; | //------------------------------------------------------------------------------------------------//
// //
// A p p P a t h s //
// //
//------------------------------------------------------------------------------------------------//
// <editor-fold defaultstate="collapsed" desc="hdr">
//
// Copyright © Audiveris 2017. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify it under the terms of the
// GNU Affero General Public License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// This program 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License along with this
// program. If not, see <http://www.gnu.org/licenses/>.
//------------------------------------------------------------------------------------------------//
// </editor-fold>
package org.audiveris.omrdataset.train;
/**
* Class {@code AppPaths} gathers paths for Omr Dataset application
*
* @author Hervé Bitteur
*/
public class AppPaths
{
//~ Static fields/initializers -----------------------------------------------------------------
/** Path to where the data is written. */ | // Path: src/main/java/org/audiveris/omrdataset/Main.java
// public class Main
// {
// //~ Static fields/initializers -----------------------------------------------------------------
//
// private static final Logger logger = LoggerFactory.getLogger(Main.class);
//
// /** CLI Parameters. */
// public static CLI cli;
//
// //~ Methods ------------------------------------------------------------------------------------
// public static void main (String[] args)
// throws Exception
// {
// cli = CLI.create(args);
//
// if (cli.help) {
// return; // Help has been printed by CLI itself
// }
//
// if (cli.outputFolder == null) {
// logger.warn("Output location not specified, please use -output option");
//
// return;
// }
//
// if (cli.names) {
// OmrShapes.printOmrShapes();
// }
//
// if (cli.clean) {
// new Clean().process();
// }
//
// if (cli.features) {
// // Extract features
// new Features().process();
// }
//
// if (cli.subimages) {
// // Extract subimages for visual check (not mandatory)
// new SubImages().process();
// }
//
// if (cli.training) {
// // Train the classifier
// new Training().process();
// }
// }
// }
//
// Path: src/main/java/org/audiveris/omrdataset/classifier/Context.java
// public static final String DIMS_NAME = "dims.dat";
//
// Path: src/main/java/org/audiveris/omrdataset/classifier/Context.java
// public static final String MODEL_NAME = "patch-classifier.zip";
//
// Path: src/main/java/org/audiveris/omrdataset/train/App.java
// public abstract class App
// {
// //~ Static fields/initializers -----------------------------------------------------------------
//
// private static final Logger logger = LoggerFactory.getLogger(App.class);
//
// /** Abscissa margin around a None symbol location. */
// public static final int NONE_X_MARGIN = (int) Math.rint(INTERLINE * 0.5);
//
// /** Ordinate margin around a None symbol location. */
// public static final int NONE_Y_MARGIN = (int) Math.rint(INTERLINE * 0.5);
//
// /** Ratio of None symbols created versus valid symbols found in page: {@value}. */
// public static final double NONE_RATIO = 0.2; // 1.0;
//
// /** Format for output images (sub-images and control-images): {@value}. */
// public static final String OUTPUT_IMAGES_FORMAT = "png";
//
// /** File extension for output images: {@value}. */
// public static final String OUTPUT_IMAGES_EXT = "." + OUTPUT_IMAGES_FORMAT;
//
// /** File extension for page info: {@value}. */
// public static final String INFO_EXT = ".xml";
//
// /** Folder name for control-images: {@value}. */
// public static final String CONTROL_IMAGES_NAME = "control-images";
//
// /** Folder name for sub-images: {@value}. */
// public static final String SUB_IMAGES_NAME = "sub-images";
//
// /** Folder name for mistakes: {@value}. */
// public static final String MISTAKES_NAME = "mistakes";
//
// /** File name for features: {@value}. */
// public static final String FEATURES_NAME = "features.csv";
//
// /** FIle name for journal: {@value}. */
// public static final String JOURNAL_NAME = "journal.csv";
//
// /** File name for sheets: {@value}. */
// public static final String SHEETS_NAME = "sheets.csv";
//
// /** File name for pixel standards: {@value}. */
// public static final String PIXELS_NAME = "pixels.dat";
// }
// Path: src/main/java/org/audiveris/omrdataset/train/AppPaths.java
import org.audiveris.omrdataset.Main;
import static org.audiveris.omrdataset.classifier.Context.DIMS_NAME;
import static org.audiveris.omrdataset.classifier.Context.MODEL_NAME;
import static org.audiveris.omrdataset.train.App.*;
import java.nio.file.Path;
import java.nio.file.Paths;
//------------------------------------------------------------------------------------------------//
// //
// A p p P a t h s //
// //
//------------------------------------------------------------------------------------------------//
// <editor-fold defaultstate="collapsed" desc="hdr">
//
// Copyright © Audiveris 2017. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify it under the terms of the
// GNU Affero General Public License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// This program 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License along with this
// program. If not, see <http://www.gnu.org/licenses/>.
//------------------------------------------------------------------------------------------------//
// </editor-fold>
package org.audiveris.omrdataset.train;
/**
* Class {@code AppPaths} gathers paths for Omr Dataset application
*
* @author Hervé Bitteur
*/
public class AppPaths
{
//~ Static fields/initializers -----------------------------------------------------------------
/** Path to where the data is written. */ | public static final Path OUTPUT_PATH = (Main.cli.outputFolder != null) ? Main.cli.outputFolder |
Audiveris/omr-dataset-tools | src/main/java/org/audiveris/omrdataset/train/AppPaths.java | // Path: src/main/java/org/audiveris/omrdataset/Main.java
// public class Main
// {
// //~ Static fields/initializers -----------------------------------------------------------------
//
// private static final Logger logger = LoggerFactory.getLogger(Main.class);
//
// /** CLI Parameters. */
// public static CLI cli;
//
// //~ Methods ------------------------------------------------------------------------------------
// public static void main (String[] args)
// throws Exception
// {
// cli = CLI.create(args);
//
// if (cli.help) {
// return; // Help has been printed by CLI itself
// }
//
// if (cli.outputFolder == null) {
// logger.warn("Output location not specified, please use -output option");
//
// return;
// }
//
// if (cli.names) {
// OmrShapes.printOmrShapes();
// }
//
// if (cli.clean) {
// new Clean().process();
// }
//
// if (cli.features) {
// // Extract features
// new Features().process();
// }
//
// if (cli.subimages) {
// // Extract subimages for visual check (not mandatory)
// new SubImages().process();
// }
//
// if (cli.training) {
// // Train the classifier
// new Training().process();
// }
// }
// }
//
// Path: src/main/java/org/audiveris/omrdataset/classifier/Context.java
// public static final String DIMS_NAME = "dims.dat";
//
// Path: src/main/java/org/audiveris/omrdataset/classifier/Context.java
// public static final String MODEL_NAME = "patch-classifier.zip";
//
// Path: src/main/java/org/audiveris/omrdataset/train/App.java
// public abstract class App
// {
// //~ Static fields/initializers -----------------------------------------------------------------
//
// private static final Logger logger = LoggerFactory.getLogger(App.class);
//
// /** Abscissa margin around a None symbol location. */
// public static final int NONE_X_MARGIN = (int) Math.rint(INTERLINE * 0.5);
//
// /** Ordinate margin around a None symbol location. */
// public static final int NONE_Y_MARGIN = (int) Math.rint(INTERLINE * 0.5);
//
// /** Ratio of None symbols created versus valid symbols found in page: {@value}. */
// public static final double NONE_RATIO = 0.2; // 1.0;
//
// /** Format for output images (sub-images and control-images): {@value}. */
// public static final String OUTPUT_IMAGES_FORMAT = "png";
//
// /** File extension for output images: {@value}. */
// public static final String OUTPUT_IMAGES_EXT = "." + OUTPUT_IMAGES_FORMAT;
//
// /** File extension for page info: {@value}. */
// public static final String INFO_EXT = ".xml";
//
// /** Folder name for control-images: {@value}. */
// public static final String CONTROL_IMAGES_NAME = "control-images";
//
// /** Folder name for sub-images: {@value}. */
// public static final String SUB_IMAGES_NAME = "sub-images";
//
// /** Folder name for mistakes: {@value}. */
// public static final String MISTAKES_NAME = "mistakes";
//
// /** File name for features: {@value}. */
// public static final String FEATURES_NAME = "features.csv";
//
// /** FIle name for journal: {@value}. */
// public static final String JOURNAL_NAME = "journal.csv";
//
// /** File name for sheets: {@value}. */
// public static final String SHEETS_NAME = "sheets.csv";
//
// /** File name for pixel standards: {@value}. */
// public static final String PIXELS_NAME = "pixels.dat";
// }
| import org.audiveris.omrdataset.Main;
import static org.audiveris.omrdataset.classifier.Context.DIMS_NAME;
import static org.audiveris.omrdataset.classifier.Context.MODEL_NAME;
import static org.audiveris.omrdataset.train.App.*;
import java.nio.file.Path;
import java.nio.file.Paths; | //------------------------------------------------------------------------------------------------//
// //
// A p p P a t h s //
// //
//------------------------------------------------------------------------------------------------//
// <editor-fold defaultstate="collapsed" desc="hdr">
//
// Copyright © Audiveris 2017. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify it under the terms of the
// GNU Affero General Public License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// This program 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License along with this
// program. If not, see <http://www.gnu.org/licenses/>.
//------------------------------------------------------------------------------------------------//
// </editor-fold>
package org.audiveris.omrdataset.train;
/**
* Class {@code AppPaths} gathers paths for Omr Dataset application
*
* @author Hervé Bitteur
*/
public class AppPaths
{
//~ Static fields/initializers -----------------------------------------------------------------
/** Path to where the data is written. */
public static final Path OUTPUT_PATH = (Main.cli.outputFolder != null) ? Main.cli.outputFolder
: Paths.get("data/output");
/** Path to created control-images. */
public static final Path CONTROL_IMAGES_PATH = OUTPUT_PATH.resolve(CONTROL_IMAGES_NAME);
/** Path to created sub-images. */
public static final Path SUB_IMAGES_PATH = OUTPUT_PATH.resolve(SUB_IMAGES_NAME);
/** Path to mistakes. */
public static final Path MISTAKES_PATH = OUTPUT_PATH.resolve(MISTAKES_NAME);
/** Path to single features file. */
public static final Path FEATURES_PATH = OUTPUT_PATH.resolve(FEATURES_NAME);
/** Path to single journal file. */
public static final Path JOURNAL_PATH = OUTPUT_PATH.resolve(JOURNAL_NAME);
/** Path to single sheets file. */
public static final Path SHEETS_PATH = OUTPUT_PATH.resolve(SHEETS_NAME);
/** Path to pixels populations. */
public static final Path PIXELS_PATH = OUTPUT_PATH.resolve(PIXELS_NAME);
/** Path to symbol dim populations. */ | // Path: src/main/java/org/audiveris/omrdataset/Main.java
// public class Main
// {
// //~ Static fields/initializers -----------------------------------------------------------------
//
// private static final Logger logger = LoggerFactory.getLogger(Main.class);
//
// /** CLI Parameters. */
// public static CLI cli;
//
// //~ Methods ------------------------------------------------------------------------------------
// public static void main (String[] args)
// throws Exception
// {
// cli = CLI.create(args);
//
// if (cli.help) {
// return; // Help has been printed by CLI itself
// }
//
// if (cli.outputFolder == null) {
// logger.warn("Output location not specified, please use -output option");
//
// return;
// }
//
// if (cli.names) {
// OmrShapes.printOmrShapes();
// }
//
// if (cli.clean) {
// new Clean().process();
// }
//
// if (cli.features) {
// // Extract features
// new Features().process();
// }
//
// if (cli.subimages) {
// // Extract subimages for visual check (not mandatory)
// new SubImages().process();
// }
//
// if (cli.training) {
// // Train the classifier
// new Training().process();
// }
// }
// }
//
// Path: src/main/java/org/audiveris/omrdataset/classifier/Context.java
// public static final String DIMS_NAME = "dims.dat";
//
// Path: src/main/java/org/audiveris/omrdataset/classifier/Context.java
// public static final String MODEL_NAME = "patch-classifier.zip";
//
// Path: src/main/java/org/audiveris/omrdataset/train/App.java
// public abstract class App
// {
// //~ Static fields/initializers -----------------------------------------------------------------
//
// private static final Logger logger = LoggerFactory.getLogger(App.class);
//
// /** Abscissa margin around a None symbol location. */
// public static final int NONE_X_MARGIN = (int) Math.rint(INTERLINE * 0.5);
//
// /** Ordinate margin around a None symbol location. */
// public static final int NONE_Y_MARGIN = (int) Math.rint(INTERLINE * 0.5);
//
// /** Ratio of None symbols created versus valid symbols found in page: {@value}. */
// public static final double NONE_RATIO = 0.2; // 1.0;
//
// /** Format for output images (sub-images and control-images): {@value}. */
// public static final String OUTPUT_IMAGES_FORMAT = "png";
//
// /** File extension for output images: {@value}. */
// public static final String OUTPUT_IMAGES_EXT = "." + OUTPUT_IMAGES_FORMAT;
//
// /** File extension for page info: {@value}. */
// public static final String INFO_EXT = ".xml";
//
// /** Folder name for control-images: {@value}. */
// public static final String CONTROL_IMAGES_NAME = "control-images";
//
// /** Folder name for sub-images: {@value}. */
// public static final String SUB_IMAGES_NAME = "sub-images";
//
// /** Folder name for mistakes: {@value}. */
// public static final String MISTAKES_NAME = "mistakes";
//
// /** File name for features: {@value}. */
// public static final String FEATURES_NAME = "features.csv";
//
// /** FIle name for journal: {@value}. */
// public static final String JOURNAL_NAME = "journal.csv";
//
// /** File name for sheets: {@value}. */
// public static final String SHEETS_NAME = "sheets.csv";
//
// /** File name for pixel standards: {@value}. */
// public static final String PIXELS_NAME = "pixels.dat";
// }
// Path: src/main/java/org/audiveris/omrdataset/train/AppPaths.java
import org.audiveris.omrdataset.Main;
import static org.audiveris.omrdataset.classifier.Context.DIMS_NAME;
import static org.audiveris.omrdataset.classifier.Context.MODEL_NAME;
import static org.audiveris.omrdataset.train.App.*;
import java.nio.file.Path;
import java.nio.file.Paths;
//------------------------------------------------------------------------------------------------//
// //
// A p p P a t h s //
// //
//------------------------------------------------------------------------------------------------//
// <editor-fold defaultstate="collapsed" desc="hdr">
//
// Copyright © Audiveris 2017. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify it under the terms of the
// GNU Affero General Public License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// This program 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License along with this
// program. If not, see <http://www.gnu.org/licenses/>.
//------------------------------------------------------------------------------------------------//
// </editor-fold>
package org.audiveris.omrdataset.train;
/**
* Class {@code AppPaths} gathers paths for Omr Dataset application
*
* @author Hervé Bitteur
*/
public class AppPaths
{
//~ Static fields/initializers -----------------------------------------------------------------
/** Path to where the data is written. */
public static final Path OUTPUT_PATH = (Main.cli.outputFolder != null) ? Main.cli.outputFolder
: Paths.get("data/output");
/** Path to created control-images. */
public static final Path CONTROL_IMAGES_PATH = OUTPUT_PATH.resolve(CONTROL_IMAGES_NAME);
/** Path to created sub-images. */
public static final Path SUB_IMAGES_PATH = OUTPUT_PATH.resolve(SUB_IMAGES_NAME);
/** Path to mistakes. */
public static final Path MISTAKES_PATH = OUTPUT_PATH.resolve(MISTAKES_NAME);
/** Path to single features file. */
public static final Path FEATURES_PATH = OUTPUT_PATH.resolve(FEATURES_NAME);
/** Path to single journal file. */
public static final Path JOURNAL_PATH = OUTPUT_PATH.resolve(JOURNAL_NAME);
/** Path to single sheets file. */
public static final Path SHEETS_PATH = OUTPUT_PATH.resolve(SHEETS_NAME);
/** Path to pixels populations. */
public static final Path PIXELS_PATH = OUTPUT_PATH.resolve(PIXELS_NAME);
/** Path to symbol dim populations. */ | public static final Path DIMS_PATH = OUTPUT_PATH.resolve(DIMS_NAME); |
Audiveris/omr-dataset-tools | src/main/java/org/audiveris/omrdataset/train/App.java | // Path: src/main/java/org/audiveris/omrdataset/classifier/Context.java
// public static final int INTERLINE = 10;
| import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.audiveris.omrdataset.classifier.Context.INTERLINE; | //------------------------------------------------------------------------------------------------//
// //
// A p p //
// //
//------------------------------------------------------------------------------------------------//
// <editor-fold defaultstate="collapsed" desc="hdr">
//
// Copyright © Audiveris 2017. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify it under the terms of the
// GNU Affero General Public License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// This program 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License along with this
// program. If not, see <http://www.gnu.org/licenses/>.
//------------------------------------------------------------------------------------------------//
// </editor-fold>
package org.audiveris.omrdataset.train;
/**
* Class {@code App} defines constants for the whole {@code OmrDataSet} application.
*
* @author Hervé Bitteur
*/
public abstract class App
{
//~ Static fields/initializers -----------------------------------------------------------------
private static final Logger logger = LoggerFactory.getLogger(App.class);
/** Abscissa margin around a None symbol location. */ | // Path: src/main/java/org/audiveris/omrdataset/classifier/Context.java
// public static final int INTERLINE = 10;
// Path: src/main/java/org/audiveris/omrdataset/train/App.java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.audiveris.omrdataset.classifier.Context.INTERLINE;
//------------------------------------------------------------------------------------------------//
// //
// A p p //
// //
//------------------------------------------------------------------------------------------------//
// <editor-fold defaultstate="collapsed" desc="hdr">
//
// Copyright © Audiveris 2017. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify it under the terms of the
// GNU Affero General Public License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// This program 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License along with this
// program. If not, see <http://www.gnu.org/licenses/>.
//------------------------------------------------------------------------------------------------//
// </editor-fold>
package org.audiveris.omrdataset.train;
/**
* Class {@code App} defines constants for the whole {@code OmrDataSet} application.
*
* @author Hervé Bitteur
*/
public abstract class App
{
//~ Static fields/initializers -----------------------------------------------------------------
private static final Logger logger = LoggerFactory.getLogger(App.class);
/** Abscissa margin around a None symbol location. */ | public static final int NONE_X_MARGIN = (int) Math.rint(INTERLINE * 0.5); |
Audiveris/omr-dataset-tools | src/main/java/org/audiveris/omrdataset/train/Clean.java | // Path: src/main/java/org/audiveris/omrdataset/train/AppPaths.java
// public static final Path OUTPUT_PATH = (Main.cli.outputFolder != null) ? Main.cli.outputFolder
// : Paths.get("data/output");
| import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Objects;
import static org.audiveris.omrdataset.train.AppPaths.OUTPUT_PATH;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path; | //------------------------------------------------------------------------------------------------//
// //
// C l e a n //
// //
//------------------------------------------------------------------------------------------------//
// <editor-fold defaultstate="collapsed" desc="hdr">
//
// Copyright © Audiveris 2017. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify it under the terms of the
// GNU Affero General Public License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// This program 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License along with this
// program. If not, see <http://www.gnu.org/licenses/>.
//------------------------------------------------------------------------------------------------//
// </editor-fold>
package org.audiveris.omrdataset.train;
/**
* Class {@code Clean} cleans up output data.
*
* @author Hervé Bitteur
*/
public class Clean
{
//~ Static fields/initializers -----------------------------------------------------------------
private static final Logger logger = LoggerFactory.getLogger(Clean.class);
//~ Methods ------------------------------------------------------------------------------------
/**
* Direct entry point.
*
* @param args not used
* @throws IOException in case of IO problem
*/
public static void main (String[] args)
throws IOException
{
new Clean().process();
}
/**
* Clean up the output folder.
*
* @throws IOException in case of IO problem
*/
public void process ()
throws IOException
{ | // Path: src/main/java/org/audiveris/omrdataset/train/AppPaths.java
// public static final Path OUTPUT_PATH = (Main.cli.outputFolder != null) ? Main.cli.outputFolder
// : Paths.get("data/output");
// Path: src/main/java/org/audiveris/omrdataset/train/Clean.java
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Objects;
import static org.audiveris.omrdataset.train.AppPaths.OUTPUT_PATH;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
//------------------------------------------------------------------------------------------------//
// //
// C l e a n //
// //
//------------------------------------------------------------------------------------------------//
// <editor-fold defaultstate="collapsed" desc="hdr">
//
// Copyright © Audiveris 2017. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify it under the terms of the
// GNU Affero General Public License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// This program 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License along with this
// program. If not, see <http://www.gnu.org/licenses/>.
//------------------------------------------------------------------------------------------------//
// </editor-fold>
package org.audiveris.omrdataset.train;
/**
* Class {@code Clean} cleans up output data.
*
* @author Hervé Bitteur
*/
public class Clean
{
//~ Static fields/initializers -----------------------------------------------------------------
private static final Logger logger = LoggerFactory.getLogger(Clean.class);
//~ Methods ------------------------------------------------------------------------------------
/**
* Direct entry point.
*
* @param args not used
* @throws IOException in case of IO problem
*/
public static void main (String[] args)
throws IOException
{
new Clean().process();
}
/**
* Clean up the output folder.
*
* @throws IOException in case of IO problem
*/
public void process ()
throws IOException
{ | if (OUTPUT_PATH == null) { |
mik3y/usb-serial-for-android | usbSerialForAndroid/src/main/java/com/hoho/android/usbserial/driver/ProlificSerialDriver.java | // Path: usbSerialForAndroid/src/main/java/com/hoho/android/usbserial/util/MonotonicClock.java
// public final class MonotonicClock {
//
// private static final long NS_PER_MS = 1_000_000;
//
// private MonotonicClock() {
// }
//
// public static long millis() {
// return System.nanoTime() / NS_PER_MS;
// }
//
// }
| import android.hardware.usb.UsbConstants;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.util.Log;
import com.hoho.android.usbserial.BuildConfig;
import com.hoho.android.usbserial.util.MonotonicClock;
import java.io.IOException;
import java.util.Collections;
import java.util.EnumSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map; | } catch(IOException ignored) {
return false;
}
}
private void doBlackMagic() throws IOException {
if (mDeviceType == DeviceType.DEVICE_TYPE_HXN)
return;
vendorIn(0x8484, 0, 1);
vendorOut(0x0404, 0, null);
vendorIn(0x8484, 0, 1);
vendorIn(0x8383, 0, 1);
vendorIn(0x8484, 0, 1);
vendorOut(0x0404, 1, null);
vendorIn(0x8484, 0, 1);
vendorIn(0x8383, 0, 1);
vendorOut(0, 1, null);
vendorOut(1, 0, null);
vendorOut(2, (mDeviceType == DeviceType.DEVICE_TYPE_01) ? 0x24 : 0x44, null);
}
private void setControlLines(int newControlLinesValue) throws IOException {
ctrlOut(SET_CONTROL_REQUEST, newControlLinesValue, 0, null);
mControlLinesValue = newControlLinesValue;
}
private void readStatusThreadFunction() {
try {
while (!mStopReadStatusThread) {
byte[] buffer = new byte[STATUS_BUFFER_SIZE]; | // Path: usbSerialForAndroid/src/main/java/com/hoho/android/usbserial/util/MonotonicClock.java
// public final class MonotonicClock {
//
// private static final long NS_PER_MS = 1_000_000;
//
// private MonotonicClock() {
// }
//
// public static long millis() {
// return System.nanoTime() / NS_PER_MS;
// }
//
// }
// Path: usbSerialForAndroid/src/main/java/com/hoho/android/usbserial/driver/ProlificSerialDriver.java
import android.hardware.usb.UsbConstants;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.util.Log;
import com.hoho.android.usbserial.BuildConfig;
import com.hoho.android.usbserial.util.MonotonicClock;
import java.io.IOException;
import java.util.Collections;
import java.util.EnumSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
} catch(IOException ignored) {
return false;
}
}
private void doBlackMagic() throws IOException {
if (mDeviceType == DeviceType.DEVICE_TYPE_HXN)
return;
vendorIn(0x8484, 0, 1);
vendorOut(0x0404, 0, null);
vendorIn(0x8484, 0, 1);
vendorIn(0x8383, 0, 1);
vendorIn(0x8484, 0, 1);
vendorOut(0x0404, 1, null);
vendorIn(0x8484, 0, 1);
vendorIn(0x8383, 0, 1);
vendorOut(0, 1, null);
vendorOut(1, 0, null);
vendorOut(2, (mDeviceType == DeviceType.DEVICE_TYPE_01) ? 0x24 : 0x44, null);
}
private void setControlLines(int newControlLinesValue) throws IOException {
ctrlOut(SET_CONTROL_REQUEST, newControlLinesValue, 0, null);
mControlLinesValue = newControlLinesValue;
}
private void readStatusThreadFunction() {
try {
while (!mStopReadStatusThread) {
byte[] buffer = new byte[STATUS_BUFFER_SIZE]; | long endTime = MonotonicClock.millis() + 500; |
mik3y/usb-serial-for-android | usbSerialForAndroid/src/main/java/com/hoho/android/usbserial/driver/FtdiSerialDriver.java | // Path: usbSerialForAndroid/src/main/java/com/hoho/android/usbserial/util/MonotonicClock.java
// public final class MonotonicClock {
//
// private static final long NS_PER_MS = 1_000_000;
//
// private MonotonicClock() {
// }
//
// public static long millis() {
// return System.nanoTime() / NS_PER_MS;
// }
//
// }
| import android.hardware.usb.UsbConstants;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.util.Log;
import com.hoho.android.usbserial.util.MonotonicClock;
import java.io.IOException;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map; | throw new IOException("Init RTS,DTR failed: result=" + result);
}
// mDevice.getVersion() would require API 23
byte[] rawDescriptors = connection.getRawDescriptors();
if(rawDescriptors == null || rawDescriptors.length < 14) {
throw new IOException("Could not get device descriptors");
}
int deviceType = rawDescriptors[13];
baudRateWithPort = deviceType == 7 || deviceType == 8 || deviceType == 9 // ...H devices
|| mDevice.getInterfaceCount() > 1; // FT2232C
}
@Override
protected void closeInt() {
try {
mConnection.releaseInterface(mDevice.getInterface(mPortNumber));
} catch(Exception ignored) {}
}
@Override
public int read(final byte[] dest, final int timeout) throws IOException {
if(dest.length <= READ_HEADER_LENGTH) {
throw new IllegalArgumentException("Read buffer to small");
// could allocate larger buffer, including space for 2 header bytes, but this would
// result in buffers not being 64 byte aligned any more, causing data loss at continuous
// data transfer at high baud rates when buffers are fully filled.
}
int nread;
if (timeout != 0) { | // Path: usbSerialForAndroid/src/main/java/com/hoho/android/usbserial/util/MonotonicClock.java
// public final class MonotonicClock {
//
// private static final long NS_PER_MS = 1_000_000;
//
// private MonotonicClock() {
// }
//
// public static long millis() {
// return System.nanoTime() / NS_PER_MS;
// }
//
// }
// Path: usbSerialForAndroid/src/main/java/com/hoho/android/usbserial/driver/FtdiSerialDriver.java
import android.hardware.usb.UsbConstants;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.util.Log;
import com.hoho.android.usbserial.util.MonotonicClock;
import java.io.IOException;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
throw new IOException("Init RTS,DTR failed: result=" + result);
}
// mDevice.getVersion() would require API 23
byte[] rawDescriptors = connection.getRawDescriptors();
if(rawDescriptors == null || rawDescriptors.length < 14) {
throw new IOException("Could not get device descriptors");
}
int deviceType = rawDescriptors[13];
baudRateWithPort = deviceType == 7 || deviceType == 8 || deviceType == 9 // ...H devices
|| mDevice.getInterfaceCount() > 1; // FT2232C
}
@Override
protected void closeInt() {
try {
mConnection.releaseInterface(mDevice.getInterface(mPortNumber));
} catch(Exception ignored) {}
}
@Override
public int read(final byte[] dest, final int timeout) throws IOException {
if(dest.length <= READ_HEADER_LENGTH) {
throw new IllegalArgumentException("Read buffer to small");
// could allocate larger buffer, including space for 2 header bytes, but this would
// result in buffers not being 64 byte aligned any more, causing data loss at continuous
// data transfer at high baud rates when buffers are fully filled.
}
int nread;
if (timeout != 0) { | long endTime = MonotonicClock.millis() + timeout; |
mik3y/usb-serial-for-android | usbSerialExamples/src/main/java/com/hoho/android/usbserial/examples/DevicesFragment.java | // Path: usbSerialForAndroid/src/main/java/com/hoho/android/usbserial/driver/UsbSerialDriver.java
// public interface UsbSerialDriver {
//
// /**
// * Returns the raw {@link UsbDevice} backing this port.
// *
// * @return the device
// */
// UsbDevice getDevice();
//
// /**
// * Returns all available ports for this device. This list must have at least
// * one entry.
// *
// * @return the ports
// */
// List<UsbSerialPort> getPorts();
// }
//
// Path: usbSerialForAndroid/src/main/java/com/hoho/android/usbserial/driver/UsbSerialProber.java
// public class UsbSerialProber {
//
// private final ProbeTable mProbeTable;
//
// public UsbSerialProber(ProbeTable probeTable) {
// mProbeTable = probeTable;
// }
//
// public static UsbSerialProber getDefaultProber() {
// return new UsbSerialProber(getDefaultProbeTable());
// }
//
// public static ProbeTable getDefaultProbeTable() {
// final ProbeTable probeTable = new ProbeTable();
// probeTable.addDriver(CdcAcmSerialDriver.class);
// probeTable.addDriver(Cp21xxSerialDriver.class);
// probeTable.addDriver(FtdiSerialDriver.class);
// probeTable.addDriver(ProlificSerialDriver.class);
// probeTable.addDriver(Ch34xSerialDriver.class);
// return probeTable;
// }
//
// /**
// * Finds and builds all possible {@link UsbSerialDriver UsbSerialDrivers}
// * from the currently-attached {@link UsbDevice} hierarchy. This method does
// * not require permission from the Android USB system, since it does not
// * open any of the devices.
// *
// * @param usbManager usb manager
// * @return a list, possibly empty, of all compatible drivers
// */
// public List<UsbSerialDriver> findAllDrivers(final UsbManager usbManager) {
// final List<UsbSerialDriver> result = new ArrayList<>();
//
// for (final UsbDevice usbDevice : usbManager.getDeviceList().values()) {
// final UsbSerialDriver driver = probeDevice(usbDevice);
// if (driver != null) {
// result.add(driver);
// }
// }
// return result;
// }
//
// /**
// * Probes a single device for a compatible driver.
// *
// * @param usbDevice the usb device to probe
// * @return a new {@link UsbSerialDriver} compatible with this device, or
// * {@code null} if none available.
// */
// public UsbSerialDriver probeDevice(final UsbDevice usbDevice) {
// final int vendorId = usbDevice.getVendorId();
// final int productId = usbDevice.getProductId();
//
// final Class<? extends UsbSerialDriver> driverClass =
// mProbeTable.findDriver(vendorId, productId);
// if (driverClass != null) {
// final UsbSerialDriver driver;
// try {
// final Constructor<? extends UsbSerialDriver> ctor =
// driverClass.getConstructor(UsbDevice.class);
// driver = ctor.newInstance(usbDevice);
// } catch (NoSuchMethodException | IllegalArgumentException | InstantiationException |
// IllegalAccessException | InvocationTargetException e) {
// throw new RuntimeException(e);
// }
// return driver;
// }
// return null;
// }
//
// }
| import android.app.AlertDialog;
import android.content.Context;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.ListFragment;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.hoho.android.usbserial.driver.UsbSerialDriver;
import com.hoho.android.usbserial.driver.UsbSerialProber;
import java.util.ArrayList;
import java.util.Locale; | package com.hoho.android.usbserial.examples;
public class DevicesFragment extends ListFragment {
static class ListItem {
UsbDevice device;
int port; | // Path: usbSerialForAndroid/src/main/java/com/hoho/android/usbserial/driver/UsbSerialDriver.java
// public interface UsbSerialDriver {
//
// /**
// * Returns the raw {@link UsbDevice} backing this port.
// *
// * @return the device
// */
// UsbDevice getDevice();
//
// /**
// * Returns all available ports for this device. This list must have at least
// * one entry.
// *
// * @return the ports
// */
// List<UsbSerialPort> getPorts();
// }
//
// Path: usbSerialForAndroid/src/main/java/com/hoho/android/usbserial/driver/UsbSerialProber.java
// public class UsbSerialProber {
//
// private final ProbeTable mProbeTable;
//
// public UsbSerialProber(ProbeTable probeTable) {
// mProbeTable = probeTable;
// }
//
// public static UsbSerialProber getDefaultProber() {
// return new UsbSerialProber(getDefaultProbeTable());
// }
//
// public static ProbeTable getDefaultProbeTable() {
// final ProbeTable probeTable = new ProbeTable();
// probeTable.addDriver(CdcAcmSerialDriver.class);
// probeTable.addDriver(Cp21xxSerialDriver.class);
// probeTable.addDriver(FtdiSerialDriver.class);
// probeTable.addDriver(ProlificSerialDriver.class);
// probeTable.addDriver(Ch34xSerialDriver.class);
// return probeTable;
// }
//
// /**
// * Finds and builds all possible {@link UsbSerialDriver UsbSerialDrivers}
// * from the currently-attached {@link UsbDevice} hierarchy. This method does
// * not require permission from the Android USB system, since it does not
// * open any of the devices.
// *
// * @param usbManager usb manager
// * @return a list, possibly empty, of all compatible drivers
// */
// public List<UsbSerialDriver> findAllDrivers(final UsbManager usbManager) {
// final List<UsbSerialDriver> result = new ArrayList<>();
//
// for (final UsbDevice usbDevice : usbManager.getDeviceList().values()) {
// final UsbSerialDriver driver = probeDevice(usbDevice);
// if (driver != null) {
// result.add(driver);
// }
// }
// return result;
// }
//
// /**
// * Probes a single device for a compatible driver.
// *
// * @param usbDevice the usb device to probe
// * @return a new {@link UsbSerialDriver} compatible with this device, or
// * {@code null} if none available.
// */
// public UsbSerialDriver probeDevice(final UsbDevice usbDevice) {
// final int vendorId = usbDevice.getVendorId();
// final int productId = usbDevice.getProductId();
//
// final Class<? extends UsbSerialDriver> driverClass =
// mProbeTable.findDriver(vendorId, productId);
// if (driverClass != null) {
// final UsbSerialDriver driver;
// try {
// final Constructor<? extends UsbSerialDriver> ctor =
// driverClass.getConstructor(UsbDevice.class);
// driver = ctor.newInstance(usbDevice);
// } catch (NoSuchMethodException | IllegalArgumentException | InstantiationException |
// IllegalAccessException | InvocationTargetException e) {
// throw new RuntimeException(e);
// }
// return driver;
// }
// return null;
// }
//
// }
// Path: usbSerialExamples/src/main/java/com/hoho/android/usbserial/examples/DevicesFragment.java
import android.app.AlertDialog;
import android.content.Context;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.ListFragment;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.hoho.android.usbserial.driver.UsbSerialDriver;
import com.hoho.android.usbserial.driver.UsbSerialProber;
import java.util.ArrayList;
import java.util.Locale;
package com.hoho.android.usbserial.examples;
public class DevicesFragment extends ListFragment {
static class ListItem {
UsbDevice device;
int port; | UsbSerialDriver driver; |
mik3y/usb-serial-for-android | usbSerialExamples/src/main/java/com/hoho/android/usbserial/examples/DevicesFragment.java | // Path: usbSerialForAndroid/src/main/java/com/hoho/android/usbserial/driver/UsbSerialDriver.java
// public interface UsbSerialDriver {
//
// /**
// * Returns the raw {@link UsbDevice} backing this port.
// *
// * @return the device
// */
// UsbDevice getDevice();
//
// /**
// * Returns all available ports for this device. This list must have at least
// * one entry.
// *
// * @return the ports
// */
// List<UsbSerialPort> getPorts();
// }
//
// Path: usbSerialForAndroid/src/main/java/com/hoho/android/usbserial/driver/UsbSerialProber.java
// public class UsbSerialProber {
//
// private final ProbeTable mProbeTable;
//
// public UsbSerialProber(ProbeTable probeTable) {
// mProbeTable = probeTable;
// }
//
// public static UsbSerialProber getDefaultProber() {
// return new UsbSerialProber(getDefaultProbeTable());
// }
//
// public static ProbeTable getDefaultProbeTable() {
// final ProbeTable probeTable = new ProbeTable();
// probeTable.addDriver(CdcAcmSerialDriver.class);
// probeTable.addDriver(Cp21xxSerialDriver.class);
// probeTable.addDriver(FtdiSerialDriver.class);
// probeTable.addDriver(ProlificSerialDriver.class);
// probeTable.addDriver(Ch34xSerialDriver.class);
// return probeTable;
// }
//
// /**
// * Finds and builds all possible {@link UsbSerialDriver UsbSerialDrivers}
// * from the currently-attached {@link UsbDevice} hierarchy. This method does
// * not require permission from the Android USB system, since it does not
// * open any of the devices.
// *
// * @param usbManager usb manager
// * @return a list, possibly empty, of all compatible drivers
// */
// public List<UsbSerialDriver> findAllDrivers(final UsbManager usbManager) {
// final List<UsbSerialDriver> result = new ArrayList<>();
//
// for (final UsbDevice usbDevice : usbManager.getDeviceList().values()) {
// final UsbSerialDriver driver = probeDevice(usbDevice);
// if (driver != null) {
// result.add(driver);
// }
// }
// return result;
// }
//
// /**
// * Probes a single device for a compatible driver.
// *
// * @param usbDevice the usb device to probe
// * @return a new {@link UsbSerialDriver} compatible with this device, or
// * {@code null} if none available.
// */
// public UsbSerialDriver probeDevice(final UsbDevice usbDevice) {
// final int vendorId = usbDevice.getVendorId();
// final int productId = usbDevice.getProductId();
//
// final Class<? extends UsbSerialDriver> driverClass =
// mProbeTable.findDriver(vendorId, productId);
// if (driverClass != null) {
// final UsbSerialDriver driver;
// try {
// final Constructor<? extends UsbSerialDriver> ctor =
// driverClass.getConstructor(UsbDevice.class);
// driver = ctor.newInstance(usbDevice);
// } catch (NoSuchMethodException | IllegalArgumentException | InstantiationException |
// IllegalAccessException | InvocationTargetException e) {
// throw new RuntimeException(e);
// }
// return driver;
// }
// return null;
// }
//
// }
| import android.app.AlertDialog;
import android.content.Context;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.ListFragment;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.hoho.android.usbserial.driver.UsbSerialDriver;
import com.hoho.android.usbserial.driver.UsbSerialProber;
import java.util.ArrayList;
import java.util.Locale; | return true;
} else if (id ==R.id.baud_rate) {
final String[] values = getResources().getStringArray(R.array.baud_rates);
int pos = java.util.Arrays.asList(values).indexOf(String.valueOf(baudRate));
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Baud rate");
builder.setSingleChoiceItems(values, pos, (dialog, which) -> {
baudRate = Integer.parseInt(values[which]);
dialog.dismiss();
});
builder.create().show();
return true;
} else if (id ==R.id.read_mode) {
final String[] values = getResources().getStringArray(R.array.read_modes);
int pos = withIoManager ? 0 : 1; // read_modes[0]=event/io-manager, read_modes[1]=direct
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Read mode");
builder.setSingleChoiceItems(values, pos, (dialog, which) -> {
withIoManager = (which == 0);
dialog.dismiss();
});
builder.create().show();
return true;
} else {
return super.onOptionsItemSelected(item);
}
}
void refresh() {
UsbManager usbManager = (UsbManager) getActivity().getSystemService(Context.USB_SERVICE); | // Path: usbSerialForAndroid/src/main/java/com/hoho/android/usbserial/driver/UsbSerialDriver.java
// public interface UsbSerialDriver {
//
// /**
// * Returns the raw {@link UsbDevice} backing this port.
// *
// * @return the device
// */
// UsbDevice getDevice();
//
// /**
// * Returns all available ports for this device. This list must have at least
// * one entry.
// *
// * @return the ports
// */
// List<UsbSerialPort> getPorts();
// }
//
// Path: usbSerialForAndroid/src/main/java/com/hoho/android/usbserial/driver/UsbSerialProber.java
// public class UsbSerialProber {
//
// private final ProbeTable mProbeTable;
//
// public UsbSerialProber(ProbeTable probeTable) {
// mProbeTable = probeTable;
// }
//
// public static UsbSerialProber getDefaultProber() {
// return new UsbSerialProber(getDefaultProbeTable());
// }
//
// public static ProbeTable getDefaultProbeTable() {
// final ProbeTable probeTable = new ProbeTable();
// probeTable.addDriver(CdcAcmSerialDriver.class);
// probeTable.addDriver(Cp21xxSerialDriver.class);
// probeTable.addDriver(FtdiSerialDriver.class);
// probeTable.addDriver(ProlificSerialDriver.class);
// probeTable.addDriver(Ch34xSerialDriver.class);
// return probeTable;
// }
//
// /**
// * Finds and builds all possible {@link UsbSerialDriver UsbSerialDrivers}
// * from the currently-attached {@link UsbDevice} hierarchy. This method does
// * not require permission from the Android USB system, since it does not
// * open any of the devices.
// *
// * @param usbManager usb manager
// * @return a list, possibly empty, of all compatible drivers
// */
// public List<UsbSerialDriver> findAllDrivers(final UsbManager usbManager) {
// final List<UsbSerialDriver> result = new ArrayList<>();
//
// for (final UsbDevice usbDevice : usbManager.getDeviceList().values()) {
// final UsbSerialDriver driver = probeDevice(usbDevice);
// if (driver != null) {
// result.add(driver);
// }
// }
// return result;
// }
//
// /**
// * Probes a single device for a compatible driver.
// *
// * @param usbDevice the usb device to probe
// * @return a new {@link UsbSerialDriver} compatible with this device, or
// * {@code null} if none available.
// */
// public UsbSerialDriver probeDevice(final UsbDevice usbDevice) {
// final int vendorId = usbDevice.getVendorId();
// final int productId = usbDevice.getProductId();
//
// final Class<? extends UsbSerialDriver> driverClass =
// mProbeTable.findDriver(vendorId, productId);
// if (driverClass != null) {
// final UsbSerialDriver driver;
// try {
// final Constructor<? extends UsbSerialDriver> ctor =
// driverClass.getConstructor(UsbDevice.class);
// driver = ctor.newInstance(usbDevice);
// } catch (NoSuchMethodException | IllegalArgumentException | InstantiationException |
// IllegalAccessException | InvocationTargetException e) {
// throw new RuntimeException(e);
// }
// return driver;
// }
// return null;
// }
//
// }
// Path: usbSerialExamples/src/main/java/com/hoho/android/usbserial/examples/DevicesFragment.java
import android.app.AlertDialog;
import android.content.Context;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.ListFragment;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.hoho.android.usbserial.driver.UsbSerialDriver;
import com.hoho.android.usbserial.driver.UsbSerialProber;
import java.util.ArrayList;
import java.util.Locale;
return true;
} else if (id ==R.id.baud_rate) {
final String[] values = getResources().getStringArray(R.array.baud_rates);
int pos = java.util.Arrays.asList(values).indexOf(String.valueOf(baudRate));
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Baud rate");
builder.setSingleChoiceItems(values, pos, (dialog, which) -> {
baudRate = Integer.parseInt(values[which]);
dialog.dismiss();
});
builder.create().show();
return true;
} else if (id ==R.id.read_mode) {
final String[] values = getResources().getStringArray(R.array.read_modes);
int pos = withIoManager ? 0 : 1; // read_modes[0]=event/io-manager, read_modes[1]=direct
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Read mode");
builder.setSingleChoiceItems(values, pos, (dialog, which) -> {
withIoManager = (which == 0);
dialog.dismiss();
});
builder.create().show();
return true;
} else {
return super.onOptionsItemSelected(item);
}
}
void refresh() {
UsbManager usbManager = (UsbManager) getActivity().getSystemService(Context.USB_SERVICE); | UsbSerialProber usbDefaultProber = UsbSerialProber.getDefaultProber(); |
mik3y/usb-serial-for-android | usbSerialForAndroid/src/main/java/com/hoho/android/usbserial/driver/CommonUsbSerialPort.java | // Path: usbSerialForAndroid/src/main/java/com/hoho/android/usbserial/util/MonotonicClock.java
// public final class MonotonicClock {
//
// private static final long NS_PER_MS = 1_000_000;
//
// private MonotonicClock() {
// }
//
// public static long millis() {
// return System.nanoTime() / NS_PER_MS;
// }
//
// }
| import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbRequest;
import android.util.Log;
import com.hoho.android.usbserial.util.MonotonicClock;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.EnumSet; | */
protected void testConnection() throws IOException {
byte[] buf = new byte[2];
int len = mConnection.controlTransfer(0x80 /*DEVICE*/, 0 /*GET_STATUS*/, 0, 0, buf, buf.length, 200);
if(len < 0)
throw new IOException("USB get_status request failed");
}
@Override
public int read(final byte[] dest, final int timeout) throws IOException {
return read(dest, timeout, true);
}
protected int read(final byte[] dest, final int timeout, boolean testConnection) throws IOException {
if(mConnection == null) {
throw new IOException("Connection closed");
}
if(dest.length <= 0) {
throw new IllegalArgumentException("Read buffer to small");
}
final int nread;
if (timeout != 0) {
// bulkTransfer will cause data loss with short timeout + high baud rates + continuous transfer
// https://stackoverflow.com/questions/9108548/android-usb-host-bulktransfer-is-losing-data
// but mConnection.requestWait(timeout) available since Android 8.0 es even worse,
// as it crashes with short timeout, e.g.
// A/libc: Fatal signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x276a in tid 29846 (pool-2-thread-1), pid 29618 (.usbserial.test)
// /system/lib64/libusbhost.so (usb_request_wait+192)
// /system/lib64/libandroid_runtime.so (android_hardware_UsbDeviceConnection_request_wait(_JNIEnv*, _jobject*, long)+84)
// data loss / crashes were observed with timeout up to 200 msec | // Path: usbSerialForAndroid/src/main/java/com/hoho/android/usbserial/util/MonotonicClock.java
// public final class MonotonicClock {
//
// private static final long NS_PER_MS = 1_000_000;
//
// private MonotonicClock() {
// }
//
// public static long millis() {
// return System.nanoTime() / NS_PER_MS;
// }
//
// }
// Path: usbSerialForAndroid/src/main/java/com/hoho/android/usbserial/driver/CommonUsbSerialPort.java
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbRequest;
import android.util.Log;
import com.hoho.android.usbserial.util.MonotonicClock;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.EnumSet;
*/
protected void testConnection() throws IOException {
byte[] buf = new byte[2];
int len = mConnection.controlTransfer(0x80 /*DEVICE*/, 0 /*GET_STATUS*/, 0, 0, buf, buf.length, 200);
if(len < 0)
throw new IOException("USB get_status request failed");
}
@Override
public int read(final byte[] dest, final int timeout) throws IOException {
return read(dest, timeout, true);
}
protected int read(final byte[] dest, final int timeout, boolean testConnection) throws IOException {
if(mConnection == null) {
throw new IOException("Connection closed");
}
if(dest.length <= 0) {
throw new IllegalArgumentException("Read buffer to small");
}
final int nread;
if (timeout != 0) {
// bulkTransfer will cause data loss with short timeout + high baud rates + continuous transfer
// https://stackoverflow.com/questions/9108548/android-usb-host-bulktransfer-is-losing-data
// but mConnection.requestWait(timeout) available since Android 8.0 es even worse,
// as it crashes with short timeout, e.g.
// A/libc: Fatal signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x276a in tid 29846 (pool-2-thread-1), pid 29618 (.usbserial.test)
// /system/lib64/libusbhost.so (usb_request_wait+192)
// /system/lib64/libandroid_runtime.so (android_hardware_UsbDeviceConnection_request_wait(_JNIEnv*, _jobject*, long)+84)
// data loss / crashes were observed with timeout up to 200 msec | long endTime = testConnection ? MonotonicClock.millis() + timeout : 0; |
jjz/android | JustShare/src/com/liucd/share/db/AccessInfoHelper.java | // Path: JustShare/src/com/liucd/share/bean/AccessInfo.java
// public class AccessInfo
// {
// //用户Id
// private String userID;
//
// //accessToken
// private String accessToken;
//
// //accessSecret
// private String accessSecret;
//
// public String getUserID() {
// return userID;
// }
// public void setUserID(String userID) {
// this.userID = userID;
// }
// public String getAccessToken() {
// return accessToken;
// }
// public void setAccessToken(String accessToken) {
// this.accessToken = accessToken;
// }
// public String getAccessSecret() {
// return accessSecret;
// }
// public void setAccessSecret(String accessSecret) {
// this.accessSecret = accessSecret;
// }
// }
| import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.liucd.share.bean.AccessInfo;
| package com.liucd.share.db;
/**
* 类说明: 数据库操作
* @author @Cundong
* @weibo http://weibo.com/liucundong
* @blog http://www.liucundong.com
* @date Apr 29, 2011 2:50:48 PM
* @version 1.0
*/
public class AccessInfoHelper
{
private DBHelper dbHelper;
private SQLiteDatabase newsDB;
private Context context;
public AccessInfoHelper( Context context )
{
this.context = context;
}
/**
* 初始化数据库连接
*/
public AccessInfoHelper open()
{
dbHelper = new DBHelper( this.context );
newsDB = dbHelper.getWritableDatabase();
return this;
}
/**
* 关闭连接
*/
public void close()
{
if(dbHelper!=null)
{
dbHelper.close();
}
}
/**
* 创建一条记录
* @param accessInfo
* @return
*/
| // Path: JustShare/src/com/liucd/share/bean/AccessInfo.java
// public class AccessInfo
// {
// //用户Id
// private String userID;
//
// //accessToken
// private String accessToken;
//
// //accessSecret
// private String accessSecret;
//
// public String getUserID() {
// return userID;
// }
// public void setUserID(String userID) {
// this.userID = userID;
// }
// public String getAccessToken() {
// return accessToken;
// }
// public void setAccessToken(String accessToken) {
// this.accessToken = accessToken;
// }
// public String getAccessSecret() {
// return accessSecret;
// }
// public void setAccessSecret(String accessSecret) {
// this.accessSecret = accessSecret;
// }
// }
// Path: JustShare/src/com/liucd/share/db/AccessInfoHelper.java
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.liucd.share.bean.AccessInfo;
package com.liucd.share.db;
/**
* 类说明: 数据库操作
* @author @Cundong
* @weibo http://weibo.com/liucundong
* @blog http://www.liucundong.com
* @date Apr 29, 2011 2:50:48 PM
* @version 1.0
*/
public class AccessInfoHelper
{
private DBHelper dbHelper;
private SQLiteDatabase newsDB;
private Context context;
public AccessInfoHelper( Context context )
{
this.context = context;
}
/**
* 初始化数据库连接
*/
public AccessInfoHelper open()
{
dbHelper = new DBHelper( this.context );
newsDB = dbHelper.getWritableDatabase();
return this;
}
/**
* 关闭连接
*/
public void close()
{
if(dbHelper!=null)
{
dbHelper.close();
}
}
/**
* 创建一条记录
* @param accessInfo
* @return
*/
| public long create( AccessInfo accessInfo )
|
jmock-developers/jmock-library | jmock/src/main/java/org/jmock/AbstractExpectations.java | // Path: jmock/src/main/java/org/jmock/api/ExpectationCollector.java
// public interface ExpectationCollector {
// void add(Expectation expectation);
// }
| import org.hamcrest.CoreMatchers;
import org.hamcrest.Matcher;
import org.hamcrest.core.*;
import org.jmock.api.Action;
import org.jmock.api.ExpectationCollector;
import org.jmock.internal.*;
import org.jmock.lib.action.*;
import org.jmock.syntax.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List; | public int intIs(Matcher<?> matcher) {
addParameterMatcher(matcher);
return 0;
}
public long longIs(Matcher<?> matcher) {
addParameterMatcher(matcher);
return 0;
}
public short shortIs(Matcher<?> matcher) {
addParameterMatcher(matcher);
return 0;
}
public <T> T is(Matcher<?> matcher) {
addParameterMatcher(matcher);
return null;
}
};
private void initialiseExpectationCapture(Cardinality cardinality) {
checkLastExpectationWasFullySpecified();
currentBuilder = new InvocationExpectationBuilder();
currentBuilder.setCardinality(cardinality);
builders.add(currentBuilder);
}
| // Path: jmock/src/main/java/org/jmock/api/ExpectationCollector.java
// public interface ExpectationCollector {
// void add(Expectation expectation);
// }
// Path: jmock/src/main/java/org/jmock/AbstractExpectations.java
import org.hamcrest.CoreMatchers;
import org.hamcrest.Matcher;
import org.hamcrest.core.*;
import org.jmock.api.Action;
import org.jmock.api.ExpectationCollector;
import org.jmock.internal.*;
import org.jmock.lib.action.*;
import org.jmock.syntax.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public int intIs(Matcher<?> matcher) {
addParameterMatcher(matcher);
return 0;
}
public long longIs(Matcher<?> matcher) {
addParameterMatcher(matcher);
return 0;
}
public short shortIs(Matcher<?> matcher) {
addParameterMatcher(matcher);
return 0;
}
public <T> T is(Matcher<?> matcher) {
addParameterMatcher(matcher);
return null;
}
};
private void initialiseExpectationCapture(Cardinality cardinality) {
checkLastExpectationWasFullySpecified();
currentBuilder = new InvocationExpectationBuilder();
currentBuilder.setCardinality(cardinality);
builders.add(currentBuilder);
}
| public void buildExpectations(Action defaultAction, ExpectationCollector collector) { |
jmock-developers/jmock-library | jmock-junit5/src/test/java/org/jmock/junit5/acceptance/JUnit5TestRunnerTests.java | // Path: jmock-junit5/src/test/java/org/jmock/junit5/testdata/jmock/acceptance/JUnit5TestThatAutoInstantiatesMocks.java
// public class JUnit5TestThatAutoInstantiatesMocks extends BaseClassWithMockery {
// @Mock Runnable runnable;
// @Auto States states;
// @Auto Sequence sequence;
//
// @Test
// public void fieldsHaveBeenAutoInstantiated() {
// assertThat(runnable, notNullValue());
// assertThat(states, notNullValue());
// assertThat(sequence, notNullValue());
// }
// }
//
// Path: jmock-junit5/src/test/java/org/jmock/junit5/testdata/jmock/acceptance/JUnit5TestThatDoesNotCreateAMockery.java
// @ExtendWith(JUnit5Mockery.class)
// public class JUnit5TestThatDoesNotCreateAMockery {
// @RegisterExtension
// JUnit5Mockery context = null;
//
// @Test
// public void happy() {
// // a-ok!
// }
// }
//
// Path: jmock-junit5/src/test/java/org/jmock/junit5/testdata/jmock/acceptance/JUnit5TestThatDoesSatisfyExpectations.java
// public class JUnit5TestThatDoesSatisfyExpectations {
//
// @RegisterExtension
// JUnit5Mockery context = new JUnit5Mockery();
//
// @Mock
// private Runnable runnable;
//
// @Test
// public void doesSatisfyExpectations() {
// context.checking(new Expectations() {{
// oneOf (runnable).run();
// }});
//
// runnable.run();
// }
// }
//
// Path: jmock-junit5/src/test/java/org/jmock/junit5/testdata/jmock/acceptance/JUnit5TestThatThrowsExpectedException.java
// @ExtendWith(ExpectationExtension.class)
// public class JUnit5TestThatThrowsExpectedException {
// @RegisterExtension
// JUnit5Mockery context = new JUnit5Mockery();
// private WithException withException = context.mock(WithException.class);
//
// @Test
// @ExpectationThrows(expected=CheckedException.class)
// public void doesNotSatisfyExpectationsWhenExpectedExceptionIsThrown() throws CheckedException {
// context.checking(new Expectations() {{
// oneOf (withException).anotherMethod();
// oneOf (withException).throwingMethod(); will(throwException(new CheckedException()));
// }});
//
// withException.throwingMethod();
// }
//
// public static class CheckedException extends Exception {
// }
//
// public interface WithException {
// void throwingMethod() throws CheckedException;
// void anotherMethod();
// }
// }
| import org.jmock.junit5.testdata.jmock.acceptance.DerivedJUnit5TestThatDoesNotSatisfyExpectations;
import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatAutoInstantiatesMocks;
import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatCreatesNoMockery;
import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatCreatesTwoMockeries;
import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatDoesNotCreateAMockery;
import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatDoesNotSatisfyExpectations;
import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatDoesSatisfyExpectations;
import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatThrowsExpectedException;
import org.junit.jupiter.api.Test; | package org.jmock.junit5.acceptance;
/**
* Wrap, running "testdata" testcases. Some of which are supposed to fail
* @author oliverbye
*
*/
public class JUnit5TestRunnerTests {
FailureRecordingTestExecutionListener listener = new FailureRecordingTestExecutionListener();
@Test
public void testTheJUnit5TestRunnerReportsPassingTestsAsSuccessful() { | // Path: jmock-junit5/src/test/java/org/jmock/junit5/testdata/jmock/acceptance/JUnit5TestThatAutoInstantiatesMocks.java
// public class JUnit5TestThatAutoInstantiatesMocks extends BaseClassWithMockery {
// @Mock Runnable runnable;
// @Auto States states;
// @Auto Sequence sequence;
//
// @Test
// public void fieldsHaveBeenAutoInstantiated() {
// assertThat(runnable, notNullValue());
// assertThat(states, notNullValue());
// assertThat(sequence, notNullValue());
// }
// }
//
// Path: jmock-junit5/src/test/java/org/jmock/junit5/testdata/jmock/acceptance/JUnit5TestThatDoesNotCreateAMockery.java
// @ExtendWith(JUnit5Mockery.class)
// public class JUnit5TestThatDoesNotCreateAMockery {
// @RegisterExtension
// JUnit5Mockery context = null;
//
// @Test
// public void happy() {
// // a-ok!
// }
// }
//
// Path: jmock-junit5/src/test/java/org/jmock/junit5/testdata/jmock/acceptance/JUnit5TestThatDoesSatisfyExpectations.java
// public class JUnit5TestThatDoesSatisfyExpectations {
//
// @RegisterExtension
// JUnit5Mockery context = new JUnit5Mockery();
//
// @Mock
// private Runnable runnable;
//
// @Test
// public void doesSatisfyExpectations() {
// context.checking(new Expectations() {{
// oneOf (runnable).run();
// }});
//
// runnable.run();
// }
// }
//
// Path: jmock-junit5/src/test/java/org/jmock/junit5/testdata/jmock/acceptance/JUnit5TestThatThrowsExpectedException.java
// @ExtendWith(ExpectationExtension.class)
// public class JUnit5TestThatThrowsExpectedException {
// @RegisterExtension
// JUnit5Mockery context = new JUnit5Mockery();
// private WithException withException = context.mock(WithException.class);
//
// @Test
// @ExpectationThrows(expected=CheckedException.class)
// public void doesNotSatisfyExpectationsWhenExpectedExceptionIsThrown() throws CheckedException {
// context.checking(new Expectations() {{
// oneOf (withException).anotherMethod();
// oneOf (withException).throwingMethod(); will(throwException(new CheckedException()));
// }});
//
// withException.throwingMethod();
// }
//
// public static class CheckedException extends Exception {
// }
//
// public interface WithException {
// void throwingMethod() throws CheckedException;
// void anotherMethod();
// }
// }
// Path: jmock-junit5/src/test/java/org/jmock/junit5/acceptance/JUnit5TestRunnerTests.java
import org.jmock.junit5.testdata.jmock.acceptance.DerivedJUnit5TestThatDoesNotSatisfyExpectations;
import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatAutoInstantiatesMocks;
import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatCreatesNoMockery;
import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatCreatesTwoMockeries;
import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatDoesNotCreateAMockery;
import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatDoesNotSatisfyExpectations;
import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatDoesSatisfyExpectations;
import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatThrowsExpectedException;
import org.junit.jupiter.api.Test;
package org.jmock.junit5.acceptance;
/**
* Wrap, running "testdata" testcases. Some of which are supposed to fail
* @author oliverbye
*
*/
public class JUnit5TestRunnerTests {
FailureRecordingTestExecutionListener listener = new FailureRecordingTestExecutionListener();
@Test
public void testTheJUnit5TestRunnerReportsPassingTestsAsSuccessful() { | listener.runTestIn(JUnit5TestThatDoesSatisfyExpectations.class); |
jmock-developers/jmock-library | jmock-junit5/src/test/java/org/jmock/junit5/acceptance/JUnit5TestRunnerTests.java | // Path: jmock-junit5/src/test/java/org/jmock/junit5/testdata/jmock/acceptance/JUnit5TestThatAutoInstantiatesMocks.java
// public class JUnit5TestThatAutoInstantiatesMocks extends BaseClassWithMockery {
// @Mock Runnable runnable;
// @Auto States states;
// @Auto Sequence sequence;
//
// @Test
// public void fieldsHaveBeenAutoInstantiated() {
// assertThat(runnable, notNullValue());
// assertThat(states, notNullValue());
// assertThat(sequence, notNullValue());
// }
// }
//
// Path: jmock-junit5/src/test/java/org/jmock/junit5/testdata/jmock/acceptance/JUnit5TestThatDoesNotCreateAMockery.java
// @ExtendWith(JUnit5Mockery.class)
// public class JUnit5TestThatDoesNotCreateAMockery {
// @RegisterExtension
// JUnit5Mockery context = null;
//
// @Test
// public void happy() {
// // a-ok!
// }
// }
//
// Path: jmock-junit5/src/test/java/org/jmock/junit5/testdata/jmock/acceptance/JUnit5TestThatDoesSatisfyExpectations.java
// public class JUnit5TestThatDoesSatisfyExpectations {
//
// @RegisterExtension
// JUnit5Mockery context = new JUnit5Mockery();
//
// @Mock
// private Runnable runnable;
//
// @Test
// public void doesSatisfyExpectations() {
// context.checking(new Expectations() {{
// oneOf (runnable).run();
// }});
//
// runnable.run();
// }
// }
//
// Path: jmock-junit5/src/test/java/org/jmock/junit5/testdata/jmock/acceptance/JUnit5TestThatThrowsExpectedException.java
// @ExtendWith(ExpectationExtension.class)
// public class JUnit5TestThatThrowsExpectedException {
// @RegisterExtension
// JUnit5Mockery context = new JUnit5Mockery();
// private WithException withException = context.mock(WithException.class);
//
// @Test
// @ExpectationThrows(expected=CheckedException.class)
// public void doesNotSatisfyExpectationsWhenExpectedExceptionIsThrown() throws CheckedException {
// context.checking(new Expectations() {{
// oneOf (withException).anotherMethod();
// oneOf (withException).throwingMethod(); will(throwException(new CheckedException()));
// }});
//
// withException.throwingMethod();
// }
//
// public static class CheckedException extends Exception {
// }
//
// public interface WithException {
// void throwingMethod() throws CheckedException;
// void anotherMethod();
// }
// }
| import org.jmock.junit5.testdata.jmock.acceptance.DerivedJUnit5TestThatDoesNotSatisfyExpectations;
import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatAutoInstantiatesMocks;
import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatCreatesNoMockery;
import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatCreatesTwoMockeries;
import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatDoesNotCreateAMockery;
import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatDoesNotSatisfyExpectations;
import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatDoesSatisfyExpectations;
import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatThrowsExpectedException;
import org.junit.jupiter.api.Test; | package org.jmock.junit5.acceptance;
/**
* Wrap, running "testdata" testcases. Some of which are supposed to fail
* @author oliverbye
*
*/
public class JUnit5TestRunnerTests {
FailureRecordingTestExecutionListener listener = new FailureRecordingTestExecutionListener();
@Test
public void testTheJUnit5TestRunnerReportsPassingTestsAsSuccessful() {
listener.runTestIn(JUnit5TestThatDoesSatisfyExpectations.class);
listener.assertTestSucceeded();
}
@Test
public void testTheJUnit5TestRunnerAutomaticallyAssertsThatAllExpectationsHaveBeenSatisfied() {
listener.runTestIn(JUnit5TestThatDoesNotSatisfyExpectations.class);
listener.assertTestFailedWith(AssertionError.class);
}
@Test
public void testTheJUnit5TestRunnerLooksForTheMockeryInBaseClasses() {
listener.runTestIn(DerivedJUnit5TestThatDoesNotSatisfyExpectations.class);
listener.assertTestFailedWith(AssertionError.class);
}
@Test
public void testTheJUnit5TestRunnerReportsAHelpfulErrorIfTheMockeryIsNull() { | // Path: jmock-junit5/src/test/java/org/jmock/junit5/testdata/jmock/acceptance/JUnit5TestThatAutoInstantiatesMocks.java
// public class JUnit5TestThatAutoInstantiatesMocks extends BaseClassWithMockery {
// @Mock Runnable runnable;
// @Auto States states;
// @Auto Sequence sequence;
//
// @Test
// public void fieldsHaveBeenAutoInstantiated() {
// assertThat(runnable, notNullValue());
// assertThat(states, notNullValue());
// assertThat(sequence, notNullValue());
// }
// }
//
// Path: jmock-junit5/src/test/java/org/jmock/junit5/testdata/jmock/acceptance/JUnit5TestThatDoesNotCreateAMockery.java
// @ExtendWith(JUnit5Mockery.class)
// public class JUnit5TestThatDoesNotCreateAMockery {
// @RegisterExtension
// JUnit5Mockery context = null;
//
// @Test
// public void happy() {
// // a-ok!
// }
// }
//
// Path: jmock-junit5/src/test/java/org/jmock/junit5/testdata/jmock/acceptance/JUnit5TestThatDoesSatisfyExpectations.java
// public class JUnit5TestThatDoesSatisfyExpectations {
//
// @RegisterExtension
// JUnit5Mockery context = new JUnit5Mockery();
//
// @Mock
// private Runnable runnable;
//
// @Test
// public void doesSatisfyExpectations() {
// context.checking(new Expectations() {{
// oneOf (runnable).run();
// }});
//
// runnable.run();
// }
// }
//
// Path: jmock-junit5/src/test/java/org/jmock/junit5/testdata/jmock/acceptance/JUnit5TestThatThrowsExpectedException.java
// @ExtendWith(ExpectationExtension.class)
// public class JUnit5TestThatThrowsExpectedException {
// @RegisterExtension
// JUnit5Mockery context = new JUnit5Mockery();
// private WithException withException = context.mock(WithException.class);
//
// @Test
// @ExpectationThrows(expected=CheckedException.class)
// public void doesNotSatisfyExpectationsWhenExpectedExceptionIsThrown() throws CheckedException {
// context.checking(new Expectations() {{
// oneOf (withException).anotherMethod();
// oneOf (withException).throwingMethod(); will(throwException(new CheckedException()));
// }});
//
// withException.throwingMethod();
// }
//
// public static class CheckedException extends Exception {
// }
//
// public interface WithException {
// void throwingMethod() throws CheckedException;
// void anotherMethod();
// }
// }
// Path: jmock-junit5/src/test/java/org/jmock/junit5/acceptance/JUnit5TestRunnerTests.java
import org.jmock.junit5.testdata.jmock.acceptance.DerivedJUnit5TestThatDoesNotSatisfyExpectations;
import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatAutoInstantiatesMocks;
import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatCreatesNoMockery;
import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatCreatesTwoMockeries;
import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatDoesNotCreateAMockery;
import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatDoesNotSatisfyExpectations;
import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatDoesSatisfyExpectations;
import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatThrowsExpectedException;
import org.junit.jupiter.api.Test;
package org.jmock.junit5.acceptance;
/**
* Wrap, running "testdata" testcases. Some of which are supposed to fail
* @author oliverbye
*
*/
public class JUnit5TestRunnerTests {
FailureRecordingTestExecutionListener listener = new FailureRecordingTestExecutionListener();
@Test
public void testTheJUnit5TestRunnerReportsPassingTestsAsSuccessful() {
listener.runTestIn(JUnit5TestThatDoesSatisfyExpectations.class);
listener.assertTestSucceeded();
}
@Test
public void testTheJUnit5TestRunnerAutomaticallyAssertsThatAllExpectationsHaveBeenSatisfied() {
listener.runTestIn(JUnit5TestThatDoesNotSatisfyExpectations.class);
listener.assertTestFailedWith(AssertionError.class);
}
@Test
public void testTheJUnit5TestRunnerLooksForTheMockeryInBaseClasses() {
listener.runTestIn(DerivedJUnit5TestThatDoesNotSatisfyExpectations.class);
listener.assertTestFailedWith(AssertionError.class);
}
@Test
public void testTheJUnit5TestRunnerReportsAHelpfulErrorIfTheMockeryIsNull() { | listener.runTestIn(JUnit5TestThatDoesNotCreateAMockery.class); |
jmock-developers/jmock-library | jmock-junit5/src/test/java/org/jmock/junit5/acceptance/JUnit5TestRunnerTests.java | // Path: jmock-junit5/src/test/java/org/jmock/junit5/testdata/jmock/acceptance/JUnit5TestThatAutoInstantiatesMocks.java
// public class JUnit5TestThatAutoInstantiatesMocks extends BaseClassWithMockery {
// @Mock Runnable runnable;
// @Auto States states;
// @Auto Sequence sequence;
//
// @Test
// public void fieldsHaveBeenAutoInstantiated() {
// assertThat(runnable, notNullValue());
// assertThat(states, notNullValue());
// assertThat(sequence, notNullValue());
// }
// }
//
// Path: jmock-junit5/src/test/java/org/jmock/junit5/testdata/jmock/acceptance/JUnit5TestThatDoesNotCreateAMockery.java
// @ExtendWith(JUnit5Mockery.class)
// public class JUnit5TestThatDoesNotCreateAMockery {
// @RegisterExtension
// JUnit5Mockery context = null;
//
// @Test
// public void happy() {
// // a-ok!
// }
// }
//
// Path: jmock-junit5/src/test/java/org/jmock/junit5/testdata/jmock/acceptance/JUnit5TestThatDoesSatisfyExpectations.java
// public class JUnit5TestThatDoesSatisfyExpectations {
//
// @RegisterExtension
// JUnit5Mockery context = new JUnit5Mockery();
//
// @Mock
// private Runnable runnable;
//
// @Test
// public void doesSatisfyExpectations() {
// context.checking(new Expectations() {{
// oneOf (runnable).run();
// }});
//
// runnable.run();
// }
// }
//
// Path: jmock-junit5/src/test/java/org/jmock/junit5/testdata/jmock/acceptance/JUnit5TestThatThrowsExpectedException.java
// @ExtendWith(ExpectationExtension.class)
// public class JUnit5TestThatThrowsExpectedException {
// @RegisterExtension
// JUnit5Mockery context = new JUnit5Mockery();
// private WithException withException = context.mock(WithException.class);
//
// @Test
// @ExpectationThrows(expected=CheckedException.class)
// public void doesNotSatisfyExpectationsWhenExpectedExceptionIsThrown() throws CheckedException {
// context.checking(new Expectations() {{
// oneOf (withException).anotherMethod();
// oneOf (withException).throwingMethod(); will(throwException(new CheckedException()));
// }});
//
// withException.throwingMethod();
// }
//
// public static class CheckedException extends Exception {
// }
//
// public interface WithException {
// void throwingMethod() throws CheckedException;
// void anotherMethod();
// }
// }
| import org.jmock.junit5.testdata.jmock.acceptance.DerivedJUnit5TestThatDoesNotSatisfyExpectations;
import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatAutoInstantiatesMocks;
import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatCreatesNoMockery;
import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatCreatesTwoMockeries;
import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatDoesNotCreateAMockery;
import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatDoesNotSatisfyExpectations;
import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatDoesSatisfyExpectations;
import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatThrowsExpectedException;
import org.junit.jupiter.api.Test; | package org.jmock.junit5.acceptance;
/**
* Wrap, running "testdata" testcases. Some of which are supposed to fail
* @author oliverbye
*
*/
public class JUnit5TestRunnerTests {
FailureRecordingTestExecutionListener listener = new FailureRecordingTestExecutionListener();
@Test
public void testTheJUnit5TestRunnerReportsPassingTestsAsSuccessful() {
listener.runTestIn(JUnit5TestThatDoesSatisfyExpectations.class);
listener.assertTestSucceeded();
}
@Test
public void testTheJUnit5TestRunnerAutomaticallyAssertsThatAllExpectationsHaveBeenSatisfied() {
listener.runTestIn(JUnit5TestThatDoesNotSatisfyExpectations.class);
listener.assertTestFailedWith(AssertionError.class);
}
@Test
public void testTheJUnit5TestRunnerLooksForTheMockeryInBaseClasses() {
listener.runTestIn(DerivedJUnit5TestThatDoesNotSatisfyExpectations.class);
listener.assertTestFailedWith(AssertionError.class);
}
@Test
public void testTheJUnit5TestRunnerReportsAHelpfulErrorIfTheMockeryIsNull() {
listener.runTestIn(JUnit5TestThatDoesNotCreateAMockery.class);
listener.assertTestFailedWith(org.junit.platform.commons.util.PreconditionViolationException.class);
}
// See issue JMOCK-156
@Test
public void testReportsMocksAreNotSatisfiedWhenExpectedExceptionIsThrown() { | // Path: jmock-junit5/src/test/java/org/jmock/junit5/testdata/jmock/acceptance/JUnit5TestThatAutoInstantiatesMocks.java
// public class JUnit5TestThatAutoInstantiatesMocks extends BaseClassWithMockery {
// @Mock Runnable runnable;
// @Auto States states;
// @Auto Sequence sequence;
//
// @Test
// public void fieldsHaveBeenAutoInstantiated() {
// assertThat(runnable, notNullValue());
// assertThat(states, notNullValue());
// assertThat(sequence, notNullValue());
// }
// }
//
// Path: jmock-junit5/src/test/java/org/jmock/junit5/testdata/jmock/acceptance/JUnit5TestThatDoesNotCreateAMockery.java
// @ExtendWith(JUnit5Mockery.class)
// public class JUnit5TestThatDoesNotCreateAMockery {
// @RegisterExtension
// JUnit5Mockery context = null;
//
// @Test
// public void happy() {
// // a-ok!
// }
// }
//
// Path: jmock-junit5/src/test/java/org/jmock/junit5/testdata/jmock/acceptance/JUnit5TestThatDoesSatisfyExpectations.java
// public class JUnit5TestThatDoesSatisfyExpectations {
//
// @RegisterExtension
// JUnit5Mockery context = new JUnit5Mockery();
//
// @Mock
// private Runnable runnable;
//
// @Test
// public void doesSatisfyExpectations() {
// context.checking(new Expectations() {{
// oneOf (runnable).run();
// }});
//
// runnable.run();
// }
// }
//
// Path: jmock-junit5/src/test/java/org/jmock/junit5/testdata/jmock/acceptance/JUnit5TestThatThrowsExpectedException.java
// @ExtendWith(ExpectationExtension.class)
// public class JUnit5TestThatThrowsExpectedException {
// @RegisterExtension
// JUnit5Mockery context = new JUnit5Mockery();
// private WithException withException = context.mock(WithException.class);
//
// @Test
// @ExpectationThrows(expected=CheckedException.class)
// public void doesNotSatisfyExpectationsWhenExpectedExceptionIsThrown() throws CheckedException {
// context.checking(new Expectations() {{
// oneOf (withException).anotherMethod();
// oneOf (withException).throwingMethod(); will(throwException(new CheckedException()));
// }});
//
// withException.throwingMethod();
// }
//
// public static class CheckedException extends Exception {
// }
//
// public interface WithException {
// void throwingMethod() throws CheckedException;
// void anotherMethod();
// }
// }
// Path: jmock-junit5/src/test/java/org/jmock/junit5/acceptance/JUnit5TestRunnerTests.java
import org.jmock.junit5.testdata.jmock.acceptance.DerivedJUnit5TestThatDoesNotSatisfyExpectations;
import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatAutoInstantiatesMocks;
import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatCreatesNoMockery;
import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatCreatesTwoMockeries;
import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatDoesNotCreateAMockery;
import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatDoesNotSatisfyExpectations;
import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatDoesSatisfyExpectations;
import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatThrowsExpectedException;
import org.junit.jupiter.api.Test;
package org.jmock.junit5.acceptance;
/**
* Wrap, running "testdata" testcases. Some of which are supposed to fail
* @author oliverbye
*
*/
public class JUnit5TestRunnerTests {
FailureRecordingTestExecutionListener listener = new FailureRecordingTestExecutionListener();
@Test
public void testTheJUnit5TestRunnerReportsPassingTestsAsSuccessful() {
listener.runTestIn(JUnit5TestThatDoesSatisfyExpectations.class);
listener.assertTestSucceeded();
}
@Test
public void testTheJUnit5TestRunnerAutomaticallyAssertsThatAllExpectationsHaveBeenSatisfied() {
listener.runTestIn(JUnit5TestThatDoesNotSatisfyExpectations.class);
listener.assertTestFailedWith(AssertionError.class);
}
@Test
public void testTheJUnit5TestRunnerLooksForTheMockeryInBaseClasses() {
listener.runTestIn(DerivedJUnit5TestThatDoesNotSatisfyExpectations.class);
listener.assertTestFailedWith(AssertionError.class);
}
@Test
public void testTheJUnit5TestRunnerReportsAHelpfulErrorIfTheMockeryIsNull() {
listener.runTestIn(JUnit5TestThatDoesNotCreateAMockery.class);
listener.assertTestFailedWith(org.junit.platform.commons.util.PreconditionViolationException.class);
}
// See issue JMOCK-156
@Test
public void testReportsMocksAreNotSatisfiedWhenExpectedExceptionIsThrown() { | listener.runTestIn(JUnit5TestThatThrowsExpectedException.class); |
jmock-developers/jmock-library | jmock-junit5/src/test/java/org/jmock/junit5/acceptance/JUnit5TestRunnerTests.java | // Path: jmock-junit5/src/test/java/org/jmock/junit5/testdata/jmock/acceptance/JUnit5TestThatAutoInstantiatesMocks.java
// public class JUnit5TestThatAutoInstantiatesMocks extends BaseClassWithMockery {
// @Mock Runnable runnable;
// @Auto States states;
// @Auto Sequence sequence;
//
// @Test
// public void fieldsHaveBeenAutoInstantiated() {
// assertThat(runnable, notNullValue());
// assertThat(states, notNullValue());
// assertThat(sequence, notNullValue());
// }
// }
//
// Path: jmock-junit5/src/test/java/org/jmock/junit5/testdata/jmock/acceptance/JUnit5TestThatDoesNotCreateAMockery.java
// @ExtendWith(JUnit5Mockery.class)
// public class JUnit5TestThatDoesNotCreateAMockery {
// @RegisterExtension
// JUnit5Mockery context = null;
//
// @Test
// public void happy() {
// // a-ok!
// }
// }
//
// Path: jmock-junit5/src/test/java/org/jmock/junit5/testdata/jmock/acceptance/JUnit5TestThatDoesSatisfyExpectations.java
// public class JUnit5TestThatDoesSatisfyExpectations {
//
// @RegisterExtension
// JUnit5Mockery context = new JUnit5Mockery();
//
// @Mock
// private Runnable runnable;
//
// @Test
// public void doesSatisfyExpectations() {
// context.checking(new Expectations() {{
// oneOf (runnable).run();
// }});
//
// runnable.run();
// }
// }
//
// Path: jmock-junit5/src/test/java/org/jmock/junit5/testdata/jmock/acceptance/JUnit5TestThatThrowsExpectedException.java
// @ExtendWith(ExpectationExtension.class)
// public class JUnit5TestThatThrowsExpectedException {
// @RegisterExtension
// JUnit5Mockery context = new JUnit5Mockery();
// private WithException withException = context.mock(WithException.class);
//
// @Test
// @ExpectationThrows(expected=CheckedException.class)
// public void doesNotSatisfyExpectationsWhenExpectedExceptionIsThrown() throws CheckedException {
// context.checking(new Expectations() {{
// oneOf (withException).anotherMethod();
// oneOf (withException).throwingMethod(); will(throwException(new CheckedException()));
// }});
//
// withException.throwingMethod();
// }
//
// public static class CheckedException extends Exception {
// }
//
// public interface WithException {
// void throwingMethod() throws CheckedException;
// void anotherMethod();
// }
// }
| import org.jmock.junit5.testdata.jmock.acceptance.DerivedJUnit5TestThatDoesNotSatisfyExpectations;
import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatAutoInstantiatesMocks;
import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatCreatesNoMockery;
import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatCreatesTwoMockeries;
import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatDoesNotCreateAMockery;
import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatDoesNotSatisfyExpectations;
import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatDoesSatisfyExpectations;
import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatThrowsExpectedException;
import org.junit.jupiter.api.Test; |
@Test
public void testTheJUnit5TestRunnerReportsAHelpfulErrorIfTheMockeryIsNull() {
listener.runTestIn(JUnit5TestThatDoesNotCreateAMockery.class);
listener.assertTestFailedWith(org.junit.platform.commons.util.PreconditionViolationException.class);
}
// See issue JMOCK-156
@Test
public void testReportsMocksAreNotSatisfiedWhenExpectedExceptionIsThrown() {
listener.runTestIn(JUnit5TestThatThrowsExpectedException.class);
listener.assertTestFailedWith(AssertionError.class);
}
// See issue JMOCK-219
@Test
public void testTheJUnit5TestRunnerReportsIfNoMockeryIsFound() {
listener.runTestIn(JUnit5TestThatCreatesNoMockery.class);
listener.assertTestFailedWithInitializationError();
}
// See issue JMOCK-219
@Test
public void testTheJUnit4TestRunnerReportsIfMoreThanOneMockeryIsFound() {
listener.runTestIn(JUnit5TestThatCreatesTwoMockeries.class);
listener.assertTestFailedWithInitializationError();
}
@Test
public void testAutoInstantiatesMocks() { | // Path: jmock-junit5/src/test/java/org/jmock/junit5/testdata/jmock/acceptance/JUnit5TestThatAutoInstantiatesMocks.java
// public class JUnit5TestThatAutoInstantiatesMocks extends BaseClassWithMockery {
// @Mock Runnable runnable;
// @Auto States states;
// @Auto Sequence sequence;
//
// @Test
// public void fieldsHaveBeenAutoInstantiated() {
// assertThat(runnable, notNullValue());
// assertThat(states, notNullValue());
// assertThat(sequence, notNullValue());
// }
// }
//
// Path: jmock-junit5/src/test/java/org/jmock/junit5/testdata/jmock/acceptance/JUnit5TestThatDoesNotCreateAMockery.java
// @ExtendWith(JUnit5Mockery.class)
// public class JUnit5TestThatDoesNotCreateAMockery {
// @RegisterExtension
// JUnit5Mockery context = null;
//
// @Test
// public void happy() {
// // a-ok!
// }
// }
//
// Path: jmock-junit5/src/test/java/org/jmock/junit5/testdata/jmock/acceptance/JUnit5TestThatDoesSatisfyExpectations.java
// public class JUnit5TestThatDoesSatisfyExpectations {
//
// @RegisterExtension
// JUnit5Mockery context = new JUnit5Mockery();
//
// @Mock
// private Runnable runnable;
//
// @Test
// public void doesSatisfyExpectations() {
// context.checking(new Expectations() {{
// oneOf (runnable).run();
// }});
//
// runnable.run();
// }
// }
//
// Path: jmock-junit5/src/test/java/org/jmock/junit5/testdata/jmock/acceptance/JUnit5TestThatThrowsExpectedException.java
// @ExtendWith(ExpectationExtension.class)
// public class JUnit5TestThatThrowsExpectedException {
// @RegisterExtension
// JUnit5Mockery context = new JUnit5Mockery();
// private WithException withException = context.mock(WithException.class);
//
// @Test
// @ExpectationThrows(expected=CheckedException.class)
// public void doesNotSatisfyExpectationsWhenExpectedExceptionIsThrown() throws CheckedException {
// context.checking(new Expectations() {{
// oneOf (withException).anotherMethod();
// oneOf (withException).throwingMethod(); will(throwException(new CheckedException()));
// }});
//
// withException.throwingMethod();
// }
//
// public static class CheckedException extends Exception {
// }
//
// public interface WithException {
// void throwingMethod() throws CheckedException;
// void anotherMethod();
// }
// }
// Path: jmock-junit5/src/test/java/org/jmock/junit5/acceptance/JUnit5TestRunnerTests.java
import org.jmock.junit5.testdata.jmock.acceptance.DerivedJUnit5TestThatDoesNotSatisfyExpectations;
import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatAutoInstantiatesMocks;
import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatCreatesNoMockery;
import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatCreatesTwoMockeries;
import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatDoesNotCreateAMockery;
import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatDoesNotSatisfyExpectations;
import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatDoesSatisfyExpectations;
import org.jmock.junit5.testdata.jmock.acceptance.JUnit5TestThatThrowsExpectedException;
import org.junit.jupiter.api.Test;
@Test
public void testTheJUnit5TestRunnerReportsAHelpfulErrorIfTheMockeryIsNull() {
listener.runTestIn(JUnit5TestThatDoesNotCreateAMockery.class);
listener.assertTestFailedWith(org.junit.platform.commons.util.PreconditionViolationException.class);
}
// See issue JMOCK-156
@Test
public void testReportsMocksAreNotSatisfiedWhenExpectedExceptionIsThrown() {
listener.runTestIn(JUnit5TestThatThrowsExpectedException.class);
listener.assertTestFailedWith(AssertionError.class);
}
// See issue JMOCK-219
@Test
public void testTheJUnit5TestRunnerReportsIfNoMockeryIsFound() {
listener.runTestIn(JUnit5TestThatCreatesNoMockery.class);
listener.assertTestFailedWithInitializationError();
}
// See issue JMOCK-219
@Test
public void testTheJUnit4TestRunnerReportsIfMoreThanOneMockeryIsFound() {
listener.runTestIn(JUnit5TestThatCreatesTwoMockeries.class);
listener.assertTestFailedWithInitializationError();
}
@Test
public void testAutoInstantiatesMocks() { | listener.runTestIn(JUnit5TestThatAutoInstantiatesMocks.class); |
jmock-developers/jmock-library | jmock-imposters-tests/src/test/java/org/jmock/test/acceptance/InvocationDescriptionAcceptanceTests.java | // Path: jmock-junit4/src/main/java/org/jmock/integration/junit4/JUnit4Mockery.java
// public class JUnit4Mockery extends Mockery {
// public JUnit4Mockery() {
// setExpectationErrorTranslator(AssertionErrorTranslator.INSTANCE);
// }
// }
//
// Path: jmock-imposters-tests/src/test/java/org/jmock/test/unit/lib/legacy/ImposteriserParameterResolver.java
// public class ImposteriserParameterResolver extends AbstractImposteriserParameterResolver {
//
// public ImposteriserParameterResolver() {
// super(ByteBuddyClassImposteriser.INSTANCE,
// ClassImposteriser.INSTANCE,
// JavaReflectionImposteriser.INSTANCE);
// }
//
// }
| import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import org.jmock.Expectations;
import org.jmock.api.Imposteriser;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.jmock.test.unit.lib.legacy.ImposteriserParameterResolver;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ArgumentsSource; | package org.jmock.test.acceptance;
/**
* @author Steve Freeman 2012 http://www.jmock.org
*/
public class InvocationDescriptionAcceptanceTests {
private static final String UNEXPECTED_ARGUMENT = "unexpected argument"; | // Path: jmock-junit4/src/main/java/org/jmock/integration/junit4/JUnit4Mockery.java
// public class JUnit4Mockery extends Mockery {
// public JUnit4Mockery() {
// setExpectationErrorTranslator(AssertionErrorTranslator.INSTANCE);
// }
// }
//
// Path: jmock-imposters-tests/src/test/java/org/jmock/test/unit/lib/legacy/ImposteriserParameterResolver.java
// public class ImposteriserParameterResolver extends AbstractImposteriserParameterResolver {
//
// public ImposteriserParameterResolver() {
// super(ByteBuddyClassImposteriser.INSTANCE,
// ClassImposteriser.INSTANCE,
// JavaReflectionImposteriser.INSTANCE);
// }
//
// }
// Path: jmock-imposters-tests/src/test/java/org/jmock/test/acceptance/InvocationDescriptionAcceptanceTests.java
import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import org.jmock.Expectations;
import org.jmock.api.Imposteriser;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.jmock.test.unit.lib.legacy.ImposteriserParameterResolver;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ArgumentsSource;
package org.jmock.test.acceptance;
/**
* @author Steve Freeman 2012 http://www.jmock.org
*/
public class InvocationDescriptionAcceptanceTests {
private static final String UNEXPECTED_ARGUMENT = "unexpected argument"; | private final JUnit4Mockery aMockContext = new JUnit4Mockery(); |
jmock-developers/jmock-library | jmock-imposters-tests/src/test/java/org/jmock/test/acceptance/InvocationDescriptionAcceptanceTests.java | // Path: jmock-junit4/src/main/java/org/jmock/integration/junit4/JUnit4Mockery.java
// public class JUnit4Mockery extends Mockery {
// public JUnit4Mockery() {
// setExpectationErrorTranslator(AssertionErrorTranslator.INSTANCE);
// }
// }
//
// Path: jmock-imposters-tests/src/test/java/org/jmock/test/unit/lib/legacy/ImposteriserParameterResolver.java
// public class ImposteriserParameterResolver extends AbstractImposteriserParameterResolver {
//
// public ImposteriserParameterResolver() {
// super(ByteBuddyClassImposteriser.INSTANCE,
// ClassImposteriser.INSTANCE,
// JavaReflectionImposteriser.INSTANCE);
// }
//
// }
| import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import org.jmock.Expectations;
import org.jmock.api.Imposteriser;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.jmock.test.unit.lib.legacy.ImposteriserParameterResolver;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ArgumentsSource; | package org.jmock.test.acceptance;
/**
* @author Steve Freeman 2012 http://www.jmock.org
*/
public class InvocationDescriptionAcceptanceTests {
private static final String UNEXPECTED_ARGUMENT = "unexpected argument";
private final JUnit4Mockery aMockContext = new JUnit4Mockery();
private final SubBean aSubBean = aMockContext.mock(SubBean.class);
private final Collaborator aCollab = aMockContext.mock(Collaborator.class);
// https://github.com/jmock-developers/jmock-library/issues/20
@ParameterizedTest | // Path: jmock-junit4/src/main/java/org/jmock/integration/junit4/JUnit4Mockery.java
// public class JUnit4Mockery extends Mockery {
// public JUnit4Mockery() {
// setExpectationErrorTranslator(AssertionErrorTranslator.INSTANCE);
// }
// }
//
// Path: jmock-imposters-tests/src/test/java/org/jmock/test/unit/lib/legacy/ImposteriserParameterResolver.java
// public class ImposteriserParameterResolver extends AbstractImposteriserParameterResolver {
//
// public ImposteriserParameterResolver() {
// super(ByteBuddyClassImposteriser.INSTANCE,
// ClassImposteriser.INSTANCE,
// JavaReflectionImposteriser.INSTANCE);
// }
//
// }
// Path: jmock-imposters-tests/src/test/java/org/jmock/test/acceptance/InvocationDescriptionAcceptanceTests.java
import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import org.jmock.Expectations;
import org.jmock.api.Imposteriser;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.jmock.test.unit.lib.legacy.ImposteriserParameterResolver;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ArgumentsSource;
package org.jmock.test.acceptance;
/**
* @author Steve Freeman 2012 http://www.jmock.org
*/
public class InvocationDescriptionAcceptanceTests {
private static final String UNEXPECTED_ARGUMENT = "unexpected argument";
private final JUnit4Mockery aMockContext = new JUnit4Mockery();
private final SubBean aSubBean = aMockContext.mock(SubBean.class);
private final Collaborator aCollab = aMockContext.mock(Collaborator.class);
// https://github.com/jmock-developers/jmock-library/issues/20
@ParameterizedTest | @ArgumentsSource(ImposteriserParameterResolver.class) |
jmock-developers/jmock-library | jmock-imposters-tests/src/test/java/org/jmock/test/acceptance/RedeclaredObjectMethodsAcceptanceTests.java | // Path: jmock-imposters-tests/src/test/java/org/jmock/test/unit/lib/legacy/ImposteriserParameterResolver.java
// public class ImposteriserParameterResolver extends AbstractImposteriserParameterResolver {
//
// public ImposteriserParameterResolver() {
// super(ByteBuddyClassImposteriser.INSTANCE,
// ClassImposteriser.INSTANCE,
// JavaReflectionImposteriser.INSTANCE);
// }
//
// }
| import static org.junit.Assert.assertEquals;
import java.util.Vector;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.api.ExpectationError;
import org.jmock.api.Imposteriser;
import org.jmock.test.unit.lib.legacy.CodeGeneratingImposteriserParameterResolver;
import org.jmock.test.unit.lib.legacy.ImposteriserParameterResolver;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ArgumentsSource; | package org.jmock.test.acceptance;
// Fixes issue JMOCK-96
public class RedeclaredObjectMethodsAcceptanceTests {
Mockery context = new Mockery();
public interface MockedInterface {
String toString();
}
public static class MockedClass {
@Override
public String toString() {
return "not mocked";
}
}
@ParameterizedTest | // Path: jmock-imposters-tests/src/test/java/org/jmock/test/unit/lib/legacy/ImposteriserParameterResolver.java
// public class ImposteriserParameterResolver extends AbstractImposteriserParameterResolver {
//
// public ImposteriserParameterResolver() {
// super(ByteBuddyClassImposteriser.INSTANCE,
// ClassImposteriser.INSTANCE,
// JavaReflectionImposteriser.INSTANCE);
// }
//
// }
// Path: jmock-imposters-tests/src/test/java/org/jmock/test/acceptance/RedeclaredObjectMethodsAcceptanceTests.java
import static org.junit.Assert.assertEquals;
import java.util.Vector;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.api.ExpectationError;
import org.jmock.api.Imposteriser;
import org.jmock.test.unit.lib.legacy.CodeGeneratingImposteriserParameterResolver;
import org.jmock.test.unit.lib.legacy.ImposteriserParameterResolver;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ArgumentsSource;
package org.jmock.test.acceptance;
// Fixes issue JMOCK-96
public class RedeclaredObjectMethodsAcceptanceTests {
Mockery context = new Mockery();
public interface MockedInterface {
String toString();
}
public static class MockedClass {
@Override
public String toString() {
return "not mocked";
}
}
@ParameterizedTest | @ArgumentsSource(ImposteriserParameterResolver.class) |
jmock-developers/jmock-library | jmock-junit5/src/test/java/org/jmock/junit5/acceptance/JUnit5WithRulesTestRunnerTests.java | // Path: jmock-junit5/src/test/java/org/jmock/junit5/testdata/jmock/acceptance/JUnit5WithRulesExamples.java
// public class JUnit5WithRulesExamples {
// public static class SatisfiesExpectations {
// @RegisterExtension
// public final JUnit5Mockery context = new JUnit5Mockery();
// private final Runnable runnable = context.mock(Runnable.class);
//
// @Test
// public void doesSatisfyExpectations() {
// context.checking(new Expectations() {
// {
// oneOf(runnable).run();
// }
// });
//
// runnable.run();
// }
// }
//
// public static class DoesNotSatisfyExpectations {
// @RegisterExtension
// public final JUnit5Mockery context = new JUnit5Mockery();
// private Runnable runnable = context.mock(Runnable.class);
//
// @Test
// public void doesNotSatisfyExpectations() {
// context.checking(new Expectations() {
// {
// oneOf(runnable).run();
// }
// });
//
// // Return without satisfying the expectation for runnable.run()
// }
// }
//
// public static class DerivedAndDoesNotSatisfyExpectations extends BaseClassWithJMockContext {
// private Runnable runnable = context.mock(Runnable.class);
//
// @Test
// public void doesNotSatisfyExpectations() {
// context.checking(new Expectations() {
// {
// oneOf(runnable).run();
// }
// });
//
// // Return without satisfying the expectation for runnable.run()
// }
// }
//
// @ExtendWith(ExpectationExtension.class)
// public static class ThrowsExpectedException {
// @RegisterExtension
// public final JUnit5Mockery context = new JUnit5Mockery();
// private WithException withException = context.mock(WithException.class);
//
// @Test
// @ExpectationThrows(expected = CheckedException.class)
// public void doesNotSatisfyExpectationsWhenExpectedExceptionIsThrown() throws CheckedException {
// context.checking(new Expectations() {
// {
// oneOf(withException).anotherMethod();
// oneOf(withException).throwingMethod();
// will(throwException(new CheckedException()));
// }
// });
//
// withException.throwingMethod();
// }
//
// @SuppressWarnings("serial")
// public static class CheckedException extends Exception {
// }
//
// public interface WithException {
// void throwingMethod() throws CheckedException;
//
// void anotherMethod();
// }
// }
//
// public static class CreatesTwoMockeries extends BaseClassWithJMockContext {
// @RegisterExtension
// public final JUnit5Mockery context = new JUnit5Mockery();
//
// @Test
// public void doesNothing() {
// // no op
// }
// }
//
// public static class AutoInstantiatesMocks extends BaseClassWithJMockContext {
// @Mock
// Runnable runnable;
// @Auto
// States states;
// @Auto
// Sequence sequence;
//
// @Test
// public void fieldsHaveBeenAutoInstantiated() {
// assertThat("runnable", runnable, notNullValue());
// assertThat("states", states, notNullValue());
// assertThat("sequence", sequence, notNullValue());
// }
// }
//
// public static class BaseClassWithJMockContext {
// @RegisterExtension
// public final JUnit5Mockery context = new JUnit5Mockery();
// }
//
// }
| import org.jmock.junit5.testdata.jmock.acceptance.JUnit5WithRulesExamples;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtensionConfigurationException; | package org.jmock.junit5.acceptance;
public class JUnit5WithRulesTestRunnerTests {
FailureRecordingTestExecutionListener listener = new FailureRecordingTestExecutionListener();
@Test
public void testTheJUnit4TestRunnerReportsPassingTestsAsSuccessful() { | // Path: jmock-junit5/src/test/java/org/jmock/junit5/testdata/jmock/acceptance/JUnit5WithRulesExamples.java
// public class JUnit5WithRulesExamples {
// public static class SatisfiesExpectations {
// @RegisterExtension
// public final JUnit5Mockery context = new JUnit5Mockery();
// private final Runnable runnable = context.mock(Runnable.class);
//
// @Test
// public void doesSatisfyExpectations() {
// context.checking(new Expectations() {
// {
// oneOf(runnable).run();
// }
// });
//
// runnable.run();
// }
// }
//
// public static class DoesNotSatisfyExpectations {
// @RegisterExtension
// public final JUnit5Mockery context = new JUnit5Mockery();
// private Runnable runnable = context.mock(Runnable.class);
//
// @Test
// public void doesNotSatisfyExpectations() {
// context.checking(new Expectations() {
// {
// oneOf(runnable).run();
// }
// });
//
// // Return without satisfying the expectation for runnable.run()
// }
// }
//
// public static class DerivedAndDoesNotSatisfyExpectations extends BaseClassWithJMockContext {
// private Runnable runnable = context.mock(Runnable.class);
//
// @Test
// public void doesNotSatisfyExpectations() {
// context.checking(new Expectations() {
// {
// oneOf(runnable).run();
// }
// });
//
// // Return without satisfying the expectation for runnable.run()
// }
// }
//
// @ExtendWith(ExpectationExtension.class)
// public static class ThrowsExpectedException {
// @RegisterExtension
// public final JUnit5Mockery context = new JUnit5Mockery();
// private WithException withException = context.mock(WithException.class);
//
// @Test
// @ExpectationThrows(expected = CheckedException.class)
// public void doesNotSatisfyExpectationsWhenExpectedExceptionIsThrown() throws CheckedException {
// context.checking(new Expectations() {
// {
// oneOf(withException).anotherMethod();
// oneOf(withException).throwingMethod();
// will(throwException(new CheckedException()));
// }
// });
//
// withException.throwingMethod();
// }
//
// @SuppressWarnings("serial")
// public static class CheckedException extends Exception {
// }
//
// public interface WithException {
// void throwingMethod() throws CheckedException;
//
// void anotherMethod();
// }
// }
//
// public static class CreatesTwoMockeries extends BaseClassWithJMockContext {
// @RegisterExtension
// public final JUnit5Mockery context = new JUnit5Mockery();
//
// @Test
// public void doesNothing() {
// // no op
// }
// }
//
// public static class AutoInstantiatesMocks extends BaseClassWithJMockContext {
// @Mock
// Runnable runnable;
// @Auto
// States states;
// @Auto
// Sequence sequence;
//
// @Test
// public void fieldsHaveBeenAutoInstantiated() {
// assertThat("runnable", runnable, notNullValue());
// assertThat("states", states, notNullValue());
// assertThat("sequence", sequence, notNullValue());
// }
// }
//
// public static class BaseClassWithJMockContext {
// @RegisterExtension
// public final JUnit5Mockery context = new JUnit5Mockery();
// }
//
// }
// Path: jmock-junit5/src/test/java/org/jmock/junit5/acceptance/JUnit5WithRulesTestRunnerTests.java
import org.jmock.junit5.testdata.jmock.acceptance.JUnit5WithRulesExamples;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtensionConfigurationException;
package org.jmock.junit5.acceptance;
public class JUnit5WithRulesTestRunnerTests {
FailureRecordingTestExecutionListener listener = new FailureRecordingTestExecutionListener();
@Test
public void testTheJUnit4TestRunnerReportsPassingTestsAsSuccessful() { | listener.runTestIn(JUnit5WithRulesExamples.SatisfiesExpectations.class); |
jmock-developers/jmock-library | jmock-imposters-tests/src/test/java/org/jmock/test/acceptance/MockeryFinalizationAcceptanceTests.java | // Path: jmock-imposters-tests/src/test/java/org/jmock/test/unit/lib/legacy/ImposteriserParameterResolver.java
// public class ImposteriserParameterResolver extends AbstractImposteriserParameterResolver {
//
// public ImposteriserParameterResolver() {
// super(ByteBuddyClassImposteriser.INSTANCE,
// ClassImposteriser.INSTANCE,
// JavaReflectionImposteriser.INSTANCE);
// }
//
// }
| import static org.hamcrest.Matchers.isEmptyOrNullString;
import static org.junit.Assert.assertThat;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.lang.ref.WeakReference;
import org.jmock.Mockery;
import org.jmock.api.Imposteriser;
import org.jmock.lib.concurrent.Synchroniser;
import org.jmock.test.unit.lib.legacy.CodeGeneratingImposteriserParameterResolver;
import org.jmock.test.unit.lib.legacy.ImposteriserParameterResolver;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ArgumentsSource; | setThreadingPolicy(new Synchroniser());
}};
private final ErrorStream capturingErr = new ErrorStream();
@BeforeAll
public static void clearAnyOutstandingMessages() {
ErrorStream localErr = new ErrorStream();
localErr.install();
String error = null;
try {
finalizeUntilMessageOrCount(localErr, FINALIZE_COUNT);
error = localErr.output();
} finally {
localErr.uninstall();
}
if (error != null)
System.err.println("WARNING - a previous test left output in finalization [" + error + "]");
}
@BeforeEach
public void captureSysErr() {
capturingErr.install();
}
@AfterEach
public void replaceSysErr() {
capturingErr.uninstall();
}
@ParameterizedTest | // Path: jmock-imposters-tests/src/test/java/org/jmock/test/unit/lib/legacy/ImposteriserParameterResolver.java
// public class ImposteriserParameterResolver extends AbstractImposteriserParameterResolver {
//
// public ImposteriserParameterResolver() {
// super(ByteBuddyClassImposteriser.INSTANCE,
// ClassImposteriser.INSTANCE,
// JavaReflectionImposteriser.INSTANCE);
// }
//
// }
// Path: jmock-imposters-tests/src/test/java/org/jmock/test/acceptance/MockeryFinalizationAcceptanceTests.java
import static org.hamcrest.Matchers.isEmptyOrNullString;
import static org.junit.Assert.assertThat;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.lang.ref.WeakReference;
import org.jmock.Mockery;
import org.jmock.api.Imposteriser;
import org.jmock.lib.concurrent.Synchroniser;
import org.jmock.test.unit.lib.legacy.CodeGeneratingImposteriserParameterResolver;
import org.jmock.test.unit.lib.legacy.ImposteriserParameterResolver;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ArgumentsSource;
setThreadingPolicy(new Synchroniser());
}};
private final ErrorStream capturingErr = new ErrorStream();
@BeforeAll
public static void clearAnyOutstandingMessages() {
ErrorStream localErr = new ErrorStream();
localErr.install();
String error = null;
try {
finalizeUntilMessageOrCount(localErr, FINALIZE_COUNT);
error = localErr.output();
} finally {
localErr.uninstall();
}
if (error != null)
System.err.println("WARNING - a previous test left output in finalization [" + error + "]");
}
@BeforeEach
public void captureSysErr() {
capturingErr.install();
}
@AfterEach
public void replaceSysErr() {
capturingErr.uninstall();
}
@ParameterizedTest | @ArgumentsSource(ImposteriserParameterResolver.class) |
lanshiqin/cloud-project | auth-server/src/main/java/com/lanshiqin/authserver/core/security/DomainUserDetailsService.java | // Path: auth-server/src/main/java/com/lanshiqin/authserver/core/entity/Account.java
// public class Account {
// @Id
// private String id; // 主键
// private String userName; // 用户名
// private String passWord; // 密码
// private String[] roles; // 角色
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public String getPassWord() {
// return passWord;
// }
//
// public void setPassWord(String passWord) {
// this.passWord = passWord;
// }
//
// public String[] getRoles() {
// return roles;
// }
//
// public void setRoles(String[] roles) {
// this.roles = roles;
// }
// }
//
// Path: auth-server/src/main/java/com/lanshiqin/authserver/core/repository/AccountRepository.java
// @Component
// public interface AccountRepository extends MongoRepository<Account, String> {
//
// /**
// * 根据用户名查找账户信息
// * @param username 用户名
// * @return 账户信息
// */
// Account findByUserName(String username);
// }
| import com.lanshiqin.authserver.core.entity.Account;
import com.lanshiqin.authserver.core.repository.AccountRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service; | package com.lanshiqin.authserver.core.security;
/**
* 用户信息服务
* 实现 Spring Security的UserDetailsService接口方法,用于身份认证
*/
@Service
public class DomainUserDetailsService implements UserDetailsService {
@Autowired | // Path: auth-server/src/main/java/com/lanshiqin/authserver/core/entity/Account.java
// public class Account {
// @Id
// private String id; // 主键
// private String userName; // 用户名
// private String passWord; // 密码
// private String[] roles; // 角色
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public String getPassWord() {
// return passWord;
// }
//
// public void setPassWord(String passWord) {
// this.passWord = passWord;
// }
//
// public String[] getRoles() {
// return roles;
// }
//
// public void setRoles(String[] roles) {
// this.roles = roles;
// }
// }
//
// Path: auth-server/src/main/java/com/lanshiqin/authserver/core/repository/AccountRepository.java
// @Component
// public interface AccountRepository extends MongoRepository<Account, String> {
//
// /**
// * 根据用户名查找账户信息
// * @param username 用户名
// * @return 账户信息
// */
// Account findByUserName(String username);
// }
// Path: auth-server/src/main/java/com/lanshiqin/authserver/core/security/DomainUserDetailsService.java
import com.lanshiqin.authserver.core.entity.Account;
import com.lanshiqin.authserver.core.repository.AccountRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
package com.lanshiqin.authserver.core.security;
/**
* 用户信息服务
* 实现 Spring Security的UserDetailsService接口方法,用于身份认证
*/
@Service
public class DomainUserDetailsService implements UserDetailsService {
@Autowired | private AccountRepository accountRepository; // 账户数据操作接口 |
lanshiqin/cloud-project | auth-server/src/main/java/com/lanshiqin/authserver/core/security/DomainUserDetailsService.java | // Path: auth-server/src/main/java/com/lanshiqin/authserver/core/entity/Account.java
// public class Account {
// @Id
// private String id; // 主键
// private String userName; // 用户名
// private String passWord; // 密码
// private String[] roles; // 角色
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public String getPassWord() {
// return passWord;
// }
//
// public void setPassWord(String passWord) {
// this.passWord = passWord;
// }
//
// public String[] getRoles() {
// return roles;
// }
//
// public void setRoles(String[] roles) {
// this.roles = roles;
// }
// }
//
// Path: auth-server/src/main/java/com/lanshiqin/authserver/core/repository/AccountRepository.java
// @Component
// public interface AccountRepository extends MongoRepository<Account, String> {
//
// /**
// * 根据用户名查找账户信息
// * @param username 用户名
// * @return 账户信息
// */
// Account findByUserName(String username);
// }
| import com.lanshiqin.authserver.core.entity.Account;
import com.lanshiqin.authserver.core.repository.AccountRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service; | package com.lanshiqin.authserver.core.security;
/**
* 用户信息服务
* 实现 Spring Security的UserDetailsService接口方法,用于身份认证
*/
@Service
public class DomainUserDetailsService implements UserDetailsService {
@Autowired
private AccountRepository accountRepository; // 账户数据操作接口
/**
* 根据用户名查找账户信息并返回用户信息实体
* @param username 用户名
* @return 用于身份认证的 UserDetails 用户信息实体
* @throws UsernameNotFoundException
*/
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { | // Path: auth-server/src/main/java/com/lanshiqin/authserver/core/entity/Account.java
// public class Account {
// @Id
// private String id; // 主键
// private String userName; // 用户名
// private String passWord; // 密码
// private String[] roles; // 角色
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public String getPassWord() {
// return passWord;
// }
//
// public void setPassWord(String passWord) {
// this.passWord = passWord;
// }
//
// public String[] getRoles() {
// return roles;
// }
//
// public void setRoles(String[] roles) {
// this.roles = roles;
// }
// }
//
// Path: auth-server/src/main/java/com/lanshiqin/authserver/core/repository/AccountRepository.java
// @Component
// public interface AccountRepository extends MongoRepository<Account, String> {
//
// /**
// * 根据用户名查找账户信息
// * @param username 用户名
// * @return 账户信息
// */
// Account findByUserName(String username);
// }
// Path: auth-server/src/main/java/com/lanshiqin/authserver/core/security/DomainUserDetailsService.java
import com.lanshiqin.authserver.core.entity.Account;
import com.lanshiqin.authserver.core.repository.AccountRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
package com.lanshiqin.authserver.core.security;
/**
* 用户信息服务
* 实现 Spring Security的UserDetailsService接口方法,用于身份认证
*/
@Service
public class DomainUserDetailsService implements UserDetailsService {
@Autowired
private AccountRepository accountRepository; // 账户数据操作接口
/**
* 根据用户名查找账户信息并返回用户信息实体
* @param username 用户名
* @return 用于身份认证的 UserDetails 用户信息实体
* @throws UsernameNotFoundException
*/
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { | Account account = accountRepository.findByUserName(username); |
lanshiqin/cloud-project | auth-server/src/main/java/com/lanshiqin/authserver/core/controller/UserController.java | // Path: auth-server/src/main/java/com/lanshiqin/authserver/core/entity/Account.java
// public class Account {
// @Id
// private String id; // 主键
// private String userName; // 用户名
// private String passWord; // 密码
// private String[] roles; // 角色
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public String getPassWord() {
// return passWord;
// }
//
// public void setPassWord(String passWord) {
// this.passWord = passWord;
// }
//
// public String[] getRoles() {
// return roles;
// }
//
// public void setRoles(String[] roles) {
// this.roles = roles;
// }
// }
//
// Path: auth-server/src/main/java/com/lanshiqin/authserver/core/repository/AccountRepository.java
// @Component
// public interface AccountRepository extends MongoRepository<Account, String> {
//
// /**
// * 根据用户名查找账户信息
// * @param username 用户名
// * @return 账户信息
// */
// Account findByUserName(String username);
// }
| import com.lanshiqin.authserver.core.entity.Account;
import com.lanshiqin.authserver.core.repository.AccountRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.security.Principal; | package com.lanshiqin.authserver.core.controller;
/**
* 用户信息控制器
*/
@RestController
public class UserController {
@Autowired | // Path: auth-server/src/main/java/com/lanshiqin/authserver/core/entity/Account.java
// public class Account {
// @Id
// private String id; // 主键
// private String userName; // 用户名
// private String passWord; // 密码
// private String[] roles; // 角色
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public String getPassWord() {
// return passWord;
// }
//
// public void setPassWord(String passWord) {
// this.passWord = passWord;
// }
//
// public String[] getRoles() {
// return roles;
// }
//
// public void setRoles(String[] roles) {
// this.roles = roles;
// }
// }
//
// Path: auth-server/src/main/java/com/lanshiqin/authserver/core/repository/AccountRepository.java
// @Component
// public interface AccountRepository extends MongoRepository<Account, String> {
//
// /**
// * 根据用户名查找账户信息
// * @param username 用户名
// * @return 账户信息
// */
// Account findByUserName(String username);
// }
// Path: auth-server/src/main/java/com/lanshiqin/authserver/core/controller/UserController.java
import com.lanshiqin.authserver.core.entity.Account;
import com.lanshiqin.authserver.core.repository.AccountRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.security.Principal;
package com.lanshiqin.authserver.core.controller;
/**
* 用户信息控制器
*/
@RestController
public class UserController {
@Autowired | private AccountRepository accountRepository; // 账户数据操作接口 |
lanshiqin/cloud-project | auth-server/src/main/java/com/lanshiqin/authserver/core/controller/UserController.java | // Path: auth-server/src/main/java/com/lanshiqin/authserver/core/entity/Account.java
// public class Account {
// @Id
// private String id; // 主键
// private String userName; // 用户名
// private String passWord; // 密码
// private String[] roles; // 角色
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public String getPassWord() {
// return passWord;
// }
//
// public void setPassWord(String passWord) {
// this.passWord = passWord;
// }
//
// public String[] getRoles() {
// return roles;
// }
//
// public void setRoles(String[] roles) {
// this.roles = roles;
// }
// }
//
// Path: auth-server/src/main/java/com/lanshiqin/authserver/core/repository/AccountRepository.java
// @Component
// public interface AccountRepository extends MongoRepository<Account, String> {
//
// /**
// * 根据用户名查找账户信息
// * @param username 用户名
// * @return 账户信息
// */
// Account findByUserName(String username);
// }
| import com.lanshiqin.authserver.core.entity.Account;
import com.lanshiqin.authserver.core.repository.AccountRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.security.Principal; | package com.lanshiqin.authserver.core.controller;
/**
* 用户信息控制器
*/
@RestController
public class UserController {
@Autowired
private AccountRepository accountRepository; // 账户数据操作接口
/**
* 初始化用户数据
*/
@Autowired
public void init(){
// 为了方便测试,这里添加了两个不同角色的账户
accountRepository.deleteAll();
| // Path: auth-server/src/main/java/com/lanshiqin/authserver/core/entity/Account.java
// public class Account {
// @Id
// private String id; // 主键
// private String userName; // 用户名
// private String passWord; // 密码
// private String[] roles; // 角色
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public String getPassWord() {
// return passWord;
// }
//
// public void setPassWord(String passWord) {
// this.passWord = passWord;
// }
//
// public String[] getRoles() {
// return roles;
// }
//
// public void setRoles(String[] roles) {
// this.roles = roles;
// }
// }
//
// Path: auth-server/src/main/java/com/lanshiqin/authserver/core/repository/AccountRepository.java
// @Component
// public interface AccountRepository extends MongoRepository<Account, String> {
//
// /**
// * 根据用户名查找账户信息
// * @param username 用户名
// * @return 账户信息
// */
// Account findByUserName(String username);
// }
// Path: auth-server/src/main/java/com/lanshiqin/authserver/core/controller/UserController.java
import com.lanshiqin.authserver.core.entity.Account;
import com.lanshiqin.authserver.core.repository.AccountRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.security.Principal;
package com.lanshiqin.authserver.core.controller;
/**
* 用户信息控制器
*/
@RestController
public class UserController {
@Autowired
private AccountRepository accountRepository; // 账户数据操作接口
/**
* 初始化用户数据
*/
@Autowired
public void init(){
// 为了方便测试,这里添加了两个不同角色的账户
accountRepository.deleteAll();
| Account accountA = new Account(); |
lanshiqin/cloud-project | auth-server/src/main/java/com/lanshiqin/authserver/core/config/SecurityConfig.java | // Path: auth-server/src/main/java/com/lanshiqin/authserver/core/security/DomainUserDetailsService.java
// @Service
// public class DomainUserDetailsService implements UserDetailsService {
//
// @Autowired
// private AccountRepository accountRepository; // 账户数据操作接口
//
// /**
// * 根据用户名查找账户信息并返回用户信息实体
// * @param username 用户名
// * @return 用于身份认证的 UserDetails 用户信息实体
// * @throws UsernameNotFoundException
// */
// @Override
// public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// Account account = accountRepository.findByUserName(username);
// if (account!=null){
// return new User(account.getUserName(),account.getPassWord(), AuthorityUtils.createAuthorityList(account.getRoles()));
// }else {
// throw new UsernameNotFoundException("用户["+username+"]不存在");
// }
// }
// }
| import com.lanshiqin.authserver.core.security.DomainUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService; | package com.lanshiqin.authserver.core.config;
/**
* 安全配置
* @ EnableWebSecurity 启用web安全配置
* @ EnableGlobalMethodSecurity 启用全局方法安全注解,就可以在方法上使用注解来对请求进行过滤
*/
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
/**
* 注入用户信息服务
* @return 用户信息服务对象
*/
@Bean
public UserDetailsService userDetailsService() { | // Path: auth-server/src/main/java/com/lanshiqin/authserver/core/security/DomainUserDetailsService.java
// @Service
// public class DomainUserDetailsService implements UserDetailsService {
//
// @Autowired
// private AccountRepository accountRepository; // 账户数据操作接口
//
// /**
// * 根据用户名查找账户信息并返回用户信息实体
// * @param username 用户名
// * @return 用于身份认证的 UserDetails 用户信息实体
// * @throws UsernameNotFoundException
// */
// @Override
// public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// Account account = accountRepository.findByUserName(username);
// if (account!=null){
// return new User(account.getUserName(),account.getPassWord(), AuthorityUtils.createAuthorityList(account.getRoles()));
// }else {
// throw new UsernameNotFoundException("用户["+username+"]不存在");
// }
// }
// }
// Path: auth-server/src/main/java/com/lanshiqin/authserver/core/config/SecurityConfig.java
import com.lanshiqin.authserver.core.security.DomainUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
package com.lanshiqin.authserver.core.config;
/**
* 安全配置
* @ EnableWebSecurity 启用web安全配置
* @ EnableGlobalMethodSecurity 启用全局方法安全注解,就可以在方法上使用注解来对请求进行过滤
*/
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
/**
* 注入用户信息服务
* @return 用户信息服务对象
*/
@Bean
public UserDetailsService userDetailsService() { | return new DomainUserDetailsService(); |
lanshiqin/cloud-project | api-gateway/src/main/java/com/lanshiqin/apigateway/ApiGatewayApplication.java | // Path: api-gateway/src/main/java/com/lanshiqin/apigateway/core/filter/pre/AccessFilter.java
// public class AccessFilter extends ZuulFilter {
//
// private static Logger logger = LoggerFactory.getLogger(AccessFilter.class);
//
// /**
// * 过滤器的类型 pre表示请求在路由之前被过滤
// * @return 类型
// */
// @Override
// public String filterType() {
// return "pre";
// }
//
// /**
// * 过滤器的执行顺序
// * @return 顺序 数字越大表示优先级越低,越后执行
// */
// @Override
// public int filterOrder() {
// return 0;
// }
//
// /**
// * 过滤器是否会被执行
// * @return true
// */
// @Override
// public boolean shouldFilter() {
// return true;
// }
//
// /**
// * 过滤逻辑
// * @return 过滤结果
// */
// @Override
// public Object run() {
// RequestContext requestContext = RequestContext.getCurrentContext();
// HttpServletRequest request = requestContext.getRequest();
//
// logger.info("send {} request to {}",request.getMethod(),request.getRequestURL().toString());
//
// Object accessToken = request.getHeader("Authorization");
// if (accessToken==null){
// logger.warn("Authorization token is empty");
// requestContext.setSendZuulResponse(false);
// requestContext.setResponseStatusCode(401);
// requestContext.setResponseBody("Authorization token is empty");
// return null;
// }
// logger.info("Authorization token is ok");
//
//
// return null;
// }
//
//
//
// }
| import com.lanshiqin.apigateway.core.filter.pre.AccessFilter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
import org.springframework.context.annotation.Bean; | package com.lanshiqin.apigateway;
/**
* API网关服务
* @ EnableZuulProxy 启用网关路由
* @ EnableOAuth2Sso 启用OAuth2单点登录
*/
@SpringBootApplication
@EnableZuulProxy
@EnableOAuth2Sso
public class ApiGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(ApiGatewayApplication.class, args);
}
/**
* 资源过滤器
* @return 资源过滤器
*/
@Bean | // Path: api-gateway/src/main/java/com/lanshiqin/apigateway/core/filter/pre/AccessFilter.java
// public class AccessFilter extends ZuulFilter {
//
// private static Logger logger = LoggerFactory.getLogger(AccessFilter.class);
//
// /**
// * 过滤器的类型 pre表示请求在路由之前被过滤
// * @return 类型
// */
// @Override
// public String filterType() {
// return "pre";
// }
//
// /**
// * 过滤器的执行顺序
// * @return 顺序 数字越大表示优先级越低,越后执行
// */
// @Override
// public int filterOrder() {
// return 0;
// }
//
// /**
// * 过滤器是否会被执行
// * @return true
// */
// @Override
// public boolean shouldFilter() {
// return true;
// }
//
// /**
// * 过滤逻辑
// * @return 过滤结果
// */
// @Override
// public Object run() {
// RequestContext requestContext = RequestContext.getCurrentContext();
// HttpServletRequest request = requestContext.getRequest();
//
// logger.info("send {} request to {}",request.getMethod(),request.getRequestURL().toString());
//
// Object accessToken = request.getHeader("Authorization");
// if (accessToken==null){
// logger.warn("Authorization token is empty");
// requestContext.setSendZuulResponse(false);
// requestContext.setResponseStatusCode(401);
// requestContext.setResponseBody("Authorization token is empty");
// return null;
// }
// logger.info("Authorization token is ok");
//
//
// return null;
// }
//
//
//
// }
// Path: api-gateway/src/main/java/com/lanshiqin/apigateway/ApiGatewayApplication.java
import com.lanshiqin.apigateway.core.filter.pre.AccessFilter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
import org.springframework.context.annotation.Bean;
package com.lanshiqin.apigateway;
/**
* API网关服务
* @ EnableZuulProxy 启用网关路由
* @ EnableOAuth2Sso 启用OAuth2单点登录
*/
@SpringBootApplication
@EnableZuulProxy
@EnableOAuth2Sso
public class ApiGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(ApiGatewayApplication.class, args);
}
/**
* 资源过滤器
* @return 资源过滤器
*/
@Bean | public AccessFilter accessFilter(){ |
lanshiqin/cloud-project | micro-services/consumer-service/src/main/java/com/lanshiqin/consumerservice/core/controller/HelloController.java | // Path: micro-services/consumer-service/src/main/java/com/lanshiqin/consumerservice/core/remote/HelloRemote.java
// @FeignClient(name = "producer-service",fallback = HelloRemoteFallback.class)
// public interface HelloRemote {
// /**
// * 远程调用方法
// * @param name 名称
// * @return 远程调用结果
// */
// @RequestMapping(value = "/hello")
// String hello(@RequestParam(value = "name") String name);
// }
| import com.lanshiqin.consumerservice.core.remote.HelloRemote;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; | package com.lanshiqin.consumerservice.core.controller;
/**
* Hello控制器 测试远程调用接口
* 将远程调用接口注入,并调用远程方法
*/
@RestController
public class HelloController {
@Autowired | // Path: micro-services/consumer-service/src/main/java/com/lanshiqin/consumerservice/core/remote/HelloRemote.java
// @FeignClient(name = "producer-service",fallback = HelloRemoteFallback.class)
// public interface HelloRemote {
// /**
// * 远程调用方法
// * @param name 名称
// * @return 远程调用结果
// */
// @RequestMapping(value = "/hello")
// String hello(@RequestParam(value = "name") String name);
// }
// Path: micro-services/consumer-service/src/main/java/com/lanshiqin/consumerservice/core/controller/HelloController.java
import com.lanshiqin.consumerservice.core.remote.HelloRemote;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
package com.lanshiqin.consumerservice.core.controller;
/**
* Hello控制器 测试远程调用接口
* 将远程调用接口注入,并调用远程方法
*/
@RestController
public class HelloController {
@Autowired | private HelloRemote helloRemote; // 远程调用接口 |
razerdp/FriendCircle | uilib/src/main/java/com/razerdp/github/uilib/base/adapter/BaseRecyclerViewAdapter.java | // Path: lib/src/main/java/com/razerdp/github/lib/utils/ToolUtil.java
// public class ToolUtil {
//
// public static boolean isEmpty(Collection<?> datas) {
// return datas == null || datas.size() <= 0;
// }
//
// public static boolean isEmpty(Map map) {
// return map == null || map.isEmpty();
// }
//
//
// public static boolean indexInCollection(Collection who, int index) {
// if (who == null) return false;
// return index >= 0 && index < who.size();
// }
//
//
// public static void install(Context context, String apkPath) {
// Intent intent = new Intent(Intent.ACTION_VIEW);
// if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
// File file = (new File(apkPath));
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Uri apkUri = FileProvider.getUriForFile(context, "github.razerdp.friendcircle", file);
// intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
// intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
// } else {
// intent.setDataAndType(Uri.fromFile(new File(apkPath)),
// "application/vnd.android.package-archive");
// }
// context.startActivity(intent);
// }
// }
//
// Path: uilib/src/main/java/com/razerdp/github/uilib/base/adapter/interfaces/OnItemClickListener.java
// public interface OnItemClickListener<T> {
//
// void onItemClick(View v, int position, T data);
// }
//
// Path: uilib/src/main/java/com/razerdp/github/uilib/base/adapter/interfaces/OnItemLongClickListener.java
// public interface OnItemLongClickListener<T> {
//
// void onItemLongClick(View v, int position, T data);
// }
//
// Path: uilib/src/main/java/com/razerdp/github/uilib/utils/ViewUtil.java
// public class ViewUtil {
//
// public static View inflate(@LayoutRes int layout, ViewGroup parent, boolean attachToParent) {
// return LayoutInflater.from(AppContext.getAppContext()).inflate(layout, parent, attachToParent);
// }
// }
| import android.content.Context;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Space;
import com.razerdp.github.lib.utils.ToolUtil;
import com.razerdp.github.uilib.base.adapter.interfaces.OnItemClickListener;
import com.razerdp.github.uilib.base.adapter.interfaces.OnItemLongClickListener;
import com.razerdp.github.uilib.utils.ViewUtil;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.core.view.GestureDetectorCompat;
import androidx.recyclerview.widget.RecyclerView; | package com.razerdp.github.uilib.base.adapter;
/**
* Created by 大灯泡 on 2019/8/2.
* <p>
* baseadapter,请注意,adapter内部的数据跟外部不是同一个对象(预防外部修改导致内部修改)
*/
@SuppressWarnings("all")
public abstract class BaseRecyclerViewAdapter<T> extends RecyclerView.Adapter<BaseRecyclerViewHolder<T>> {
protected final String TAG = getClass().getSimpleName();
protected Context mContext;
protected List<T> mDatas;
| // Path: lib/src/main/java/com/razerdp/github/lib/utils/ToolUtil.java
// public class ToolUtil {
//
// public static boolean isEmpty(Collection<?> datas) {
// return datas == null || datas.size() <= 0;
// }
//
// public static boolean isEmpty(Map map) {
// return map == null || map.isEmpty();
// }
//
//
// public static boolean indexInCollection(Collection who, int index) {
// if (who == null) return false;
// return index >= 0 && index < who.size();
// }
//
//
// public static void install(Context context, String apkPath) {
// Intent intent = new Intent(Intent.ACTION_VIEW);
// if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
// File file = (new File(apkPath));
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Uri apkUri = FileProvider.getUriForFile(context, "github.razerdp.friendcircle", file);
// intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
// intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
// } else {
// intent.setDataAndType(Uri.fromFile(new File(apkPath)),
// "application/vnd.android.package-archive");
// }
// context.startActivity(intent);
// }
// }
//
// Path: uilib/src/main/java/com/razerdp/github/uilib/base/adapter/interfaces/OnItemClickListener.java
// public interface OnItemClickListener<T> {
//
// void onItemClick(View v, int position, T data);
// }
//
// Path: uilib/src/main/java/com/razerdp/github/uilib/base/adapter/interfaces/OnItemLongClickListener.java
// public interface OnItemLongClickListener<T> {
//
// void onItemLongClick(View v, int position, T data);
// }
//
// Path: uilib/src/main/java/com/razerdp/github/uilib/utils/ViewUtil.java
// public class ViewUtil {
//
// public static View inflate(@LayoutRes int layout, ViewGroup parent, boolean attachToParent) {
// return LayoutInflater.from(AppContext.getAppContext()).inflate(layout, parent, attachToParent);
// }
// }
// Path: uilib/src/main/java/com/razerdp/github/uilib/base/adapter/BaseRecyclerViewAdapter.java
import android.content.Context;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Space;
import com.razerdp.github.lib.utils.ToolUtil;
import com.razerdp.github.uilib.base.adapter.interfaces.OnItemClickListener;
import com.razerdp.github.uilib.base.adapter.interfaces.OnItemLongClickListener;
import com.razerdp.github.uilib.utils.ViewUtil;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.core.view.GestureDetectorCompat;
import androidx.recyclerview.widget.RecyclerView;
package com.razerdp.github.uilib.base.adapter;
/**
* Created by 大灯泡 on 2019/8/2.
* <p>
* baseadapter,请注意,adapter内部的数据跟外部不是同一个对象(预防外部修改导致内部修改)
*/
@SuppressWarnings("all")
public abstract class BaseRecyclerViewAdapter<T> extends RecyclerView.Adapter<BaseRecyclerViewHolder<T>> {
protected final String TAG = getClass().getSimpleName();
protected Context mContext;
protected List<T> mDatas;
| private OnItemClickListener<T> mOnItemClickListener; |
razerdp/FriendCircle | uilib/src/main/java/com/razerdp/github/uilib/base/adapter/BaseRecyclerViewAdapter.java | // Path: lib/src/main/java/com/razerdp/github/lib/utils/ToolUtil.java
// public class ToolUtil {
//
// public static boolean isEmpty(Collection<?> datas) {
// return datas == null || datas.size() <= 0;
// }
//
// public static boolean isEmpty(Map map) {
// return map == null || map.isEmpty();
// }
//
//
// public static boolean indexInCollection(Collection who, int index) {
// if (who == null) return false;
// return index >= 0 && index < who.size();
// }
//
//
// public static void install(Context context, String apkPath) {
// Intent intent = new Intent(Intent.ACTION_VIEW);
// if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
// File file = (new File(apkPath));
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Uri apkUri = FileProvider.getUriForFile(context, "github.razerdp.friendcircle", file);
// intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
// intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
// } else {
// intent.setDataAndType(Uri.fromFile(new File(apkPath)),
// "application/vnd.android.package-archive");
// }
// context.startActivity(intent);
// }
// }
//
// Path: uilib/src/main/java/com/razerdp/github/uilib/base/adapter/interfaces/OnItemClickListener.java
// public interface OnItemClickListener<T> {
//
// void onItemClick(View v, int position, T data);
// }
//
// Path: uilib/src/main/java/com/razerdp/github/uilib/base/adapter/interfaces/OnItemLongClickListener.java
// public interface OnItemLongClickListener<T> {
//
// void onItemLongClick(View v, int position, T data);
// }
//
// Path: uilib/src/main/java/com/razerdp/github/uilib/utils/ViewUtil.java
// public class ViewUtil {
//
// public static View inflate(@LayoutRes int layout, ViewGroup parent, boolean attachToParent) {
// return LayoutInflater.from(AppContext.getAppContext()).inflate(layout, parent, attachToParent);
// }
// }
| import android.content.Context;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Space;
import com.razerdp.github.lib.utils.ToolUtil;
import com.razerdp.github.uilib.base.adapter.interfaces.OnItemClickListener;
import com.razerdp.github.uilib.base.adapter.interfaces.OnItemLongClickListener;
import com.razerdp.github.uilib.utils.ViewUtil;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.core.view.GestureDetectorCompat;
import androidx.recyclerview.widget.RecyclerView; | package com.razerdp.github.uilib.base.adapter;
/**
* Created by 大灯泡 on 2019/8/2.
* <p>
* baseadapter,请注意,adapter内部的数据跟外部不是同一个对象(预防外部修改导致内部修改)
*/
@SuppressWarnings("all")
public abstract class BaseRecyclerViewAdapter<T> extends RecyclerView.Adapter<BaseRecyclerViewHolder<T>> {
protected final String TAG = getClass().getSimpleName();
protected Context mContext;
protected List<T> mDatas;
private OnItemClickListener<T> mOnItemClickListener; | // Path: lib/src/main/java/com/razerdp/github/lib/utils/ToolUtil.java
// public class ToolUtil {
//
// public static boolean isEmpty(Collection<?> datas) {
// return datas == null || datas.size() <= 0;
// }
//
// public static boolean isEmpty(Map map) {
// return map == null || map.isEmpty();
// }
//
//
// public static boolean indexInCollection(Collection who, int index) {
// if (who == null) return false;
// return index >= 0 && index < who.size();
// }
//
//
// public static void install(Context context, String apkPath) {
// Intent intent = new Intent(Intent.ACTION_VIEW);
// if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
// File file = (new File(apkPath));
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Uri apkUri = FileProvider.getUriForFile(context, "github.razerdp.friendcircle", file);
// intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
// intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
// } else {
// intent.setDataAndType(Uri.fromFile(new File(apkPath)),
// "application/vnd.android.package-archive");
// }
// context.startActivity(intent);
// }
// }
//
// Path: uilib/src/main/java/com/razerdp/github/uilib/base/adapter/interfaces/OnItemClickListener.java
// public interface OnItemClickListener<T> {
//
// void onItemClick(View v, int position, T data);
// }
//
// Path: uilib/src/main/java/com/razerdp/github/uilib/base/adapter/interfaces/OnItemLongClickListener.java
// public interface OnItemLongClickListener<T> {
//
// void onItemLongClick(View v, int position, T data);
// }
//
// Path: uilib/src/main/java/com/razerdp/github/uilib/utils/ViewUtil.java
// public class ViewUtil {
//
// public static View inflate(@LayoutRes int layout, ViewGroup parent, boolean attachToParent) {
// return LayoutInflater.from(AppContext.getAppContext()).inflate(layout, parent, attachToParent);
// }
// }
// Path: uilib/src/main/java/com/razerdp/github/uilib/base/adapter/BaseRecyclerViewAdapter.java
import android.content.Context;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Space;
import com.razerdp.github.lib.utils.ToolUtil;
import com.razerdp.github.uilib.base.adapter.interfaces.OnItemClickListener;
import com.razerdp.github.uilib.base.adapter.interfaces.OnItemLongClickListener;
import com.razerdp.github.uilib.utils.ViewUtil;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.core.view.GestureDetectorCompat;
import androidx.recyclerview.widget.RecyclerView;
package com.razerdp.github.uilib.base.adapter;
/**
* Created by 大灯泡 on 2019/8/2.
* <p>
* baseadapter,请注意,adapter内部的数据跟外部不是同一个对象(预防外部修改导致内部修改)
*/
@SuppressWarnings("all")
public abstract class BaseRecyclerViewAdapter<T> extends RecyclerView.Adapter<BaseRecyclerViewHolder<T>> {
protected final String TAG = getClass().getSimpleName();
protected Context mContext;
protected List<T> mDatas;
private OnItemClickListener<T> mOnItemClickListener; | private OnItemLongClickListener<T> mOnItemLongClickListener; |
razerdp/FriendCircle | uilib/src/main/java/com/razerdp/github/uilib/base/adapter/BaseRecyclerViewAdapter.java | // Path: lib/src/main/java/com/razerdp/github/lib/utils/ToolUtil.java
// public class ToolUtil {
//
// public static boolean isEmpty(Collection<?> datas) {
// return datas == null || datas.size() <= 0;
// }
//
// public static boolean isEmpty(Map map) {
// return map == null || map.isEmpty();
// }
//
//
// public static boolean indexInCollection(Collection who, int index) {
// if (who == null) return false;
// return index >= 0 && index < who.size();
// }
//
//
// public static void install(Context context, String apkPath) {
// Intent intent = new Intent(Intent.ACTION_VIEW);
// if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
// File file = (new File(apkPath));
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Uri apkUri = FileProvider.getUriForFile(context, "github.razerdp.friendcircle", file);
// intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
// intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
// } else {
// intent.setDataAndType(Uri.fromFile(new File(apkPath)),
// "application/vnd.android.package-archive");
// }
// context.startActivity(intent);
// }
// }
//
// Path: uilib/src/main/java/com/razerdp/github/uilib/base/adapter/interfaces/OnItemClickListener.java
// public interface OnItemClickListener<T> {
//
// void onItemClick(View v, int position, T data);
// }
//
// Path: uilib/src/main/java/com/razerdp/github/uilib/base/adapter/interfaces/OnItemLongClickListener.java
// public interface OnItemLongClickListener<T> {
//
// void onItemLongClick(View v, int position, T data);
// }
//
// Path: uilib/src/main/java/com/razerdp/github/uilib/utils/ViewUtil.java
// public class ViewUtil {
//
// public static View inflate(@LayoutRes int layout, ViewGroup parent, boolean attachToParent) {
// return LayoutInflater.from(AppContext.getAppContext()).inflate(layout, parent, attachToParent);
// }
// }
| import android.content.Context;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Space;
import com.razerdp.github.lib.utils.ToolUtil;
import com.razerdp.github.uilib.base.adapter.interfaces.OnItemClickListener;
import com.razerdp.github.uilib.base.adapter.interfaces.OnItemLongClickListener;
import com.razerdp.github.uilib.utils.ViewUtil;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.core.view.GestureDetectorCompat;
import androidx.recyclerview.widget.RecyclerView; | package com.razerdp.github.uilib.base.adapter;
/**
* Created by 大灯泡 on 2019/8/2.
* <p>
* baseadapter,请注意,adapter内部的数据跟外部不是同一个对象(预防外部修改导致内部修改)
*/
@SuppressWarnings("all")
public abstract class BaseRecyclerViewAdapter<T> extends RecyclerView.Adapter<BaseRecyclerViewHolder<T>> {
protected final String TAG = getClass().getSimpleName();
protected Context mContext;
protected List<T> mDatas;
private OnItemClickListener<T> mOnItemClickListener;
private OnItemLongClickListener<T> mOnItemLongClickListener;
public BaseRecyclerViewAdapter(Context context) {
this(context, new ArrayList<T>());
}
public BaseRecyclerViewAdapter(Context context, List<T> datas) {
mContext = context;
mDatas = new ArrayList<>(); | // Path: lib/src/main/java/com/razerdp/github/lib/utils/ToolUtil.java
// public class ToolUtil {
//
// public static boolean isEmpty(Collection<?> datas) {
// return datas == null || datas.size() <= 0;
// }
//
// public static boolean isEmpty(Map map) {
// return map == null || map.isEmpty();
// }
//
//
// public static boolean indexInCollection(Collection who, int index) {
// if (who == null) return false;
// return index >= 0 && index < who.size();
// }
//
//
// public static void install(Context context, String apkPath) {
// Intent intent = new Intent(Intent.ACTION_VIEW);
// if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
// File file = (new File(apkPath));
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Uri apkUri = FileProvider.getUriForFile(context, "github.razerdp.friendcircle", file);
// intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
// intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
// } else {
// intent.setDataAndType(Uri.fromFile(new File(apkPath)),
// "application/vnd.android.package-archive");
// }
// context.startActivity(intent);
// }
// }
//
// Path: uilib/src/main/java/com/razerdp/github/uilib/base/adapter/interfaces/OnItemClickListener.java
// public interface OnItemClickListener<T> {
//
// void onItemClick(View v, int position, T data);
// }
//
// Path: uilib/src/main/java/com/razerdp/github/uilib/base/adapter/interfaces/OnItemLongClickListener.java
// public interface OnItemLongClickListener<T> {
//
// void onItemLongClick(View v, int position, T data);
// }
//
// Path: uilib/src/main/java/com/razerdp/github/uilib/utils/ViewUtil.java
// public class ViewUtil {
//
// public static View inflate(@LayoutRes int layout, ViewGroup parent, boolean attachToParent) {
// return LayoutInflater.from(AppContext.getAppContext()).inflate(layout, parent, attachToParent);
// }
// }
// Path: uilib/src/main/java/com/razerdp/github/uilib/base/adapter/BaseRecyclerViewAdapter.java
import android.content.Context;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Space;
import com.razerdp.github.lib.utils.ToolUtil;
import com.razerdp.github.uilib.base.adapter.interfaces.OnItemClickListener;
import com.razerdp.github.uilib.base.adapter.interfaces.OnItemLongClickListener;
import com.razerdp.github.uilib.utils.ViewUtil;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.core.view.GestureDetectorCompat;
import androidx.recyclerview.widget.RecyclerView;
package com.razerdp.github.uilib.base.adapter;
/**
* Created by 大灯泡 on 2019/8/2.
* <p>
* baseadapter,请注意,adapter内部的数据跟外部不是同一个对象(预防外部修改导致内部修改)
*/
@SuppressWarnings("all")
public abstract class BaseRecyclerViewAdapter<T> extends RecyclerView.Adapter<BaseRecyclerViewHolder<T>> {
protected final String TAG = getClass().getSimpleName();
protected Context mContext;
protected List<T> mDatas;
private OnItemClickListener<T> mOnItemClickListener;
private OnItemLongClickListener<T> mOnItemLongClickListener;
public BaseRecyclerViewAdapter(Context context) {
this(context, new ArrayList<T>());
}
public BaseRecyclerViewAdapter(Context context, List<T> datas) {
mContext = context;
mDatas = new ArrayList<>(); | if (!ToolUtil.isEmpty(datas)) { |
razerdp/FriendCircle | uilib/src/main/java/com/razerdp/github/uilib/base/adapter/BaseRecyclerViewAdapter.java | // Path: lib/src/main/java/com/razerdp/github/lib/utils/ToolUtil.java
// public class ToolUtil {
//
// public static boolean isEmpty(Collection<?> datas) {
// return datas == null || datas.size() <= 0;
// }
//
// public static boolean isEmpty(Map map) {
// return map == null || map.isEmpty();
// }
//
//
// public static boolean indexInCollection(Collection who, int index) {
// if (who == null) return false;
// return index >= 0 && index < who.size();
// }
//
//
// public static void install(Context context, String apkPath) {
// Intent intent = new Intent(Intent.ACTION_VIEW);
// if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
// File file = (new File(apkPath));
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Uri apkUri = FileProvider.getUriForFile(context, "github.razerdp.friendcircle", file);
// intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
// intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
// } else {
// intent.setDataAndType(Uri.fromFile(new File(apkPath)),
// "application/vnd.android.package-archive");
// }
// context.startActivity(intent);
// }
// }
//
// Path: uilib/src/main/java/com/razerdp/github/uilib/base/adapter/interfaces/OnItemClickListener.java
// public interface OnItemClickListener<T> {
//
// void onItemClick(View v, int position, T data);
// }
//
// Path: uilib/src/main/java/com/razerdp/github/uilib/base/adapter/interfaces/OnItemLongClickListener.java
// public interface OnItemLongClickListener<T> {
//
// void onItemLongClick(View v, int position, T data);
// }
//
// Path: uilib/src/main/java/com/razerdp/github/uilib/utils/ViewUtil.java
// public class ViewUtil {
//
// public static View inflate(@LayoutRes int layout, ViewGroup parent, boolean attachToParent) {
// return LayoutInflater.from(AppContext.getAppContext()).inflate(layout, parent, attachToParent);
// }
// }
| import android.content.Context;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Space;
import com.razerdp.github.lib.utils.ToolUtil;
import com.razerdp.github.uilib.base.adapter.interfaces.OnItemClickListener;
import com.razerdp.github.uilib.base.adapter.interfaces.OnItemLongClickListener;
import com.razerdp.github.uilib.utils.ViewUtil;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.core.view.GestureDetectorCompat;
import androidx.recyclerview.widget.RecyclerView; | View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child == null) return;
try {
RecyclerView.ViewHolder holder = recyclerView.getChildViewHolder(child);
int position = holder.getLayoutPosition();
mOnItemLongClickListener.onItemLongClick(child, position, mDatas.get(position));
} catch (Exception error) {
error.printStackTrace();
}
return;
}
});
recyclerView.addOnItemTouchListener(new RecyclerView.SimpleOnItemTouchListener() {
@Override
public boolean onInterceptTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) {
if (mGestureDetectorCompat.onTouchEvent(e)) {
return true;
}
return super.onInterceptTouchEvent(rv, e);
}
});
}
@NonNull
@Override
public BaseRecyclerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
BaseRecyclerViewHolder holder = null;
int layout = holderLayout(viewType);
if (layout != 0) {
holder = createViewHolder(parent, | // Path: lib/src/main/java/com/razerdp/github/lib/utils/ToolUtil.java
// public class ToolUtil {
//
// public static boolean isEmpty(Collection<?> datas) {
// return datas == null || datas.size() <= 0;
// }
//
// public static boolean isEmpty(Map map) {
// return map == null || map.isEmpty();
// }
//
//
// public static boolean indexInCollection(Collection who, int index) {
// if (who == null) return false;
// return index >= 0 && index < who.size();
// }
//
//
// public static void install(Context context, String apkPath) {
// Intent intent = new Intent(Intent.ACTION_VIEW);
// if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
// File file = (new File(apkPath));
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Uri apkUri = FileProvider.getUriForFile(context, "github.razerdp.friendcircle", file);
// intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
// intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
// } else {
// intent.setDataAndType(Uri.fromFile(new File(apkPath)),
// "application/vnd.android.package-archive");
// }
// context.startActivity(intent);
// }
// }
//
// Path: uilib/src/main/java/com/razerdp/github/uilib/base/adapter/interfaces/OnItemClickListener.java
// public interface OnItemClickListener<T> {
//
// void onItemClick(View v, int position, T data);
// }
//
// Path: uilib/src/main/java/com/razerdp/github/uilib/base/adapter/interfaces/OnItemLongClickListener.java
// public interface OnItemLongClickListener<T> {
//
// void onItemLongClick(View v, int position, T data);
// }
//
// Path: uilib/src/main/java/com/razerdp/github/uilib/utils/ViewUtil.java
// public class ViewUtil {
//
// public static View inflate(@LayoutRes int layout, ViewGroup parent, boolean attachToParent) {
// return LayoutInflater.from(AppContext.getAppContext()).inflate(layout, parent, attachToParent);
// }
// }
// Path: uilib/src/main/java/com/razerdp/github/uilib/base/adapter/BaseRecyclerViewAdapter.java
import android.content.Context;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Space;
import com.razerdp.github.lib.utils.ToolUtil;
import com.razerdp.github.uilib.base.adapter.interfaces.OnItemClickListener;
import com.razerdp.github.uilib.base.adapter.interfaces.OnItemLongClickListener;
import com.razerdp.github.uilib.utils.ViewUtil;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.core.view.GestureDetectorCompat;
import androidx.recyclerview.widget.RecyclerView;
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child == null) return;
try {
RecyclerView.ViewHolder holder = recyclerView.getChildViewHolder(child);
int position = holder.getLayoutPosition();
mOnItemLongClickListener.onItemLongClick(child, position, mDatas.get(position));
} catch (Exception error) {
error.printStackTrace();
}
return;
}
});
recyclerView.addOnItemTouchListener(new RecyclerView.SimpleOnItemTouchListener() {
@Override
public boolean onInterceptTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) {
if (mGestureDetectorCompat.onTouchEvent(e)) {
return true;
}
return super.onInterceptTouchEvent(rv, e);
}
});
}
@NonNull
@Override
public BaseRecyclerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
BaseRecyclerViewHolder holder = null;
int layout = holderLayout(viewType);
if (layout != 0) {
holder = createViewHolder(parent, | ViewUtil.inflate(layout, parent, false), |
razerdp/FriendCircle | uilib/src/main/java/com/razerdp/github/uilib/utils/ViewUtil.java | // Path: lib/src/main/java/com/razerdp/github/lib/api/AppContext.java
// public class AppContext {
//
// private static final String TAG = "AppContext";
// public static final Application sApplication;
// private static final InnerLifecycleHandler INNER_LIFECYCLE_HANDLER;
//
// static {
// Application app = null;
// try {
// app = (Application) Class.forName("android.app.AppGlobals").getMethod("getInitialApplication").invoke(null);
// if (app == null)
// throw new IllegalStateException("Static initialization of Applications must be on main thread.");
// } catch (final Exception e) {
// Log.e(TAG, "Failed to get current application from AppGlobals." + e.getMessage());
// try {
// app = (Application) Class.forName("android.app.ActivityThread").getMethod("currentApplication").invoke(null);
// } catch (final Exception ex) {
// Log.e(TAG, "Failed to get current application from ActivityThread." + e.getMessage());
// }
// } finally {
// sApplication = app;
// }
// INNER_LIFECYCLE_HANDLER = new InnerLifecycleHandler();
// if (sApplication != null) {
// sApplication.registerActivityLifecycleCallbacks(INNER_LIFECYCLE_HANDLER);
// }
// }
//
// public static boolean isAppVisable() {
// return INNER_LIFECYCLE_HANDLER != null && INNER_LIFECYCLE_HANDLER.started > INNER_LIFECYCLE_HANDLER.stopped;
// }
//
// public static boolean isAppBackground() {
// return INNER_LIFECYCLE_HANDLER != null && INNER_LIFECYCLE_HANDLER.resumed <= INNER_LIFECYCLE_HANDLER.stopped;
// }
//
// private static void checkAppContext() {
// if (sApplication == null)
// throw new IllegalStateException("app reference is null");
// }
//
// public static Application getAppInstance() {
// checkAppContext();
// return sApplication;
// }
//
// public static Context getAppContext() {
// checkAppContext();
// return sApplication.getApplicationContext();
// }
//
// public static Resources getResources() {
// checkAppContext();
// return sApplication.getResources();
// }
//
// public static boolean isMainThread() {
// return Looper.getMainLooper().getThread() == Thread.currentThread();
// }
//
//
// @Nullable
// public static FragmentActivity getTopActivity() {
// return INNER_LIFECYCLE_HANDLER.mTopActivity == null ? null : INNER_LIFECYCLE_HANDLER.mTopActivity.get();
// }
//
// private static class InnerLifecycleHandler implements Application.ActivityLifecycleCallbacks {
// private int created;
// private int resumed;
// private int paused;
// private int started;
// private int stopped;
// private WeakReference<FragmentActivity> mTopActivity;
//
// @Override
// public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
// ++created;
//
// }
//
// @Override
// public void onActivityStarted(Activity activity) {
// ++started;
//
// }
//
// @Override
// public void onActivityResumed(Activity activity) {
// ++resumed;
// if (mTopActivity != null) {
// mTopActivity.clear();
// }
// if (activity instanceof FragmentActivity) {
// mTopActivity = new WeakReference<>((FragmentActivity) activity);
// }
// }
//
// @Override
// public void onActivityPaused(Activity activity) {
// ++paused;
//
// }
//
// @Override
// public void onActivityStopped(Activity activity) {
// ++stopped;
//
// }
//
// @Override
// public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
//
// }
//
// @Override
// public void onActivityDestroyed(Activity activity) {
//
// }
// }
//
// }
| import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.razerdp.github.lib.api.AppContext;
import androidx.annotation.LayoutRes; | package com.razerdp.github.uilib.utils;
/**
* Created by 大灯泡 on 2019/8/2.
*/
public class ViewUtil {
public static View inflate(@LayoutRes int layout, ViewGroup parent, boolean attachToParent) { | // Path: lib/src/main/java/com/razerdp/github/lib/api/AppContext.java
// public class AppContext {
//
// private static final String TAG = "AppContext";
// public static final Application sApplication;
// private static final InnerLifecycleHandler INNER_LIFECYCLE_HANDLER;
//
// static {
// Application app = null;
// try {
// app = (Application) Class.forName("android.app.AppGlobals").getMethod("getInitialApplication").invoke(null);
// if (app == null)
// throw new IllegalStateException("Static initialization of Applications must be on main thread.");
// } catch (final Exception e) {
// Log.e(TAG, "Failed to get current application from AppGlobals." + e.getMessage());
// try {
// app = (Application) Class.forName("android.app.ActivityThread").getMethod("currentApplication").invoke(null);
// } catch (final Exception ex) {
// Log.e(TAG, "Failed to get current application from ActivityThread." + e.getMessage());
// }
// } finally {
// sApplication = app;
// }
// INNER_LIFECYCLE_HANDLER = new InnerLifecycleHandler();
// if (sApplication != null) {
// sApplication.registerActivityLifecycleCallbacks(INNER_LIFECYCLE_HANDLER);
// }
// }
//
// public static boolean isAppVisable() {
// return INNER_LIFECYCLE_HANDLER != null && INNER_LIFECYCLE_HANDLER.started > INNER_LIFECYCLE_HANDLER.stopped;
// }
//
// public static boolean isAppBackground() {
// return INNER_LIFECYCLE_HANDLER != null && INNER_LIFECYCLE_HANDLER.resumed <= INNER_LIFECYCLE_HANDLER.stopped;
// }
//
// private static void checkAppContext() {
// if (sApplication == null)
// throw new IllegalStateException("app reference is null");
// }
//
// public static Application getAppInstance() {
// checkAppContext();
// return sApplication;
// }
//
// public static Context getAppContext() {
// checkAppContext();
// return sApplication.getApplicationContext();
// }
//
// public static Resources getResources() {
// checkAppContext();
// return sApplication.getResources();
// }
//
// public static boolean isMainThread() {
// return Looper.getMainLooper().getThread() == Thread.currentThread();
// }
//
//
// @Nullable
// public static FragmentActivity getTopActivity() {
// return INNER_LIFECYCLE_HANDLER.mTopActivity == null ? null : INNER_LIFECYCLE_HANDLER.mTopActivity.get();
// }
//
// private static class InnerLifecycleHandler implements Application.ActivityLifecycleCallbacks {
// private int created;
// private int resumed;
// private int paused;
// private int started;
// private int stopped;
// private WeakReference<FragmentActivity> mTopActivity;
//
// @Override
// public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
// ++created;
//
// }
//
// @Override
// public void onActivityStarted(Activity activity) {
// ++started;
//
// }
//
// @Override
// public void onActivityResumed(Activity activity) {
// ++resumed;
// if (mTopActivity != null) {
// mTopActivity.clear();
// }
// if (activity instanceof FragmentActivity) {
// mTopActivity = new WeakReference<>((FragmentActivity) activity);
// }
// }
//
// @Override
// public void onActivityPaused(Activity activity) {
// ++paused;
//
// }
//
// @Override
// public void onActivityStopped(Activity activity) {
// ++stopped;
//
// }
//
// @Override
// public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
//
// }
//
// @Override
// public void onActivityDestroyed(Activity activity) {
//
// }
// }
//
// }
// Path: uilib/src/main/java/com/razerdp/github/uilib/utils/ViewUtil.java
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.razerdp.github.lib.api.AppContext;
import androidx.annotation.LayoutRes;
package com.razerdp.github.uilib.utils;
/**
* Created by 大灯泡 on 2019/8/2.
*/
public class ViewUtil {
public static View inflate(@LayoutRes int layout, ViewGroup parent, boolean attachToParent) { | return LayoutInflater.from(AppContext.getAppContext()).inflate(layout, parent, attachToParent); |
razerdp/FriendCircle | lib/src/main/java/com/razerdp/github/lib/utils/VersionUtil.java | // Path: lib/src/main/java/com/razerdp/github/lib/api/AppContext.java
// public class AppContext {
//
// private static final String TAG = "AppContext";
// public static final Application sApplication;
// private static final InnerLifecycleHandler INNER_LIFECYCLE_HANDLER;
//
// static {
// Application app = null;
// try {
// app = (Application) Class.forName("android.app.AppGlobals").getMethod("getInitialApplication").invoke(null);
// if (app == null)
// throw new IllegalStateException("Static initialization of Applications must be on main thread.");
// } catch (final Exception e) {
// Log.e(TAG, "Failed to get current application from AppGlobals." + e.getMessage());
// try {
// app = (Application) Class.forName("android.app.ActivityThread").getMethod("currentApplication").invoke(null);
// } catch (final Exception ex) {
// Log.e(TAG, "Failed to get current application from ActivityThread." + e.getMessage());
// }
// } finally {
// sApplication = app;
// }
// INNER_LIFECYCLE_HANDLER = new InnerLifecycleHandler();
// if (sApplication != null) {
// sApplication.registerActivityLifecycleCallbacks(INNER_LIFECYCLE_HANDLER);
// }
// }
//
// public static boolean isAppVisable() {
// return INNER_LIFECYCLE_HANDLER != null && INNER_LIFECYCLE_HANDLER.started > INNER_LIFECYCLE_HANDLER.stopped;
// }
//
// public static boolean isAppBackground() {
// return INNER_LIFECYCLE_HANDLER != null && INNER_LIFECYCLE_HANDLER.resumed <= INNER_LIFECYCLE_HANDLER.stopped;
// }
//
// private static void checkAppContext() {
// if (sApplication == null)
// throw new IllegalStateException("app reference is null");
// }
//
// public static Application getAppInstance() {
// checkAppContext();
// return sApplication;
// }
//
// public static Context getAppContext() {
// checkAppContext();
// return sApplication.getApplicationContext();
// }
//
// public static Resources getResources() {
// checkAppContext();
// return sApplication.getResources();
// }
//
// public static boolean isMainThread() {
// return Looper.getMainLooper().getThread() == Thread.currentThread();
// }
//
//
// @Nullable
// public static FragmentActivity getTopActivity() {
// return INNER_LIFECYCLE_HANDLER.mTopActivity == null ? null : INNER_LIFECYCLE_HANDLER.mTopActivity.get();
// }
//
// private static class InnerLifecycleHandler implements Application.ActivityLifecycleCallbacks {
// private int created;
// private int resumed;
// private int paused;
// private int started;
// private int stopped;
// private WeakReference<FragmentActivity> mTopActivity;
//
// @Override
// public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
// ++created;
//
// }
//
// @Override
// public void onActivityStarted(Activity activity) {
// ++started;
//
// }
//
// @Override
// public void onActivityResumed(Activity activity) {
// ++resumed;
// if (mTopActivity != null) {
// mTopActivity.clear();
// }
// if (activity instanceof FragmentActivity) {
// mTopActivity = new WeakReference<>((FragmentActivity) activity);
// }
// }
//
// @Override
// public void onActivityPaused(Activity activity) {
// ++paused;
//
// }
//
// @Override
// public void onActivityStopped(Activity activity) {
// ++stopped;
//
// }
//
// @Override
// public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
//
// }
//
// @Override
// public void onActivityDestroyed(Activity activity) {
//
// }
// }
//
// }
| import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import com.razerdp.github.lib.api.AppContext; | package com.razerdp.github.lib.utils;
public class VersionUtil {
public static String getAppVersionName() {
try {
String versionName = ""; | // Path: lib/src/main/java/com/razerdp/github/lib/api/AppContext.java
// public class AppContext {
//
// private static final String TAG = "AppContext";
// public static final Application sApplication;
// private static final InnerLifecycleHandler INNER_LIFECYCLE_HANDLER;
//
// static {
// Application app = null;
// try {
// app = (Application) Class.forName("android.app.AppGlobals").getMethod("getInitialApplication").invoke(null);
// if (app == null)
// throw new IllegalStateException("Static initialization of Applications must be on main thread.");
// } catch (final Exception e) {
// Log.e(TAG, "Failed to get current application from AppGlobals." + e.getMessage());
// try {
// app = (Application) Class.forName("android.app.ActivityThread").getMethod("currentApplication").invoke(null);
// } catch (final Exception ex) {
// Log.e(TAG, "Failed to get current application from ActivityThread." + e.getMessage());
// }
// } finally {
// sApplication = app;
// }
// INNER_LIFECYCLE_HANDLER = new InnerLifecycleHandler();
// if (sApplication != null) {
// sApplication.registerActivityLifecycleCallbacks(INNER_LIFECYCLE_HANDLER);
// }
// }
//
// public static boolean isAppVisable() {
// return INNER_LIFECYCLE_HANDLER != null && INNER_LIFECYCLE_HANDLER.started > INNER_LIFECYCLE_HANDLER.stopped;
// }
//
// public static boolean isAppBackground() {
// return INNER_LIFECYCLE_HANDLER != null && INNER_LIFECYCLE_HANDLER.resumed <= INNER_LIFECYCLE_HANDLER.stopped;
// }
//
// private static void checkAppContext() {
// if (sApplication == null)
// throw new IllegalStateException("app reference is null");
// }
//
// public static Application getAppInstance() {
// checkAppContext();
// return sApplication;
// }
//
// public static Context getAppContext() {
// checkAppContext();
// return sApplication.getApplicationContext();
// }
//
// public static Resources getResources() {
// checkAppContext();
// return sApplication.getResources();
// }
//
// public static boolean isMainThread() {
// return Looper.getMainLooper().getThread() == Thread.currentThread();
// }
//
//
// @Nullable
// public static FragmentActivity getTopActivity() {
// return INNER_LIFECYCLE_HANDLER.mTopActivity == null ? null : INNER_LIFECYCLE_HANDLER.mTopActivity.get();
// }
//
// private static class InnerLifecycleHandler implements Application.ActivityLifecycleCallbacks {
// private int created;
// private int resumed;
// private int paused;
// private int started;
// private int stopped;
// private WeakReference<FragmentActivity> mTopActivity;
//
// @Override
// public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
// ++created;
//
// }
//
// @Override
// public void onActivityStarted(Activity activity) {
// ++started;
//
// }
//
// @Override
// public void onActivityResumed(Activity activity) {
// ++resumed;
// if (mTopActivity != null) {
// mTopActivity.clear();
// }
// if (activity instanceof FragmentActivity) {
// mTopActivity = new WeakReference<>((FragmentActivity) activity);
// }
// }
//
// @Override
// public void onActivityPaused(Activity activity) {
// ++paused;
//
// }
//
// @Override
// public void onActivityStopped(Activity activity) {
// ++stopped;
//
// }
//
// @Override
// public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
//
// }
//
// @Override
// public void onActivityDestroyed(Activity activity) {
//
// }
// }
//
// }
// Path: lib/src/main/java/com/razerdp/github/lib/utils/VersionUtil.java
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import com.razerdp.github.lib.api.AppContext;
package com.razerdp.github.lib.utils;
public class VersionUtil {
public static String getAppVersionName() {
try {
String versionName = ""; | Context context = AppContext.getAppContext(); |
razerdp/FriendCircle | module_main/src/main/java/com/razerdp/github/module/main/services/TestServiceImpl.java | // Path: lib/src/main/java/com/razerdp/github/lib/utils/UIHelper.java
// public class UIHelper {
//
// public static int getColor(@ColorRes int colorResId) {
// try {
// return ContextCompat.getColor(AppContext.getAppContext(), colorResId);
// } catch (Exception e) {
// return Color.TRANSPARENT;
// }
// }
//
//
// public static void toast(@StringRes int textResId) {
// toast(StringUtil.getString(textResId));
// }
//
// public static void toast(String text) {
// toast(text, Toast.LENGTH_SHORT);
// }
//
// public static void toast(@StringRes int textResId, int duration) {
// toast(StringUtil.getString(textResId), duration);
// }
//
// public static void toast(String text, int duration) {
// Toast.makeText(AppContext.getAppContext(), text, duration).show();
// }
//
// public static int getNavigationBarHeight() {
// Resources resources = AppContext.getResources();
// int resourceId = resources.getIdentifier("navigation_bar_height",
// "dimen", "android");
// if (resourceId > 0) {
// //获取NavigationBar的高度
// return resources.getDimensionPixelSize(resourceId);
// }
// return 0;
// }
//
// /**
// * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
// */
// public static int dip2px(float dpValue) {
// final float scale = Resources.getSystem().getDisplayMetrics().density;
// return (int) (dpValue * scale + 0.5f);
// }
//
// /**
// * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
// */
// public static int px2dip(float pxValue) {
// final float scale = Resources.getSystem().getDisplayMetrics().density;
// return (int) (pxValue / scale + 0.5f);
// }
//
// public static int sp2px(float spValue) {
// return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
// spValue, Resources.getSystem().getDisplayMetrics());
// }
//
// public static int getScreenWidth() {
// return Resources.getSystem().getDisplayMetrics().widthPixels;
// }
//
// public static int getScreenHeight() {
// return Resources.getSystem().getDisplayMetrics().heightPixels;
// }
// }
//
// Path: router/src/main/java/com/razerdp/github/router/TestService.java
// public interface TestService {
//
// void test();
// }
| import com.razerdp.github.lib.utils.UIHelper;
import com.razerdp.github.router.TestService;
import com.razerdp.lib.annotations.ServiceImpl; | package com.razerdp.github.module.main.services;
/**
* Created by 大灯泡 on 2019/8/14.
*/
@ServiceImpl
public class TestServiceImpl implements TestService {
@Override
public void test() { | // Path: lib/src/main/java/com/razerdp/github/lib/utils/UIHelper.java
// public class UIHelper {
//
// public static int getColor(@ColorRes int colorResId) {
// try {
// return ContextCompat.getColor(AppContext.getAppContext(), colorResId);
// } catch (Exception e) {
// return Color.TRANSPARENT;
// }
// }
//
//
// public static void toast(@StringRes int textResId) {
// toast(StringUtil.getString(textResId));
// }
//
// public static void toast(String text) {
// toast(text, Toast.LENGTH_SHORT);
// }
//
// public static void toast(@StringRes int textResId, int duration) {
// toast(StringUtil.getString(textResId), duration);
// }
//
// public static void toast(String text, int duration) {
// Toast.makeText(AppContext.getAppContext(), text, duration).show();
// }
//
// public static int getNavigationBarHeight() {
// Resources resources = AppContext.getResources();
// int resourceId = resources.getIdentifier("navigation_bar_height",
// "dimen", "android");
// if (resourceId > 0) {
// //获取NavigationBar的高度
// return resources.getDimensionPixelSize(resourceId);
// }
// return 0;
// }
//
// /**
// * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
// */
// public static int dip2px(float dpValue) {
// final float scale = Resources.getSystem().getDisplayMetrics().density;
// return (int) (dpValue * scale + 0.5f);
// }
//
// /**
// * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
// */
// public static int px2dip(float pxValue) {
// final float scale = Resources.getSystem().getDisplayMetrics().density;
// return (int) (pxValue / scale + 0.5f);
// }
//
// public static int sp2px(float spValue) {
// return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
// spValue, Resources.getSystem().getDisplayMetrics());
// }
//
// public static int getScreenWidth() {
// return Resources.getSystem().getDisplayMetrics().widthPixels;
// }
//
// public static int getScreenHeight() {
// return Resources.getSystem().getDisplayMetrics().heightPixels;
// }
// }
//
// Path: router/src/main/java/com/razerdp/github/router/TestService.java
// public interface TestService {
//
// void test();
// }
// Path: module_main/src/main/java/com/razerdp/github/module/main/services/TestServiceImpl.java
import com.razerdp.github.lib.utils.UIHelper;
import com.razerdp.github.router.TestService;
import com.razerdp.lib.annotations.ServiceImpl;
package com.razerdp.github.module.main.services;
/**
* Created by 大灯泡 on 2019/8/14.
*/
@ServiceImpl
public class TestServiceImpl implements TestService {
@Override
public void test() { | UIHelper.toast("Test"); |
razerdp/FriendCircle | lib/src/main/java/com/razerdp/github/lib/utils/log/KLog.java | // Path: lib/src/main/java/com/razerdp/github/lib/api/AppContext.java
// public class AppContext {
//
// private static final String TAG = "AppContext";
// public static final Application sApplication;
// private static final InnerLifecycleHandler INNER_LIFECYCLE_HANDLER;
//
// static {
// Application app = null;
// try {
// app = (Application) Class.forName("android.app.AppGlobals").getMethod("getInitialApplication").invoke(null);
// if (app == null)
// throw new IllegalStateException("Static initialization of Applications must be on main thread.");
// } catch (final Exception e) {
// Log.e(TAG, "Failed to get current application from AppGlobals." + e.getMessage());
// try {
// app = (Application) Class.forName("android.app.ActivityThread").getMethod("currentApplication").invoke(null);
// } catch (final Exception ex) {
// Log.e(TAG, "Failed to get current application from ActivityThread." + e.getMessage());
// }
// } finally {
// sApplication = app;
// }
// INNER_LIFECYCLE_HANDLER = new InnerLifecycleHandler();
// if (sApplication != null) {
// sApplication.registerActivityLifecycleCallbacks(INNER_LIFECYCLE_HANDLER);
// }
// }
//
// public static boolean isAppVisable() {
// return INNER_LIFECYCLE_HANDLER != null && INNER_LIFECYCLE_HANDLER.started > INNER_LIFECYCLE_HANDLER.stopped;
// }
//
// public static boolean isAppBackground() {
// return INNER_LIFECYCLE_HANDLER != null && INNER_LIFECYCLE_HANDLER.resumed <= INNER_LIFECYCLE_HANDLER.stopped;
// }
//
// private static void checkAppContext() {
// if (sApplication == null)
// throw new IllegalStateException("app reference is null");
// }
//
// public static Application getAppInstance() {
// checkAppContext();
// return sApplication;
// }
//
// public static Context getAppContext() {
// checkAppContext();
// return sApplication.getApplicationContext();
// }
//
// public static Resources getResources() {
// checkAppContext();
// return sApplication.getResources();
// }
//
// public static boolean isMainThread() {
// return Looper.getMainLooper().getThread() == Thread.currentThread();
// }
//
//
// @Nullable
// public static FragmentActivity getTopActivity() {
// return INNER_LIFECYCLE_HANDLER.mTopActivity == null ? null : INNER_LIFECYCLE_HANDLER.mTopActivity.get();
// }
//
// private static class InnerLifecycleHandler implements Application.ActivityLifecycleCallbacks {
// private int created;
// private int resumed;
// private int paused;
// private int started;
// private int stopped;
// private WeakReference<FragmentActivity> mTopActivity;
//
// @Override
// public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
// ++created;
//
// }
//
// @Override
// public void onActivityStarted(Activity activity) {
// ++started;
//
// }
//
// @Override
// public void onActivityResumed(Activity activity) {
// ++resumed;
// if (mTopActivity != null) {
// mTopActivity.clear();
// }
// if (activity instanceof FragmentActivity) {
// mTopActivity = new WeakReference<>((FragmentActivity) activity);
// }
// }
//
// @Override
// public void onActivityPaused(Activity activity) {
// ++paused;
//
// }
//
// @Override
// public void onActivityStopped(Activity activity) {
// ++stopped;
//
// }
//
// @Override
// public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
//
// }
//
// @Override
// public void onActivityDestroyed(Activity activity) {
//
// }
// }
//
// }
| import android.text.TextUtils;
import android.util.Log;
import com.razerdp.github.lib.api.AppContext;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.logging.Logger; | package com.razerdp.github.lib.utils.log;
/**
* Created by 大灯泡 on 2019/7/30.
*/
public class KLog {
public enum LogLevel {
v(5),
i(4),
d(3),
w(2),
e(1);
public final int level;
LogLevel(int level) {
this.level = level;
}
}
| // Path: lib/src/main/java/com/razerdp/github/lib/api/AppContext.java
// public class AppContext {
//
// private static final String TAG = "AppContext";
// public static final Application sApplication;
// private static final InnerLifecycleHandler INNER_LIFECYCLE_HANDLER;
//
// static {
// Application app = null;
// try {
// app = (Application) Class.forName("android.app.AppGlobals").getMethod("getInitialApplication").invoke(null);
// if (app == null)
// throw new IllegalStateException("Static initialization of Applications must be on main thread.");
// } catch (final Exception e) {
// Log.e(TAG, "Failed to get current application from AppGlobals." + e.getMessage());
// try {
// app = (Application) Class.forName("android.app.ActivityThread").getMethod("currentApplication").invoke(null);
// } catch (final Exception ex) {
// Log.e(TAG, "Failed to get current application from ActivityThread." + e.getMessage());
// }
// } finally {
// sApplication = app;
// }
// INNER_LIFECYCLE_HANDLER = new InnerLifecycleHandler();
// if (sApplication != null) {
// sApplication.registerActivityLifecycleCallbacks(INNER_LIFECYCLE_HANDLER);
// }
// }
//
// public static boolean isAppVisable() {
// return INNER_LIFECYCLE_HANDLER != null && INNER_LIFECYCLE_HANDLER.started > INNER_LIFECYCLE_HANDLER.stopped;
// }
//
// public static boolean isAppBackground() {
// return INNER_LIFECYCLE_HANDLER != null && INNER_LIFECYCLE_HANDLER.resumed <= INNER_LIFECYCLE_HANDLER.stopped;
// }
//
// private static void checkAppContext() {
// if (sApplication == null)
// throw new IllegalStateException("app reference is null");
// }
//
// public static Application getAppInstance() {
// checkAppContext();
// return sApplication;
// }
//
// public static Context getAppContext() {
// checkAppContext();
// return sApplication.getApplicationContext();
// }
//
// public static Resources getResources() {
// checkAppContext();
// return sApplication.getResources();
// }
//
// public static boolean isMainThread() {
// return Looper.getMainLooper().getThread() == Thread.currentThread();
// }
//
//
// @Nullable
// public static FragmentActivity getTopActivity() {
// return INNER_LIFECYCLE_HANDLER.mTopActivity == null ? null : INNER_LIFECYCLE_HANDLER.mTopActivity.get();
// }
//
// private static class InnerLifecycleHandler implements Application.ActivityLifecycleCallbacks {
// private int created;
// private int resumed;
// private int paused;
// private int started;
// private int stopped;
// private WeakReference<FragmentActivity> mTopActivity;
//
// @Override
// public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
// ++created;
//
// }
//
// @Override
// public void onActivityStarted(Activity activity) {
// ++started;
//
// }
//
// @Override
// public void onActivityResumed(Activity activity) {
// ++resumed;
// if (mTopActivity != null) {
// mTopActivity.clear();
// }
// if (activity instanceof FragmentActivity) {
// mTopActivity = new WeakReference<>((FragmentActivity) activity);
// }
// }
//
// @Override
// public void onActivityPaused(Activity activity) {
// ++paused;
//
// }
//
// @Override
// public void onActivityStopped(Activity activity) {
// ++stopped;
//
// }
//
// @Override
// public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
//
// }
//
// @Override
// public void onActivityDestroyed(Activity activity) {
//
// }
// }
//
// }
// Path: lib/src/main/java/com/razerdp/github/lib/utils/log/KLog.java
import android.text.TextUtils;
import android.util.Log;
import com.razerdp.github.lib.api.AppContext;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.logging.Logger;
package com.razerdp.github.lib.utils.log;
/**
* Created by 大灯泡 on 2019/7/30.
*/
public class KLog {
public enum LogLevel {
v(5),
i(4),
d(3),
w(2),
e(1);
public final int level;
LogLevel(int level) {
this.level = level;
}
}
| private static final String TAG = AppContext.getAppContext().getPackageName(); |
razerdp/FriendCircle | lib/src/main/java/com/razerdp/github/lib/helper/SharePreferenceHelper.java | // Path: lib/src/main/java/com/razerdp/github/lib/api/AppContext.java
// public class AppContext {
//
// private static final String TAG = "AppContext";
// public static final Application sApplication;
// private static final InnerLifecycleHandler INNER_LIFECYCLE_HANDLER;
//
// static {
// Application app = null;
// try {
// app = (Application) Class.forName("android.app.AppGlobals").getMethod("getInitialApplication").invoke(null);
// if (app == null)
// throw new IllegalStateException("Static initialization of Applications must be on main thread.");
// } catch (final Exception e) {
// Log.e(TAG, "Failed to get current application from AppGlobals." + e.getMessage());
// try {
// app = (Application) Class.forName("android.app.ActivityThread").getMethod("currentApplication").invoke(null);
// } catch (final Exception ex) {
// Log.e(TAG, "Failed to get current application from ActivityThread." + e.getMessage());
// }
// } finally {
// sApplication = app;
// }
// INNER_LIFECYCLE_HANDLER = new InnerLifecycleHandler();
// if (sApplication != null) {
// sApplication.registerActivityLifecycleCallbacks(INNER_LIFECYCLE_HANDLER);
// }
// }
//
// public static boolean isAppVisable() {
// return INNER_LIFECYCLE_HANDLER != null && INNER_LIFECYCLE_HANDLER.started > INNER_LIFECYCLE_HANDLER.stopped;
// }
//
// public static boolean isAppBackground() {
// return INNER_LIFECYCLE_HANDLER != null && INNER_LIFECYCLE_HANDLER.resumed <= INNER_LIFECYCLE_HANDLER.stopped;
// }
//
// private static void checkAppContext() {
// if (sApplication == null)
// throw new IllegalStateException("app reference is null");
// }
//
// public static Application getAppInstance() {
// checkAppContext();
// return sApplication;
// }
//
// public static Context getAppContext() {
// checkAppContext();
// return sApplication.getApplicationContext();
// }
//
// public static Resources getResources() {
// checkAppContext();
// return sApplication.getResources();
// }
//
// public static boolean isMainThread() {
// return Looper.getMainLooper().getThread() == Thread.currentThread();
// }
//
//
// @Nullable
// public static FragmentActivity getTopActivity() {
// return INNER_LIFECYCLE_HANDLER.mTopActivity == null ? null : INNER_LIFECYCLE_HANDLER.mTopActivity.get();
// }
//
// private static class InnerLifecycleHandler implements Application.ActivityLifecycleCallbacks {
// private int created;
// private int resumed;
// private int paused;
// private int started;
// private int stopped;
// private WeakReference<FragmentActivity> mTopActivity;
//
// @Override
// public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
// ++created;
//
// }
//
// @Override
// public void onActivityStarted(Activity activity) {
// ++started;
//
// }
//
// @Override
// public void onActivityResumed(Activity activity) {
// ++resumed;
// if (mTopActivity != null) {
// mTopActivity.clear();
// }
// if (activity instanceof FragmentActivity) {
// mTopActivity = new WeakReference<>((FragmentActivity) activity);
// }
// }
//
// @Override
// public void onActivityPaused(Activity activity) {
// ++paused;
//
// }
//
// @Override
// public void onActivityStopped(Activity activity) {
// ++stopped;
//
// }
//
// @Override
// public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
//
// }
//
// @Override
// public void onActivityDestroyed(Activity activity) {
//
// }
// }
//
// }
| import android.content.Context;
import android.content.SharedPreferences;
import com.razerdp.github.lib.api.AppContext;
import java.util.Map; | package com.razerdp.github.lib.helper;
/**
* Created by 大灯泡 on 2016/10/28.
* <p>
* preference单例
*/
public class SharePreferenceHelper {
public static final String HAS_LOGIN = "haslogin";
public static final String HOST_NAME = "hostName";
public static final String HOST_AVATAR = "hostAvatar";
public static final String HOST_NICK = "hostNick";
public static final String HOST_ID = "hostId";
public static final String HOST_COVER = "cover";
public static final String CHECK_REGISTER = "check_register";
public static final String APP_HAS_SCAN_IMG = "has_scan_img";
public static final String APP_LAST_SCAN_IMG_TIME = "last_scan_image_time";
private static final String PERFERENCE_NAME = "FriendCircleData"; | // Path: lib/src/main/java/com/razerdp/github/lib/api/AppContext.java
// public class AppContext {
//
// private static final String TAG = "AppContext";
// public static final Application sApplication;
// private static final InnerLifecycleHandler INNER_LIFECYCLE_HANDLER;
//
// static {
// Application app = null;
// try {
// app = (Application) Class.forName("android.app.AppGlobals").getMethod("getInitialApplication").invoke(null);
// if (app == null)
// throw new IllegalStateException("Static initialization of Applications must be on main thread.");
// } catch (final Exception e) {
// Log.e(TAG, "Failed to get current application from AppGlobals." + e.getMessage());
// try {
// app = (Application) Class.forName("android.app.ActivityThread").getMethod("currentApplication").invoke(null);
// } catch (final Exception ex) {
// Log.e(TAG, "Failed to get current application from ActivityThread." + e.getMessage());
// }
// } finally {
// sApplication = app;
// }
// INNER_LIFECYCLE_HANDLER = new InnerLifecycleHandler();
// if (sApplication != null) {
// sApplication.registerActivityLifecycleCallbacks(INNER_LIFECYCLE_HANDLER);
// }
// }
//
// public static boolean isAppVisable() {
// return INNER_LIFECYCLE_HANDLER != null && INNER_LIFECYCLE_HANDLER.started > INNER_LIFECYCLE_HANDLER.stopped;
// }
//
// public static boolean isAppBackground() {
// return INNER_LIFECYCLE_HANDLER != null && INNER_LIFECYCLE_HANDLER.resumed <= INNER_LIFECYCLE_HANDLER.stopped;
// }
//
// private static void checkAppContext() {
// if (sApplication == null)
// throw new IllegalStateException("app reference is null");
// }
//
// public static Application getAppInstance() {
// checkAppContext();
// return sApplication;
// }
//
// public static Context getAppContext() {
// checkAppContext();
// return sApplication.getApplicationContext();
// }
//
// public static Resources getResources() {
// checkAppContext();
// return sApplication.getResources();
// }
//
// public static boolean isMainThread() {
// return Looper.getMainLooper().getThread() == Thread.currentThread();
// }
//
//
// @Nullable
// public static FragmentActivity getTopActivity() {
// return INNER_LIFECYCLE_HANDLER.mTopActivity == null ? null : INNER_LIFECYCLE_HANDLER.mTopActivity.get();
// }
//
// private static class InnerLifecycleHandler implements Application.ActivityLifecycleCallbacks {
// private int created;
// private int resumed;
// private int paused;
// private int started;
// private int stopped;
// private WeakReference<FragmentActivity> mTopActivity;
//
// @Override
// public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
// ++created;
//
// }
//
// @Override
// public void onActivityStarted(Activity activity) {
// ++started;
//
// }
//
// @Override
// public void onActivityResumed(Activity activity) {
// ++resumed;
// if (mTopActivity != null) {
// mTopActivity.clear();
// }
// if (activity instanceof FragmentActivity) {
// mTopActivity = new WeakReference<>((FragmentActivity) activity);
// }
// }
//
// @Override
// public void onActivityPaused(Activity activity) {
// ++paused;
//
// }
//
// @Override
// public void onActivityStopped(Activity activity) {
// ++stopped;
//
// }
//
// @Override
// public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
//
// }
//
// @Override
// public void onActivityDestroyed(Activity activity) {
//
// }
// }
//
// }
// Path: lib/src/main/java/com/razerdp/github/lib/helper/SharePreferenceHelper.java
import android.content.Context;
import android.content.SharedPreferences;
import com.razerdp.github.lib.api.AppContext;
import java.util.Map;
package com.razerdp.github.lib.helper;
/**
* Created by 大灯泡 on 2016/10/28.
* <p>
* preference单例
*/
public class SharePreferenceHelper {
public static final String HAS_LOGIN = "haslogin";
public static final String HOST_NAME = "hostName";
public static final String HOST_AVATAR = "hostAvatar";
public static final String HOST_NICK = "hostNick";
public static final String HOST_ID = "hostId";
public static final String HOST_COVER = "cover";
public static final String CHECK_REGISTER = "check_register";
public static final String APP_HAS_SCAN_IMG = "has_scan_img";
public static final String APP_LAST_SCAN_IMG_TIME = "last_scan_image_time";
private static final String PERFERENCE_NAME = "FriendCircleData"; | private static SharedPreferences sharedPreferences = AppContext.getAppContext().getSharedPreferences(PERFERENCE_NAME, Context.MODE_PRIVATE); |
razerdp/FriendCircle | lib/src/main/java/com/razerdp/github/lib/utils/UIHelper.java | // Path: lib/src/main/java/com/razerdp/github/lib/api/AppContext.java
// public class AppContext {
//
// private static final String TAG = "AppContext";
// public static final Application sApplication;
// private static final InnerLifecycleHandler INNER_LIFECYCLE_HANDLER;
//
// static {
// Application app = null;
// try {
// app = (Application) Class.forName("android.app.AppGlobals").getMethod("getInitialApplication").invoke(null);
// if (app == null)
// throw new IllegalStateException("Static initialization of Applications must be on main thread.");
// } catch (final Exception e) {
// Log.e(TAG, "Failed to get current application from AppGlobals." + e.getMessage());
// try {
// app = (Application) Class.forName("android.app.ActivityThread").getMethod("currentApplication").invoke(null);
// } catch (final Exception ex) {
// Log.e(TAG, "Failed to get current application from ActivityThread." + e.getMessage());
// }
// } finally {
// sApplication = app;
// }
// INNER_LIFECYCLE_HANDLER = new InnerLifecycleHandler();
// if (sApplication != null) {
// sApplication.registerActivityLifecycleCallbacks(INNER_LIFECYCLE_HANDLER);
// }
// }
//
// public static boolean isAppVisable() {
// return INNER_LIFECYCLE_HANDLER != null && INNER_LIFECYCLE_HANDLER.started > INNER_LIFECYCLE_HANDLER.stopped;
// }
//
// public static boolean isAppBackground() {
// return INNER_LIFECYCLE_HANDLER != null && INNER_LIFECYCLE_HANDLER.resumed <= INNER_LIFECYCLE_HANDLER.stopped;
// }
//
// private static void checkAppContext() {
// if (sApplication == null)
// throw new IllegalStateException("app reference is null");
// }
//
// public static Application getAppInstance() {
// checkAppContext();
// return sApplication;
// }
//
// public static Context getAppContext() {
// checkAppContext();
// return sApplication.getApplicationContext();
// }
//
// public static Resources getResources() {
// checkAppContext();
// return sApplication.getResources();
// }
//
// public static boolean isMainThread() {
// return Looper.getMainLooper().getThread() == Thread.currentThread();
// }
//
//
// @Nullable
// public static FragmentActivity getTopActivity() {
// return INNER_LIFECYCLE_HANDLER.mTopActivity == null ? null : INNER_LIFECYCLE_HANDLER.mTopActivity.get();
// }
//
// private static class InnerLifecycleHandler implements Application.ActivityLifecycleCallbacks {
// private int created;
// private int resumed;
// private int paused;
// private int started;
// private int stopped;
// private WeakReference<FragmentActivity> mTopActivity;
//
// @Override
// public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
// ++created;
//
// }
//
// @Override
// public void onActivityStarted(Activity activity) {
// ++started;
//
// }
//
// @Override
// public void onActivityResumed(Activity activity) {
// ++resumed;
// if (mTopActivity != null) {
// mTopActivity.clear();
// }
// if (activity instanceof FragmentActivity) {
// mTopActivity = new WeakReference<>((FragmentActivity) activity);
// }
// }
//
// @Override
// public void onActivityPaused(Activity activity) {
// ++paused;
//
// }
//
// @Override
// public void onActivityStopped(Activity activity) {
// ++stopped;
//
// }
//
// @Override
// public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
//
// }
//
// @Override
// public void onActivityDestroyed(Activity activity) {
//
// }
// }
//
// }
| import android.content.res.Resources;
import android.graphics.Color;
import android.util.TypedValue;
import android.widget.Toast;
import com.razerdp.github.lib.api.AppContext;
import androidx.annotation.ColorRes;
import androidx.annotation.StringRes;
import androidx.core.content.ContextCompat; | package com.razerdp.github.lib.utils;
/**
* Created by 大灯泡 on 2019/8/3.
*/
public class UIHelper {
public static int getColor(@ColorRes int colorResId) {
try { | // Path: lib/src/main/java/com/razerdp/github/lib/api/AppContext.java
// public class AppContext {
//
// private static final String TAG = "AppContext";
// public static final Application sApplication;
// private static final InnerLifecycleHandler INNER_LIFECYCLE_HANDLER;
//
// static {
// Application app = null;
// try {
// app = (Application) Class.forName("android.app.AppGlobals").getMethod("getInitialApplication").invoke(null);
// if (app == null)
// throw new IllegalStateException("Static initialization of Applications must be on main thread.");
// } catch (final Exception e) {
// Log.e(TAG, "Failed to get current application from AppGlobals." + e.getMessage());
// try {
// app = (Application) Class.forName("android.app.ActivityThread").getMethod("currentApplication").invoke(null);
// } catch (final Exception ex) {
// Log.e(TAG, "Failed to get current application from ActivityThread." + e.getMessage());
// }
// } finally {
// sApplication = app;
// }
// INNER_LIFECYCLE_HANDLER = new InnerLifecycleHandler();
// if (sApplication != null) {
// sApplication.registerActivityLifecycleCallbacks(INNER_LIFECYCLE_HANDLER);
// }
// }
//
// public static boolean isAppVisable() {
// return INNER_LIFECYCLE_HANDLER != null && INNER_LIFECYCLE_HANDLER.started > INNER_LIFECYCLE_HANDLER.stopped;
// }
//
// public static boolean isAppBackground() {
// return INNER_LIFECYCLE_HANDLER != null && INNER_LIFECYCLE_HANDLER.resumed <= INNER_LIFECYCLE_HANDLER.stopped;
// }
//
// private static void checkAppContext() {
// if (sApplication == null)
// throw new IllegalStateException("app reference is null");
// }
//
// public static Application getAppInstance() {
// checkAppContext();
// return sApplication;
// }
//
// public static Context getAppContext() {
// checkAppContext();
// return sApplication.getApplicationContext();
// }
//
// public static Resources getResources() {
// checkAppContext();
// return sApplication.getResources();
// }
//
// public static boolean isMainThread() {
// return Looper.getMainLooper().getThread() == Thread.currentThread();
// }
//
//
// @Nullable
// public static FragmentActivity getTopActivity() {
// return INNER_LIFECYCLE_HANDLER.mTopActivity == null ? null : INNER_LIFECYCLE_HANDLER.mTopActivity.get();
// }
//
// private static class InnerLifecycleHandler implements Application.ActivityLifecycleCallbacks {
// private int created;
// private int resumed;
// private int paused;
// private int started;
// private int stopped;
// private WeakReference<FragmentActivity> mTopActivity;
//
// @Override
// public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
// ++created;
//
// }
//
// @Override
// public void onActivityStarted(Activity activity) {
// ++started;
//
// }
//
// @Override
// public void onActivityResumed(Activity activity) {
// ++resumed;
// if (mTopActivity != null) {
// mTopActivity.clear();
// }
// if (activity instanceof FragmentActivity) {
// mTopActivity = new WeakReference<>((FragmentActivity) activity);
// }
// }
//
// @Override
// public void onActivityPaused(Activity activity) {
// ++paused;
//
// }
//
// @Override
// public void onActivityStopped(Activity activity) {
// ++stopped;
//
// }
//
// @Override
// public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
//
// }
//
// @Override
// public void onActivityDestroyed(Activity activity) {
//
// }
// }
//
// }
// Path: lib/src/main/java/com/razerdp/github/lib/utils/UIHelper.java
import android.content.res.Resources;
import android.graphics.Color;
import android.util.TypedValue;
import android.widget.Toast;
import com.razerdp.github.lib.api.AppContext;
import androidx.annotation.ColorRes;
import androidx.annotation.StringRes;
import androidx.core.content.ContextCompat;
package com.razerdp.github.lib.utils;
/**
* Created by 大灯泡 on 2019/8/3.
*/
public class UIHelper {
public static int getColor(@ColorRes int colorResId) {
try { | return ContextCompat.getColor(AppContext.getAppContext(), colorResId); |
razerdp/FriendCircle | lib_processor/src/main/java/com/razerdp/lib/processor/BaseProcessor.java | // Path: lib_processor/src/main/java/com/razerdp/lib/processor/util/Logger.java
// public class Logger {
// private Messager msg;
//
// public Logger(Messager msg) {
// this.msg = msg;
// }
//
// public void i(CharSequence info) {
// msg.printMessage(Diagnostic.Kind.NOTE, info);
// }
//
// public void e(CharSequence error) {
// msg.printMessage(Diagnostic.Kind.ERROR, error);
// }
//
// public void w(CharSequence warning) {
// msg.printMessage(Diagnostic.Kind.WARNING, warning);
// }
//
// public void e(Throwable error) {
// msg.printMessage(Diagnostic.Kind.ERROR, "Catch Exception : [" + error.getMessage() + "]\n" + loadStackTrace(error));
// }
//
//
// private String loadStackTrace(Throwable error) {
// StringBuilder builder = new StringBuilder();
// StackTraceElement[] traceElements = error.getStackTrace();
// for (StackTraceElement traceElement : traceElements) {
// builder.append("\tat ")
// .append(traceElement.toString())
// .append('\n');
// }
// return builder.toString();
//
// }
// }
| import com.razerdp.lib.processor.util.Logger;
import java.lang.annotation.Annotation;
import java.util.LinkedHashSet;
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Filer;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.SourceVersion;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types; | package com.razerdp.lib.processor;
/**
* Created by razerdp on 2019/8/12.
*/
public abstract class BaseProcessor extends AbstractProcessor {
protected Filer mFiler; | // Path: lib_processor/src/main/java/com/razerdp/lib/processor/util/Logger.java
// public class Logger {
// private Messager msg;
//
// public Logger(Messager msg) {
// this.msg = msg;
// }
//
// public void i(CharSequence info) {
// msg.printMessage(Diagnostic.Kind.NOTE, info);
// }
//
// public void e(CharSequence error) {
// msg.printMessage(Diagnostic.Kind.ERROR, error);
// }
//
// public void w(CharSequence warning) {
// msg.printMessage(Diagnostic.Kind.WARNING, warning);
// }
//
// public void e(Throwable error) {
// msg.printMessage(Diagnostic.Kind.ERROR, "Catch Exception : [" + error.getMessage() + "]\n" + loadStackTrace(error));
// }
//
//
// private String loadStackTrace(Throwable error) {
// StringBuilder builder = new StringBuilder();
// StackTraceElement[] traceElements = error.getStackTrace();
// for (StackTraceElement traceElement : traceElements) {
// builder.append("\tat ")
// .append(traceElement.toString())
// .append('\n');
// }
// return builder.toString();
//
// }
// }
// Path: lib_processor/src/main/java/com/razerdp/lib/processor/BaseProcessor.java
import com.razerdp.lib.processor.util.Logger;
import java.lang.annotation.Annotation;
import java.util.LinkedHashSet;
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Filer;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.SourceVersion;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
package com.razerdp.lib.processor;
/**
* Created by razerdp on 2019/8/12.
*/
public abstract class BaseProcessor extends AbstractProcessor {
protected Filer mFiler; | protected Logger mLogger; |
razerdp/FriendCircle | lib/src/main/java/com/razerdp/github/lib/utils/StringUtil.java | // Path: lib/src/main/java/com/razerdp/github/lib/api/AppContext.java
// public class AppContext {
//
// private static final String TAG = "AppContext";
// public static final Application sApplication;
// private static final InnerLifecycleHandler INNER_LIFECYCLE_HANDLER;
//
// static {
// Application app = null;
// try {
// app = (Application) Class.forName("android.app.AppGlobals").getMethod("getInitialApplication").invoke(null);
// if (app == null)
// throw new IllegalStateException("Static initialization of Applications must be on main thread.");
// } catch (final Exception e) {
// Log.e(TAG, "Failed to get current application from AppGlobals." + e.getMessage());
// try {
// app = (Application) Class.forName("android.app.ActivityThread").getMethod("currentApplication").invoke(null);
// } catch (final Exception ex) {
// Log.e(TAG, "Failed to get current application from ActivityThread." + e.getMessage());
// }
// } finally {
// sApplication = app;
// }
// INNER_LIFECYCLE_HANDLER = new InnerLifecycleHandler();
// if (sApplication != null) {
// sApplication.registerActivityLifecycleCallbacks(INNER_LIFECYCLE_HANDLER);
// }
// }
//
// public static boolean isAppVisable() {
// return INNER_LIFECYCLE_HANDLER != null && INNER_LIFECYCLE_HANDLER.started > INNER_LIFECYCLE_HANDLER.stopped;
// }
//
// public static boolean isAppBackground() {
// return INNER_LIFECYCLE_HANDLER != null && INNER_LIFECYCLE_HANDLER.resumed <= INNER_LIFECYCLE_HANDLER.stopped;
// }
//
// private static void checkAppContext() {
// if (sApplication == null)
// throw new IllegalStateException("app reference is null");
// }
//
// public static Application getAppInstance() {
// checkAppContext();
// return sApplication;
// }
//
// public static Context getAppContext() {
// checkAppContext();
// return sApplication.getApplicationContext();
// }
//
// public static Resources getResources() {
// checkAppContext();
// return sApplication.getResources();
// }
//
// public static boolean isMainThread() {
// return Looper.getMainLooper().getThread() == Thread.currentThread();
// }
//
//
// @Nullable
// public static FragmentActivity getTopActivity() {
// return INNER_LIFECYCLE_HANDLER.mTopActivity == null ? null : INNER_LIFECYCLE_HANDLER.mTopActivity.get();
// }
//
// private static class InnerLifecycleHandler implements Application.ActivityLifecycleCallbacks {
// private int created;
// private int resumed;
// private int paused;
// private int started;
// private int stopped;
// private WeakReference<FragmentActivity> mTopActivity;
//
// @Override
// public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
// ++created;
//
// }
//
// @Override
// public void onActivityStarted(Activity activity) {
// ++started;
//
// }
//
// @Override
// public void onActivityResumed(Activity activity) {
// ++resumed;
// if (mTopActivity != null) {
// mTopActivity.clear();
// }
// if (activity instanceof FragmentActivity) {
// mTopActivity = new WeakReference<>((FragmentActivity) activity);
// }
// }
//
// @Override
// public void onActivityPaused(Activity activity) {
// ++paused;
//
// }
//
// @Override
// public void onActivityStopped(Activity activity) {
// ++stopped;
//
// }
//
// @Override
// public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
//
// }
//
// @Override
// public void onActivityDestroyed(Activity activity) {
//
// }
// }
//
// }
| import android.text.TextUtils;
import com.razerdp.github.lib.api.AppContext;
import androidx.annotation.ArrayRes;
import androidx.annotation.StringRes; | package com.razerdp.github.lib.utils;
/**
* Created by 大灯泡 on 2016/10/28.
* <p>
* 字符串工具类
*/
public class StringUtil {
public static boolean noEmpty(String originStr) {
return !TextUtils.isEmpty(originStr);
}
public static boolean noEmpty(String... originStr) {
boolean noEmpty = true;
for (String s : originStr) {
if (TextUtils.isEmpty(s)) {
noEmpty = false;
break;
}
}
return noEmpty;
}
/**
* 从资源文件拿到文字
*/
public static String getString(@StringRes int strId, Object... objs) {
if (strId == 0) return null; | // Path: lib/src/main/java/com/razerdp/github/lib/api/AppContext.java
// public class AppContext {
//
// private static final String TAG = "AppContext";
// public static final Application sApplication;
// private static final InnerLifecycleHandler INNER_LIFECYCLE_HANDLER;
//
// static {
// Application app = null;
// try {
// app = (Application) Class.forName("android.app.AppGlobals").getMethod("getInitialApplication").invoke(null);
// if (app == null)
// throw new IllegalStateException("Static initialization of Applications must be on main thread.");
// } catch (final Exception e) {
// Log.e(TAG, "Failed to get current application from AppGlobals." + e.getMessage());
// try {
// app = (Application) Class.forName("android.app.ActivityThread").getMethod("currentApplication").invoke(null);
// } catch (final Exception ex) {
// Log.e(TAG, "Failed to get current application from ActivityThread." + e.getMessage());
// }
// } finally {
// sApplication = app;
// }
// INNER_LIFECYCLE_HANDLER = new InnerLifecycleHandler();
// if (sApplication != null) {
// sApplication.registerActivityLifecycleCallbacks(INNER_LIFECYCLE_HANDLER);
// }
// }
//
// public static boolean isAppVisable() {
// return INNER_LIFECYCLE_HANDLER != null && INNER_LIFECYCLE_HANDLER.started > INNER_LIFECYCLE_HANDLER.stopped;
// }
//
// public static boolean isAppBackground() {
// return INNER_LIFECYCLE_HANDLER != null && INNER_LIFECYCLE_HANDLER.resumed <= INNER_LIFECYCLE_HANDLER.stopped;
// }
//
// private static void checkAppContext() {
// if (sApplication == null)
// throw new IllegalStateException("app reference is null");
// }
//
// public static Application getAppInstance() {
// checkAppContext();
// return sApplication;
// }
//
// public static Context getAppContext() {
// checkAppContext();
// return sApplication.getApplicationContext();
// }
//
// public static Resources getResources() {
// checkAppContext();
// return sApplication.getResources();
// }
//
// public static boolean isMainThread() {
// return Looper.getMainLooper().getThread() == Thread.currentThread();
// }
//
//
// @Nullable
// public static FragmentActivity getTopActivity() {
// return INNER_LIFECYCLE_HANDLER.mTopActivity == null ? null : INNER_LIFECYCLE_HANDLER.mTopActivity.get();
// }
//
// private static class InnerLifecycleHandler implements Application.ActivityLifecycleCallbacks {
// private int created;
// private int resumed;
// private int paused;
// private int started;
// private int stopped;
// private WeakReference<FragmentActivity> mTopActivity;
//
// @Override
// public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
// ++created;
//
// }
//
// @Override
// public void onActivityStarted(Activity activity) {
// ++started;
//
// }
//
// @Override
// public void onActivityResumed(Activity activity) {
// ++resumed;
// if (mTopActivity != null) {
// mTopActivity.clear();
// }
// if (activity instanceof FragmentActivity) {
// mTopActivity = new WeakReference<>((FragmentActivity) activity);
// }
// }
//
// @Override
// public void onActivityPaused(Activity activity) {
// ++paused;
//
// }
//
// @Override
// public void onActivityStopped(Activity activity) {
// ++stopped;
//
// }
//
// @Override
// public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
//
// }
//
// @Override
// public void onActivityDestroyed(Activity activity) {
//
// }
// }
//
// }
// Path: lib/src/main/java/com/razerdp/github/lib/utils/StringUtil.java
import android.text.TextUtils;
import com.razerdp.github.lib.api.AppContext;
import androidx.annotation.ArrayRes;
import androidx.annotation.StringRes;
package com.razerdp.github.lib.utils;
/**
* Created by 大灯泡 on 2016/10/28.
* <p>
* 字符串工具类
*/
public class StringUtil {
public static boolean noEmpty(String originStr) {
return !TextUtils.isEmpty(originStr);
}
public static boolean noEmpty(String... originStr) {
boolean noEmpty = true;
for (String s : originStr) {
if (TextUtils.isEmpty(s)) {
noEmpty = false;
break;
}
}
return noEmpty;
}
/**
* 从资源文件拿到文字
*/
public static String getString(@StringRes int strId, Object... objs) {
if (strId == 0) return null; | return AppContext.getAppContext().getResources().getString(strId, objs); |
razerdp/FriendCircle | lib_processor/src/main/java/com/razerdp/lib/processor/service/ModuleServiceProcessor.java | // Path: lib_processor/src/main/java/com/razerdp/lib/processor/BaseProcessor.java
// public abstract class BaseProcessor extends AbstractProcessor {
// protected Filer mFiler;
// protected Logger mLogger;
// protected Types mTypesUtil;
// protected Elements mElementUtil;
//
// @Override
// public synchronized void init(ProcessingEnvironment processingEnvironment) {
// super.init(processingEnvironment);
//
// mFiler = processingEnvironment.getFiler();
// mTypesUtil = processingEnvironment.getTypeUtils();
// mElementUtil = processingEnvironment.getElementUtils();
//
// mLogger = new Logger(processingEnvironment.getMessager());
// }
//
// @Override
// public SourceVersion getSupportedSourceVersion() {
// return SourceVersion.latestSupported();
// }
//
// @Override
// public Set<String> getSupportedAnnotationTypes() {
// Set<String> supportedAnnotationsSet = new LinkedHashSet<>();
// Set<Class<? extends Annotation>> result = new LinkedHashSet<>();
// onSetSupportedAnnotation(result);
// for (Class<? extends Annotation> aClass : result) {
// supportedAnnotationsSet.add(aClass.getCanonicalName());
// }
// return supportedAnnotationsSet;
// }
//
// protected abstract void onSetSupportedAnnotation(Set<Class<? extends Annotation>> result);
//
//
// public void logi(CharSequence which) {
// mLogger.i(which);
// }
//
// public void loge(CharSequence which) {
// mLogger.e(which);
// }
//
// public void logw(CharSequence which) {
// mLogger.w(which);
// }
//
// public void loge(Throwable which) {
// mLogger.e(which);
// }
// }
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String PACKAGE_SPARSEARRAY = "android.util";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_FIELD_NAME="SERVICE_IMPL_MAP";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_FILE_NAME = "ServiceImplGen";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_INTERFACE = "com.razerdp.github.common.modules.base.IModuleServiceProvider";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_INTERFACE_METHOD="getServiceImplMap";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_PACKAGE_NAME = PACKAGE_NAME + ".apt.gen";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String PACKAGE_NAME = "com.razerdp.github";
| import com.razerdp.lib.annotations.ServiceImpl;
import com.razerdp.lib.processor.BaseProcessor;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.CodeBlock;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import static com.razerdp.lib.config.AnnotationConfig.AndroidConfig.PACKAGE_SPARSEARRAY;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_FIELD_NAME;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_FILE_NAME;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_INTERFACE;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_INTERFACE_METHOD;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_PACKAGE_NAME;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.PACKAGE_NAME; | package com.razerdp.lib.processor.service;
/**
* Created by razerdp on 2019/8/12.
*/
public class ModuleServiceProcessor extends BaseProcessor {
private static final String TAG = "ModuleServiceProcessor";
//get module arguments from gradle
private static final String KEY_MODULE_NAME = "MODULE_NAME";
private String moduleName;
//key = service interface for every module
//value = list service impl from key for every module
private static final HashMap<TypeName, List<InnerAptInfo>> mServiceImplMap = new HashMap<>();
private final ParameterizedTypeName hashMapClass = ParameterizedTypeName.get(
ClassName.get(HashMap.class),//hashmap.class
ClassName.get(Class.class),//key class
ParameterizedTypeName.get( | // Path: lib_processor/src/main/java/com/razerdp/lib/processor/BaseProcessor.java
// public abstract class BaseProcessor extends AbstractProcessor {
// protected Filer mFiler;
// protected Logger mLogger;
// protected Types mTypesUtil;
// protected Elements mElementUtil;
//
// @Override
// public synchronized void init(ProcessingEnvironment processingEnvironment) {
// super.init(processingEnvironment);
//
// mFiler = processingEnvironment.getFiler();
// mTypesUtil = processingEnvironment.getTypeUtils();
// mElementUtil = processingEnvironment.getElementUtils();
//
// mLogger = new Logger(processingEnvironment.getMessager());
// }
//
// @Override
// public SourceVersion getSupportedSourceVersion() {
// return SourceVersion.latestSupported();
// }
//
// @Override
// public Set<String> getSupportedAnnotationTypes() {
// Set<String> supportedAnnotationsSet = new LinkedHashSet<>();
// Set<Class<? extends Annotation>> result = new LinkedHashSet<>();
// onSetSupportedAnnotation(result);
// for (Class<? extends Annotation> aClass : result) {
// supportedAnnotationsSet.add(aClass.getCanonicalName());
// }
// return supportedAnnotationsSet;
// }
//
// protected abstract void onSetSupportedAnnotation(Set<Class<? extends Annotation>> result);
//
//
// public void logi(CharSequence which) {
// mLogger.i(which);
// }
//
// public void loge(CharSequence which) {
// mLogger.e(which);
// }
//
// public void logw(CharSequence which) {
// mLogger.w(which);
// }
//
// public void loge(Throwable which) {
// mLogger.e(which);
// }
// }
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String PACKAGE_SPARSEARRAY = "android.util";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_FIELD_NAME="SERVICE_IMPL_MAP";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_FILE_NAME = "ServiceImplGen";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_INTERFACE = "com.razerdp.github.common.modules.base.IModuleServiceProvider";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_INTERFACE_METHOD="getServiceImplMap";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_PACKAGE_NAME = PACKAGE_NAME + ".apt.gen";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String PACKAGE_NAME = "com.razerdp.github";
// Path: lib_processor/src/main/java/com/razerdp/lib/processor/service/ModuleServiceProcessor.java
import com.razerdp.lib.annotations.ServiceImpl;
import com.razerdp.lib.processor.BaseProcessor;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.CodeBlock;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import static com.razerdp.lib.config.AnnotationConfig.AndroidConfig.PACKAGE_SPARSEARRAY;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_FIELD_NAME;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_FILE_NAME;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_INTERFACE;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_INTERFACE_METHOD;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_PACKAGE_NAME;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.PACKAGE_NAME;
package com.razerdp.lib.processor.service;
/**
* Created by razerdp on 2019/8/12.
*/
public class ModuleServiceProcessor extends BaseProcessor {
private static final String TAG = "ModuleServiceProcessor";
//get module arguments from gradle
private static final String KEY_MODULE_NAME = "MODULE_NAME";
private String moduleName;
//key = service interface for every module
//value = list service impl from key for every module
private static final HashMap<TypeName, List<InnerAptInfo>> mServiceImplMap = new HashMap<>();
private final ParameterizedTypeName hashMapClass = ParameterizedTypeName.get(
ClassName.get(HashMap.class),//hashmap.class
ClassName.get(Class.class),//key class
ParameterizedTypeName.get( | ClassName.get(PACKAGE_SPARSEARRAY, "SparseArray"),//sparsearray.class, |
razerdp/FriendCircle | lib_processor/src/main/java/com/razerdp/lib/processor/service/ModuleServiceProcessor.java | // Path: lib_processor/src/main/java/com/razerdp/lib/processor/BaseProcessor.java
// public abstract class BaseProcessor extends AbstractProcessor {
// protected Filer mFiler;
// protected Logger mLogger;
// protected Types mTypesUtil;
// protected Elements mElementUtil;
//
// @Override
// public synchronized void init(ProcessingEnvironment processingEnvironment) {
// super.init(processingEnvironment);
//
// mFiler = processingEnvironment.getFiler();
// mTypesUtil = processingEnvironment.getTypeUtils();
// mElementUtil = processingEnvironment.getElementUtils();
//
// mLogger = new Logger(processingEnvironment.getMessager());
// }
//
// @Override
// public SourceVersion getSupportedSourceVersion() {
// return SourceVersion.latestSupported();
// }
//
// @Override
// public Set<String> getSupportedAnnotationTypes() {
// Set<String> supportedAnnotationsSet = new LinkedHashSet<>();
// Set<Class<? extends Annotation>> result = new LinkedHashSet<>();
// onSetSupportedAnnotation(result);
// for (Class<? extends Annotation> aClass : result) {
// supportedAnnotationsSet.add(aClass.getCanonicalName());
// }
// return supportedAnnotationsSet;
// }
//
// protected abstract void onSetSupportedAnnotation(Set<Class<? extends Annotation>> result);
//
//
// public void logi(CharSequence which) {
// mLogger.i(which);
// }
//
// public void loge(CharSequence which) {
// mLogger.e(which);
// }
//
// public void logw(CharSequence which) {
// mLogger.w(which);
// }
//
// public void loge(Throwable which) {
// mLogger.e(which);
// }
// }
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String PACKAGE_SPARSEARRAY = "android.util";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_FIELD_NAME="SERVICE_IMPL_MAP";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_FILE_NAME = "ServiceImplGen";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_INTERFACE = "com.razerdp.github.common.modules.base.IModuleServiceProvider";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_INTERFACE_METHOD="getServiceImplMap";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_PACKAGE_NAME = PACKAGE_NAME + ".apt.gen";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String PACKAGE_NAME = "com.razerdp.github";
| import com.razerdp.lib.annotations.ServiceImpl;
import com.razerdp.lib.processor.BaseProcessor;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.CodeBlock;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import static com.razerdp.lib.config.AnnotationConfig.AndroidConfig.PACKAGE_SPARSEARRAY;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_FIELD_NAME;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_FILE_NAME;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_INTERFACE;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_INTERFACE_METHOD;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_PACKAGE_NAME;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.PACKAGE_NAME; | }
@Override
public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
if (roundEnvironment.processingOver()) {
if (!set.isEmpty()) {
return false;
}
}
if (set.isEmpty()) {
logi(TAG + "annotations is empty,return");
return false;
}
logi(TAG + "start processing =========== ");
mServiceImplMap.clear();
scanClass(set, roundEnvironment);
if (mServiceImplMap.isEmpty()) {
loge(TAG + " find no class impl for @ServiceImpl");
return false;
}
printScanned();
generateJavaFile();
return false;
}
private void generateJavaFile() {
try { | // Path: lib_processor/src/main/java/com/razerdp/lib/processor/BaseProcessor.java
// public abstract class BaseProcessor extends AbstractProcessor {
// protected Filer mFiler;
// protected Logger mLogger;
// protected Types mTypesUtil;
// protected Elements mElementUtil;
//
// @Override
// public synchronized void init(ProcessingEnvironment processingEnvironment) {
// super.init(processingEnvironment);
//
// mFiler = processingEnvironment.getFiler();
// mTypesUtil = processingEnvironment.getTypeUtils();
// mElementUtil = processingEnvironment.getElementUtils();
//
// mLogger = new Logger(processingEnvironment.getMessager());
// }
//
// @Override
// public SourceVersion getSupportedSourceVersion() {
// return SourceVersion.latestSupported();
// }
//
// @Override
// public Set<String> getSupportedAnnotationTypes() {
// Set<String> supportedAnnotationsSet = new LinkedHashSet<>();
// Set<Class<? extends Annotation>> result = new LinkedHashSet<>();
// onSetSupportedAnnotation(result);
// for (Class<? extends Annotation> aClass : result) {
// supportedAnnotationsSet.add(aClass.getCanonicalName());
// }
// return supportedAnnotationsSet;
// }
//
// protected abstract void onSetSupportedAnnotation(Set<Class<? extends Annotation>> result);
//
//
// public void logi(CharSequence which) {
// mLogger.i(which);
// }
//
// public void loge(CharSequence which) {
// mLogger.e(which);
// }
//
// public void logw(CharSequence which) {
// mLogger.w(which);
// }
//
// public void loge(Throwable which) {
// mLogger.e(which);
// }
// }
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String PACKAGE_SPARSEARRAY = "android.util";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_FIELD_NAME="SERVICE_IMPL_MAP";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_FILE_NAME = "ServiceImplGen";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_INTERFACE = "com.razerdp.github.common.modules.base.IModuleServiceProvider";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_INTERFACE_METHOD="getServiceImplMap";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_PACKAGE_NAME = PACKAGE_NAME + ".apt.gen";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String PACKAGE_NAME = "com.razerdp.github";
// Path: lib_processor/src/main/java/com/razerdp/lib/processor/service/ModuleServiceProcessor.java
import com.razerdp.lib.annotations.ServiceImpl;
import com.razerdp.lib.processor.BaseProcessor;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.CodeBlock;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import static com.razerdp.lib.config.AnnotationConfig.AndroidConfig.PACKAGE_SPARSEARRAY;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_FIELD_NAME;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_FILE_NAME;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_INTERFACE;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_INTERFACE_METHOD;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_PACKAGE_NAME;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.PACKAGE_NAME;
}
@Override
public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
if (roundEnvironment.processingOver()) {
if (!set.isEmpty()) {
return false;
}
}
if (set.isEmpty()) {
logi(TAG + "annotations is empty,return");
return false;
}
logi(TAG + "start processing =========== ");
mServiceImplMap.clear();
scanClass(set, roundEnvironment);
if (mServiceImplMap.isEmpty()) {
loge(TAG + " find no class impl for @ServiceImpl");
return false;
}
printScanned();
generateJavaFile();
return false;
}
private void generateJavaFile() {
try { | JavaFile javaFile = JavaFile.builder(APT_PACKAGE_NAME, createType()) |
razerdp/FriendCircle | lib_processor/src/main/java/com/razerdp/lib/processor/service/ModuleServiceProcessor.java | // Path: lib_processor/src/main/java/com/razerdp/lib/processor/BaseProcessor.java
// public abstract class BaseProcessor extends AbstractProcessor {
// protected Filer mFiler;
// protected Logger mLogger;
// protected Types mTypesUtil;
// protected Elements mElementUtil;
//
// @Override
// public synchronized void init(ProcessingEnvironment processingEnvironment) {
// super.init(processingEnvironment);
//
// mFiler = processingEnvironment.getFiler();
// mTypesUtil = processingEnvironment.getTypeUtils();
// mElementUtil = processingEnvironment.getElementUtils();
//
// mLogger = new Logger(processingEnvironment.getMessager());
// }
//
// @Override
// public SourceVersion getSupportedSourceVersion() {
// return SourceVersion.latestSupported();
// }
//
// @Override
// public Set<String> getSupportedAnnotationTypes() {
// Set<String> supportedAnnotationsSet = new LinkedHashSet<>();
// Set<Class<? extends Annotation>> result = new LinkedHashSet<>();
// onSetSupportedAnnotation(result);
// for (Class<? extends Annotation> aClass : result) {
// supportedAnnotationsSet.add(aClass.getCanonicalName());
// }
// return supportedAnnotationsSet;
// }
//
// protected abstract void onSetSupportedAnnotation(Set<Class<? extends Annotation>> result);
//
//
// public void logi(CharSequence which) {
// mLogger.i(which);
// }
//
// public void loge(CharSequence which) {
// mLogger.e(which);
// }
//
// public void logw(CharSequence which) {
// mLogger.w(which);
// }
//
// public void loge(Throwable which) {
// mLogger.e(which);
// }
// }
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String PACKAGE_SPARSEARRAY = "android.util";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_FIELD_NAME="SERVICE_IMPL_MAP";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_FILE_NAME = "ServiceImplGen";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_INTERFACE = "com.razerdp.github.common.modules.base.IModuleServiceProvider";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_INTERFACE_METHOD="getServiceImplMap";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_PACKAGE_NAME = PACKAGE_NAME + ".apt.gen";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String PACKAGE_NAME = "com.razerdp.github";
| import com.razerdp.lib.annotations.ServiceImpl;
import com.razerdp.lib.processor.BaseProcessor;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.CodeBlock;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import static com.razerdp.lib.config.AnnotationConfig.AndroidConfig.PACKAGE_SPARSEARRAY;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_FIELD_NAME;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_FILE_NAME;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_INTERFACE;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_INTERFACE_METHOD;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_PACKAGE_NAME;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.PACKAGE_NAME; |
@Override
public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
if (roundEnvironment.processingOver()) {
if (!set.isEmpty()) {
return false;
}
}
if (set.isEmpty()) {
logi(TAG + "annotations is empty,return");
return false;
}
logi(TAG + "start processing =========== ");
mServiceImplMap.clear();
scanClass(set, roundEnvironment);
if (mServiceImplMap.isEmpty()) {
loge(TAG + " find no class impl for @ServiceImpl");
return false;
}
printScanned();
generateJavaFile();
return false;
}
private void generateJavaFile() {
try {
JavaFile javaFile = JavaFile.builder(APT_PACKAGE_NAME, createType()) | // Path: lib_processor/src/main/java/com/razerdp/lib/processor/BaseProcessor.java
// public abstract class BaseProcessor extends AbstractProcessor {
// protected Filer mFiler;
// protected Logger mLogger;
// protected Types mTypesUtil;
// protected Elements mElementUtil;
//
// @Override
// public synchronized void init(ProcessingEnvironment processingEnvironment) {
// super.init(processingEnvironment);
//
// mFiler = processingEnvironment.getFiler();
// mTypesUtil = processingEnvironment.getTypeUtils();
// mElementUtil = processingEnvironment.getElementUtils();
//
// mLogger = new Logger(processingEnvironment.getMessager());
// }
//
// @Override
// public SourceVersion getSupportedSourceVersion() {
// return SourceVersion.latestSupported();
// }
//
// @Override
// public Set<String> getSupportedAnnotationTypes() {
// Set<String> supportedAnnotationsSet = new LinkedHashSet<>();
// Set<Class<? extends Annotation>> result = new LinkedHashSet<>();
// onSetSupportedAnnotation(result);
// for (Class<? extends Annotation> aClass : result) {
// supportedAnnotationsSet.add(aClass.getCanonicalName());
// }
// return supportedAnnotationsSet;
// }
//
// protected abstract void onSetSupportedAnnotation(Set<Class<? extends Annotation>> result);
//
//
// public void logi(CharSequence which) {
// mLogger.i(which);
// }
//
// public void loge(CharSequence which) {
// mLogger.e(which);
// }
//
// public void logw(CharSequence which) {
// mLogger.w(which);
// }
//
// public void loge(Throwable which) {
// mLogger.e(which);
// }
// }
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String PACKAGE_SPARSEARRAY = "android.util";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_FIELD_NAME="SERVICE_IMPL_MAP";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_FILE_NAME = "ServiceImplGen";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_INTERFACE = "com.razerdp.github.common.modules.base.IModuleServiceProvider";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_INTERFACE_METHOD="getServiceImplMap";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_PACKAGE_NAME = PACKAGE_NAME + ".apt.gen";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String PACKAGE_NAME = "com.razerdp.github";
// Path: lib_processor/src/main/java/com/razerdp/lib/processor/service/ModuleServiceProcessor.java
import com.razerdp.lib.annotations.ServiceImpl;
import com.razerdp.lib.processor.BaseProcessor;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.CodeBlock;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import static com.razerdp.lib.config.AnnotationConfig.AndroidConfig.PACKAGE_SPARSEARRAY;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_FIELD_NAME;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_FILE_NAME;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_INTERFACE;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_INTERFACE_METHOD;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_PACKAGE_NAME;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.PACKAGE_NAME;
@Override
public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
if (roundEnvironment.processingOver()) {
if (!set.isEmpty()) {
return false;
}
}
if (set.isEmpty()) {
logi(TAG + "annotations is empty,return");
return false;
}
logi(TAG + "start processing =========== ");
mServiceImplMap.clear();
scanClass(set, roundEnvironment);
if (mServiceImplMap.isEmpty()) {
loge(TAG + " find no class impl for @ServiceImpl");
return false;
}
printScanned();
generateJavaFile();
return false;
}
private void generateJavaFile() {
try {
JavaFile javaFile = JavaFile.builder(APT_PACKAGE_NAME, createType()) | .addFileComment("$S", "Generated code from " + APT_PACKAGE_NAME + "." + APT_FILE_NAME + " Do not modify!") |
razerdp/FriendCircle | lib_processor/src/main/java/com/razerdp/lib/processor/service/ModuleServiceProcessor.java | // Path: lib_processor/src/main/java/com/razerdp/lib/processor/BaseProcessor.java
// public abstract class BaseProcessor extends AbstractProcessor {
// protected Filer mFiler;
// protected Logger mLogger;
// protected Types mTypesUtil;
// protected Elements mElementUtil;
//
// @Override
// public synchronized void init(ProcessingEnvironment processingEnvironment) {
// super.init(processingEnvironment);
//
// mFiler = processingEnvironment.getFiler();
// mTypesUtil = processingEnvironment.getTypeUtils();
// mElementUtil = processingEnvironment.getElementUtils();
//
// mLogger = new Logger(processingEnvironment.getMessager());
// }
//
// @Override
// public SourceVersion getSupportedSourceVersion() {
// return SourceVersion.latestSupported();
// }
//
// @Override
// public Set<String> getSupportedAnnotationTypes() {
// Set<String> supportedAnnotationsSet = new LinkedHashSet<>();
// Set<Class<? extends Annotation>> result = new LinkedHashSet<>();
// onSetSupportedAnnotation(result);
// for (Class<? extends Annotation> aClass : result) {
// supportedAnnotationsSet.add(aClass.getCanonicalName());
// }
// return supportedAnnotationsSet;
// }
//
// protected abstract void onSetSupportedAnnotation(Set<Class<? extends Annotation>> result);
//
//
// public void logi(CharSequence which) {
// mLogger.i(which);
// }
//
// public void loge(CharSequence which) {
// mLogger.e(which);
// }
//
// public void logw(CharSequence which) {
// mLogger.w(which);
// }
//
// public void loge(Throwable which) {
// mLogger.e(which);
// }
// }
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String PACKAGE_SPARSEARRAY = "android.util";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_FIELD_NAME="SERVICE_IMPL_MAP";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_FILE_NAME = "ServiceImplGen";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_INTERFACE = "com.razerdp.github.common.modules.base.IModuleServiceProvider";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_INTERFACE_METHOD="getServiceImplMap";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_PACKAGE_NAME = PACKAGE_NAME + ".apt.gen";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String PACKAGE_NAME = "com.razerdp.github";
| import com.razerdp.lib.annotations.ServiceImpl;
import com.razerdp.lib.processor.BaseProcessor;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.CodeBlock;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import static com.razerdp.lib.config.AnnotationConfig.AndroidConfig.PACKAGE_SPARSEARRAY;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_FIELD_NAME;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_FILE_NAME;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_INTERFACE;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_INTERFACE_METHOD;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_PACKAGE_NAME;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.PACKAGE_NAME; | logi(TAG + "start processing =========== ");
mServiceImplMap.clear();
scanClass(set, roundEnvironment);
if (mServiceImplMap.isEmpty()) {
loge(TAG + " find no class impl for @ServiceImpl");
return false;
}
printScanned();
generateJavaFile();
return false;
}
private void generateJavaFile() {
try {
JavaFile javaFile = JavaFile.builder(APT_PACKAGE_NAME, createType())
.addFileComment("$S", "Generated code from " + APT_PACKAGE_NAME + "." + APT_FILE_NAME + " Do not modify!")
.build();
javaFile.writeTo(mFiler);
} catch (IOException e) {
loge(e);
}
}
private TypeSpec createType() {
//public final ServiceImplGen
TypeSpec.Builder types = TypeSpec.classBuilder(APT_FILE_NAME + "$$" + moduleName)
.addModifiers(Modifier.PUBLIC, Modifier.FINAL);
//add interface | // Path: lib_processor/src/main/java/com/razerdp/lib/processor/BaseProcessor.java
// public abstract class BaseProcessor extends AbstractProcessor {
// protected Filer mFiler;
// protected Logger mLogger;
// protected Types mTypesUtil;
// protected Elements mElementUtil;
//
// @Override
// public synchronized void init(ProcessingEnvironment processingEnvironment) {
// super.init(processingEnvironment);
//
// mFiler = processingEnvironment.getFiler();
// mTypesUtil = processingEnvironment.getTypeUtils();
// mElementUtil = processingEnvironment.getElementUtils();
//
// mLogger = new Logger(processingEnvironment.getMessager());
// }
//
// @Override
// public SourceVersion getSupportedSourceVersion() {
// return SourceVersion.latestSupported();
// }
//
// @Override
// public Set<String> getSupportedAnnotationTypes() {
// Set<String> supportedAnnotationsSet = new LinkedHashSet<>();
// Set<Class<? extends Annotation>> result = new LinkedHashSet<>();
// onSetSupportedAnnotation(result);
// for (Class<? extends Annotation> aClass : result) {
// supportedAnnotationsSet.add(aClass.getCanonicalName());
// }
// return supportedAnnotationsSet;
// }
//
// protected abstract void onSetSupportedAnnotation(Set<Class<? extends Annotation>> result);
//
//
// public void logi(CharSequence which) {
// mLogger.i(which);
// }
//
// public void loge(CharSequence which) {
// mLogger.e(which);
// }
//
// public void logw(CharSequence which) {
// mLogger.w(which);
// }
//
// public void loge(Throwable which) {
// mLogger.e(which);
// }
// }
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String PACKAGE_SPARSEARRAY = "android.util";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_FIELD_NAME="SERVICE_IMPL_MAP";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_FILE_NAME = "ServiceImplGen";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_INTERFACE = "com.razerdp.github.common.modules.base.IModuleServiceProvider";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_INTERFACE_METHOD="getServiceImplMap";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_PACKAGE_NAME = PACKAGE_NAME + ".apt.gen";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String PACKAGE_NAME = "com.razerdp.github";
// Path: lib_processor/src/main/java/com/razerdp/lib/processor/service/ModuleServiceProcessor.java
import com.razerdp.lib.annotations.ServiceImpl;
import com.razerdp.lib.processor.BaseProcessor;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.CodeBlock;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import static com.razerdp.lib.config.AnnotationConfig.AndroidConfig.PACKAGE_SPARSEARRAY;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_FIELD_NAME;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_FILE_NAME;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_INTERFACE;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_INTERFACE_METHOD;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_PACKAGE_NAME;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.PACKAGE_NAME;
logi(TAG + "start processing =========== ");
mServiceImplMap.clear();
scanClass(set, roundEnvironment);
if (mServiceImplMap.isEmpty()) {
loge(TAG + " find no class impl for @ServiceImpl");
return false;
}
printScanned();
generateJavaFile();
return false;
}
private void generateJavaFile() {
try {
JavaFile javaFile = JavaFile.builder(APT_PACKAGE_NAME, createType())
.addFileComment("$S", "Generated code from " + APT_PACKAGE_NAME + "." + APT_FILE_NAME + " Do not modify!")
.build();
javaFile.writeTo(mFiler);
} catch (IOException e) {
loge(e);
}
}
private TypeSpec createType() {
//public final ServiceImplGen
TypeSpec.Builder types = TypeSpec.classBuilder(APT_FILE_NAME + "$$" + moduleName)
.addModifiers(Modifier.PUBLIC, Modifier.FINAL);
//add interface | types.addSuperinterface(ClassName.get(mElementUtil.getTypeElement(APT_INTERFACE))); |
razerdp/FriendCircle | lib_processor/src/main/java/com/razerdp/lib/processor/service/ModuleServiceProcessor.java | // Path: lib_processor/src/main/java/com/razerdp/lib/processor/BaseProcessor.java
// public abstract class BaseProcessor extends AbstractProcessor {
// protected Filer mFiler;
// protected Logger mLogger;
// protected Types mTypesUtil;
// protected Elements mElementUtil;
//
// @Override
// public synchronized void init(ProcessingEnvironment processingEnvironment) {
// super.init(processingEnvironment);
//
// mFiler = processingEnvironment.getFiler();
// mTypesUtil = processingEnvironment.getTypeUtils();
// mElementUtil = processingEnvironment.getElementUtils();
//
// mLogger = new Logger(processingEnvironment.getMessager());
// }
//
// @Override
// public SourceVersion getSupportedSourceVersion() {
// return SourceVersion.latestSupported();
// }
//
// @Override
// public Set<String> getSupportedAnnotationTypes() {
// Set<String> supportedAnnotationsSet = new LinkedHashSet<>();
// Set<Class<? extends Annotation>> result = new LinkedHashSet<>();
// onSetSupportedAnnotation(result);
// for (Class<? extends Annotation> aClass : result) {
// supportedAnnotationsSet.add(aClass.getCanonicalName());
// }
// return supportedAnnotationsSet;
// }
//
// protected abstract void onSetSupportedAnnotation(Set<Class<? extends Annotation>> result);
//
//
// public void logi(CharSequence which) {
// mLogger.i(which);
// }
//
// public void loge(CharSequence which) {
// mLogger.e(which);
// }
//
// public void logw(CharSequence which) {
// mLogger.w(which);
// }
//
// public void loge(Throwable which) {
// mLogger.e(which);
// }
// }
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String PACKAGE_SPARSEARRAY = "android.util";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_FIELD_NAME="SERVICE_IMPL_MAP";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_FILE_NAME = "ServiceImplGen";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_INTERFACE = "com.razerdp.github.common.modules.base.IModuleServiceProvider";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_INTERFACE_METHOD="getServiceImplMap";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_PACKAGE_NAME = PACKAGE_NAME + ".apt.gen";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String PACKAGE_NAME = "com.razerdp.github";
| import com.razerdp.lib.annotations.ServiceImpl;
import com.razerdp.lib.processor.BaseProcessor;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.CodeBlock;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import static com.razerdp.lib.config.AnnotationConfig.AndroidConfig.PACKAGE_SPARSEARRAY;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_FIELD_NAME;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_FILE_NAME;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_INTERFACE;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_INTERFACE_METHOD;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_PACKAGE_NAME;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.PACKAGE_NAME; |
private void generateJavaFile() {
try {
JavaFile javaFile = JavaFile.builder(APT_PACKAGE_NAME, createType())
.addFileComment("$S", "Generated code from " + APT_PACKAGE_NAME + "." + APT_FILE_NAME + " Do not modify!")
.build();
javaFile.writeTo(mFiler);
} catch (IOException e) {
loge(e);
}
}
private TypeSpec createType() {
//public final ServiceImplGen
TypeSpec.Builder types = TypeSpec.classBuilder(APT_FILE_NAME + "$$" + moduleName)
.addModifiers(Modifier.PUBLIC, Modifier.FINAL);
//add interface
types.addSuperinterface(ClassName.get(mElementUtil.getTypeElement(APT_INTERFACE)));
//add hashmap field
types.addField(createField());
//add static code for hashmap
types.addStaticBlock(createStaticBlock());
//add interface method
types.addMethod(createInterfaceMethod());
return types.build();
}
private FieldSpec createField() {
//private static final SERVICE_IMPL_MAP = new HashMap(); | // Path: lib_processor/src/main/java/com/razerdp/lib/processor/BaseProcessor.java
// public abstract class BaseProcessor extends AbstractProcessor {
// protected Filer mFiler;
// protected Logger mLogger;
// protected Types mTypesUtil;
// protected Elements mElementUtil;
//
// @Override
// public synchronized void init(ProcessingEnvironment processingEnvironment) {
// super.init(processingEnvironment);
//
// mFiler = processingEnvironment.getFiler();
// mTypesUtil = processingEnvironment.getTypeUtils();
// mElementUtil = processingEnvironment.getElementUtils();
//
// mLogger = new Logger(processingEnvironment.getMessager());
// }
//
// @Override
// public SourceVersion getSupportedSourceVersion() {
// return SourceVersion.latestSupported();
// }
//
// @Override
// public Set<String> getSupportedAnnotationTypes() {
// Set<String> supportedAnnotationsSet = new LinkedHashSet<>();
// Set<Class<? extends Annotation>> result = new LinkedHashSet<>();
// onSetSupportedAnnotation(result);
// for (Class<? extends Annotation> aClass : result) {
// supportedAnnotationsSet.add(aClass.getCanonicalName());
// }
// return supportedAnnotationsSet;
// }
//
// protected abstract void onSetSupportedAnnotation(Set<Class<? extends Annotation>> result);
//
//
// public void logi(CharSequence which) {
// mLogger.i(which);
// }
//
// public void loge(CharSequence which) {
// mLogger.e(which);
// }
//
// public void logw(CharSequence which) {
// mLogger.w(which);
// }
//
// public void loge(Throwable which) {
// mLogger.e(which);
// }
// }
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String PACKAGE_SPARSEARRAY = "android.util";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_FIELD_NAME="SERVICE_IMPL_MAP";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_FILE_NAME = "ServiceImplGen";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_INTERFACE = "com.razerdp.github.common.modules.base.IModuleServiceProvider";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_INTERFACE_METHOD="getServiceImplMap";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_PACKAGE_NAME = PACKAGE_NAME + ".apt.gen";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String PACKAGE_NAME = "com.razerdp.github";
// Path: lib_processor/src/main/java/com/razerdp/lib/processor/service/ModuleServiceProcessor.java
import com.razerdp.lib.annotations.ServiceImpl;
import com.razerdp.lib.processor.BaseProcessor;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.CodeBlock;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import static com.razerdp.lib.config.AnnotationConfig.AndroidConfig.PACKAGE_SPARSEARRAY;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_FIELD_NAME;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_FILE_NAME;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_INTERFACE;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_INTERFACE_METHOD;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_PACKAGE_NAME;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.PACKAGE_NAME;
private void generateJavaFile() {
try {
JavaFile javaFile = JavaFile.builder(APT_PACKAGE_NAME, createType())
.addFileComment("$S", "Generated code from " + APT_PACKAGE_NAME + "." + APT_FILE_NAME + " Do not modify!")
.build();
javaFile.writeTo(mFiler);
} catch (IOException e) {
loge(e);
}
}
private TypeSpec createType() {
//public final ServiceImplGen
TypeSpec.Builder types = TypeSpec.classBuilder(APT_FILE_NAME + "$$" + moduleName)
.addModifiers(Modifier.PUBLIC, Modifier.FINAL);
//add interface
types.addSuperinterface(ClassName.get(mElementUtil.getTypeElement(APT_INTERFACE)));
//add hashmap field
types.addField(createField());
//add static code for hashmap
types.addStaticBlock(createStaticBlock());
//add interface method
types.addMethod(createInterfaceMethod());
return types.build();
}
private FieldSpec createField() {
//private static final SERVICE_IMPL_MAP = new HashMap(); | FieldSpec.Builder builder = FieldSpec.builder(hashMapClass, APT_FIELD_NAME) |
razerdp/FriendCircle | lib_processor/src/main/java/com/razerdp/lib/processor/service/ModuleServiceProcessor.java | // Path: lib_processor/src/main/java/com/razerdp/lib/processor/BaseProcessor.java
// public abstract class BaseProcessor extends AbstractProcessor {
// protected Filer mFiler;
// protected Logger mLogger;
// protected Types mTypesUtil;
// protected Elements mElementUtil;
//
// @Override
// public synchronized void init(ProcessingEnvironment processingEnvironment) {
// super.init(processingEnvironment);
//
// mFiler = processingEnvironment.getFiler();
// mTypesUtil = processingEnvironment.getTypeUtils();
// mElementUtil = processingEnvironment.getElementUtils();
//
// mLogger = new Logger(processingEnvironment.getMessager());
// }
//
// @Override
// public SourceVersion getSupportedSourceVersion() {
// return SourceVersion.latestSupported();
// }
//
// @Override
// public Set<String> getSupportedAnnotationTypes() {
// Set<String> supportedAnnotationsSet = new LinkedHashSet<>();
// Set<Class<? extends Annotation>> result = new LinkedHashSet<>();
// onSetSupportedAnnotation(result);
// for (Class<? extends Annotation> aClass : result) {
// supportedAnnotationsSet.add(aClass.getCanonicalName());
// }
// return supportedAnnotationsSet;
// }
//
// protected abstract void onSetSupportedAnnotation(Set<Class<? extends Annotation>> result);
//
//
// public void logi(CharSequence which) {
// mLogger.i(which);
// }
//
// public void loge(CharSequence which) {
// mLogger.e(which);
// }
//
// public void logw(CharSequence which) {
// mLogger.w(which);
// }
//
// public void loge(Throwable which) {
// mLogger.e(which);
// }
// }
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String PACKAGE_SPARSEARRAY = "android.util";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_FIELD_NAME="SERVICE_IMPL_MAP";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_FILE_NAME = "ServiceImplGen";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_INTERFACE = "com.razerdp.github.common.modules.base.IModuleServiceProvider";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_INTERFACE_METHOD="getServiceImplMap";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_PACKAGE_NAME = PACKAGE_NAME + ".apt.gen";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String PACKAGE_NAME = "com.razerdp.github";
| import com.razerdp.lib.annotations.ServiceImpl;
import com.razerdp.lib.processor.BaseProcessor;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.CodeBlock;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import static com.razerdp.lib.config.AnnotationConfig.AndroidConfig.PACKAGE_SPARSEARRAY;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_FIELD_NAME;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_FILE_NAME;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_INTERFACE;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_INTERFACE_METHOD;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_PACKAGE_NAME;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.PACKAGE_NAME; | }
private CodeBlock createStaticBlock() {
CodeBlock.Builder builder = CodeBlock.builder();
final String listName = "mServiceImplList";
final TypeName sparseArrayType = ClassName.get(PACKAGE_SPARSEARRAY, "SparseArray");
//SparseArray mServiceImplList
builder.addStatement("$T " + listName, sparseArrayType);
for (Map.Entry<TypeName, List<InnerAptInfo>> entry : mServiceImplMap.entrySet()) {
//mServiceImplList = new SparseArray();
builder.addStatement(listName + " = new $T()", sparseArrayType);
for (InnerAptInfo aptInfo : entry.getValue()) {
//mServiceImplList.put(tag,new impl());
builder.addStatement(listName + ".put($L , new $T())",
aptInfo.tag,
ClassName.get(aptInfo.mirror));
}
//SERVICE_IMPL_MAP.put(impl.calss,mServiceImplList)
builder.addStatement(APT_FIELD_NAME + ".put($T.class," + listName + ")", entry.getKey());
}
return builder.build();
}
private MethodSpec createInterfaceMethod() { | // Path: lib_processor/src/main/java/com/razerdp/lib/processor/BaseProcessor.java
// public abstract class BaseProcessor extends AbstractProcessor {
// protected Filer mFiler;
// protected Logger mLogger;
// protected Types mTypesUtil;
// protected Elements mElementUtil;
//
// @Override
// public synchronized void init(ProcessingEnvironment processingEnvironment) {
// super.init(processingEnvironment);
//
// mFiler = processingEnvironment.getFiler();
// mTypesUtil = processingEnvironment.getTypeUtils();
// mElementUtil = processingEnvironment.getElementUtils();
//
// mLogger = new Logger(processingEnvironment.getMessager());
// }
//
// @Override
// public SourceVersion getSupportedSourceVersion() {
// return SourceVersion.latestSupported();
// }
//
// @Override
// public Set<String> getSupportedAnnotationTypes() {
// Set<String> supportedAnnotationsSet = new LinkedHashSet<>();
// Set<Class<? extends Annotation>> result = new LinkedHashSet<>();
// onSetSupportedAnnotation(result);
// for (Class<? extends Annotation> aClass : result) {
// supportedAnnotationsSet.add(aClass.getCanonicalName());
// }
// return supportedAnnotationsSet;
// }
//
// protected abstract void onSetSupportedAnnotation(Set<Class<? extends Annotation>> result);
//
//
// public void logi(CharSequence which) {
// mLogger.i(which);
// }
//
// public void loge(CharSequence which) {
// mLogger.e(which);
// }
//
// public void logw(CharSequence which) {
// mLogger.w(which);
// }
//
// public void loge(Throwable which) {
// mLogger.e(which);
// }
// }
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String PACKAGE_SPARSEARRAY = "android.util";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_FIELD_NAME="SERVICE_IMPL_MAP";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_FILE_NAME = "ServiceImplGen";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_INTERFACE = "com.razerdp.github.common.modules.base.IModuleServiceProvider";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_INTERFACE_METHOD="getServiceImplMap";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_PACKAGE_NAME = PACKAGE_NAME + ".apt.gen";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String PACKAGE_NAME = "com.razerdp.github";
// Path: lib_processor/src/main/java/com/razerdp/lib/processor/service/ModuleServiceProcessor.java
import com.razerdp.lib.annotations.ServiceImpl;
import com.razerdp.lib.processor.BaseProcessor;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.CodeBlock;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import static com.razerdp.lib.config.AnnotationConfig.AndroidConfig.PACKAGE_SPARSEARRAY;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_FIELD_NAME;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_FILE_NAME;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_INTERFACE;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_INTERFACE_METHOD;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_PACKAGE_NAME;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.PACKAGE_NAME;
}
private CodeBlock createStaticBlock() {
CodeBlock.Builder builder = CodeBlock.builder();
final String listName = "mServiceImplList";
final TypeName sparseArrayType = ClassName.get(PACKAGE_SPARSEARRAY, "SparseArray");
//SparseArray mServiceImplList
builder.addStatement("$T " + listName, sparseArrayType);
for (Map.Entry<TypeName, List<InnerAptInfo>> entry : mServiceImplMap.entrySet()) {
//mServiceImplList = new SparseArray();
builder.addStatement(listName + " = new $T()", sparseArrayType);
for (InnerAptInfo aptInfo : entry.getValue()) {
//mServiceImplList.put(tag,new impl());
builder.addStatement(listName + ".put($L , new $T())",
aptInfo.tag,
ClassName.get(aptInfo.mirror));
}
//SERVICE_IMPL_MAP.put(impl.calss,mServiceImplList)
builder.addStatement(APT_FIELD_NAME + ".put($T.class," + listName + ")", entry.getKey());
}
return builder.build();
}
private MethodSpec createInterfaceMethod() { | MethodSpec.Builder builder = MethodSpec.methodBuilder(APT_INTERFACE_METHOD) |
razerdp/FriendCircle | lib_processor/src/main/java/com/razerdp/lib/processor/service/ModuleServiceProcessor.java | // Path: lib_processor/src/main/java/com/razerdp/lib/processor/BaseProcessor.java
// public abstract class BaseProcessor extends AbstractProcessor {
// protected Filer mFiler;
// protected Logger mLogger;
// protected Types mTypesUtil;
// protected Elements mElementUtil;
//
// @Override
// public synchronized void init(ProcessingEnvironment processingEnvironment) {
// super.init(processingEnvironment);
//
// mFiler = processingEnvironment.getFiler();
// mTypesUtil = processingEnvironment.getTypeUtils();
// mElementUtil = processingEnvironment.getElementUtils();
//
// mLogger = new Logger(processingEnvironment.getMessager());
// }
//
// @Override
// public SourceVersion getSupportedSourceVersion() {
// return SourceVersion.latestSupported();
// }
//
// @Override
// public Set<String> getSupportedAnnotationTypes() {
// Set<String> supportedAnnotationsSet = new LinkedHashSet<>();
// Set<Class<? extends Annotation>> result = new LinkedHashSet<>();
// onSetSupportedAnnotation(result);
// for (Class<? extends Annotation> aClass : result) {
// supportedAnnotationsSet.add(aClass.getCanonicalName());
// }
// return supportedAnnotationsSet;
// }
//
// protected abstract void onSetSupportedAnnotation(Set<Class<? extends Annotation>> result);
//
//
// public void logi(CharSequence which) {
// mLogger.i(which);
// }
//
// public void loge(CharSequence which) {
// mLogger.e(which);
// }
//
// public void logw(CharSequence which) {
// mLogger.w(which);
// }
//
// public void loge(Throwable which) {
// mLogger.e(which);
// }
// }
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String PACKAGE_SPARSEARRAY = "android.util";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_FIELD_NAME="SERVICE_IMPL_MAP";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_FILE_NAME = "ServiceImplGen";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_INTERFACE = "com.razerdp.github.common.modules.base.IModuleServiceProvider";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_INTERFACE_METHOD="getServiceImplMap";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_PACKAGE_NAME = PACKAGE_NAME + ".apt.gen";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String PACKAGE_NAME = "com.razerdp.github";
| import com.razerdp.lib.annotations.ServiceImpl;
import com.razerdp.lib.processor.BaseProcessor;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.CodeBlock;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import static com.razerdp.lib.config.AnnotationConfig.AndroidConfig.PACKAGE_SPARSEARRAY;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_FIELD_NAME;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_FILE_NAME;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_INTERFACE;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_INTERFACE_METHOD;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_PACKAGE_NAME;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.PACKAGE_NAME; | private void scanClass(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
//scan for service impl
Set<? extends Element> elements = roundEnvironment.getElementsAnnotatedWith(ServiceImpl.class);
for (Element element : elements) {
//only get annotation for class type
if (!(element instanceof TypeElement)) continue;
if (element.getKind() != ElementKind.CLASS) {
loge(TAG + " @ServiceImpl is only for class");
continue;
}
if (!element.getModifiers().contains(Modifier.PUBLIC)) {
loge(TAG + " @ServiceImpl is only for public class");
continue;
}
TypeElement typeElement = (TypeElement) element;
TypeMirror mirror = typeElement.asType();
if (!(mirror.getKind() == TypeKind.DECLARED)) {
continue;
}
// check interface
List<? extends TypeMirror> superClassElement = mTypesUtil.directSupertypes(mirror);
if (superClassElement == null || superClassElement.size() <= 0) continue;
TypeMirror serviceInterfaceElement = null;
for (TypeMirror typeMirror : superClassElement) { | // Path: lib_processor/src/main/java/com/razerdp/lib/processor/BaseProcessor.java
// public abstract class BaseProcessor extends AbstractProcessor {
// protected Filer mFiler;
// protected Logger mLogger;
// protected Types mTypesUtil;
// protected Elements mElementUtil;
//
// @Override
// public synchronized void init(ProcessingEnvironment processingEnvironment) {
// super.init(processingEnvironment);
//
// mFiler = processingEnvironment.getFiler();
// mTypesUtil = processingEnvironment.getTypeUtils();
// mElementUtil = processingEnvironment.getElementUtils();
//
// mLogger = new Logger(processingEnvironment.getMessager());
// }
//
// @Override
// public SourceVersion getSupportedSourceVersion() {
// return SourceVersion.latestSupported();
// }
//
// @Override
// public Set<String> getSupportedAnnotationTypes() {
// Set<String> supportedAnnotationsSet = new LinkedHashSet<>();
// Set<Class<? extends Annotation>> result = new LinkedHashSet<>();
// onSetSupportedAnnotation(result);
// for (Class<? extends Annotation> aClass : result) {
// supportedAnnotationsSet.add(aClass.getCanonicalName());
// }
// return supportedAnnotationsSet;
// }
//
// protected abstract void onSetSupportedAnnotation(Set<Class<? extends Annotation>> result);
//
//
// public void logi(CharSequence which) {
// mLogger.i(which);
// }
//
// public void loge(CharSequence which) {
// mLogger.e(which);
// }
//
// public void logw(CharSequence which) {
// mLogger.w(which);
// }
//
// public void loge(Throwable which) {
// mLogger.e(which);
// }
// }
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String PACKAGE_SPARSEARRAY = "android.util";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_FIELD_NAME="SERVICE_IMPL_MAP";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_FILE_NAME = "ServiceImplGen";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_INTERFACE = "com.razerdp.github.common.modules.base.IModuleServiceProvider";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_INTERFACE_METHOD="getServiceImplMap";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String APT_PACKAGE_NAME = PACKAGE_NAME + ".apt.gen";
//
// Path: lib_annotations/src/main/java/com/razerdp/lib/config/AnnotationConfig.java
// public static final String PACKAGE_NAME = "com.razerdp.github";
// Path: lib_processor/src/main/java/com/razerdp/lib/processor/service/ModuleServiceProcessor.java
import com.razerdp.lib.annotations.ServiceImpl;
import com.razerdp.lib.processor.BaseProcessor;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.CodeBlock;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import static com.razerdp.lib.config.AnnotationConfig.AndroidConfig.PACKAGE_SPARSEARRAY;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_FIELD_NAME;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_FILE_NAME;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_INTERFACE;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_INTERFACE_METHOD;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.APT_PACKAGE_NAME;
import static com.razerdp.lib.config.AnnotationConfig.ServiceConfig.PACKAGE_NAME;
private void scanClass(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
//scan for service impl
Set<? extends Element> elements = roundEnvironment.getElementsAnnotatedWith(ServiceImpl.class);
for (Element element : elements) {
//only get annotation for class type
if (!(element instanceof TypeElement)) continue;
if (element.getKind() != ElementKind.CLASS) {
loge(TAG + " @ServiceImpl is only for class");
continue;
}
if (!element.getModifiers().contains(Modifier.PUBLIC)) {
loge(TAG + " @ServiceImpl is only for public class");
continue;
}
TypeElement typeElement = (TypeElement) element;
TypeMirror mirror = typeElement.asType();
if (!(mirror.getKind() == TypeKind.DECLARED)) {
continue;
}
// check interface
List<? extends TypeMirror> superClassElement = mTypesUtil.directSupertypes(mirror);
if (superClassElement == null || superClassElement.size() <= 0) continue;
TypeMirror serviceInterfaceElement = null;
for (TypeMirror typeMirror : superClassElement) { | if (typeMirror.toString().startsWith(PACKAGE_NAME)) { |
razerdp/FriendCircle | lib/src/main/java/com/razerdp/github/lib/helper/FragmentInjectHelper.java | // Path: lib/src/main/java/com/razerdp/github/lib/utils/ActivityUtil.java
// public class ActivityUtil {
//
// /**
// * 检查activity是否存活
// */
// public static boolean isAlive(Activity act) {
// if (act == null) return false;
// return !act.isFinishing() && !act.isDestroyed();
// }
// }
| import android.os.Bundle;
import android.text.TextUtils;
import com.razerdp.github.lib.utils.ActivityUtil;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager; | package com.razerdp.github.lib.helper;
/**
* Created by 大灯泡 on 2019/8/1.
* <p>
* fragment注入工具
*/
public class FragmentInjectHelper {
@Nullable
public static <F extends Fragment> F inject(@NonNull FragmentActivity target,
@NonNull Class<F> fragClass) {
return inject(target, fragClass, null);
}
@Nullable
public static <F extends Fragment> F inject(@NonNull FragmentActivity target,
@NonNull Class<F> fragClass,
@Nullable Bundle arguments) {
return inject(target, fragClass, arguments, fragClass.getName());
}
@Nullable
public static <F extends Fragment> F inject(@NonNull FragmentActivity target,
@NonNull Class<F> fragClass,
@Nullable Bundle arguments,
@Nullable String tag) { | // Path: lib/src/main/java/com/razerdp/github/lib/utils/ActivityUtil.java
// public class ActivityUtil {
//
// /**
// * 检查activity是否存活
// */
// public static boolean isAlive(Activity act) {
// if (act == null) return false;
// return !act.isFinishing() && !act.isDestroyed();
// }
// }
// Path: lib/src/main/java/com/razerdp/github/lib/helper/FragmentInjectHelper.java
import android.os.Bundle;
import android.text.TextUtils;
import com.razerdp.github.lib.utils.ActivityUtil;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
package com.razerdp.github.lib.helper;
/**
* Created by 大灯泡 on 2019/8/1.
* <p>
* fragment注入工具
*/
public class FragmentInjectHelper {
@Nullable
public static <F extends Fragment> F inject(@NonNull FragmentActivity target,
@NonNull Class<F> fragClass) {
return inject(target, fragClass, null);
}
@Nullable
public static <F extends Fragment> F inject(@NonNull FragmentActivity target,
@NonNull Class<F> fragClass,
@Nullable Bundle arguments) {
return inject(target, fragClass, arguments, fragClass.getName());
}
@Nullable
public static <F extends Fragment> F inject(@NonNull FragmentActivity target,
@NonNull Class<F> fragClass,
@Nullable Bundle arguments,
@Nullable String tag) { | if (!ActivityUtil.isAlive(target)) return null; |
razerdp/FriendCircle | lib/src/main/java/com/razerdp/github/lib/manager/compress/CompressTaskQueue.java | // Path: lib/src/main/java/com/razerdp/github/lib/utils/ToolUtil.java
// public class ToolUtil {
//
// public static boolean isEmpty(Collection<?> datas) {
// return datas == null || datas.size() <= 0;
// }
//
// public static boolean isEmpty(Map map) {
// return map == null || map.isEmpty();
// }
//
//
// public static boolean indexInCollection(Collection who, int index) {
// if (who == null) return false;
// return index >= 0 && index < who.size();
// }
//
//
// public static void install(Context context, String apkPath) {
// Intent intent = new Intent(Intent.ACTION_VIEW);
// if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
// File file = (new File(apkPath));
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Uri apkUri = FileProvider.getUriForFile(context, "github.razerdp.friendcircle", file);
// intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
// intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
// } else {
// intent.setDataAndType(Uri.fromFile(new File(apkPath)),
// "application/vnd.android.package-archive");
// }
// context.startActivity(intent);
// }
// }
| import android.content.Context;
import com.razerdp.github.lib.utils.ToolUtil;
import java.util.ArrayList;
import java.util.List; | package com.razerdp.github.lib.manager.compress;
/**
* Created by 大灯泡 on 2018/1/10.
*/
public class CompressTaskQueue extends BaseCompressTaskHelper<List<CompressOption>> {
private List<CompressTaskHelper> mTaskHelpers;
private List<CompressResult> result;
private int taskSize;
private volatile boolean abort = false;
CompressTaskQueue(Context context, List<CompressOption> options, OnCompressListener onCompressListener) {
super(context, options, onCompressListener);
}
@Override
public void start() { | // Path: lib/src/main/java/com/razerdp/github/lib/utils/ToolUtil.java
// public class ToolUtil {
//
// public static boolean isEmpty(Collection<?> datas) {
// return datas == null || datas.size() <= 0;
// }
//
// public static boolean isEmpty(Map map) {
// return map == null || map.isEmpty();
// }
//
//
// public static boolean indexInCollection(Collection who, int index) {
// if (who == null) return false;
// return index >= 0 && index < who.size();
// }
//
//
// public static void install(Context context, String apkPath) {
// Intent intent = new Intent(Intent.ACTION_VIEW);
// if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
// File file = (new File(apkPath));
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Uri apkUri = FileProvider.getUriForFile(context, "github.razerdp.friendcircle", file);
// intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
// intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
// } else {
// intent.setDataAndType(Uri.fromFile(new File(apkPath)),
// "application/vnd.android.package-archive");
// }
// context.startActivity(intent);
// }
// }
// Path: lib/src/main/java/com/razerdp/github/lib/manager/compress/CompressTaskQueue.java
import android.content.Context;
import com.razerdp.github.lib.utils.ToolUtil;
import java.util.ArrayList;
import java.util.List;
package com.razerdp.github.lib.manager.compress;
/**
* Created by 大灯泡 on 2018/1/10.
*/
public class CompressTaskQueue extends BaseCompressTaskHelper<List<CompressOption>> {
private List<CompressTaskHelper> mTaskHelpers;
private List<CompressResult> result;
private int taskSize;
private volatile boolean abort = false;
CompressTaskQueue(Context context, List<CompressOption> options, OnCompressListener onCompressListener) {
super(context, options, onCompressListener);
}
@Override
public void start() { | if (ToolUtil.isEmpty(data)) { |
52inc/android-Showcase | app/src/main/java/com/ftinc/showcase/ui/screens/setup/LockscreenSetupPresenterImpl.java | // Path: app/src/main/java/com/ftinc/showcase/ui/lock/LockType.java
// public enum LockType{
// NONE("None"),
// PIN("PIN"),
// PATTERN("Pattern"),
// PASSWORD("Password");
//
// // The proper name
// private final String mName;
//
// /**
// * Constructor
// * @param name the proper name for this enum
// */
// LockType(String name){
// mName = name;
// }
//
// public static LockType from(int ordinal){
// return LockType.values()[ordinal];
// }
//
// /**
// * Create the lockscreen for this given type
// * @return the lockscreen implementation for this type
// */
// public Lockscreen create(Context ctx){
// switch (this){
// case PIN:
// return new Lockscreen.Builder(ctx, this)
// .ui(new PinUI())
// .storage(new SecurePrefStorage(ctx))
// .authenticator(new BasicAuth())
// .build();
//
// case PATTERN:
// return new Lockscreen.Builder(ctx, this)
// .ui(new PatternUI())
// .storage(new SecurePrefStorage(ctx))
// .authenticator(new BasicAuth())
// .build();
//
// case PASSWORD:
// return null;
// default:
// return null;
// }
// }
//
// /**
// * Get this lockscreen's storage key
// */
// public String getKey(){
// return String.format("lockscreen_key_%s", toString());
// }
//
// /**
// * Get the proper name for this enum
// * @return the enum's proper name
// */
// public String getName(){
// return mName;
// }
//
// }
//
// Path: app/src/main/java/com/ftinc/showcase/ui/lock/LockType.java
// public enum LockType{
// NONE("None"),
// PIN("PIN"),
// PATTERN("Pattern"),
// PASSWORD("Password");
//
// // The proper name
// private final String mName;
//
// /**
// * Constructor
// * @param name the proper name for this enum
// */
// LockType(String name){
// mName = name;
// }
//
// public static LockType from(int ordinal){
// return LockType.values()[ordinal];
// }
//
// /**
// * Create the lockscreen for this given type
// * @return the lockscreen implementation for this type
// */
// public Lockscreen create(Context ctx){
// switch (this){
// case PIN:
// return new Lockscreen.Builder(ctx, this)
// .ui(new PinUI())
// .storage(new SecurePrefStorage(ctx))
// .authenticator(new BasicAuth())
// .build();
//
// case PATTERN:
// return new Lockscreen.Builder(ctx, this)
// .ui(new PatternUI())
// .storage(new SecurePrefStorage(ctx))
// .authenticator(new BasicAuth())
// .build();
//
// case PASSWORD:
// return null;
// default:
// return null;
// }
// }
//
// /**
// * Get this lockscreen's storage key
// */
// public String getKey(){
// return String.format("lockscreen_key_%s", toString());
// }
//
// /**
// * Get the proper name for this enum
// * @return the enum's proper name
// */
// public String getName(){
// return mName;
// }
//
// }
| import android.content.Intent;
import android.os.Bundle;
import com.ftinc.showcase.ui.lock.LockType;
import static com.ftinc.showcase.ui.lock.LockType.*; | package com.ftinc.showcase.ui.screens.setup;
/**
* Project: Showcase
* Package: com.ftinc.showcase.ui.screens.setup
* Created by drew.heavner on 2/26/15.
*/
public class LockscreenSetupPresenterImpl implements LockscreenSetupPresenter {
private LockscreenSetupView mView; | // Path: app/src/main/java/com/ftinc/showcase/ui/lock/LockType.java
// public enum LockType{
// NONE("None"),
// PIN("PIN"),
// PATTERN("Pattern"),
// PASSWORD("Password");
//
// // The proper name
// private final String mName;
//
// /**
// * Constructor
// * @param name the proper name for this enum
// */
// LockType(String name){
// mName = name;
// }
//
// public static LockType from(int ordinal){
// return LockType.values()[ordinal];
// }
//
// /**
// * Create the lockscreen for this given type
// * @return the lockscreen implementation for this type
// */
// public Lockscreen create(Context ctx){
// switch (this){
// case PIN:
// return new Lockscreen.Builder(ctx, this)
// .ui(new PinUI())
// .storage(new SecurePrefStorage(ctx))
// .authenticator(new BasicAuth())
// .build();
//
// case PATTERN:
// return new Lockscreen.Builder(ctx, this)
// .ui(new PatternUI())
// .storage(new SecurePrefStorage(ctx))
// .authenticator(new BasicAuth())
// .build();
//
// case PASSWORD:
// return null;
// default:
// return null;
// }
// }
//
// /**
// * Get this lockscreen's storage key
// */
// public String getKey(){
// return String.format("lockscreen_key_%s", toString());
// }
//
// /**
// * Get the proper name for this enum
// * @return the enum's proper name
// */
// public String getName(){
// return mName;
// }
//
// }
//
// Path: app/src/main/java/com/ftinc/showcase/ui/lock/LockType.java
// public enum LockType{
// NONE("None"),
// PIN("PIN"),
// PATTERN("Pattern"),
// PASSWORD("Password");
//
// // The proper name
// private final String mName;
//
// /**
// * Constructor
// * @param name the proper name for this enum
// */
// LockType(String name){
// mName = name;
// }
//
// public static LockType from(int ordinal){
// return LockType.values()[ordinal];
// }
//
// /**
// * Create the lockscreen for this given type
// * @return the lockscreen implementation for this type
// */
// public Lockscreen create(Context ctx){
// switch (this){
// case PIN:
// return new Lockscreen.Builder(ctx, this)
// .ui(new PinUI())
// .storage(new SecurePrefStorage(ctx))
// .authenticator(new BasicAuth())
// .build();
//
// case PATTERN:
// return new Lockscreen.Builder(ctx, this)
// .ui(new PatternUI())
// .storage(new SecurePrefStorage(ctx))
// .authenticator(new BasicAuth())
// .build();
//
// case PASSWORD:
// return null;
// default:
// return null;
// }
// }
//
// /**
// * Get this lockscreen's storage key
// */
// public String getKey(){
// return String.format("lockscreen_key_%s", toString());
// }
//
// /**
// * Get the proper name for this enum
// * @return the enum's proper name
// */
// public String getName(){
// return mName;
// }
//
// }
// Path: app/src/main/java/com/ftinc/showcase/ui/screens/setup/LockscreenSetupPresenterImpl.java
import android.content.Intent;
import android.os.Bundle;
import com.ftinc.showcase.ui.lock.LockType;
import static com.ftinc.showcase.ui.lock.LockType.*;
package com.ftinc.showcase.ui.screens.setup;
/**
* Project: Showcase
* Package: com.ftinc.showcase.ui.screens.setup
* Created by drew.heavner on 2/26/15.
*/
public class LockscreenSetupPresenterImpl implements LockscreenSetupPresenter {
private LockscreenSetupView mView; | private LockType mType; |
52inc/android-Showcase | app/src/main/java/com/ftinc/showcase/ui/lock/storage/SecurePrefStorage.java | // Path: app/src/main/java/com/ftinc/showcase/ShowcaseApp.java
// public class ShowcaseApp extends Application {
//
// public static final String DB_NAME = "Showcase.db";
// public static final int DB_VERSION = 1;
//
// private ObjectGraph objectGraph;
//
// @Override
// public void onCreate() {
//
// if(BuildConfig.DEBUG){
// Timber.plant(new Timber.DebugTree());
// Timber.plant(new CrashlyticsTree(this));
// }else{
// Timber.plant(new CrashlyticsTree(this));
// }
//
// // Initialize PostOffice
// PostOffice.lick(new Stamp.Builder(this)
// .setCancelable(true)
// .setCanceledOnTouchOutside(true)
// .setDesign(Design.MATERIAL_LIGHT)
// .setThemeColorResource(R.color.accent)
// .build());
//
// // Intialize Ollie
// Ollie.with(this)
// .setName(DB_NAME)
// .setVersion(DB_VERSION)
// .setLogLevel(BuildConfig.DEBUG ? Ollie.LogLevel.FULL : Ollie.LogLevel.NONE)
// .init();
//
// // Build and Inject Dagger Object Graph
// buildObjectGraphAndInject();
//
// }
//
// @DebugLog
// public void buildObjectGraphAndInject(){
// objectGraph = ObjectGraph.create(new Object[]{
// new ShowcaseModule(this)
// });
// objectGraph.inject(this);
// }
//
// /**
// * Create a scoped object graph
// *
// * @param modules the list of modules to add to the scope
// * @return the scoped graph
// */
// public ObjectGraph createScopedGraph(Object... modules){
// return objectGraph.plus(modules);
// }
//
// /**
// * Inject an object with the object graph
// */
// public void inject(Object o){
// objectGraph.inject(o);
// }
//
// /**
// * Get a reference to the Application
// *
// * @param ctx the context
// *
// * @return the ChipperApp reference
// */
// public static ShowcaseApp get(Context ctx){
// return (ShowcaseApp) ctx.getApplicationContext();
// }
//
// /**
// * Get a reference to this application with a service
// * object
// *
// * @param ctx
// * @return
// */
// public static ShowcaseApp get(Service ctx){
// return (ShowcaseApp) ctx.getApplication();
// }
//
// }
//
// Path: app/src/main/java/com/ftinc/showcase/ui/lock/LockType.java
// public enum LockType{
// NONE("None"),
// PIN("PIN"),
// PATTERN("Pattern"),
// PASSWORD("Password");
//
// // The proper name
// private final String mName;
//
// /**
// * Constructor
// * @param name the proper name for this enum
// */
// LockType(String name){
// mName = name;
// }
//
// public static LockType from(int ordinal){
// return LockType.values()[ordinal];
// }
//
// /**
// * Create the lockscreen for this given type
// * @return the lockscreen implementation for this type
// */
// public Lockscreen create(Context ctx){
// switch (this){
// case PIN:
// return new Lockscreen.Builder(ctx, this)
// .ui(new PinUI())
// .storage(new SecurePrefStorage(ctx))
// .authenticator(new BasicAuth())
// .build();
//
// case PATTERN:
// return new Lockscreen.Builder(ctx, this)
// .ui(new PatternUI())
// .storage(new SecurePrefStorage(ctx))
// .authenticator(new BasicAuth())
// .build();
//
// case PASSWORD:
// return null;
// default:
// return null;
// }
// }
//
// /**
// * Get this lockscreen's storage key
// */
// public String getKey(){
// return String.format("lockscreen_key_%s", toString());
// }
//
// /**
// * Get the proper name for this enum
// * @return the enum's proper name
// */
// public String getName(){
// return mName;
// }
//
// }
| import android.content.Context;
import android.util.Base64;
import com.ftinc.kit.preferences.SecurePreferences;
import com.ftinc.showcase.ShowcaseApp;
import com.ftinc.showcase.ui.lock.LockType;
import javax.inject.Inject; | package com.ftinc.showcase.ui.lock.storage;
/**
* Basic storage mechanism that stores the data in base64 strings using {@link android.util.Base64}
* in the Secure AES-256 SharedPreference wrapper: {@link SecurePreferences}
*
* Project: Showcase
* Package: com.ftinc.showcase.ui.lock.storage
* Created by drew.heavner on 3/2/15.
*/
public class SecurePrefStorage implements Storage{
@Inject
SecurePreferences mSecPrefs;
/**
* Constructor
*
* @param ctx the context reference to inject with
*/
public SecurePrefStorage(Context ctx){ | // Path: app/src/main/java/com/ftinc/showcase/ShowcaseApp.java
// public class ShowcaseApp extends Application {
//
// public static final String DB_NAME = "Showcase.db";
// public static final int DB_VERSION = 1;
//
// private ObjectGraph objectGraph;
//
// @Override
// public void onCreate() {
//
// if(BuildConfig.DEBUG){
// Timber.plant(new Timber.DebugTree());
// Timber.plant(new CrashlyticsTree(this));
// }else{
// Timber.plant(new CrashlyticsTree(this));
// }
//
// // Initialize PostOffice
// PostOffice.lick(new Stamp.Builder(this)
// .setCancelable(true)
// .setCanceledOnTouchOutside(true)
// .setDesign(Design.MATERIAL_LIGHT)
// .setThemeColorResource(R.color.accent)
// .build());
//
// // Intialize Ollie
// Ollie.with(this)
// .setName(DB_NAME)
// .setVersion(DB_VERSION)
// .setLogLevel(BuildConfig.DEBUG ? Ollie.LogLevel.FULL : Ollie.LogLevel.NONE)
// .init();
//
// // Build and Inject Dagger Object Graph
// buildObjectGraphAndInject();
//
// }
//
// @DebugLog
// public void buildObjectGraphAndInject(){
// objectGraph = ObjectGraph.create(new Object[]{
// new ShowcaseModule(this)
// });
// objectGraph.inject(this);
// }
//
// /**
// * Create a scoped object graph
// *
// * @param modules the list of modules to add to the scope
// * @return the scoped graph
// */
// public ObjectGraph createScopedGraph(Object... modules){
// return objectGraph.plus(modules);
// }
//
// /**
// * Inject an object with the object graph
// */
// public void inject(Object o){
// objectGraph.inject(o);
// }
//
// /**
// * Get a reference to the Application
// *
// * @param ctx the context
// *
// * @return the ChipperApp reference
// */
// public static ShowcaseApp get(Context ctx){
// return (ShowcaseApp) ctx.getApplicationContext();
// }
//
// /**
// * Get a reference to this application with a service
// * object
// *
// * @param ctx
// * @return
// */
// public static ShowcaseApp get(Service ctx){
// return (ShowcaseApp) ctx.getApplication();
// }
//
// }
//
// Path: app/src/main/java/com/ftinc/showcase/ui/lock/LockType.java
// public enum LockType{
// NONE("None"),
// PIN("PIN"),
// PATTERN("Pattern"),
// PASSWORD("Password");
//
// // The proper name
// private final String mName;
//
// /**
// * Constructor
// * @param name the proper name for this enum
// */
// LockType(String name){
// mName = name;
// }
//
// public static LockType from(int ordinal){
// return LockType.values()[ordinal];
// }
//
// /**
// * Create the lockscreen for this given type
// * @return the lockscreen implementation for this type
// */
// public Lockscreen create(Context ctx){
// switch (this){
// case PIN:
// return new Lockscreen.Builder(ctx, this)
// .ui(new PinUI())
// .storage(new SecurePrefStorage(ctx))
// .authenticator(new BasicAuth())
// .build();
//
// case PATTERN:
// return new Lockscreen.Builder(ctx, this)
// .ui(new PatternUI())
// .storage(new SecurePrefStorage(ctx))
// .authenticator(new BasicAuth())
// .build();
//
// case PASSWORD:
// return null;
// default:
// return null;
// }
// }
//
// /**
// * Get this lockscreen's storage key
// */
// public String getKey(){
// return String.format("lockscreen_key_%s", toString());
// }
//
// /**
// * Get the proper name for this enum
// * @return the enum's proper name
// */
// public String getName(){
// return mName;
// }
//
// }
// Path: app/src/main/java/com/ftinc/showcase/ui/lock/storage/SecurePrefStorage.java
import android.content.Context;
import android.util.Base64;
import com.ftinc.kit.preferences.SecurePreferences;
import com.ftinc.showcase.ShowcaseApp;
import com.ftinc.showcase.ui.lock.LockType;
import javax.inject.Inject;
package com.ftinc.showcase.ui.lock.storage;
/**
* Basic storage mechanism that stores the data in base64 strings using {@link android.util.Base64}
* in the Secure AES-256 SharedPreference wrapper: {@link SecurePreferences}
*
* Project: Showcase
* Package: com.ftinc.showcase.ui.lock.storage
* Created by drew.heavner on 3/2/15.
*/
public class SecurePrefStorage implements Storage{
@Inject
SecurePreferences mSecPrefs;
/**
* Constructor
*
* @param ctx the context reference to inject with
*/
public SecurePrefStorage(Context ctx){ | ShowcaseApp.get(ctx).inject(this); |
52inc/android-Showcase | app/src/main/java/com/ftinc/showcase/ui/lock/storage/SecurePrefStorage.java | // Path: app/src/main/java/com/ftinc/showcase/ShowcaseApp.java
// public class ShowcaseApp extends Application {
//
// public static final String DB_NAME = "Showcase.db";
// public static final int DB_VERSION = 1;
//
// private ObjectGraph objectGraph;
//
// @Override
// public void onCreate() {
//
// if(BuildConfig.DEBUG){
// Timber.plant(new Timber.DebugTree());
// Timber.plant(new CrashlyticsTree(this));
// }else{
// Timber.plant(new CrashlyticsTree(this));
// }
//
// // Initialize PostOffice
// PostOffice.lick(new Stamp.Builder(this)
// .setCancelable(true)
// .setCanceledOnTouchOutside(true)
// .setDesign(Design.MATERIAL_LIGHT)
// .setThemeColorResource(R.color.accent)
// .build());
//
// // Intialize Ollie
// Ollie.with(this)
// .setName(DB_NAME)
// .setVersion(DB_VERSION)
// .setLogLevel(BuildConfig.DEBUG ? Ollie.LogLevel.FULL : Ollie.LogLevel.NONE)
// .init();
//
// // Build and Inject Dagger Object Graph
// buildObjectGraphAndInject();
//
// }
//
// @DebugLog
// public void buildObjectGraphAndInject(){
// objectGraph = ObjectGraph.create(new Object[]{
// new ShowcaseModule(this)
// });
// objectGraph.inject(this);
// }
//
// /**
// * Create a scoped object graph
// *
// * @param modules the list of modules to add to the scope
// * @return the scoped graph
// */
// public ObjectGraph createScopedGraph(Object... modules){
// return objectGraph.plus(modules);
// }
//
// /**
// * Inject an object with the object graph
// */
// public void inject(Object o){
// objectGraph.inject(o);
// }
//
// /**
// * Get a reference to the Application
// *
// * @param ctx the context
// *
// * @return the ChipperApp reference
// */
// public static ShowcaseApp get(Context ctx){
// return (ShowcaseApp) ctx.getApplicationContext();
// }
//
// /**
// * Get a reference to this application with a service
// * object
// *
// * @param ctx
// * @return
// */
// public static ShowcaseApp get(Service ctx){
// return (ShowcaseApp) ctx.getApplication();
// }
//
// }
//
// Path: app/src/main/java/com/ftinc/showcase/ui/lock/LockType.java
// public enum LockType{
// NONE("None"),
// PIN("PIN"),
// PATTERN("Pattern"),
// PASSWORD("Password");
//
// // The proper name
// private final String mName;
//
// /**
// * Constructor
// * @param name the proper name for this enum
// */
// LockType(String name){
// mName = name;
// }
//
// public static LockType from(int ordinal){
// return LockType.values()[ordinal];
// }
//
// /**
// * Create the lockscreen for this given type
// * @return the lockscreen implementation for this type
// */
// public Lockscreen create(Context ctx){
// switch (this){
// case PIN:
// return new Lockscreen.Builder(ctx, this)
// .ui(new PinUI())
// .storage(new SecurePrefStorage(ctx))
// .authenticator(new BasicAuth())
// .build();
//
// case PATTERN:
// return new Lockscreen.Builder(ctx, this)
// .ui(new PatternUI())
// .storage(new SecurePrefStorage(ctx))
// .authenticator(new BasicAuth())
// .build();
//
// case PASSWORD:
// return null;
// default:
// return null;
// }
// }
//
// /**
// * Get this lockscreen's storage key
// */
// public String getKey(){
// return String.format("lockscreen_key_%s", toString());
// }
//
// /**
// * Get the proper name for this enum
// * @return the enum's proper name
// */
// public String getName(){
// return mName;
// }
//
// }
| import android.content.Context;
import android.util.Base64;
import com.ftinc.kit.preferences.SecurePreferences;
import com.ftinc.showcase.ShowcaseApp;
import com.ftinc.showcase.ui.lock.LockType;
import javax.inject.Inject; | package com.ftinc.showcase.ui.lock.storage;
/**
* Basic storage mechanism that stores the data in base64 strings using {@link android.util.Base64}
* in the Secure AES-256 SharedPreference wrapper: {@link SecurePreferences}
*
* Project: Showcase
* Package: com.ftinc.showcase.ui.lock.storage
* Created by drew.heavner on 3/2/15.
*/
public class SecurePrefStorage implements Storage{
@Inject
SecurePreferences mSecPrefs;
/**
* Constructor
*
* @param ctx the context reference to inject with
*/
public SecurePrefStorage(Context ctx){
ShowcaseApp.get(ctx).inject(this);
}
@Override | // Path: app/src/main/java/com/ftinc/showcase/ShowcaseApp.java
// public class ShowcaseApp extends Application {
//
// public static final String DB_NAME = "Showcase.db";
// public static final int DB_VERSION = 1;
//
// private ObjectGraph objectGraph;
//
// @Override
// public void onCreate() {
//
// if(BuildConfig.DEBUG){
// Timber.plant(new Timber.DebugTree());
// Timber.plant(new CrashlyticsTree(this));
// }else{
// Timber.plant(new CrashlyticsTree(this));
// }
//
// // Initialize PostOffice
// PostOffice.lick(new Stamp.Builder(this)
// .setCancelable(true)
// .setCanceledOnTouchOutside(true)
// .setDesign(Design.MATERIAL_LIGHT)
// .setThemeColorResource(R.color.accent)
// .build());
//
// // Intialize Ollie
// Ollie.with(this)
// .setName(DB_NAME)
// .setVersion(DB_VERSION)
// .setLogLevel(BuildConfig.DEBUG ? Ollie.LogLevel.FULL : Ollie.LogLevel.NONE)
// .init();
//
// // Build and Inject Dagger Object Graph
// buildObjectGraphAndInject();
//
// }
//
// @DebugLog
// public void buildObjectGraphAndInject(){
// objectGraph = ObjectGraph.create(new Object[]{
// new ShowcaseModule(this)
// });
// objectGraph.inject(this);
// }
//
// /**
// * Create a scoped object graph
// *
// * @param modules the list of modules to add to the scope
// * @return the scoped graph
// */
// public ObjectGraph createScopedGraph(Object... modules){
// return objectGraph.plus(modules);
// }
//
// /**
// * Inject an object with the object graph
// */
// public void inject(Object o){
// objectGraph.inject(o);
// }
//
// /**
// * Get a reference to the Application
// *
// * @param ctx the context
// *
// * @return the ChipperApp reference
// */
// public static ShowcaseApp get(Context ctx){
// return (ShowcaseApp) ctx.getApplicationContext();
// }
//
// /**
// * Get a reference to this application with a service
// * object
// *
// * @param ctx
// * @return
// */
// public static ShowcaseApp get(Service ctx){
// return (ShowcaseApp) ctx.getApplication();
// }
//
// }
//
// Path: app/src/main/java/com/ftinc/showcase/ui/lock/LockType.java
// public enum LockType{
// NONE("None"),
// PIN("PIN"),
// PATTERN("Pattern"),
// PASSWORD("Password");
//
// // The proper name
// private final String mName;
//
// /**
// * Constructor
// * @param name the proper name for this enum
// */
// LockType(String name){
// mName = name;
// }
//
// public static LockType from(int ordinal){
// return LockType.values()[ordinal];
// }
//
// /**
// * Create the lockscreen for this given type
// * @return the lockscreen implementation for this type
// */
// public Lockscreen create(Context ctx){
// switch (this){
// case PIN:
// return new Lockscreen.Builder(ctx, this)
// .ui(new PinUI())
// .storage(new SecurePrefStorage(ctx))
// .authenticator(new BasicAuth())
// .build();
//
// case PATTERN:
// return new Lockscreen.Builder(ctx, this)
// .ui(new PatternUI())
// .storage(new SecurePrefStorage(ctx))
// .authenticator(new BasicAuth())
// .build();
//
// case PASSWORD:
// return null;
// default:
// return null;
// }
// }
//
// /**
// * Get this lockscreen's storage key
// */
// public String getKey(){
// return String.format("lockscreen_key_%s", toString());
// }
//
// /**
// * Get the proper name for this enum
// * @return the enum's proper name
// */
// public String getName(){
// return mName;
// }
//
// }
// Path: app/src/main/java/com/ftinc/showcase/ui/lock/storage/SecurePrefStorage.java
import android.content.Context;
import android.util.Base64;
import com.ftinc.kit.preferences.SecurePreferences;
import com.ftinc.showcase.ShowcaseApp;
import com.ftinc.showcase.ui.lock.LockType;
import javax.inject.Inject;
package com.ftinc.showcase.ui.lock.storage;
/**
* Basic storage mechanism that stores the data in base64 strings using {@link android.util.Base64}
* in the Secure AES-256 SharedPreference wrapper: {@link SecurePreferences}
*
* Project: Showcase
* Package: com.ftinc.showcase.ui.lock.storage
* Created by drew.heavner on 3/2/15.
*/
public class SecurePrefStorage implements Storage{
@Inject
SecurePreferences mSecPrefs;
/**
* Constructor
*
* @param ctx the context reference to inject with
*/
public SecurePrefStorage(Context ctx){
ShowcaseApp.get(ctx).inject(this);
}
@Override | public void deposit(byte[] input, LockType type) { |
52inc/android-Showcase | app/src/main/java/com/ftinc/showcase/data/DataModule.java | // Path: app/src/main/java/com/ftinc/showcase/ui/lock/LockType.java
// public enum LockType{
// NONE("None"),
// PIN("PIN"),
// PATTERN("Pattern"),
// PASSWORD("Password");
//
// // The proper name
// private final String mName;
//
// /**
// * Constructor
// * @param name the proper name for this enum
// */
// LockType(String name){
// mName = name;
// }
//
// public static LockType from(int ordinal){
// return LockType.values()[ordinal];
// }
//
// /**
// * Create the lockscreen for this given type
// * @return the lockscreen implementation for this type
// */
// public Lockscreen create(Context ctx){
// switch (this){
// case PIN:
// return new Lockscreen.Builder(ctx, this)
// .ui(new PinUI())
// .storage(new SecurePrefStorage(ctx))
// .authenticator(new BasicAuth())
// .build();
//
// case PATTERN:
// return new Lockscreen.Builder(ctx, this)
// .ui(new PatternUI())
// .storage(new SecurePrefStorage(ctx))
// .authenticator(new BasicAuth())
// .build();
//
// case PASSWORD:
// return null;
// default:
// return null;
// }
// }
//
// /**
// * Get this lockscreen's storage key
// */
// public String getKey(){
// return String.format("lockscreen_key_%s", toString());
// }
//
// /**
// * Get the proper name for this enum
// * @return the enum's proper name
// */
// public String getName(){
// return mName;
// }
//
// }
| import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import com.ftinc.kit.preferences.BooleanPreference;
import com.ftinc.kit.preferences.IntPreference;
import com.ftinc.kit.preferences.SecurePreferences;
import com.ftinc.kit.preferences.StringPreference;
import com.ftinc.showcase.BuildConfig;
import com.ftinc.showcase.ui.lock.LockType;
import javax.inject.Singleton;
import com.ftinc.showcase.utils.qualifiers.AlarmSoundName;
import com.ftinc.showcase.utils.qualifiers.AlarmSoundPath;
import com.ftinc.showcase.utils.qualifiers.LockTimeout;
import com.ftinc.showcase.utils.qualifiers.Onboarding;
import com.ftinc.showcase.utils.qualifiers.SirenEnabled;
import com.ftinc.showcase.utils.qualifiers.SirenMessage;
import com.ftinc.showcase.utils.qualifiers.VideoAudio;
import com.ftinc.showcase.utils.qualifiers.VideoConstraints;
import com.ftinc.showcase.utils.qualifiers.VideoLock;
import dagger.Module;
import dagger.Provides; | private static final String SAUCE = BuildConfig.SECURE_KEY;
private static final String FLAVOR = BuildConfig.SECURE_SALT;
@Provides @Singleton
SecurePreferences provideSecurePreferences(Context ctx){
return new SecurePreferences(ctx, PREFS_SECURE_NAME, SAUCE, FLAVOR, true);
}
@Provides @Singleton
SharedPreferences provideDefaultPrefs(Context ctx){
return PreferenceManager.getDefaultSharedPreferences(ctx);
}
@Provides @Singleton @Onboarding
BooleanPreference provideShowOnboardingPreference(SharedPreferences prefs){
return new BooleanPreference(prefs, PREF_SHOW_ONBOARDING, true);
}
@Provides @Singleton @AlarmSoundName
StringPreference provideAlarmSoundNamePreference(SharedPreferences prefs){
return new StringPreference(prefs, PREF_ALARM_SOUND_NAME);
}
@Provides @Singleton @AlarmSoundPath
StringPreference provideAlarmSoundPathPreference(SharedPreferences prefs){
return new StringPreference(prefs, PREF_ALARM_SOUND_PATH);
}
@Provides @Singleton @VideoLock
IntPreference provideVideoLockPreference(SharedPreferences prefs){ | // Path: app/src/main/java/com/ftinc/showcase/ui/lock/LockType.java
// public enum LockType{
// NONE("None"),
// PIN("PIN"),
// PATTERN("Pattern"),
// PASSWORD("Password");
//
// // The proper name
// private final String mName;
//
// /**
// * Constructor
// * @param name the proper name for this enum
// */
// LockType(String name){
// mName = name;
// }
//
// public static LockType from(int ordinal){
// return LockType.values()[ordinal];
// }
//
// /**
// * Create the lockscreen for this given type
// * @return the lockscreen implementation for this type
// */
// public Lockscreen create(Context ctx){
// switch (this){
// case PIN:
// return new Lockscreen.Builder(ctx, this)
// .ui(new PinUI())
// .storage(new SecurePrefStorage(ctx))
// .authenticator(new BasicAuth())
// .build();
//
// case PATTERN:
// return new Lockscreen.Builder(ctx, this)
// .ui(new PatternUI())
// .storage(new SecurePrefStorage(ctx))
// .authenticator(new BasicAuth())
// .build();
//
// case PASSWORD:
// return null;
// default:
// return null;
// }
// }
//
// /**
// * Get this lockscreen's storage key
// */
// public String getKey(){
// return String.format("lockscreen_key_%s", toString());
// }
//
// /**
// * Get the proper name for this enum
// * @return the enum's proper name
// */
// public String getName(){
// return mName;
// }
//
// }
// Path: app/src/main/java/com/ftinc/showcase/data/DataModule.java
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import com.ftinc.kit.preferences.BooleanPreference;
import com.ftinc.kit.preferences.IntPreference;
import com.ftinc.kit.preferences.SecurePreferences;
import com.ftinc.kit.preferences.StringPreference;
import com.ftinc.showcase.BuildConfig;
import com.ftinc.showcase.ui.lock.LockType;
import javax.inject.Singleton;
import com.ftinc.showcase.utils.qualifiers.AlarmSoundName;
import com.ftinc.showcase.utils.qualifiers.AlarmSoundPath;
import com.ftinc.showcase.utils.qualifiers.LockTimeout;
import com.ftinc.showcase.utils.qualifiers.Onboarding;
import com.ftinc.showcase.utils.qualifiers.SirenEnabled;
import com.ftinc.showcase.utils.qualifiers.SirenMessage;
import com.ftinc.showcase.utils.qualifiers.VideoAudio;
import com.ftinc.showcase.utils.qualifiers.VideoConstraints;
import com.ftinc.showcase.utils.qualifiers.VideoLock;
import dagger.Module;
import dagger.Provides;
private static final String SAUCE = BuildConfig.SECURE_KEY;
private static final String FLAVOR = BuildConfig.SECURE_SALT;
@Provides @Singleton
SecurePreferences provideSecurePreferences(Context ctx){
return new SecurePreferences(ctx, PREFS_SECURE_NAME, SAUCE, FLAVOR, true);
}
@Provides @Singleton
SharedPreferences provideDefaultPrefs(Context ctx){
return PreferenceManager.getDefaultSharedPreferences(ctx);
}
@Provides @Singleton @Onboarding
BooleanPreference provideShowOnboardingPreference(SharedPreferences prefs){
return new BooleanPreference(prefs, PREF_SHOW_ONBOARDING, true);
}
@Provides @Singleton @AlarmSoundName
StringPreference provideAlarmSoundNamePreference(SharedPreferences prefs){
return new StringPreference(prefs, PREF_ALARM_SOUND_NAME);
}
@Provides @Singleton @AlarmSoundPath
StringPreference provideAlarmSoundPathPreference(SharedPreferences prefs){
return new StringPreference(prefs, PREF_ALARM_SOUND_PATH);
}
@Provides @Singleton @VideoLock
IntPreference provideVideoLockPreference(SharedPreferences prefs){ | return new IntPreference(prefs, PREF_VIDEO_LOCK, LockType.NONE.ordinal()); |
52inc/android-Showcase | app/src/main/java/com/ftinc/showcase/ShowcaseApp.java | // Path: app/src/main/java/com/ftinc/showcase/utils/CrashlyticsTree.java
// public class CrashlyticsTree extends Timber.Tree {
//
// /**
// * Constructor
// * @param ctx
// */
// public CrashlyticsTree(Context ctx){
// Fabric.with(ctx, new Crashlytics());
// }
//
// @Override
// protected void log(int priority, String tag, String message, Throwable t) {
// throwShade(priority, tag, message, t);
// }
//
// private void throwShade(int priority, String tag, String message, Throwable t) {
// if (message == null || message.length() == 0) {
// if (t != null) {
// message = Log.getStackTraceString(t);
// } else {
// // Swallow message if it's null and there's no throwable.
// return;
// }
// } else if (t != null) {
// message += "\n" + Log.getStackTraceString(t);
// }
//
// if (message.length() < 4000) {
// log(priority, tag, message);
// } else {
// // It's rare that the message will be this large, so we're ok with the perf hit of splitting
// // and calling Log.println N times. It's possible but unlikely that a single line will be
// // longer than 4000 characters: we're explicitly ignoring this case here.
// String[] lines = message.split("\n");
// for (String line : lines) {
// log(priority, tag, line);
// }
// }
// }
//
// /**
// * Convienence function for logging to the crashlytics server
// *
// * @param priority the logging priority
// * @param tag the log tag
// * @param message the log message
// */
// private void log(int priority, String tag, String message){
// Crashlytics.log(priority, tag, message);
// }
// }
| import android.app.Application;
import android.app.Service;
import android.content.Context;
import com.crashlytics.android.Crashlytics;
import com.r0adkll.postoffice.PostOffice;
import com.r0adkll.postoffice.model.Design;
import com.r0adkll.postoffice.model.Stamp;
import com.ftinc.showcase.utils.CrashlyticsTree;
import dagger.ObjectGraph;
import hugo.weaving.DebugLog;
import io.fabric.sdk.android.Fabric;
import ollie.Ollie;
import timber.log.Timber; | package com.ftinc.showcase;
/**
* Created by drew.heavner on 2/27/14.
*/
public class ShowcaseApp extends Application {
public static final String DB_NAME = "Showcase.db";
public static final int DB_VERSION = 1;
private ObjectGraph objectGraph;
@Override
public void onCreate() {
if(BuildConfig.DEBUG){
Timber.plant(new Timber.DebugTree()); | // Path: app/src/main/java/com/ftinc/showcase/utils/CrashlyticsTree.java
// public class CrashlyticsTree extends Timber.Tree {
//
// /**
// * Constructor
// * @param ctx
// */
// public CrashlyticsTree(Context ctx){
// Fabric.with(ctx, new Crashlytics());
// }
//
// @Override
// protected void log(int priority, String tag, String message, Throwable t) {
// throwShade(priority, tag, message, t);
// }
//
// private void throwShade(int priority, String tag, String message, Throwable t) {
// if (message == null || message.length() == 0) {
// if (t != null) {
// message = Log.getStackTraceString(t);
// } else {
// // Swallow message if it's null and there's no throwable.
// return;
// }
// } else if (t != null) {
// message += "\n" + Log.getStackTraceString(t);
// }
//
// if (message.length() < 4000) {
// log(priority, tag, message);
// } else {
// // It's rare that the message will be this large, so we're ok with the perf hit of splitting
// // and calling Log.println N times. It's possible but unlikely that a single line will be
// // longer than 4000 characters: we're explicitly ignoring this case here.
// String[] lines = message.split("\n");
// for (String line : lines) {
// log(priority, tag, line);
// }
// }
// }
//
// /**
// * Convienence function for logging to the crashlytics server
// *
// * @param priority the logging priority
// * @param tag the log tag
// * @param message the log message
// */
// private void log(int priority, String tag, String message){
// Crashlytics.log(priority, tag, message);
// }
// }
// Path: app/src/main/java/com/ftinc/showcase/ShowcaseApp.java
import android.app.Application;
import android.app.Service;
import android.content.Context;
import com.crashlytics.android.Crashlytics;
import com.r0adkll.postoffice.PostOffice;
import com.r0adkll.postoffice.model.Design;
import com.r0adkll.postoffice.model.Stamp;
import com.ftinc.showcase.utils.CrashlyticsTree;
import dagger.ObjectGraph;
import hugo.weaving.DebugLog;
import io.fabric.sdk.android.Fabric;
import ollie.Ollie;
import timber.log.Timber;
package com.ftinc.showcase;
/**
* Created by drew.heavner on 2/27/14.
*/
public class ShowcaseApp extends Application {
public static final String DB_NAME = "Showcase.db";
public static final int DB_VERSION = 1;
private ObjectGraph objectGraph;
@Override
public void onCreate() {
if(BuildConfig.DEBUG){
Timber.plant(new Timber.DebugTree()); | Timber.plant(new CrashlyticsTree(this)); |
52inc/android-Showcase | app/src/main/java/com/ftinc/showcase/ui/screens/home/HomePresenter.java | // Path: app/src/main/java/com/ftinc/showcase/data/model/Video.java
// @Table("videos")
// public class Video extends Model{
//
// @Column("path")
// public String file;
//
// @Column("name")
// public String name;
//
// @Column("thumbnail_path")
// public String thumbnail = "";
//
// /**
// * Empty constructor
// */
// public Video(){
// super();
// }
//
// /**
// * File constructor
// * @param videoFile
// */
// public Video(File videoFile){
// this();
// file = videoFile.getAbsolutePath();
// name = videoFile.getName();
// }
//
// }
| import android.net.Uri;
import android.util.SparseArray;
import com.ftinc.showcase.data.model.Video; | package com.ftinc.showcase.ui.screens.home;
/**
* Project: Kiosk
* Package: co.ftinc.kiosk.ui.screens.home
* Created by drew.heavner on 2/18/15.
*/
public interface HomePresenter {
public void loadVideos();
| // Path: app/src/main/java/com/ftinc/showcase/data/model/Video.java
// @Table("videos")
// public class Video extends Model{
//
// @Column("path")
// public String file;
//
// @Column("name")
// public String name;
//
// @Column("thumbnail_path")
// public String thumbnail = "";
//
// /**
// * Empty constructor
// */
// public Video(){
// super();
// }
//
// /**
// * File constructor
// * @param videoFile
// */
// public Video(File videoFile){
// this();
// file = videoFile.getAbsolutePath();
// name = videoFile.getName();
// }
//
// }
// Path: app/src/main/java/com/ftinc/showcase/ui/screens/home/HomePresenter.java
import android.net.Uri;
import android.util.SparseArray;
import com.ftinc.showcase.data.model.Video;
package com.ftinc.showcase.ui.screens.home;
/**
* Project: Kiosk
* Package: co.ftinc.kiosk.ui.screens.home
* Created by drew.heavner on 2/18/15.
*/
public interface HomePresenter {
public void loadVideos();
| public void deleteVideos(SparseArray<Video> videos); |
52inc/android-Showcase | app/src/main/java/com/ftinc/showcase/ui/screens/setup/LockscreenSetupPresenter.java | // Path: app/src/main/java/com/ftinc/showcase/ui/lock/LockType.java
// public enum LockType{
// NONE("None"),
// PIN("PIN"),
// PATTERN("Pattern"),
// PASSWORD("Password");
//
// // The proper name
// private final String mName;
//
// /**
// * Constructor
// * @param name the proper name for this enum
// */
// LockType(String name){
// mName = name;
// }
//
// public static LockType from(int ordinal){
// return LockType.values()[ordinal];
// }
//
// /**
// * Create the lockscreen for this given type
// * @return the lockscreen implementation for this type
// */
// public Lockscreen create(Context ctx){
// switch (this){
// case PIN:
// return new Lockscreen.Builder(ctx, this)
// .ui(new PinUI())
// .storage(new SecurePrefStorage(ctx))
// .authenticator(new BasicAuth())
// .build();
//
// case PATTERN:
// return new Lockscreen.Builder(ctx, this)
// .ui(new PatternUI())
// .storage(new SecurePrefStorage(ctx))
// .authenticator(new BasicAuth())
// .build();
//
// case PASSWORD:
// return null;
// default:
// return null;
// }
// }
//
// /**
// * Get this lockscreen's storage key
// */
// public String getKey(){
// return String.format("lockscreen_key_%s", toString());
// }
//
// /**
// * Get the proper name for this enum
// * @return the enum's proper name
// */
// public String getName(){
// return mName;
// }
//
// }
| import android.os.Bundle;
import com.ftinc.showcase.ui.lock.LockType; | package com.ftinc.showcase.ui.screens.setup;
/**
* Project: Showcase
* Package: com.ftinc.showcase.ui.screens.setup
* Created by drew.heavner on 2/26/15.
*/
public interface LockscreenSetupPresenter {
public void parseExtras(Bundle icicle);
public void saveInstanceState(Bundle out);
| // Path: app/src/main/java/com/ftinc/showcase/ui/lock/LockType.java
// public enum LockType{
// NONE("None"),
// PIN("PIN"),
// PATTERN("Pattern"),
// PASSWORD("Password");
//
// // The proper name
// private final String mName;
//
// /**
// * Constructor
// * @param name the proper name for this enum
// */
// LockType(String name){
// mName = name;
// }
//
// public static LockType from(int ordinal){
// return LockType.values()[ordinal];
// }
//
// /**
// * Create the lockscreen for this given type
// * @return the lockscreen implementation for this type
// */
// public Lockscreen create(Context ctx){
// switch (this){
// case PIN:
// return new Lockscreen.Builder(ctx, this)
// .ui(new PinUI())
// .storage(new SecurePrefStorage(ctx))
// .authenticator(new BasicAuth())
// .build();
//
// case PATTERN:
// return new Lockscreen.Builder(ctx, this)
// .ui(new PatternUI())
// .storage(new SecurePrefStorage(ctx))
// .authenticator(new BasicAuth())
// .build();
//
// case PASSWORD:
// return null;
// default:
// return null;
// }
// }
//
// /**
// * Get this lockscreen's storage key
// */
// public String getKey(){
// return String.format("lockscreen_key_%s", toString());
// }
//
// /**
// * Get the proper name for this enum
// * @return the enum's proper name
// */
// public String getName(){
// return mName;
// }
//
// }
// Path: app/src/main/java/com/ftinc/showcase/ui/screens/setup/LockscreenSetupPresenter.java
import android.os.Bundle;
import com.ftinc.showcase.ui.lock.LockType;
package com.ftinc.showcase.ui.screens.setup;
/**
* Project: Showcase
* Package: com.ftinc.showcase.ui.screens.setup
* Created by drew.heavner on 2/26/15.
*/
public interface LockscreenSetupPresenter {
public void parseExtras(Bundle icicle);
public void saveInstanceState(Bundle out);
| public LockType getType(); |
52inc/android-Showcase | app/src/main/java/com/ftinc/showcase/ui/adapters/VideoListAdapter.java | // Path: app/src/main/java/com/ftinc/showcase/data/model/Video.java
// @Table("videos")
// public class Video extends Model{
//
// @Column("path")
// public String file;
//
// @Column("name")
// public String name;
//
// @Column("thumbnail_path")
// public String thumbnail = "";
//
// /**
// * Empty constructor
// */
// public Video(){
// super();
// }
//
// /**
// * File constructor
// * @param videoFile
// */
// public Video(File videoFile){
// this();
// file = videoFile.getAbsolutePath();
// name = videoFile.getName();
// }
//
// }
//
// Path: app/src/main/java/com/ftinc/showcase/utils/CircleTransform.java
// public class CircleTransform implements Transformation {
// @Override
// public Bitmap transform(Bitmap source) {
// int size = Math.min(source.getWidth(), source.getHeight());
//
// int x = (source.getWidth() - size) / 2;
// int y = (source.getHeight() - size) / 2;
//
// Bitmap squaredBitmap = Bitmap.createBitmap(source, x, y, size, size);
// if (squaredBitmap != source) {
// source.recycle();
// }
//
// Bitmap bitmap = Bitmap.createBitmap(size, size, source.getConfig());
//
// Canvas canvas = new Canvas(bitmap);
// Paint paint = new Paint();
// BitmapShader shader = new BitmapShader(squaredBitmap, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP);
// paint.setShader(shader);
// paint.setAntiAlias(true);
//
// float r = size/2f;
// canvas.drawCircle(r, r, r , paint);
//
// squaredBitmap.recycle();
// return bitmap;
// }
//
// @Override
// public String key() {
// return "circle:v1";
// }
// }
//
// Path: app/src/main/java/com/ftinc/showcase/ui/adapters/VideoListAdapter.java
// public static class VideoViewHolder extends BetterListAdapter.ViewHolder {
//
// @InjectView(R.id.thumbnail) ImageView thumbnail;
// @InjectView(R.id.title) TextView title;
// @InjectView(R.id.description) TextView description;
//
// /**
// * Butterknife injector constructor
// *
// * @param view the view to inject
// */
// public VideoViewHolder(View view) {
// super(view);
// ButterKnife.inject(this, view);
// FontLoader.applyTypeface(title, Types.ROBOTO_REGULAR);
// FontLoader.applyTypeface(description, Types.ROBOTO_REGULAR);
// }
//
// }
| import android.content.Context;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.ftinc.kit.adapter.BetterListAdapter;
import com.ftinc.showcase.R;
import com.ftinc.showcase.data.model.Video;
import com.ftinc.showcase.utils.CircleTransform;
import com.ftinc.fontloader.FontLoader;
import com.ftinc.fontloader.Types;
import com.squareup.picasso.Picasso;
import java.io.File;
import java.util.List;
import butterknife.ButterKnife;
import butterknife.InjectView;
import com.ftinc.showcase.ui.adapters.VideoListAdapter.VideoViewHolder; | package com.ftinc.showcase.ui.adapters;
/**
* Project: VideoLooperProject
* Package: com.ftapps.kiosk.adapters
* Created by drew.heavner on 10/3/14.
*/
public class VideoListAdapter extends BetterListAdapter<Video, VideoViewHolder> {
/**
* Constructor
*/
public VideoListAdapter(Context context, List<Video> objects) {
super(context, R.layout.layout_video_item, objects);
}
@Override
public VideoViewHolder createHolder(View view) {
return new VideoViewHolder(view);
}
@Override
public void bindHolder(VideoViewHolder holder, int i, Video video) {
holder.title.setText(video.name);
File file = new File(video.file);
String parent = file.getParent();
if(parent != null){
String desc = parent.replace("/storage/emulated/0", "/sdcard");
holder.description.setText(desc);
}else{
String desc = video.file.replace("/storage/emulated/0", "/sdcard");
holder.description.setText(desc);
}
// Load the thumbnail
if(video.thumbnail != null && !video.thumbnail.isEmpty()){
holder.thumbnail.setVisibility(View.VISIBLE);
File thumb = new File(video.thumbnail);
Picasso.with(getContext())
.load(thumb) | // Path: app/src/main/java/com/ftinc/showcase/data/model/Video.java
// @Table("videos")
// public class Video extends Model{
//
// @Column("path")
// public String file;
//
// @Column("name")
// public String name;
//
// @Column("thumbnail_path")
// public String thumbnail = "";
//
// /**
// * Empty constructor
// */
// public Video(){
// super();
// }
//
// /**
// * File constructor
// * @param videoFile
// */
// public Video(File videoFile){
// this();
// file = videoFile.getAbsolutePath();
// name = videoFile.getName();
// }
//
// }
//
// Path: app/src/main/java/com/ftinc/showcase/utils/CircleTransform.java
// public class CircleTransform implements Transformation {
// @Override
// public Bitmap transform(Bitmap source) {
// int size = Math.min(source.getWidth(), source.getHeight());
//
// int x = (source.getWidth() - size) / 2;
// int y = (source.getHeight() - size) / 2;
//
// Bitmap squaredBitmap = Bitmap.createBitmap(source, x, y, size, size);
// if (squaredBitmap != source) {
// source.recycle();
// }
//
// Bitmap bitmap = Bitmap.createBitmap(size, size, source.getConfig());
//
// Canvas canvas = new Canvas(bitmap);
// Paint paint = new Paint();
// BitmapShader shader = new BitmapShader(squaredBitmap, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP);
// paint.setShader(shader);
// paint.setAntiAlias(true);
//
// float r = size/2f;
// canvas.drawCircle(r, r, r , paint);
//
// squaredBitmap.recycle();
// return bitmap;
// }
//
// @Override
// public String key() {
// return "circle:v1";
// }
// }
//
// Path: app/src/main/java/com/ftinc/showcase/ui/adapters/VideoListAdapter.java
// public static class VideoViewHolder extends BetterListAdapter.ViewHolder {
//
// @InjectView(R.id.thumbnail) ImageView thumbnail;
// @InjectView(R.id.title) TextView title;
// @InjectView(R.id.description) TextView description;
//
// /**
// * Butterknife injector constructor
// *
// * @param view the view to inject
// */
// public VideoViewHolder(View view) {
// super(view);
// ButterKnife.inject(this, view);
// FontLoader.applyTypeface(title, Types.ROBOTO_REGULAR);
// FontLoader.applyTypeface(description, Types.ROBOTO_REGULAR);
// }
//
// }
// Path: app/src/main/java/com/ftinc/showcase/ui/adapters/VideoListAdapter.java
import android.content.Context;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.ftinc.kit.adapter.BetterListAdapter;
import com.ftinc.showcase.R;
import com.ftinc.showcase.data.model.Video;
import com.ftinc.showcase.utils.CircleTransform;
import com.ftinc.fontloader.FontLoader;
import com.ftinc.fontloader.Types;
import com.squareup.picasso.Picasso;
import java.io.File;
import java.util.List;
import butterknife.ButterKnife;
import butterknife.InjectView;
import com.ftinc.showcase.ui.adapters.VideoListAdapter.VideoViewHolder;
package com.ftinc.showcase.ui.adapters;
/**
* Project: VideoLooperProject
* Package: com.ftapps.kiosk.adapters
* Created by drew.heavner on 10/3/14.
*/
public class VideoListAdapter extends BetterListAdapter<Video, VideoViewHolder> {
/**
* Constructor
*/
public VideoListAdapter(Context context, List<Video> objects) {
super(context, R.layout.layout_video_item, objects);
}
@Override
public VideoViewHolder createHolder(View view) {
return new VideoViewHolder(view);
}
@Override
public void bindHolder(VideoViewHolder holder, int i, Video video) {
holder.title.setText(video.name);
File file = new File(video.file);
String parent = file.getParent();
if(parent != null){
String desc = parent.replace("/storage/emulated/0", "/sdcard");
holder.description.setText(desc);
}else{
String desc = video.file.replace("/storage/emulated/0", "/sdcard");
holder.description.setText(desc);
}
// Load the thumbnail
if(video.thumbnail != null && !video.thumbnail.isEmpty()){
holder.thumbnail.setVisibility(View.VISIBLE);
File thumb = new File(video.thumbnail);
Picasso.with(getContext())
.load(thumb) | .transform(new CircleTransform()) |
52inc/android-Showcase | app/src/main/java/com/ftinc/showcase/ui/screens/home/HomeModule.java | // Path: app/src/main/java/com/ftinc/showcase/ui/UiModule.java
// @Module(
// injects = {
// SettingsActivity.SettingsFragment.class,
// SecurePrefStorage.class
// },
// library = true,
// complete = false
// )
// public class UiModule {
//
// @Provides @Singleton
// WindowManager provideWindowManager(Context ctx){
// return (WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE);
// }
//
// @Provides @Singleton
// AudioManager provideAudioManager(Context ctx){
// return (AudioManager) ctx.getSystemService(Context.AUDIO_SERVICE);
// }
//
// @Provides @Singleton
// LayoutInflater provideLayoutInflater(Context ctx){
// return LayoutInflater.from(ctx);
// }
//
// }
| import javax.inject.Singleton;
import com.ftinc.kit.preferences.IntPreference;
import com.ftinc.showcase.ui.UiModule;
import com.ftinc.showcase.utils.qualifiers.VideoLock;
import dagger.Module;
import dagger.Provides; | package com.ftinc.showcase.ui.screens.home;
/**
* Project: Kiosk
* Package: co.ftinc.kiosk.ui.screens.home
* Created by drew.heavner on 2/18/15.
*/
@Module(
injects = HomeActivity.class, | // Path: app/src/main/java/com/ftinc/showcase/ui/UiModule.java
// @Module(
// injects = {
// SettingsActivity.SettingsFragment.class,
// SecurePrefStorage.class
// },
// library = true,
// complete = false
// )
// public class UiModule {
//
// @Provides @Singleton
// WindowManager provideWindowManager(Context ctx){
// return (WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE);
// }
//
// @Provides @Singleton
// AudioManager provideAudioManager(Context ctx){
// return (AudioManager) ctx.getSystemService(Context.AUDIO_SERVICE);
// }
//
// @Provides @Singleton
// LayoutInflater provideLayoutInflater(Context ctx){
// return LayoutInflater.from(ctx);
// }
//
// }
// Path: app/src/main/java/com/ftinc/showcase/ui/screens/home/HomeModule.java
import javax.inject.Singleton;
import com.ftinc.kit.preferences.IntPreference;
import com.ftinc.showcase.ui.UiModule;
import com.ftinc.showcase.utils.qualifiers.VideoLock;
import dagger.Module;
import dagger.Provides;
package com.ftinc.showcase.ui.screens.home;
/**
* Project: Kiosk
* Package: co.ftinc.kiosk.ui.screens.home
* Created by drew.heavner on 2/18/15.
*/
@Module(
injects = HomeActivity.class, | addsTo = UiModule.class, |
52inc/android-Showcase | app/src/main/java/com/ftinc/showcase/ui/model/BaseActivity.java | // Path: app/src/main/java/com/ftinc/showcase/ShowcaseApp.java
// public class ShowcaseApp extends Application {
//
// public static final String DB_NAME = "Showcase.db";
// public static final int DB_VERSION = 1;
//
// private ObjectGraph objectGraph;
//
// @Override
// public void onCreate() {
//
// if(BuildConfig.DEBUG){
// Timber.plant(new Timber.DebugTree());
// Timber.plant(new CrashlyticsTree(this));
// }else{
// Timber.plant(new CrashlyticsTree(this));
// }
//
// // Initialize PostOffice
// PostOffice.lick(new Stamp.Builder(this)
// .setCancelable(true)
// .setCanceledOnTouchOutside(true)
// .setDesign(Design.MATERIAL_LIGHT)
// .setThemeColorResource(R.color.accent)
// .build());
//
// // Intialize Ollie
// Ollie.with(this)
// .setName(DB_NAME)
// .setVersion(DB_VERSION)
// .setLogLevel(BuildConfig.DEBUG ? Ollie.LogLevel.FULL : Ollie.LogLevel.NONE)
// .init();
//
// // Build and Inject Dagger Object Graph
// buildObjectGraphAndInject();
//
// }
//
// @DebugLog
// public void buildObjectGraphAndInject(){
// objectGraph = ObjectGraph.create(new Object[]{
// new ShowcaseModule(this)
// });
// objectGraph.inject(this);
// }
//
// /**
// * Create a scoped object graph
// *
// * @param modules the list of modules to add to the scope
// * @return the scoped graph
// */
// public ObjectGraph createScopedGraph(Object... modules){
// return objectGraph.plus(modules);
// }
//
// /**
// * Inject an object with the object graph
// */
// public void inject(Object o){
// objectGraph.inject(o);
// }
//
// /**
// * Get a reference to the Application
// *
// * @param ctx the context
// *
// * @return the ChipperApp reference
// */
// public static ShowcaseApp get(Context ctx){
// return (ShowcaseApp) ctx.getApplicationContext();
// }
//
// /**
// * Get a reference to this application with a service
// * object
// *
// * @param ctx
// * @return
// */
// public static ShowcaseApp get(Service ctx){
// return (ShowcaseApp) ctx.getApplication();
// }
//
// }
| import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import com.ftinc.showcase.ShowcaseApp;
import dagger.ObjectGraph; | package com.ftinc.showcase.ui.model;
/**
* This is a base UI activity that assists in creating a scoped
* object graph on the activity for DI
*
* Project: Chipper
* Package: com.r0adkll.chipper.ui
* Created by drew.heavner on 11/12/14.
*/
public abstract class BaseActivity extends AppCompatActivity {
private ObjectGraph activityGraph;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); | // Path: app/src/main/java/com/ftinc/showcase/ShowcaseApp.java
// public class ShowcaseApp extends Application {
//
// public static final String DB_NAME = "Showcase.db";
// public static final int DB_VERSION = 1;
//
// private ObjectGraph objectGraph;
//
// @Override
// public void onCreate() {
//
// if(BuildConfig.DEBUG){
// Timber.plant(new Timber.DebugTree());
// Timber.plant(new CrashlyticsTree(this));
// }else{
// Timber.plant(new CrashlyticsTree(this));
// }
//
// // Initialize PostOffice
// PostOffice.lick(new Stamp.Builder(this)
// .setCancelable(true)
// .setCanceledOnTouchOutside(true)
// .setDesign(Design.MATERIAL_LIGHT)
// .setThemeColorResource(R.color.accent)
// .build());
//
// // Intialize Ollie
// Ollie.with(this)
// .setName(DB_NAME)
// .setVersion(DB_VERSION)
// .setLogLevel(BuildConfig.DEBUG ? Ollie.LogLevel.FULL : Ollie.LogLevel.NONE)
// .init();
//
// // Build and Inject Dagger Object Graph
// buildObjectGraphAndInject();
//
// }
//
// @DebugLog
// public void buildObjectGraphAndInject(){
// objectGraph = ObjectGraph.create(new Object[]{
// new ShowcaseModule(this)
// });
// objectGraph.inject(this);
// }
//
// /**
// * Create a scoped object graph
// *
// * @param modules the list of modules to add to the scope
// * @return the scoped graph
// */
// public ObjectGraph createScopedGraph(Object... modules){
// return objectGraph.plus(modules);
// }
//
// /**
// * Inject an object with the object graph
// */
// public void inject(Object o){
// objectGraph.inject(o);
// }
//
// /**
// * Get a reference to the Application
// *
// * @param ctx the context
// *
// * @return the ChipperApp reference
// */
// public static ShowcaseApp get(Context ctx){
// return (ShowcaseApp) ctx.getApplicationContext();
// }
//
// /**
// * Get a reference to this application with a service
// * object
// *
// * @param ctx
// * @return
// */
// public static ShowcaseApp get(Service ctx){
// return (ShowcaseApp) ctx.getApplication();
// }
//
// }
// Path: app/src/main/java/com/ftinc/showcase/ui/model/BaseActivity.java
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import com.ftinc.showcase.ShowcaseApp;
import dagger.ObjectGraph;
package com.ftinc.showcase.ui.model;
/**
* This is a base UI activity that assists in creating a scoped
* object graph on the activity for DI
*
* Project: Chipper
* Package: com.r0adkll.chipper.ui
* Created by drew.heavner on 11/12/14.
*/
public abstract class BaseActivity extends AppCompatActivity {
private ObjectGraph activityGraph;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); | activityGraph = ShowcaseApp.get(this).createScopedGraph(getModules()); |
52inc/android-Showcase | app/src/main/java/com/ftinc/showcase/ui/screens/setup/LockscreenSetupModule.java | // Path: app/src/main/java/com/ftinc/showcase/ui/UiModule.java
// @Module(
// injects = {
// SettingsActivity.SettingsFragment.class,
// SecurePrefStorage.class
// },
// library = true,
// complete = false
// )
// public class UiModule {
//
// @Provides @Singleton
// WindowManager provideWindowManager(Context ctx){
// return (WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE);
// }
//
// @Provides @Singleton
// AudioManager provideAudioManager(Context ctx){
// return (AudioManager) ctx.getSystemService(Context.AUDIO_SERVICE);
// }
//
// @Provides @Singleton
// LayoutInflater provideLayoutInflater(Context ctx){
// return LayoutInflater.from(ctx);
// }
//
// }
| import com.ftinc.showcase.ui.UiModule;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides; | package com.ftinc.showcase.ui.screens.setup;
/**
* Project: Showcase
* Package: com.ftinc.showcase.ui.screens.setup
* Created by drew.heavner on 2/26/15.
*/
@Module(
injects = LockscreenSetupActivity.class, | // Path: app/src/main/java/com/ftinc/showcase/ui/UiModule.java
// @Module(
// injects = {
// SettingsActivity.SettingsFragment.class,
// SecurePrefStorage.class
// },
// library = true,
// complete = false
// )
// public class UiModule {
//
// @Provides @Singleton
// WindowManager provideWindowManager(Context ctx){
// return (WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE);
// }
//
// @Provides @Singleton
// AudioManager provideAudioManager(Context ctx){
// return (AudioManager) ctx.getSystemService(Context.AUDIO_SERVICE);
// }
//
// @Provides @Singleton
// LayoutInflater provideLayoutInflater(Context ctx){
// return LayoutInflater.from(ctx);
// }
//
// }
// Path: app/src/main/java/com/ftinc/showcase/ui/screens/setup/LockscreenSetupModule.java
import com.ftinc.showcase.ui.UiModule;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
package com.ftinc.showcase.ui.screens.setup;
/**
* Project: Showcase
* Package: com.ftinc.showcase.ui.screens.setup
* Created by drew.heavner on 2/26/15.
*/
@Module(
injects = LockscreenSetupActivity.class, | addsTo = UiModule.class, |
52inc/android-Showcase | app/src/main/java/com/ftinc/showcase/ui/lock/ui/LockUI.java | // Path: app/src/main/java/com/ftinc/showcase/ui/lock/LockState.java
// public enum LockState {
// SETUP,
// CONFIRM,
// LOCKED,
// UNLOCKED;
// }
| import android.content.Context;
import android.content.res.Resources;
import android.support.annotation.ColorRes;
import android.support.annotation.StringRes;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.ftinc.showcase.ui.lock.LockState; | package com.ftinc.showcase.ui.lock.ui;
/**
* Project: Showcase
* Package: com.ftinc.showcase.ui.lock
* Created by drew.heavner on 2/27/15.
*/
public abstract class LockUI {
/***********************************************************************************************
*
* Variables
*
*/
private Context mCtx;
private UICallbacks mCallbacks; | // Path: app/src/main/java/com/ftinc/showcase/ui/lock/LockState.java
// public enum LockState {
// SETUP,
// CONFIRM,
// LOCKED,
// UNLOCKED;
// }
// Path: app/src/main/java/com/ftinc/showcase/ui/lock/ui/LockUI.java
import android.content.Context;
import android.content.res.Resources;
import android.support.annotation.ColorRes;
import android.support.annotation.StringRes;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.ftinc.showcase.ui.lock.LockState;
package com.ftinc.showcase.ui.lock.ui;
/**
* Project: Showcase
* Package: com.ftinc.showcase.ui.lock
* Created by drew.heavner on 2/27/15.
*/
public abstract class LockUI {
/***********************************************************************************************
*
* Variables
*
*/
private Context mCtx;
private UICallbacks mCallbacks; | private LockState mState; |
compasses/elastic-rabbitmq | elasticservice/src/main/java/elasticsearch/searchservice/config/ElasticServiceConfig.java | // Path: elasticservice/src/main/java/elasticsearch/searchservice/ESService.java
// @Service
// public class ESService {
// private static final Logger logger = LoggerFactory.getLogger(ESService.class);
//
// private static String baseURL;
// private static String searchProductURL;
// private static String countProductURL;
//
// @Autowired
// ElasticRestClient client;
//
// public ESService(String url) {
// this.setBaseURL(url);
// this.setSearchProductURL(url+"/storessearch/product/_search");
// this.setCountProductURL(url+"/storessearch/product/_count");
// logger.info("Initial ESService done, url: " + url);
// }
//
// public void setBaseURL(String url) {
// this.baseURL = url;
// }
//
// public void setSearchProductURL(String searchURL) {
// ESService.searchProductURL = searchURL;
// }
//
// public static void setCountProductURL(String countProductURL) {
// ESService.countProductURL = countProductURL;
// }
//
// // public RestResponse postSearch(byte[] body) {
// // // only return ids
// // map.put("_source", "id");
// // try {
// // return client.post(searchProductURL, body, map);
// // } catch (RestClientException e) {
// // //logger.warn("DO search failed " + e);
// // return null;
// // }
// // }
// //
// // public RestResponse postSearchCount(byte[] body) {
// // try {
// // return client.post(countProductURL, body, map);
// // } catch (RestClientException e) {
// // //logger.warn("DO search failed " + e);
// // return null;
// // }
// // }
// }
| import elasticsearch.searchservice.ESService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
| package elasticsearch.searchservice.config;
/**
* Created by I311352 on 10/18/2016.
*/
@Configuration
public class ElasticServiceConfig extends WebMvcConfigurerAdapter {
public static final String LOCAL_CONFIG_PATH = "META-INF/resources/es.properties";
public static final String PRODUCTION_CONFIG_PATH = "/etc/secrets/es/es.properties";
private static final Logger logger = LoggerFactory.getLogger(ElasticServiceConfig.class);
@Bean
public ESConnectionConfig esConnectionConfig(){
Properties properties = loadProperties(LOCAL_CONFIG_PATH, PRODUCTION_CONFIG_PATH);
ESConnectionConfig config = new ESConnectionConfig();
config.setEsDatabase(StringUtils.trimToNull(properties.getProperty("ES_DATABASE")));
config.setEsHost(StringUtils.trimToNull(properties.getProperty("ES_HOST")));
config.setEsPort(Integer.parseInt(StringUtils.trimToNull(properties.getProperty("ES_PORT"))));
return config;
}
| // Path: elasticservice/src/main/java/elasticsearch/searchservice/ESService.java
// @Service
// public class ESService {
// private static final Logger logger = LoggerFactory.getLogger(ESService.class);
//
// private static String baseURL;
// private static String searchProductURL;
// private static String countProductURL;
//
// @Autowired
// ElasticRestClient client;
//
// public ESService(String url) {
// this.setBaseURL(url);
// this.setSearchProductURL(url+"/storessearch/product/_search");
// this.setCountProductURL(url+"/storessearch/product/_count");
// logger.info("Initial ESService done, url: " + url);
// }
//
// public void setBaseURL(String url) {
// this.baseURL = url;
// }
//
// public void setSearchProductURL(String searchURL) {
// ESService.searchProductURL = searchURL;
// }
//
// public static void setCountProductURL(String countProductURL) {
// ESService.countProductURL = countProductURL;
// }
//
// // public RestResponse postSearch(byte[] body) {
// // // only return ids
// // map.put("_source", "id");
// // try {
// // return client.post(searchProductURL, body, map);
// // } catch (RestClientException e) {
// // //logger.warn("DO search failed " + e);
// // return null;
// // }
// // }
// //
// // public RestResponse postSearchCount(byte[] body) {
// // try {
// // return client.post(countProductURL, body, map);
// // } catch (RestClientException e) {
// // //logger.warn("DO search failed " + e);
// // return null;
// // }
// // }
// }
// Path: elasticservice/src/main/java/elasticsearch/searchservice/config/ElasticServiceConfig.java
import elasticsearch.searchservice.ESService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
package elasticsearch.searchservice.config;
/**
* Created by I311352 on 10/18/2016.
*/
@Configuration
public class ElasticServiceConfig extends WebMvcConfigurerAdapter {
public static final String LOCAL_CONFIG_PATH = "META-INF/resources/es.properties";
public static final String PRODUCTION_CONFIG_PATH = "/etc/secrets/es/es.properties";
private static final Logger logger = LoggerFactory.getLogger(ElasticServiceConfig.class);
@Bean
public ESConnectionConfig esConnectionConfig(){
Properties properties = loadProperties(LOCAL_CONFIG_PATH, PRODUCTION_CONFIG_PATH);
ESConnectionConfig config = new ESConnectionConfig();
config.setEsDatabase(StringUtils.trimToNull(properties.getProperty("ES_DATABASE")));
config.setEsHost(StringUtils.trimToNull(properties.getProperty("ES_HOST")));
config.setEsPort(Integer.parseInt(StringUtils.trimToNull(properties.getProperty("ES_PORT"))));
return config;
}
| @Bean(name = {"ESService"})
|
compasses/elastic-rabbitmq | elasticservice/src/main/java/elasticsearch/esapi/DocumentService.java | // Path: elasticservice/src/main/java/elasticsearch/exception/ElasticAPIException.java
// public class ElasticAPIException extends RuntimeException {
// public ElasticAPIException(String message) {
// super(message);
// }
//
// public ElasticAPIException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: elasticservice/src/main/java/elasticsearch/exception/ElasticQueryException.java
// public class ElasticQueryException extends RuntimeException {
// public ElasticQueryException(String message) {
// super(message);
// }
//
// public ElasticQueryException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: elasticservice/src/main/java/elasticsearch/exception/ElasticVersionConflictException.java
// public class ElasticVersionConflictException extends RuntimeException {
// public ElasticVersionConflictException(String message) {
// super(message);
// }
//
// public ElasticVersionConflictException(String message, Throwable cause) {
// super(message, cause);
// }
// }
| import com.google.gson.Gson;
import com.google.gson.JsonObject;
import elasticsearch.esapi.resp.*;
import elasticsearch.exception.ElasticAPIException;
import elasticsearch.exception.ElasticQueryException;
import elasticsearch.exception.ElasticVersionConflictException;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.Charsets;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.entity.StringEntity;
import org.apache.log4j.Logger;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.ResponseException;
import org.elasticsearch.client.RestClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
| package elasticsearch.esapi;
/**
* Created by I311352 on 10/3/2016.
*/
@Component
public class DocumentService {
private static final Logger logger = Logger.getLogger(DocumentService.class);
private final RestClient client;
private final Gson gson;
private final IndexService indexService;
@Autowired
public DocumentService(RestClient client, Gson gson, IndexService indexService) {
this.client = client;
this.gson = gson;
this.indexService = indexService;
}
public boolean isDocExist(String index, String type, Long sourceId, HashMap param) {
Map<String, String> params = addTenantId2Param(param);
try {
Response response = client.performRequest("HEAD", index + "/" + type + "/" + sourceId, params);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
return true;
} else if (statusCode == 404) {
return false;
}
| // Path: elasticservice/src/main/java/elasticsearch/exception/ElasticAPIException.java
// public class ElasticAPIException extends RuntimeException {
// public ElasticAPIException(String message) {
// super(message);
// }
//
// public ElasticAPIException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: elasticservice/src/main/java/elasticsearch/exception/ElasticQueryException.java
// public class ElasticQueryException extends RuntimeException {
// public ElasticQueryException(String message) {
// super(message);
// }
//
// public ElasticQueryException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: elasticservice/src/main/java/elasticsearch/exception/ElasticVersionConflictException.java
// public class ElasticVersionConflictException extends RuntimeException {
// public ElasticVersionConflictException(String message) {
// super(message);
// }
//
// public ElasticVersionConflictException(String message, Throwable cause) {
// super(message, cause);
// }
// }
// Path: elasticservice/src/main/java/elasticsearch/esapi/DocumentService.java
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import elasticsearch.esapi.resp.*;
import elasticsearch.exception.ElasticAPIException;
import elasticsearch.exception.ElasticQueryException;
import elasticsearch.exception.ElasticVersionConflictException;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.Charsets;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.entity.StringEntity;
import org.apache.log4j.Logger;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.ResponseException;
import org.elasticsearch.client.RestClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
package elasticsearch.esapi;
/**
* Created by I311352 on 10/3/2016.
*/
@Component
public class DocumentService {
private static final Logger logger = Logger.getLogger(DocumentService.class);
private final RestClient client;
private final Gson gson;
private final IndexService indexService;
@Autowired
public DocumentService(RestClient client, Gson gson, IndexService indexService) {
this.client = client;
this.gson = gson;
this.indexService = indexService;
}
public boolean isDocExist(String index, String type, Long sourceId, HashMap param) {
Map<String, String> params = addTenantId2Param(param);
try {
Response response = client.performRequest("HEAD", index + "/" + type + "/" + sourceId, params);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
return true;
} else if (statusCode == 404) {
return false;
}
| throw new ElasticQueryException("Exception for Doc Exist query");
|
compasses/elastic-rabbitmq | elasticservice/src/main/java/elasticsearch/esapi/DocumentService.java | // Path: elasticservice/src/main/java/elasticsearch/exception/ElasticAPIException.java
// public class ElasticAPIException extends RuntimeException {
// public ElasticAPIException(String message) {
// super(message);
// }
//
// public ElasticAPIException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: elasticservice/src/main/java/elasticsearch/exception/ElasticQueryException.java
// public class ElasticQueryException extends RuntimeException {
// public ElasticQueryException(String message) {
// super(message);
// }
//
// public ElasticQueryException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: elasticservice/src/main/java/elasticsearch/exception/ElasticVersionConflictException.java
// public class ElasticVersionConflictException extends RuntimeException {
// public ElasticVersionConflictException(String message) {
// super(message);
// }
//
// public ElasticVersionConflictException(String message, Throwable cause) {
// super(message, cause);
// }
// }
| import com.google.gson.Gson;
import com.google.gson.JsonObject;
import elasticsearch.esapi.resp.*;
import elasticsearch.exception.ElasticAPIException;
import elasticsearch.exception.ElasticQueryException;
import elasticsearch.exception.ElasticVersionConflictException;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.Charsets;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.entity.StringEntity;
import org.apache.log4j.Logger;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.ResponseException;
import org.elasticsearch.client.RestClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
| package elasticsearch.esapi;
/**
* Created by I311352 on 10/3/2016.
*/
@Component
public class DocumentService {
private static final Logger logger = Logger.getLogger(DocumentService.class);
private final RestClient client;
private final Gson gson;
private final IndexService indexService;
@Autowired
public DocumentService(RestClient client, Gson gson, IndexService indexService) {
this.client = client;
this.gson = gson;
this.indexService = indexService;
}
public boolean isDocExist(String index, String type, Long sourceId, HashMap param) {
Map<String, String> params = addTenantId2Param(param);
try {
Response response = client.performRequest("HEAD", index + "/" + type + "/" + sourceId, params);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
return true;
} else if (statusCode == 404) {
return false;
}
throw new ElasticQueryException("Exception for Doc Exist query");
} catch (IOException e) {
logger.warn("Failed to verify the index existence ", e);
| // Path: elasticservice/src/main/java/elasticsearch/exception/ElasticAPIException.java
// public class ElasticAPIException extends RuntimeException {
// public ElasticAPIException(String message) {
// super(message);
// }
//
// public ElasticAPIException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: elasticservice/src/main/java/elasticsearch/exception/ElasticQueryException.java
// public class ElasticQueryException extends RuntimeException {
// public ElasticQueryException(String message) {
// super(message);
// }
//
// public ElasticQueryException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: elasticservice/src/main/java/elasticsearch/exception/ElasticVersionConflictException.java
// public class ElasticVersionConflictException extends RuntimeException {
// public ElasticVersionConflictException(String message) {
// super(message);
// }
//
// public ElasticVersionConflictException(String message, Throwable cause) {
// super(message, cause);
// }
// }
// Path: elasticservice/src/main/java/elasticsearch/esapi/DocumentService.java
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import elasticsearch.esapi.resp.*;
import elasticsearch.exception.ElasticAPIException;
import elasticsearch.exception.ElasticQueryException;
import elasticsearch.exception.ElasticVersionConflictException;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.Charsets;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.entity.StringEntity;
import org.apache.log4j.Logger;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.ResponseException;
import org.elasticsearch.client.RestClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
package elasticsearch.esapi;
/**
* Created by I311352 on 10/3/2016.
*/
@Component
public class DocumentService {
private static final Logger logger = Logger.getLogger(DocumentService.class);
private final RestClient client;
private final Gson gson;
private final IndexService indexService;
@Autowired
public DocumentService(RestClient client, Gson gson, IndexService indexService) {
this.client = client;
this.gson = gson;
this.indexService = indexService;
}
public boolean isDocExist(String index, String type, Long sourceId, HashMap param) {
Map<String, String> params = addTenantId2Param(param);
try {
Response response = client.performRequest("HEAD", index + "/" + type + "/" + sourceId, params);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
return true;
} else if (statusCode == 404) {
return false;
}
throw new ElasticQueryException("Exception for Doc Exist query");
} catch (IOException e) {
logger.warn("Failed to verify the index existence ", e);
| throw new ElasticAPIException("Call indexExist HEAD exception:"+e.getMessage());
|
compasses/elastic-rabbitmq | elasticservice/src/main/java/elasticsearch/esapi/DocumentService.java | // Path: elasticservice/src/main/java/elasticsearch/exception/ElasticAPIException.java
// public class ElasticAPIException extends RuntimeException {
// public ElasticAPIException(String message) {
// super(message);
// }
//
// public ElasticAPIException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: elasticservice/src/main/java/elasticsearch/exception/ElasticQueryException.java
// public class ElasticQueryException extends RuntimeException {
// public ElasticQueryException(String message) {
// super(message);
// }
//
// public ElasticQueryException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: elasticservice/src/main/java/elasticsearch/exception/ElasticVersionConflictException.java
// public class ElasticVersionConflictException extends RuntimeException {
// public ElasticVersionConflictException(String message) {
// super(message);
// }
//
// public ElasticVersionConflictException(String message, Throwable cause) {
// super(message, cause);
// }
// }
| import com.google.gson.Gson;
import com.google.gson.JsonObject;
import elasticsearch.esapi.resp.*;
import elasticsearch.exception.ElasticAPIException;
import elasticsearch.exception.ElasticQueryException;
import elasticsearch.exception.ElasticVersionConflictException;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.Charsets;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.entity.StringEntity;
import org.apache.log4j.Logger;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.ResponseException;
import org.elasticsearch.client.RestClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
| return null;
}
public ESSaveResponse update(String index, String type, Long sourceId, Map<String, String> params, HttpEntity requestBody) {
params = addTenantId2Param(params);
// for real-time fetch
//params.put("refresh", "true");
try {
Response response = client.performRequest(
"POST",
index + "/" + type + "/" + sourceId + "/_update",
params,
requestBody);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode > 299) {
logger.warn("Problem while indexing a document: {}" +
response.getStatusLine().getReasonPhrase());
throw new ElasticAPIException("Could not index a document, status code is " + statusCode);
}
ESSaveResponse esResponse = gson.fromJson(IOUtils.toString(response.getEntity().getContent()),
ESSaveResponse.class);
return esResponse;
} catch (ResponseException rex) {
logger.warn("Got elasticsearch exception " + rex);
Response res = rex.getResponse();
if (res.getStatusLine().getStatusCode() == 409) {
logger.warn("Conflict on store object");
| // Path: elasticservice/src/main/java/elasticsearch/exception/ElasticAPIException.java
// public class ElasticAPIException extends RuntimeException {
// public ElasticAPIException(String message) {
// super(message);
// }
//
// public ElasticAPIException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: elasticservice/src/main/java/elasticsearch/exception/ElasticQueryException.java
// public class ElasticQueryException extends RuntimeException {
// public ElasticQueryException(String message) {
// super(message);
// }
//
// public ElasticQueryException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: elasticservice/src/main/java/elasticsearch/exception/ElasticVersionConflictException.java
// public class ElasticVersionConflictException extends RuntimeException {
// public ElasticVersionConflictException(String message) {
// super(message);
// }
//
// public ElasticVersionConflictException(String message, Throwable cause) {
// super(message, cause);
// }
// }
// Path: elasticservice/src/main/java/elasticsearch/esapi/DocumentService.java
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import elasticsearch.esapi.resp.*;
import elasticsearch.exception.ElasticAPIException;
import elasticsearch.exception.ElasticQueryException;
import elasticsearch.exception.ElasticVersionConflictException;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.Charsets;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.entity.StringEntity;
import org.apache.log4j.Logger;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.ResponseException;
import org.elasticsearch.client.RestClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
return null;
}
public ESSaveResponse update(String index, String type, Long sourceId, Map<String, String> params, HttpEntity requestBody) {
params = addTenantId2Param(params);
// for real-time fetch
//params.put("refresh", "true");
try {
Response response = client.performRequest(
"POST",
index + "/" + type + "/" + sourceId + "/_update",
params,
requestBody);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode > 299) {
logger.warn("Problem while indexing a document: {}" +
response.getStatusLine().getReasonPhrase());
throw new ElasticAPIException("Could not index a document, status code is " + statusCode);
}
ESSaveResponse esResponse = gson.fromJson(IOUtils.toString(response.getEntity().getContent()),
ESSaveResponse.class);
return esResponse;
} catch (ResponseException rex) {
logger.warn("Got elasticsearch exception " + rex);
Response res = rex.getResponse();
if (res.getStatusLine().getStatusCode() == 409) {
logger.warn("Conflict on store object");
| throw new ElasticVersionConflictException("type:" + type + " params:" + params.toString()
|
compasses/elastic-rabbitmq | elasticservice/src/main/java/elasticsearch/exportimport/LoadData.java | // Path: elasticservice/src/main/java/elasticsearch/ElasticRestClient.java
// @Component
// public class ElasticRestClient extends AbstractFactoryBean<RestClient> {
// private static Logger logger = Logger.getLogger(ElasticRestClient.class);
// private ClusterFailureListener clusterFailureListener;
// private volatile RestClient restClient;
// private static List<String> hosts = new ArrayList<>();
// private Sniffer sniffer;
//
// static {
// hosts.add("10.128.161.107:9200");
// }
//
// @Override
// public Class<?> getObjectType() {
// return RestClient.class;
// }
//
//
// @Override
// public RestClient createInstance() throws Exception {
// if (this.restClient != null) {
// return this.restClient;
// }
//
// HttpHost[] addresses = new HttpHost[hosts.size()];
// for (int i = 0; i < hosts.size(); i++) {
// addresses[i] = HttpHost.create(hosts.get(i));
// }
//
// this.restClient = RestClient
// .builder(addresses)
// .setMaxRetryTimeoutMillis(ESConstants.RESTCLIENT_TIMEOUT)
// .build();
//
// // this.sniffer = Sniffer.builder(this.restClient)
// // .setSniffIntervalMillis(60000).build();
//
// return this.restClient;
// }
//
// @Override
// protected void destroyInstance(RestClient instance) throws Exception {
// try {
// logger.info("Closing sniffer");
// instance.close();
// this.sniffer.close();
// } catch (IOException e) {
// logger.warn("Error during close sniffer", e);
// }
// }
//
// public void setHosts(List<String> hosts) {
// this.hosts = hosts;
// }
// }
//
// Path: elasticservice/src/main/java/elasticsearch/constant/ESConstants.java
// public class ESConstants {
// public static final String STORE_INDEX = "stores";
// public static final String PRODUCT_TYPE = "product";
// public static final String SKU_TYPE = "sku";
// public static final String PRODUCT_PROPERTY = "productproperty";
// public static final String CHANNEL_TYPE = "channels";
// public static final int SNIFFER_INTERVAL = 15000;
// public static final int RESTCLIENT_TIMEOUT = 20000; // 20s
//
//
// public static final Pattern ROUTINGKEY_PATTERN = Pattern.compile("([\\w\\.]+)\\.(\\w+)\\.(\\d+)");
//
// }
| import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import elasticsearch.ElasticRestClient;
import elasticsearch.constant.ESConstants;
import elasticsearch.esapi.resp.*;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.entity.StringEntity;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.Executor;
| package elasticsearch.exportimport;
/**
* Created by I311352 on 11/26/2016.
*/
@Service
public class LoadData {
private static final Logger logger = LoggerFactory.getLogger(LoadData.class);
private RestClient client = null;//new ElasticRestClient().createInstance();
private final Gson gson = new Gson();
//bulk operation
private final Integer STEP_SIZE = 500;
// aggregate fields
public void saveData(String fileName, Long tenantId, String s3buket, String EShosts) throws Exception {
| // Path: elasticservice/src/main/java/elasticsearch/ElasticRestClient.java
// @Component
// public class ElasticRestClient extends AbstractFactoryBean<RestClient> {
// private static Logger logger = Logger.getLogger(ElasticRestClient.class);
// private ClusterFailureListener clusterFailureListener;
// private volatile RestClient restClient;
// private static List<String> hosts = new ArrayList<>();
// private Sniffer sniffer;
//
// static {
// hosts.add("10.128.161.107:9200");
// }
//
// @Override
// public Class<?> getObjectType() {
// return RestClient.class;
// }
//
//
// @Override
// public RestClient createInstance() throws Exception {
// if (this.restClient != null) {
// return this.restClient;
// }
//
// HttpHost[] addresses = new HttpHost[hosts.size()];
// for (int i = 0; i < hosts.size(); i++) {
// addresses[i] = HttpHost.create(hosts.get(i));
// }
//
// this.restClient = RestClient
// .builder(addresses)
// .setMaxRetryTimeoutMillis(ESConstants.RESTCLIENT_TIMEOUT)
// .build();
//
// // this.sniffer = Sniffer.builder(this.restClient)
// // .setSniffIntervalMillis(60000).build();
//
// return this.restClient;
// }
//
// @Override
// protected void destroyInstance(RestClient instance) throws Exception {
// try {
// logger.info("Closing sniffer");
// instance.close();
// this.sniffer.close();
// } catch (IOException e) {
// logger.warn("Error during close sniffer", e);
// }
// }
//
// public void setHosts(List<String> hosts) {
// this.hosts = hosts;
// }
// }
//
// Path: elasticservice/src/main/java/elasticsearch/constant/ESConstants.java
// public class ESConstants {
// public static final String STORE_INDEX = "stores";
// public static final String PRODUCT_TYPE = "product";
// public static final String SKU_TYPE = "sku";
// public static final String PRODUCT_PROPERTY = "productproperty";
// public static final String CHANNEL_TYPE = "channels";
// public static final int SNIFFER_INTERVAL = 15000;
// public static final int RESTCLIENT_TIMEOUT = 20000; // 20s
//
//
// public static final Pattern ROUTINGKEY_PATTERN = Pattern.compile("([\\w\\.]+)\\.(\\w+)\\.(\\d+)");
//
// }
// Path: elasticservice/src/main/java/elasticsearch/exportimport/LoadData.java
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import elasticsearch.ElasticRestClient;
import elasticsearch.constant.ESConstants;
import elasticsearch.esapi.resp.*;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.entity.StringEntity;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.Executor;
package elasticsearch.exportimport;
/**
* Created by I311352 on 11/26/2016.
*/
@Service
public class LoadData {
private static final Logger logger = LoggerFactory.getLogger(LoadData.class);
private RestClient client = null;//new ElasticRestClient().createInstance();
private final Gson gson = new Gson();
//bulk operation
private final Integer STEP_SIZE = 500;
// aggregate fields
public void saveData(String fileName, Long tenantId, String s3buket, String EShosts) throws Exception {
| ElasticRestClient sclient = new ElasticRestClient();
|
compasses/elastic-rabbitmq | elasticservice/src/main/java/elasticsearch/exportimport/LoadData.java | // Path: elasticservice/src/main/java/elasticsearch/ElasticRestClient.java
// @Component
// public class ElasticRestClient extends AbstractFactoryBean<RestClient> {
// private static Logger logger = Logger.getLogger(ElasticRestClient.class);
// private ClusterFailureListener clusterFailureListener;
// private volatile RestClient restClient;
// private static List<String> hosts = new ArrayList<>();
// private Sniffer sniffer;
//
// static {
// hosts.add("10.128.161.107:9200");
// }
//
// @Override
// public Class<?> getObjectType() {
// return RestClient.class;
// }
//
//
// @Override
// public RestClient createInstance() throws Exception {
// if (this.restClient != null) {
// return this.restClient;
// }
//
// HttpHost[] addresses = new HttpHost[hosts.size()];
// for (int i = 0; i < hosts.size(); i++) {
// addresses[i] = HttpHost.create(hosts.get(i));
// }
//
// this.restClient = RestClient
// .builder(addresses)
// .setMaxRetryTimeoutMillis(ESConstants.RESTCLIENT_TIMEOUT)
// .build();
//
// // this.sniffer = Sniffer.builder(this.restClient)
// // .setSniffIntervalMillis(60000).build();
//
// return this.restClient;
// }
//
// @Override
// protected void destroyInstance(RestClient instance) throws Exception {
// try {
// logger.info("Closing sniffer");
// instance.close();
// this.sniffer.close();
// } catch (IOException e) {
// logger.warn("Error during close sniffer", e);
// }
// }
//
// public void setHosts(List<String> hosts) {
// this.hosts = hosts;
// }
// }
//
// Path: elasticservice/src/main/java/elasticsearch/constant/ESConstants.java
// public class ESConstants {
// public static final String STORE_INDEX = "stores";
// public static final String PRODUCT_TYPE = "product";
// public static final String SKU_TYPE = "sku";
// public static final String PRODUCT_PROPERTY = "productproperty";
// public static final String CHANNEL_TYPE = "channels";
// public static final int SNIFFER_INTERVAL = 15000;
// public static final int RESTCLIENT_TIMEOUT = 20000; // 20s
//
//
// public static final Pattern ROUTINGKEY_PATTERN = Pattern.compile("([\\w\\.]+)\\.(\\w+)\\.(\\d+)");
//
// }
| import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import elasticsearch.ElasticRestClient;
import elasticsearch.constant.ESConstants;
import elasticsearch.esapi.resp.*;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.entity.StringEntity;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.Executor;
| public void postCheckUpdate(Long size) {
if (size <= 0) {
return;
}
// post check should be ok, during upgrade should be less 10000 new created product.
if (size >= 10000) {
size = 9999L;
}
logger.info("Post check update result");
String body = "{ \"query\": {\"bool\" : { \"must_not\" : {\"term\" : { \"upgradeTag\" : 1612} }} }}";
HashMap<String, String> param = new HashMap<>();
param.put("size", size.toString());
ESQueryResponse res = searchAll(param, body);
if (res.getHit().getTotal() > 0) {
logger.warn("Some product miss update, recover it totalCount=" + res.getHit().getTotal());
// do it again
doUpdate(res);
}
logger.info("Upgrade to 1612 end.");
}
public void flush() {
try {
client.performRequest(
"POST",
| // Path: elasticservice/src/main/java/elasticsearch/ElasticRestClient.java
// @Component
// public class ElasticRestClient extends AbstractFactoryBean<RestClient> {
// private static Logger logger = Logger.getLogger(ElasticRestClient.class);
// private ClusterFailureListener clusterFailureListener;
// private volatile RestClient restClient;
// private static List<String> hosts = new ArrayList<>();
// private Sniffer sniffer;
//
// static {
// hosts.add("10.128.161.107:9200");
// }
//
// @Override
// public Class<?> getObjectType() {
// return RestClient.class;
// }
//
//
// @Override
// public RestClient createInstance() throws Exception {
// if (this.restClient != null) {
// return this.restClient;
// }
//
// HttpHost[] addresses = new HttpHost[hosts.size()];
// for (int i = 0; i < hosts.size(); i++) {
// addresses[i] = HttpHost.create(hosts.get(i));
// }
//
// this.restClient = RestClient
// .builder(addresses)
// .setMaxRetryTimeoutMillis(ESConstants.RESTCLIENT_TIMEOUT)
// .build();
//
// // this.sniffer = Sniffer.builder(this.restClient)
// // .setSniffIntervalMillis(60000).build();
//
// return this.restClient;
// }
//
// @Override
// protected void destroyInstance(RestClient instance) throws Exception {
// try {
// logger.info("Closing sniffer");
// instance.close();
// this.sniffer.close();
// } catch (IOException e) {
// logger.warn("Error during close sniffer", e);
// }
// }
//
// public void setHosts(List<String> hosts) {
// this.hosts = hosts;
// }
// }
//
// Path: elasticservice/src/main/java/elasticsearch/constant/ESConstants.java
// public class ESConstants {
// public static final String STORE_INDEX = "stores";
// public static final String PRODUCT_TYPE = "product";
// public static final String SKU_TYPE = "sku";
// public static final String PRODUCT_PROPERTY = "productproperty";
// public static final String CHANNEL_TYPE = "channels";
// public static final int SNIFFER_INTERVAL = 15000;
// public static final int RESTCLIENT_TIMEOUT = 20000; // 20s
//
//
// public static final Pattern ROUTINGKEY_PATTERN = Pattern.compile("([\\w\\.]+)\\.(\\w+)\\.(\\d+)");
//
// }
// Path: elasticservice/src/main/java/elasticsearch/exportimport/LoadData.java
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import elasticsearch.ElasticRestClient;
import elasticsearch.constant.ESConstants;
import elasticsearch.esapi.resp.*;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.entity.StringEntity;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.Executor;
public void postCheckUpdate(Long size) {
if (size <= 0) {
return;
}
// post check should be ok, during upgrade should be less 10000 new created product.
if (size >= 10000) {
size = 9999L;
}
logger.info("Post check update result");
String body = "{ \"query\": {\"bool\" : { \"must_not\" : {\"term\" : { \"upgradeTag\" : 1612} }} }}";
HashMap<String, String> param = new HashMap<>();
param.put("size", size.toString());
ESQueryResponse res = searchAll(param, body);
if (res.getHit().getTotal() > 0) {
logger.warn("Some product miss update, recover it totalCount=" + res.getHit().getTotal());
// do it again
doUpdate(res);
}
logger.info("Upgrade to 1612 end.");
}
public void flush() {
try {
client.performRequest(
"POST",
| ESConstants.STORE_INDEX + "/_flush?wait_if_ongoing=true");
|
compasses/elastic-rabbitmq | rabbitmqservice/src/main/java/sync/handler/impl/ESSKUSyncHandler.java | // Path: elasticservice/src/main/java/elasticsearch/constant/ESConstants.java
// public class ESConstants {
// public static final String STORE_INDEX = "stores";
// public static final String PRODUCT_TYPE = "product";
// public static final String SKU_TYPE = "sku";
// public static final String PRODUCT_PROPERTY = "productproperty";
// public static final String CHANNEL_TYPE = "channels";
// public static final int SNIFFER_INTERVAL = 15000;
// public static final int RESTCLIENT_TIMEOUT = 20000; // 20s
//
//
// public static final Pattern ROUTINGKEY_PATTERN = Pattern.compile("([\\w\\.]+)\\.(\\w+)\\.(\\d+)");
//
// }
//
// Path: elasticservice/src/main/java/elasticsearch/esapi/resp/ESGetByIdResponse.java
// public class ESGetByIdResponse extends ESBaseResponse {
// private Boolean found;
// @SerializedName("_source")
// private JsonObject object;
//
// public Boolean getFound() {
// return found;
// }
//
// public void setFound(Boolean found) {
// this.found = found;
// }
//
// public JsonObject getObject() {
// return object;
// }
//
// public void setObject(JsonObject object) {
// this.object = object;
// }
//
// @Override
// public String toString() {
// return super.toString() + "ESGetByIdResponse{" +
// "found=" + found +
// ", object=" + object +
// '}';
// }
// }
//
// Path: rabbitmqservice/src/main/java/sync/common/ESHandleMessage.java
// public class ESHandleMessage {
// private Long tenantId;
// private String type;
// private OperateAction action;
// private byte[] msgBody;
// private JsonElement jsonElement;
//
// private boolean needSendEvent = true;
// private boolean isEventGenerated = false;
//
// private List<Long> productIds = null;
// private Long channelId = null;
//
// public ESHandleMessage() {
// }
//
// public ESHandleMessage(Long tenantId, String indexType, String action, byte[] msgBody) {
// this.tenantId = tenantId;
// this.type = indexType;
// this.action = OperateAction.valueOf(action);
// this.msgBody = msgBody;
// }
//
// public Long getTenantId() {
// return tenantId;
// }
//
// public void setTenantId(Long tenantId) {
// this.tenantId = tenantId;
// }
//
// public String getType() {
// return type;
// }
//
// public void setType(String type) {
// this.type = type;
// }
//
// public OperateAction getAction() {
// return action;
// }
//
// public void setAction(OperateAction action) {
// this.action = action;
// }
//
// public byte[] getMsgBody() {
// return msgBody;
// }
//
// public void setMsgBody(byte[] msgBody) {
// this.msgBody = msgBody;
// }
//
// public List<Long> getProductIds() {
// return productIds;
// }
//
// public void setProductIds(List<Long> productIds) {
// this.productIds = productIds;
// }
//
// public boolean isNeedSendEvent() {
// return needSendEvent;
// }
//
// public boolean isProductIdsEmpty() {
// return CollectionUtils.isEmpty(this.productIds);
// }
//
// public void setNeedSendEvent(boolean needSendEvent) {
// this.needSendEvent = needSendEvent;
// }
//
// public JsonElement getJsonElement() {
// return jsonElement;
// }
//
// public void setJsonElement(JsonElement jsonElement) {
// this.jsonElement = jsonElement;
// }
//
// public Long getChannelId() {
// return channelId;
// }
//
// public void setChannelId(Long channelId) {
// this.channelId = channelId;
// }
//
// public boolean isEventGenerated() {
// return isEventGenerated;
// }
//
// public void setEventGenerated(boolean eventGenerated) {
// isEventGenerated = eventGenerated;
// }
//
// @Override
// public String toString() {
// return "ESHandleMessage{" +
// "tenantId=" + tenantId +
// ", type='" + type + '\'' +
// ", searchcommand=" + action +
// ", needSendEvent=" + needSendEvent +
// ", isEventGenerated=" + isEventGenerated +
// ", productIds=" + productIds +
// ", channelId=" + channelId +
// '}';
// }
// }
//
// Path: rabbitmqservice/src/main/java/sync/common/OperateAction.java
// public enum OperateAction {
// CREATE,
// UPDATE,
// DELETE,
// ASSOCIATE,
// DISASSOCIATE,
// LIST,
// UNLIST
// }
| import com.google.gson.JsonObject;
import elasticsearch.constant.ESConstants;
import elasticsearch.esapi.resp.ESGetByIdResponse;
import sync.common.ESHandleMessage;
import sync.common.OperateAction;
import java.util.ArrayList;
import java.util.HashMap;
| package sync.handler.impl;
/**
* Created by I311352 on 10/17/2016.
*/
public class ESSKUSyncHandler extends ESAbstractHandler{
@Override
| // Path: elasticservice/src/main/java/elasticsearch/constant/ESConstants.java
// public class ESConstants {
// public static final String STORE_INDEX = "stores";
// public static final String PRODUCT_TYPE = "product";
// public static final String SKU_TYPE = "sku";
// public static final String PRODUCT_PROPERTY = "productproperty";
// public static final String CHANNEL_TYPE = "channels";
// public static final int SNIFFER_INTERVAL = 15000;
// public static final int RESTCLIENT_TIMEOUT = 20000; // 20s
//
//
// public static final Pattern ROUTINGKEY_PATTERN = Pattern.compile("([\\w\\.]+)\\.(\\w+)\\.(\\d+)");
//
// }
//
// Path: elasticservice/src/main/java/elasticsearch/esapi/resp/ESGetByIdResponse.java
// public class ESGetByIdResponse extends ESBaseResponse {
// private Boolean found;
// @SerializedName("_source")
// private JsonObject object;
//
// public Boolean getFound() {
// return found;
// }
//
// public void setFound(Boolean found) {
// this.found = found;
// }
//
// public JsonObject getObject() {
// return object;
// }
//
// public void setObject(JsonObject object) {
// this.object = object;
// }
//
// @Override
// public String toString() {
// return super.toString() + "ESGetByIdResponse{" +
// "found=" + found +
// ", object=" + object +
// '}';
// }
// }
//
// Path: rabbitmqservice/src/main/java/sync/common/ESHandleMessage.java
// public class ESHandleMessage {
// private Long tenantId;
// private String type;
// private OperateAction action;
// private byte[] msgBody;
// private JsonElement jsonElement;
//
// private boolean needSendEvent = true;
// private boolean isEventGenerated = false;
//
// private List<Long> productIds = null;
// private Long channelId = null;
//
// public ESHandleMessage() {
// }
//
// public ESHandleMessage(Long tenantId, String indexType, String action, byte[] msgBody) {
// this.tenantId = tenantId;
// this.type = indexType;
// this.action = OperateAction.valueOf(action);
// this.msgBody = msgBody;
// }
//
// public Long getTenantId() {
// return tenantId;
// }
//
// public void setTenantId(Long tenantId) {
// this.tenantId = tenantId;
// }
//
// public String getType() {
// return type;
// }
//
// public void setType(String type) {
// this.type = type;
// }
//
// public OperateAction getAction() {
// return action;
// }
//
// public void setAction(OperateAction action) {
// this.action = action;
// }
//
// public byte[] getMsgBody() {
// return msgBody;
// }
//
// public void setMsgBody(byte[] msgBody) {
// this.msgBody = msgBody;
// }
//
// public List<Long> getProductIds() {
// return productIds;
// }
//
// public void setProductIds(List<Long> productIds) {
// this.productIds = productIds;
// }
//
// public boolean isNeedSendEvent() {
// return needSendEvent;
// }
//
// public boolean isProductIdsEmpty() {
// return CollectionUtils.isEmpty(this.productIds);
// }
//
// public void setNeedSendEvent(boolean needSendEvent) {
// this.needSendEvent = needSendEvent;
// }
//
// public JsonElement getJsonElement() {
// return jsonElement;
// }
//
// public void setJsonElement(JsonElement jsonElement) {
// this.jsonElement = jsonElement;
// }
//
// public Long getChannelId() {
// return channelId;
// }
//
// public void setChannelId(Long channelId) {
// this.channelId = channelId;
// }
//
// public boolean isEventGenerated() {
// return isEventGenerated;
// }
//
// public void setEventGenerated(boolean eventGenerated) {
// isEventGenerated = eventGenerated;
// }
//
// @Override
// public String toString() {
// return "ESHandleMessage{" +
// "tenantId=" + tenantId +
// ", type='" + type + '\'' +
// ", searchcommand=" + action +
// ", needSendEvent=" + needSendEvent +
// ", isEventGenerated=" + isEventGenerated +
// ", productIds=" + productIds +
// ", channelId=" + channelId +
// '}';
// }
// }
//
// Path: rabbitmqservice/src/main/java/sync/common/OperateAction.java
// public enum OperateAction {
// CREATE,
// UPDATE,
// DELETE,
// ASSOCIATE,
// DISASSOCIATE,
// LIST,
// UNLIST
// }
// Path: rabbitmqservice/src/main/java/sync/handler/impl/ESSKUSyncHandler.java
import com.google.gson.JsonObject;
import elasticsearch.constant.ESConstants;
import elasticsearch.esapi.resp.ESGetByIdResponse;
import sync.common.ESHandleMessage;
import sync.common.OperateAction;
import java.util.ArrayList;
import java.util.HashMap;
package sync.handler.impl;
/**
* Created by I311352 on 10/17/2016.
*/
public class ESSKUSyncHandler extends ESAbstractHandler{
@Override
| public boolean handleCreate(ESHandleMessage message) {
|
compasses/elastic-rabbitmq | elasticservice/src/main/java/elasticsearch/searchservice/dsl/DLSGenerateServiceImpl.java | // Path: elasticservice/src/main/java/elasticsearch/searchservice/models/Meta.java
// public class Meta {
// private String key;
// private List<String> value;
// private String operator;
//
// public Meta() {}
// public Meta(String key, List<String> value, String operator) {
// this.key = key;
// this.value = value;
// this.operator = operator;
// }
//
// public String getKey() {
// return key;
// }
//
// public void setKey(String key) {
// this.key = key;
// }
//
// public List<String> getValue() {
// return value;
// }
//
// public void setValue(List<String> value) {
// this.value = value;
// }
//
// public String getOperator() {
// return operator;
// }
//
// public void setOperator(String operator) {
// this.operator = operator;
// }
// }
//
// Path: elasticservice/src/main/java/elasticsearch/searchservice/models/QueryParam.java
// public class QueryParam {
// private List<Meta> filter;
// private Collection collection;
// private String orderByField;
// private String orderByOrder;
// private Long channelId;
// private Integer pageSize;
// private Integer offSet;
// private Boolean isCount = Boolean.FALSE;
//
// public List<Meta> getFilter() {
// return filter;
// }
//
// public void setFilter(List<Meta> filter) {
// this.filter = filter;
// }
//
// public Collection getCollection() {
// return collection;
// }
//
// public void setCollection(Collection collection) {
// this.collection = collection;
// }
//
// public String getOrderByField() {
// return orderByField;
// }
//
// public void setOrderByField(String orderByField) {
// this.orderByField = orderByField;
// }
//
// public String getOrderByOrder() {
// return orderByOrder;
// }
//
// public void setOrderByOrder(String orderByOrder) {
// this.orderByOrder = orderByOrder;
// }
//
// public Integer getPageSize() {
// return pageSize;
// }
//
// public void setPageSize(Integer pageSize) {
// this.pageSize = pageSize;
// }
//
// public Integer getOffSet() {
// return offSet;
// }
//
// public void setOffSet(Integer offSet) {
// this.offSet = offSet;
// }
//
// public Long getChannelId() {
// return channelId;
// }
//
// public void setChannelId(Long channelId) {
// this.channelId = channelId;
// }
//
// public Boolean getCount() {
// return isCount;
// }
//
// public void setCount(Boolean count) {
// isCount = count;
// }
// }
| import com.mitchellbosecke.pebble.PebbleEngine;
import com.mitchellbosecke.pebble.error.PebbleException;
import com.mitchellbosecke.pebble.template.PebbleTemplate;
import elasticsearch.searchservice.models.Meta;
import elasticsearch.searchservice.models.QueryParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.*;
| package elasticsearch.searchservice.dsl;
/**
* Created by i311352 on 5/3/2017.
*/
@Service
public class DLSGenerateServiceImpl implements DSLGenerateService {
private static final Logger logger = LoggerFactory.getLogger(DLSGenerateServiceImpl.class);
private static String SYSFIELD = "systemField";
private static String UDFFIELD = "customField";
private static String VARIANT = "sku.variantList.variantValueId";
private static String FULLSEARCH = "keywords";
private static String PRICEFIELD = "channels.prices.price";
private static String CATEGORY = "category.order";
private static String ATTRIBUTES = "attributes";
private final PebbleEngine engine = new PebbleEngine.Builder().build();
@Override
| // Path: elasticservice/src/main/java/elasticsearch/searchservice/models/Meta.java
// public class Meta {
// private String key;
// private List<String> value;
// private String operator;
//
// public Meta() {}
// public Meta(String key, List<String> value, String operator) {
// this.key = key;
// this.value = value;
// this.operator = operator;
// }
//
// public String getKey() {
// return key;
// }
//
// public void setKey(String key) {
// this.key = key;
// }
//
// public List<String> getValue() {
// return value;
// }
//
// public void setValue(List<String> value) {
// this.value = value;
// }
//
// public String getOperator() {
// return operator;
// }
//
// public void setOperator(String operator) {
// this.operator = operator;
// }
// }
//
// Path: elasticservice/src/main/java/elasticsearch/searchservice/models/QueryParam.java
// public class QueryParam {
// private List<Meta> filter;
// private Collection collection;
// private String orderByField;
// private String orderByOrder;
// private Long channelId;
// private Integer pageSize;
// private Integer offSet;
// private Boolean isCount = Boolean.FALSE;
//
// public List<Meta> getFilter() {
// return filter;
// }
//
// public void setFilter(List<Meta> filter) {
// this.filter = filter;
// }
//
// public Collection getCollection() {
// return collection;
// }
//
// public void setCollection(Collection collection) {
// this.collection = collection;
// }
//
// public String getOrderByField() {
// return orderByField;
// }
//
// public void setOrderByField(String orderByField) {
// this.orderByField = orderByField;
// }
//
// public String getOrderByOrder() {
// return orderByOrder;
// }
//
// public void setOrderByOrder(String orderByOrder) {
// this.orderByOrder = orderByOrder;
// }
//
// public Integer getPageSize() {
// return pageSize;
// }
//
// public void setPageSize(Integer pageSize) {
// this.pageSize = pageSize;
// }
//
// public Integer getOffSet() {
// return offSet;
// }
//
// public void setOffSet(Integer offSet) {
// this.offSet = offSet;
// }
//
// public Long getChannelId() {
// return channelId;
// }
//
// public void setChannelId(Long channelId) {
// this.channelId = channelId;
// }
//
// public Boolean getCount() {
// return isCount;
// }
//
// public void setCount(Boolean count) {
// isCount = count;
// }
// }
// Path: elasticservice/src/main/java/elasticsearch/searchservice/dsl/DLSGenerateServiceImpl.java
import com.mitchellbosecke.pebble.PebbleEngine;
import com.mitchellbosecke.pebble.error.PebbleException;
import com.mitchellbosecke.pebble.template.PebbleTemplate;
import elasticsearch.searchservice.models.Meta;
import elasticsearch.searchservice.models.QueryParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.*;
package elasticsearch.searchservice.dsl;
/**
* Created by i311352 on 5/3/2017.
*/
@Service
public class DLSGenerateServiceImpl implements DSLGenerateService {
private static final Logger logger = LoggerFactory.getLogger(DLSGenerateServiceImpl.class);
private static String SYSFIELD = "systemField";
private static String UDFFIELD = "customField";
private static String VARIANT = "sku.variantList.variantValueId";
private static String FULLSEARCH = "keywords";
private static String PRICEFIELD = "channels.prices.price";
private static String CATEGORY = "category.order";
private static String ATTRIBUTES = "attributes";
private final PebbleEngine engine = new PebbleEngine.Builder().build();
@Override
| public String fromQueryParam(QueryParam param) {
|
compasses/elastic-rabbitmq | elasticservice/src/main/java/elasticsearch/searchservice/dsl/DLSGenerateServiceImpl.java | // Path: elasticservice/src/main/java/elasticsearch/searchservice/models/Meta.java
// public class Meta {
// private String key;
// private List<String> value;
// private String operator;
//
// public Meta() {}
// public Meta(String key, List<String> value, String operator) {
// this.key = key;
// this.value = value;
// this.operator = operator;
// }
//
// public String getKey() {
// return key;
// }
//
// public void setKey(String key) {
// this.key = key;
// }
//
// public List<String> getValue() {
// return value;
// }
//
// public void setValue(List<String> value) {
// this.value = value;
// }
//
// public String getOperator() {
// return operator;
// }
//
// public void setOperator(String operator) {
// this.operator = operator;
// }
// }
//
// Path: elasticservice/src/main/java/elasticsearch/searchservice/models/QueryParam.java
// public class QueryParam {
// private List<Meta> filter;
// private Collection collection;
// private String orderByField;
// private String orderByOrder;
// private Long channelId;
// private Integer pageSize;
// private Integer offSet;
// private Boolean isCount = Boolean.FALSE;
//
// public List<Meta> getFilter() {
// return filter;
// }
//
// public void setFilter(List<Meta> filter) {
// this.filter = filter;
// }
//
// public Collection getCollection() {
// return collection;
// }
//
// public void setCollection(Collection collection) {
// this.collection = collection;
// }
//
// public String getOrderByField() {
// return orderByField;
// }
//
// public void setOrderByField(String orderByField) {
// this.orderByField = orderByField;
// }
//
// public String getOrderByOrder() {
// return orderByOrder;
// }
//
// public void setOrderByOrder(String orderByOrder) {
// this.orderByOrder = orderByOrder;
// }
//
// public Integer getPageSize() {
// return pageSize;
// }
//
// public void setPageSize(Integer pageSize) {
// this.pageSize = pageSize;
// }
//
// public Integer getOffSet() {
// return offSet;
// }
//
// public void setOffSet(Integer offSet) {
// this.offSet = offSet;
// }
//
// public Long getChannelId() {
// return channelId;
// }
//
// public void setChannelId(Long channelId) {
// this.channelId = channelId;
// }
//
// public Boolean getCount() {
// return isCount;
// }
//
// public void setCount(Boolean count) {
// isCount = count;
// }
// }
| import com.mitchellbosecke.pebble.PebbleEngine;
import com.mitchellbosecke.pebble.error.PebbleException;
import com.mitchellbosecke.pebble.template.PebbleTemplate;
import elasticsearch.searchservice.models.Meta;
import elasticsearch.searchservice.models.QueryParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.*;
| if (param.getCollection() != null && param.getCollection().getConditions().size() > 0) {
if (param.getCollection().getConditionType().equals("AND")) {
fillDSLQueryMeta(param.getCollection().getConditions(), filter);
} else {
// or condition
List<DSLMeta> orcondition = new ArrayList<>();
fillDSLQueryMeta(param.getCollection().getConditions(), orcondition);
if (orcondition.size() > 0) {
context.put("collectionForOr", orcondition);
}
}
}
context.put("filter", filter);
String orderFiled = param.getOrderByField();
if (orderFiled.startsWith("price_")) {
context.put("orderByField", PRICEFIELD);
} else {
// use arrival time to do it
context.put("orderByField", "updateTime");
}
context.put("orderByOrder", param.getOrderByOrder().toLowerCase());
context.put("channelId", param.getChannelId());
context.put("from", param.getOffSet().toString());
context.put("size", param.getPageSize().toString());
return context;
}
| // Path: elasticservice/src/main/java/elasticsearch/searchservice/models/Meta.java
// public class Meta {
// private String key;
// private List<String> value;
// private String operator;
//
// public Meta() {}
// public Meta(String key, List<String> value, String operator) {
// this.key = key;
// this.value = value;
// this.operator = operator;
// }
//
// public String getKey() {
// return key;
// }
//
// public void setKey(String key) {
// this.key = key;
// }
//
// public List<String> getValue() {
// return value;
// }
//
// public void setValue(List<String> value) {
// this.value = value;
// }
//
// public String getOperator() {
// return operator;
// }
//
// public void setOperator(String operator) {
// this.operator = operator;
// }
// }
//
// Path: elasticservice/src/main/java/elasticsearch/searchservice/models/QueryParam.java
// public class QueryParam {
// private List<Meta> filter;
// private Collection collection;
// private String orderByField;
// private String orderByOrder;
// private Long channelId;
// private Integer pageSize;
// private Integer offSet;
// private Boolean isCount = Boolean.FALSE;
//
// public List<Meta> getFilter() {
// return filter;
// }
//
// public void setFilter(List<Meta> filter) {
// this.filter = filter;
// }
//
// public Collection getCollection() {
// return collection;
// }
//
// public void setCollection(Collection collection) {
// this.collection = collection;
// }
//
// public String getOrderByField() {
// return orderByField;
// }
//
// public void setOrderByField(String orderByField) {
// this.orderByField = orderByField;
// }
//
// public String getOrderByOrder() {
// return orderByOrder;
// }
//
// public void setOrderByOrder(String orderByOrder) {
// this.orderByOrder = orderByOrder;
// }
//
// public Integer getPageSize() {
// return pageSize;
// }
//
// public void setPageSize(Integer pageSize) {
// this.pageSize = pageSize;
// }
//
// public Integer getOffSet() {
// return offSet;
// }
//
// public void setOffSet(Integer offSet) {
// this.offSet = offSet;
// }
//
// public Long getChannelId() {
// return channelId;
// }
//
// public void setChannelId(Long channelId) {
// this.channelId = channelId;
// }
//
// public Boolean getCount() {
// return isCount;
// }
//
// public void setCount(Boolean count) {
// isCount = count;
// }
// }
// Path: elasticservice/src/main/java/elasticsearch/searchservice/dsl/DLSGenerateServiceImpl.java
import com.mitchellbosecke.pebble.PebbleEngine;
import com.mitchellbosecke.pebble.error.PebbleException;
import com.mitchellbosecke.pebble.template.PebbleTemplate;
import elasticsearch.searchservice.models.Meta;
import elasticsearch.searchservice.models.QueryParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.*;
if (param.getCollection() != null && param.getCollection().getConditions().size() > 0) {
if (param.getCollection().getConditionType().equals("AND")) {
fillDSLQueryMeta(param.getCollection().getConditions(), filter);
} else {
// or condition
List<DSLMeta> orcondition = new ArrayList<>();
fillDSLQueryMeta(param.getCollection().getConditions(), orcondition);
if (orcondition.size() > 0) {
context.put("collectionForOr", orcondition);
}
}
}
context.put("filter", filter);
String orderFiled = param.getOrderByField();
if (orderFiled.startsWith("price_")) {
context.put("orderByField", PRICEFIELD);
} else {
// use arrival time to do it
context.put("orderByField", "updateTime");
}
context.put("orderByOrder", param.getOrderByOrder().toLowerCase());
context.put("channelId", param.getChannelId());
context.put("from", param.getOffSet().toString());
context.put("size", param.getPageSize().toString());
return context;
}
| private void fillDSLQueryMeta(List<Meta> metas, List<DSLMeta> dslMetas) {
|
compasses/elastic-rabbitmq | netty-http/src/main/java/http/DefaultServerInitializer.java | // Path: elasticservice/src/main/java/elasticsearch/ElasticRestClient.java
// @Component
// public class ElasticRestClient extends AbstractFactoryBean<RestClient> {
// private static Logger logger = Logger.getLogger(ElasticRestClient.class);
// private ClusterFailureListener clusterFailureListener;
// private volatile RestClient restClient;
// private static List<String> hosts = new ArrayList<>();
// private Sniffer sniffer;
//
// static {
// hosts.add("10.128.161.107:9200");
// }
//
// @Override
// public Class<?> getObjectType() {
// return RestClient.class;
// }
//
//
// @Override
// public RestClient createInstance() throws Exception {
// if (this.restClient != null) {
// return this.restClient;
// }
//
// HttpHost[] addresses = new HttpHost[hosts.size()];
// for (int i = 0; i < hosts.size(); i++) {
// addresses[i] = HttpHost.create(hosts.get(i));
// }
//
// this.restClient = RestClient
// .builder(addresses)
// .setMaxRetryTimeoutMillis(ESConstants.RESTCLIENT_TIMEOUT)
// .build();
//
// // this.sniffer = Sniffer.builder(this.restClient)
// // .setSniffIntervalMillis(60000).build();
//
// return this.restClient;
// }
//
// @Override
// protected void destroyInstance(RestClient instance) throws Exception {
// try {
// logger.info("Closing sniffer");
// instance.close();
// this.sniffer.close();
// } catch (IOException e) {
// logger.warn("Error during close sniffer", e);
// }
// }
//
// public void setHosts(List<String> hosts) {
// this.hosts = hosts;
// }
// }
//
// Path: netty-http/src/main/java/http/worker/SearchWorker.java
// public class SearchWorker extends ThreadPoolExecutor {
// private final static Logger logger = LoggerFactory.getLogger(SearchWorker.class);
// private static SearchWorker instance;
//
// public SearchWorker(int size, String name, BlockingQueue blockingQueue) {
// super(size, size+5, 0L, TimeUnit.MILLISECONDS, blockingQueue, new WorkerThread(name));
// }
//
// @Override
// protected void beforeExecute(Thread t, Runnable r) {
// logger.info("start to exectue: " + t);
// super.beforeExecute(t, r);
// }
//
// @Override
// protected void afterExecute(Runnable r, Throwable t) {
// super.afterExecute(r, t);
// logger.info("after to exectue: " + t);
// }
//
// public INotifyingFuture doSearch(SearchRequest request) {
// SearchingFuture future = new SearchingFuture(request);
// future.setExecutor(this);
// future.run();
// return future;
// }
//
// public String monitorInfo() {
// StringBuilder result = new StringBuilder(100);
// result.append("\r\n QueueSize :" + this.getQueue().size());
// result.append("ThreadCount :" + this.getPoolSize() + "\r\n");
// return result.toString();
// }
// }
| import elasticsearch.ElasticRestClient;
import http.worker.SearchWorker;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.util.concurrent.DefaultEventExecutorGroup;
import io.netty.util.concurrent.EventExecutorGroup;
import org.elasticsearch.client.RestClient;
import org.springframework.context.ConfigurableApplicationContext;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
| package http;
/**
* Created by i311352 on 2/13/2017.
*/
public class DefaultServerInitializer extends ChannelInitializer<SocketChannel> {
private final Config conf;
//private final EventExecutorGroup executor;
private final ExecutorService executor;
private final ConfigurableApplicationContext applicationContext;
public DefaultServerInitializer(Config conf, ConfigurableApplicationContext applicationContext) {
this.conf = conf;
this.applicationContext = applicationContext;
| // Path: elasticservice/src/main/java/elasticsearch/ElasticRestClient.java
// @Component
// public class ElasticRestClient extends AbstractFactoryBean<RestClient> {
// private static Logger logger = Logger.getLogger(ElasticRestClient.class);
// private ClusterFailureListener clusterFailureListener;
// private volatile RestClient restClient;
// private static List<String> hosts = new ArrayList<>();
// private Sniffer sniffer;
//
// static {
// hosts.add("10.128.161.107:9200");
// }
//
// @Override
// public Class<?> getObjectType() {
// return RestClient.class;
// }
//
//
// @Override
// public RestClient createInstance() throws Exception {
// if (this.restClient != null) {
// return this.restClient;
// }
//
// HttpHost[] addresses = new HttpHost[hosts.size()];
// for (int i = 0; i < hosts.size(); i++) {
// addresses[i] = HttpHost.create(hosts.get(i));
// }
//
// this.restClient = RestClient
// .builder(addresses)
// .setMaxRetryTimeoutMillis(ESConstants.RESTCLIENT_TIMEOUT)
// .build();
//
// // this.sniffer = Sniffer.builder(this.restClient)
// // .setSniffIntervalMillis(60000).build();
//
// return this.restClient;
// }
//
// @Override
// protected void destroyInstance(RestClient instance) throws Exception {
// try {
// logger.info("Closing sniffer");
// instance.close();
// this.sniffer.close();
// } catch (IOException e) {
// logger.warn("Error during close sniffer", e);
// }
// }
//
// public void setHosts(List<String> hosts) {
// this.hosts = hosts;
// }
// }
//
// Path: netty-http/src/main/java/http/worker/SearchWorker.java
// public class SearchWorker extends ThreadPoolExecutor {
// private final static Logger logger = LoggerFactory.getLogger(SearchWorker.class);
// private static SearchWorker instance;
//
// public SearchWorker(int size, String name, BlockingQueue blockingQueue) {
// super(size, size+5, 0L, TimeUnit.MILLISECONDS, blockingQueue, new WorkerThread(name));
// }
//
// @Override
// protected void beforeExecute(Thread t, Runnable r) {
// logger.info("start to exectue: " + t);
// super.beforeExecute(t, r);
// }
//
// @Override
// protected void afterExecute(Runnable r, Throwable t) {
// super.afterExecute(r, t);
// logger.info("after to exectue: " + t);
// }
//
// public INotifyingFuture doSearch(SearchRequest request) {
// SearchingFuture future = new SearchingFuture(request);
// future.setExecutor(this);
// future.run();
// return future;
// }
//
// public String monitorInfo() {
// StringBuilder result = new StringBuilder(100);
// result.append("\r\n QueueSize :" + this.getQueue().size());
// result.append("ThreadCount :" + this.getPoolSize() + "\r\n");
// return result.toString();
// }
// }
// Path: netty-http/src/main/java/http/DefaultServerInitializer.java
import elasticsearch.ElasticRestClient;
import http.worker.SearchWorker;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.util.concurrent.DefaultEventExecutorGroup;
import io.netty.util.concurrent.EventExecutorGroup;
import org.elasticsearch.client.RestClient;
import org.springframework.context.ConfigurableApplicationContext;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
package http;
/**
* Created by i311352 on 2/13/2017.
*/
public class DefaultServerInitializer extends ChannelInitializer<SocketChannel> {
private final Config conf;
//private final EventExecutorGroup executor;
private final ExecutorService executor;
private final ConfigurableApplicationContext applicationContext;
public DefaultServerInitializer(Config conf, ConfigurableApplicationContext applicationContext) {
this.conf = conf;
this.applicationContext = applicationContext;
| this.executor = new SearchWorker(conf.getTaskThreadPoolSize(), "SearchWorkder", new ArrayBlockingQueue(5));
|
compasses/elastic-rabbitmq | netty-http/src/main/java/http/DefaultExceptionHandler.java | // Path: netty-http/src/main/java/http/exception/BadRequestException.java
// public class BadRequestException extends Exception{
//
// public BadRequestException(Throwable throwable) {
// super(throwable);
// }
// }
| import http.exception.BadRequestException;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.util.CharsetUtil;
import org.apache.log4j.Logger;
import java.io.PrintWriter;
import java.io.StringWriter;
import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_LENGTH;
import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
| package http;
/**
* Created by i311352 on 2/13/2017.
*/
public class DefaultExceptionHandler extends ChannelInboundHandlerAdapter {
private final Logger logger = Logger.getLogger(DefaultExceptionHandler.class);
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
logger.error("Exception caught: " + cause);
| // Path: netty-http/src/main/java/http/exception/BadRequestException.java
// public class BadRequestException extends Exception{
//
// public BadRequestException(Throwable throwable) {
// super(throwable);
// }
// }
// Path: netty-http/src/main/java/http/DefaultExceptionHandler.java
import http.exception.BadRequestException;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.util.CharsetUtil;
import org.apache.log4j.Logger;
import java.io.PrintWriter;
import java.io.StringWriter;
import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_LENGTH;
import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
package http;
/**
* Created by i311352 on 2/13/2017.
*/
public class DefaultExceptionHandler extends ChannelInboundHandlerAdapter {
private final Logger logger = Logger.getLogger(DefaultExceptionHandler.class);
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
logger.error("Exception caught: " + cause);
| HttpResponseStatus status = (cause instanceof BadRequestException) ? HttpResponseStatus.BAD_REQUEST :
|
compasses/elastic-rabbitmq | netty-http/src/main/java/HttpServerBoot.java | // Path: netty-http/src/main/java/http/Config.java
// public class Config {
// public Integer getBacklog() {
// return 1280;
// }
//
// public Integer getPort() {
// return 9999;
// }
//
// public Integer getClientMaxBodySize() {
// return 1024*1024*10;
// }
//
// public Integer getTaskThreadPoolSize() {
// return 0;
// }
//
// public Integer getEventLoopThreadCount() {
// return 10;
// }
// }
//
// Path: netty-http/src/main/java/http/DefaultServerInitializer.java
// public class DefaultServerInitializer extends ChannelInitializer<SocketChannel> {
// private final Config conf;
//
// //private final EventExecutorGroup executor;
// private final ExecutorService executor;
// private final ConfigurableApplicationContext applicationContext;
//
// public DefaultServerInitializer(Config conf, ConfigurableApplicationContext applicationContext) {
// this.conf = conf;
// this.applicationContext = applicationContext;
//
// this.executor = new SearchWorker(conf.getTaskThreadPoolSize(), "SearchWorkder", new ArrayBlockingQueue(5));
//
// // new DefaultEventExecutorGroup(
// // conf.getTaskThreadPoolSize());
// }
//
// @Override
// protected void initChannel(SocketChannel ch) throws Exception {
// final ChannelPipeline pipeline = ch.pipeline();
// pipeline.addLast("httpDecoder", new HttpRequestDecoder());
//
// pipeline.addLast("httpAggregator", new HttpObjectAggregator(conf.getClientMaxBodySize()));
// pipeline.addLast("httpResponseEncoder", new HttpResponseEncoder());
// pipeline.addLast("httpMyResponseHandler", new HttpSearchResponseHandler());
//
// pipeline.addLast("httpSearchDecoder", new SearchQueryDecoder());
//
// RestClient restClient = applicationContext.getBean("elasticRestClient", RestClient.class);
//
// pipeline.addLast("httpSearchHandler", new HttpSearchHandler(this.executor, restClient));
// }
// }
| import http.Config;
import http.DefaultServerInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.epoll.Epoll;
import io.netty.channel.epoll.EpollEventLoopGroup;
import io.netty.channel.epoll.EpollServerSocketChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.context.ConfigurableApplicationContext;
|
/**
* Created by i311352 on 2/16/2017.
*/
public class HttpServerBoot {
ConfigurableApplicationContext context;
private Config conf = new Config();
public HttpServerBoot(ConfigurableApplicationContext configurableApplicationContext) {
this.context = configurableApplicationContext;
}
protected static boolean isEpollAvailable = false;
static {
isEpollAvailable = Epoll.isAvailable();
}
public void run() throws Exception {
ServerBootstrap b = new ServerBootstrap();
try {
if (isEpollAvailable) {
b.group(new EpollEventLoopGroup(this.conf.getEventLoopThreadCount()))
.channel(EpollServerSocketChannel.class);
} else {
b.group(new NioEventLoopGroup(this.conf.getEventLoopThreadCount()))
.channel(NioServerSocketChannel.class);
}
| // Path: netty-http/src/main/java/http/Config.java
// public class Config {
// public Integer getBacklog() {
// return 1280;
// }
//
// public Integer getPort() {
// return 9999;
// }
//
// public Integer getClientMaxBodySize() {
// return 1024*1024*10;
// }
//
// public Integer getTaskThreadPoolSize() {
// return 0;
// }
//
// public Integer getEventLoopThreadCount() {
// return 10;
// }
// }
//
// Path: netty-http/src/main/java/http/DefaultServerInitializer.java
// public class DefaultServerInitializer extends ChannelInitializer<SocketChannel> {
// private final Config conf;
//
// //private final EventExecutorGroup executor;
// private final ExecutorService executor;
// private final ConfigurableApplicationContext applicationContext;
//
// public DefaultServerInitializer(Config conf, ConfigurableApplicationContext applicationContext) {
// this.conf = conf;
// this.applicationContext = applicationContext;
//
// this.executor = new SearchWorker(conf.getTaskThreadPoolSize(), "SearchWorkder", new ArrayBlockingQueue(5));
//
// // new DefaultEventExecutorGroup(
// // conf.getTaskThreadPoolSize());
// }
//
// @Override
// protected void initChannel(SocketChannel ch) throws Exception {
// final ChannelPipeline pipeline = ch.pipeline();
// pipeline.addLast("httpDecoder", new HttpRequestDecoder());
//
// pipeline.addLast("httpAggregator", new HttpObjectAggregator(conf.getClientMaxBodySize()));
// pipeline.addLast("httpResponseEncoder", new HttpResponseEncoder());
// pipeline.addLast("httpMyResponseHandler", new HttpSearchResponseHandler());
//
// pipeline.addLast("httpSearchDecoder", new SearchQueryDecoder());
//
// RestClient restClient = applicationContext.getBean("elasticRestClient", RestClient.class);
//
// pipeline.addLast("httpSearchHandler", new HttpSearchHandler(this.executor, restClient));
// }
// }
// Path: netty-http/src/main/java/HttpServerBoot.java
import http.Config;
import http.DefaultServerInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.epoll.Epoll;
import io.netty.channel.epoll.EpollEventLoopGroup;
import io.netty.channel.epoll.EpollServerSocketChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.context.ConfigurableApplicationContext;
/**
* Created by i311352 on 2/16/2017.
*/
public class HttpServerBoot {
ConfigurableApplicationContext context;
private Config conf = new Config();
public HttpServerBoot(ConfigurableApplicationContext configurableApplicationContext) {
this.context = configurableApplicationContext;
}
protected static boolean isEpollAvailable = false;
static {
isEpollAvailable = Epoll.isAvailable();
}
public void run() throws Exception {
ServerBootstrap b = new ServerBootstrap();
try {
if (isEpollAvailable) {
b.group(new EpollEventLoopGroup(this.conf.getEventLoopThreadCount()))
.channel(EpollServerSocketChannel.class);
} else {
b.group(new NioEventLoopGroup(this.conf.getEventLoopThreadCount()))
.channel(NioServerSocketChannel.class);
}
| b.childHandler(new DefaultServerInitializer(conf, context))
|
compasses/elastic-rabbitmq | elasticservice/src/main/java/elasticsearch/ElasticRestClient.java | // Path: elasticservice/src/main/java/elasticsearch/constant/ESConstants.java
// public class ESConstants {
// public static final String STORE_INDEX = "stores";
// public static final String PRODUCT_TYPE = "product";
// public static final String SKU_TYPE = "sku";
// public static final String PRODUCT_PROPERTY = "productproperty";
// public static final String CHANNEL_TYPE = "channels";
// public static final int SNIFFER_INTERVAL = 15000;
// public static final int RESTCLIENT_TIMEOUT = 20000; // 20s
//
//
// public static final Pattern ROUTINGKEY_PATTERN = Pattern.compile("([\\w\\.]+)\\.(\\w+)\\.(\\d+)");
//
// }
| import elasticsearch.constant.ESConstants;
import org.apache.http.HttpHost;
import org.apache.log4j.Logger;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.sniff.Sniffer;
import org.springframework.beans.factory.config.AbstractFactoryBean;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
| package elasticsearch;
/**
* Created by I311352 on 9/30/2016.
*/
@Component
public class ElasticRestClient extends AbstractFactoryBean<RestClient> {
private static Logger logger = Logger.getLogger(ElasticRestClient.class);
private ClusterFailureListener clusterFailureListener;
private volatile RestClient restClient;
private static List<String> hosts = new ArrayList<>();
private Sniffer sniffer;
static {
hosts.add("10.128.161.107:9200");
}
@Override
public Class<?> getObjectType() {
return RestClient.class;
}
@Override
public RestClient createInstance() throws Exception {
if (this.restClient != null) {
return this.restClient;
}
HttpHost[] addresses = new HttpHost[hosts.size()];
for (int i = 0; i < hosts.size(); i++) {
addresses[i] = HttpHost.create(hosts.get(i));
}
this.restClient = RestClient
.builder(addresses)
| // Path: elasticservice/src/main/java/elasticsearch/constant/ESConstants.java
// public class ESConstants {
// public static final String STORE_INDEX = "stores";
// public static final String PRODUCT_TYPE = "product";
// public static final String SKU_TYPE = "sku";
// public static final String PRODUCT_PROPERTY = "productproperty";
// public static final String CHANNEL_TYPE = "channels";
// public static final int SNIFFER_INTERVAL = 15000;
// public static final int RESTCLIENT_TIMEOUT = 20000; // 20s
//
//
// public static final Pattern ROUTINGKEY_PATTERN = Pattern.compile("([\\w\\.]+)\\.(\\w+)\\.(\\d+)");
//
// }
// Path: elasticservice/src/main/java/elasticsearch/ElasticRestClient.java
import elasticsearch.constant.ESConstants;
import org.apache.http.HttpHost;
import org.apache.log4j.Logger;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.sniff.Sniffer;
import org.springframework.beans.factory.config.AbstractFactoryBean;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
package elasticsearch;
/**
* Created by I311352 on 9/30/2016.
*/
@Component
public class ElasticRestClient extends AbstractFactoryBean<RestClient> {
private static Logger logger = Logger.getLogger(ElasticRestClient.class);
private ClusterFailureListener clusterFailureListener;
private volatile RestClient restClient;
private static List<String> hosts = new ArrayList<>();
private Sniffer sniffer;
static {
hosts.add("10.128.161.107:9200");
}
@Override
public Class<?> getObjectType() {
return RestClient.class;
}
@Override
public RestClient createInstance() throws Exception {
if (this.restClient != null) {
return this.restClient;
}
HttpHost[] addresses = new HttpHost[hosts.size()];
for (int i = 0; i < hosts.size(); i++) {
addresses[i] = HttpHost.create(hosts.get(i));
}
this.restClient = RestClient
.builder(addresses)
| .setMaxRetryTimeoutMillis(ESConstants.RESTCLIENT_TIMEOUT)
|
compasses/elastic-rabbitmq | elasticservice/src/main/java/elasticsearch/searchservice/dsl/DSLGenerateService.java | // Path: elasticservice/src/main/java/elasticsearch/searchservice/models/QueryParam.java
// public class QueryParam {
// private List<Meta> filter;
// private Collection collection;
// private String orderByField;
// private String orderByOrder;
// private Long channelId;
// private Integer pageSize;
// private Integer offSet;
// private Boolean isCount = Boolean.FALSE;
//
// public List<Meta> getFilter() {
// return filter;
// }
//
// public void setFilter(List<Meta> filter) {
// this.filter = filter;
// }
//
// public Collection getCollection() {
// return collection;
// }
//
// public void setCollection(Collection collection) {
// this.collection = collection;
// }
//
// public String getOrderByField() {
// return orderByField;
// }
//
// public void setOrderByField(String orderByField) {
// this.orderByField = orderByField;
// }
//
// public String getOrderByOrder() {
// return orderByOrder;
// }
//
// public void setOrderByOrder(String orderByOrder) {
// this.orderByOrder = orderByOrder;
// }
//
// public Integer getPageSize() {
// return pageSize;
// }
//
// public void setPageSize(Integer pageSize) {
// this.pageSize = pageSize;
// }
//
// public Integer getOffSet() {
// return offSet;
// }
//
// public void setOffSet(Integer offSet) {
// this.offSet = offSet;
// }
//
// public Long getChannelId() {
// return channelId;
// }
//
// public void setChannelId(Long channelId) {
// this.channelId = channelId;
// }
//
// public Boolean getCount() {
// return isCount;
// }
//
// public void setCount(Boolean count) {
// isCount = count;
// }
// }
| import elasticsearch.searchservice.models.QueryParam;
import org.springframework.stereotype.Service;
| package elasticsearch.searchservice.dsl;
/**
* Created by i311352 on 5/3/2017.
*/
@Service
public interface DSLGenerateService {
| // Path: elasticservice/src/main/java/elasticsearch/searchservice/models/QueryParam.java
// public class QueryParam {
// private List<Meta> filter;
// private Collection collection;
// private String orderByField;
// private String orderByOrder;
// private Long channelId;
// private Integer pageSize;
// private Integer offSet;
// private Boolean isCount = Boolean.FALSE;
//
// public List<Meta> getFilter() {
// return filter;
// }
//
// public void setFilter(List<Meta> filter) {
// this.filter = filter;
// }
//
// public Collection getCollection() {
// return collection;
// }
//
// public void setCollection(Collection collection) {
// this.collection = collection;
// }
//
// public String getOrderByField() {
// return orderByField;
// }
//
// public void setOrderByField(String orderByField) {
// this.orderByField = orderByField;
// }
//
// public String getOrderByOrder() {
// return orderByOrder;
// }
//
// public void setOrderByOrder(String orderByOrder) {
// this.orderByOrder = orderByOrder;
// }
//
// public Integer getPageSize() {
// return pageSize;
// }
//
// public void setPageSize(Integer pageSize) {
// this.pageSize = pageSize;
// }
//
// public Integer getOffSet() {
// return offSet;
// }
//
// public void setOffSet(Integer offSet) {
// this.offSet = offSet;
// }
//
// public Long getChannelId() {
// return channelId;
// }
//
// public void setChannelId(Long channelId) {
// this.channelId = channelId;
// }
//
// public Boolean getCount() {
// return isCount;
// }
//
// public void setCount(Boolean count) {
// isCount = count;
// }
// }
// Path: elasticservice/src/main/java/elasticsearch/searchservice/dsl/DSLGenerateService.java
import elasticsearch.searchservice.models.QueryParam;
import org.springframework.stereotype.Service;
package elasticsearch.searchservice.dsl;
/**
* Created by i311352 on 5/3/2017.
*/
@Service
public interface DSLGenerateService {
| String fromQueryParam(QueryParam param);
|
compasses/elastic-rabbitmq | netty-http/src/main/java/http/HttpSearchResponseHandler.java | // Path: netty-http/src/main/java/http/elasticaction/RestResponse.java
// public class RestResponse {
//
// private HttpRequest httpRequest;
// private Object body;
//
// public Object getBody() {
// return body;
// }
//
// public void setBody(Object body) {
// this.body = body;
// }
//
// public HttpRequest getHttpRequest() {
// return httpRequest;
// }
//
// public void setHttpRequest(HttpRequest httpRequest) {
// this.httpRequest = httpRequest;
// }
// }
| import com.google.gson.Gson;
import http.elasticaction.RestResponse;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;
import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_LENGTH;
import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE;
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
| package http;
/**
* Created by i311352 on 2/14/2017.
*/
public class HttpSearchResponseHandler extends ChannelOutboundHandlerAdapter {
Gson gson = new Gson();
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
if (msg instanceof HttpResponse) {
super.write(ctx, msg, promise);
return;
}
| // Path: netty-http/src/main/java/http/elasticaction/RestResponse.java
// public class RestResponse {
//
// private HttpRequest httpRequest;
// private Object body;
//
// public Object getBody() {
// return body;
// }
//
// public void setBody(Object body) {
// this.body = body;
// }
//
// public HttpRequest getHttpRequest() {
// return httpRequest;
// }
//
// public void setHttpRequest(HttpRequest httpRequest) {
// this.httpRequest = httpRequest;
// }
// }
// Path: netty-http/src/main/java/http/HttpSearchResponseHandler.java
import com.google.gson.Gson;
import http.elasticaction.RestResponse;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;
import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_LENGTH;
import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE;
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
package http;
/**
* Created by i311352 on 2/14/2017.
*/
public class HttpSearchResponseHandler extends ChannelOutboundHandlerAdapter {
Gson gson = new Gson();
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
if (msg instanceof HttpResponse) {
super.write(ctx, msg, promise);
return;
}
| RestResponse response = (RestResponse) msg;
|
compasses/elastic-rabbitmq | elasticservice/src/main/java/elasticsearch/searchservice/ESService.java | // Path: elasticservice/src/main/java/elasticsearch/ElasticRestClient.java
// @Component
// public class ElasticRestClient extends AbstractFactoryBean<RestClient> {
// private static Logger logger = Logger.getLogger(ElasticRestClient.class);
// private ClusterFailureListener clusterFailureListener;
// private volatile RestClient restClient;
// private static List<String> hosts = new ArrayList<>();
// private Sniffer sniffer;
//
// static {
// hosts.add("10.128.161.107:9200");
// }
//
// @Override
// public Class<?> getObjectType() {
// return RestClient.class;
// }
//
//
// @Override
// public RestClient createInstance() throws Exception {
// if (this.restClient != null) {
// return this.restClient;
// }
//
// HttpHost[] addresses = new HttpHost[hosts.size()];
// for (int i = 0; i < hosts.size(); i++) {
// addresses[i] = HttpHost.create(hosts.get(i));
// }
//
// this.restClient = RestClient
// .builder(addresses)
// .setMaxRetryTimeoutMillis(ESConstants.RESTCLIENT_TIMEOUT)
// .build();
//
// // this.sniffer = Sniffer.builder(this.restClient)
// // .setSniffIntervalMillis(60000).build();
//
// return this.restClient;
// }
//
// @Override
// protected void destroyInstance(RestClient instance) throws Exception {
// try {
// logger.info("Closing sniffer");
// instance.close();
// this.sniffer.close();
// } catch (IOException e) {
// logger.warn("Error during close sniffer", e);
// }
// }
//
// public void setHosts(List<String> hosts) {
// this.hosts = hosts;
// }
// }
| import elasticsearch.ElasticRestClient;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.rest.RestResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
| package elasticsearch.searchservice;
/**
* Created by i311352 on 5/2/2017.
*/
@Service
public class ESService {
private static final Logger logger = LoggerFactory.getLogger(ESService.class);
private static String baseURL;
private static String searchProductURL;
private static String countProductURL;
@Autowired
| // Path: elasticservice/src/main/java/elasticsearch/ElasticRestClient.java
// @Component
// public class ElasticRestClient extends AbstractFactoryBean<RestClient> {
// private static Logger logger = Logger.getLogger(ElasticRestClient.class);
// private ClusterFailureListener clusterFailureListener;
// private volatile RestClient restClient;
// private static List<String> hosts = new ArrayList<>();
// private Sniffer sniffer;
//
// static {
// hosts.add("10.128.161.107:9200");
// }
//
// @Override
// public Class<?> getObjectType() {
// return RestClient.class;
// }
//
//
// @Override
// public RestClient createInstance() throws Exception {
// if (this.restClient != null) {
// return this.restClient;
// }
//
// HttpHost[] addresses = new HttpHost[hosts.size()];
// for (int i = 0; i < hosts.size(); i++) {
// addresses[i] = HttpHost.create(hosts.get(i));
// }
//
// this.restClient = RestClient
// .builder(addresses)
// .setMaxRetryTimeoutMillis(ESConstants.RESTCLIENT_TIMEOUT)
// .build();
//
// // this.sniffer = Sniffer.builder(this.restClient)
// // .setSniffIntervalMillis(60000).build();
//
// return this.restClient;
// }
//
// @Override
// protected void destroyInstance(RestClient instance) throws Exception {
// try {
// logger.info("Closing sniffer");
// instance.close();
// this.sniffer.close();
// } catch (IOException e) {
// logger.warn("Error during close sniffer", e);
// }
// }
//
// public void setHosts(List<String> hosts) {
// this.hosts = hosts;
// }
// }
// Path: elasticservice/src/main/java/elasticsearch/searchservice/ESService.java
import elasticsearch.ElasticRestClient;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.rest.RestResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
package elasticsearch.searchservice;
/**
* Created by i311352 on 5/2/2017.
*/
@Service
public class ESService {
private static final Logger logger = LoggerFactory.getLogger(ESService.class);
private static String baseURL;
private static String searchProductURL;
private static String countProductURL;
@Autowired
| ElasticRestClient client;
|
compasses/elastic-rabbitmq | rabbitmqservice/src/main/java/rabbitmq/MessageListenerProxy.java | // Path: rabbitmqservice/src/main/java/sync/common/MQMessageConst.java
// public class MQMessageConst {
// public static final String H_MESSAGEID = "X-Message-ID";
// public static final String H_TRACEID = "X-Trace-ID";
// public static final String H_TENANTID = "X-Tenant-ID";
// public static final String H_EMPLOYEEID = "X-Employee-ID";
// public static final String H_USERID = "X-User-ID";
// public static final String H_USERTYPE = "X-User-Type";
// public static final String H_USER_LOCALE = "X-Locale";
// public static final String H_SYSTEM_LOCALE = "X-System-Locale";
// public static final String H_SESSIONID = "X-Session-ID";
// public static final String H_SOURCE = "X-Source";
// public static final String H_ORIGIN_USER_ID = "X-Origin-User-ID";
// public static final String H_ORIGIN_EMPLOYEE_ID = "X-Origin-Employee-ID";
// public static final String H_ACCESS_TOKEN = "X-Access-Token";
// public static final String H_ORIGIN_USER_TYPE = "X-Origin-User-Type";
// public static final String H_RO_ID = "X-Ro-ID";
// public static String H_RETRIGGER_FLAG = "false";
// public static final String H_EVENT_TYPE = "X-Event-Type";
// public static final String H_JOBNAME = "header_jobname";
// public static final String H_SIMPLEJOBNAME = "header_simplejobname";
// public static final String H_IMPERSONATE = "header_impersonate";
// public static final String H_STARTTIME = "header_starttime";
// public static final String H_REPEATCOUNT = "header_repeatcount";
// public static final String QUARTZMSGQUEUENAME = "quartz.msg.queue";
// public static final String QUARTZMSGUSERDATAMAP = "header_quartzmsg_userdatamap";
// public static final String H_INTERVALINSECONDS = "header_intervalInSeconds";
// public static final String H_JOBDATA = "header_jobData";
// public static final String H_JOBPREFIX = "header_jobPrefix";
//
// public MQMessageConst() {
// }
// }
| import org.apache.log4j.Logger;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import sync.common.MQMessageConst;
| package rabbitmq;
/**
* Created by I311352 on 12/28/2016.
*/
public class MessageListenerProxy implements MessageListener {
private static final Logger logger = Logger.getLogger(MessageListenerProxy.class);
private final MessageListener delegate;
private final String jobName;
public MessageListenerProxy(MessageListener listener, String jobName) {
this.delegate = listener;
this.jobName = jobName;
}
private void beforeOnMessage(Message message) {
logger.info("Get message");
this.markJobThread(message);
}
@Override
public void onMessage(Message message) {
try {
beforeOnMessage(message);
delegate.onMessage(message);
} finally {
afterOnMessage(message);
}
}
private void afterOnMessage(Message message) {
logger.info("Finish message");
this.unmarkJobThread();
}
private void markJobThread(Message message) {
StringBuilder sb = new StringBuilder();
sb.append("Thread_EventJob_").append(this.jobName).append("_tenant_");
Object tenantId = message.getMessageProperties().getHeaders()
| // Path: rabbitmqservice/src/main/java/sync/common/MQMessageConst.java
// public class MQMessageConst {
// public static final String H_MESSAGEID = "X-Message-ID";
// public static final String H_TRACEID = "X-Trace-ID";
// public static final String H_TENANTID = "X-Tenant-ID";
// public static final String H_EMPLOYEEID = "X-Employee-ID";
// public static final String H_USERID = "X-User-ID";
// public static final String H_USERTYPE = "X-User-Type";
// public static final String H_USER_LOCALE = "X-Locale";
// public static final String H_SYSTEM_LOCALE = "X-System-Locale";
// public static final String H_SESSIONID = "X-Session-ID";
// public static final String H_SOURCE = "X-Source";
// public static final String H_ORIGIN_USER_ID = "X-Origin-User-ID";
// public static final String H_ORIGIN_EMPLOYEE_ID = "X-Origin-Employee-ID";
// public static final String H_ACCESS_TOKEN = "X-Access-Token";
// public static final String H_ORIGIN_USER_TYPE = "X-Origin-User-Type";
// public static final String H_RO_ID = "X-Ro-ID";
// public static String H_RETRIGGER_FLAG = "false";
// public static final String H_EVENT_TYPE = "X-Event-Type";
// public static final String H_JOBNAME = "header_jobname";
// public static final String H_SIMPLEJOBNAME = "header_simplejobname";
// public static final String H_IMPERSONATE = "header_impersonate";
// public static final String H_STARTTIME = "header_starttime";
// public static final String H_REPEATCOUNT = "header_repeatcount";
// public static final String QUARTZMSGQUEUENAME = "quartz.msg.queue";
// public static final String QUARTZMSGUSERDATAMAP = "header_quartzmsg_userdatamap";
// public static final String H_INTERVALINSECONDS = "header_intervalInSeconds";
// public static final String H_JOBDATA = "header_jobData";
// public static final String H_JOBPREFIX = "header_jobPrefix";
//
// public MQMessageConst() {
// }
// }
// Path: rabbitmqservice/src/main/java/rabbitmq/MessageListenerProxy.java
import org.apache.log4j.Logger;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import sync.common.MQMessageConst;
package rabbitmq;
/**
* Created by I311352 on 12/28/2016.
*/
public class MessageListenerProxy implements MessageListener {
private static final Logger logger = Logger.getLogger(MessageListenerProxy.class);
private final MessageListener delegate;
private final String jobName;
public MessageListenerProxy(MessageListener listener, String jobName) {
this.delegate = listener;
this.jobName = jobName;
}
private void beforeOnMessage(Message message) {
logger.info("Get message");
this.markJobThread(message);
}
@Override
public void onMessage(Message message) {
try {
beforeOnMessage(message);
delegate.onMessage(message);
} finally {
afterOnMessage(message);
}
}
private void afterOnMessage(Message message) {
logger.info("Finish message");
this.unmarkJobThread();
}
private void markJobThread(Message message) {
StringBuilder sb = new StringBuilder();
sb.append("Thread_EventJob_").append(this.jobName).append("_tenant_");
Object tenantId = message.getMessageProperties().getHeaders()
| .get(MQMessageConst.H_TENANTID);
|
compasses/elastic-rabbitmq | netty-http/src/main/java/http/SearchQueryDecoder.java | // Path: netty-http/src/main/java/http/exception/BadRequestException.java
// public class BadRequestException extends Exception{
//
// public BadRequestException(Throwable throwable) {
// super(throwable);
// }
// }
//
// Path: netty-http/src/main/java/http/message/DecodedSearchRequest.java
// public class DecodedSearchRequest {
// private final HttpRequest httpRequest;
// private final long orderNumber;
//
// private QueryMeta queryMeta;
//
// public DecodedSearchRequest(HttpRequest request, QueryMeta meta, long orderNumber) {
// this.httpRequest = request;
// this.queryMeta = meta;
// this.orderNumber = orderNumber;
// }
// public QueryMeta getQueryMeta() {
// return queryMeta;
// }
//
// public void setQueryMeta(QueryMeta queryMeta) {
// this.queryMeta = queryMeta;
// }
//
// public HttpRequest getHttpRequest() {
// return httpRequest;
// }
//
// public long getOrderNumber() {
// return orderNumber;
// }
//
// @Override
// public String toString() {
// return "DecodedSearchRequest{" +
// "httpRequest=" + httpRequest +
// ", orderNumber=" + orderNumber +
// ", queryMeta=" + queryMeta +
// '}';
// }
// }
//
// Path: netty-http/src/main/java/http/message/QueryMeta.java
// public class QueryMeta {
//
// private String orderBy;
// private HashMap<String, String> filters = new HashMap<String, String>();
//
// public HashMap addMeta(String type, String value) {
// filters.put(type, value);
// return filters;
// }
//
// public String getOrderBy() {
// return orderBy;
// }
//
// public void setOrderBy(String orderBy) {
// this.orderBy = orderBy;
// }
//
// public HashMap<String, String> getFilters() {
// return filters;
// }
//
// public void setFilters(HashMap<String, String> filters) {
// this.filters = filters;
// }
//
// @Override
// public String toString() {
// return "QueryMeta{" +
// "orderBy='" + orderBy + '\'' +
// ", filters=" + filters +
// '}';
// }
// }
| import http.exception.BadRequestException;
import http.message.DecodedSearchRequest;
import http.message.QueryMeta;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.DecoderResult;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.QueryStringDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Map;
| package http;
/**
* Created by i311352 on 2/13/2017.
*/
public class SearchQueryDecoder extends SimpleChannelInboundHandler<FullHttpRequest> {
private long orderNumber;
private static Logger logger = LoggerFactory.getLogger(SearchQueryDecoder.class);
public SearchQueryDecoder() {
super(false);
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest httpRequest) throws Exception {
DecoderResult result = httpRequest.decoderResult();
if (!result.isSuccess()) {
| // Path: netty-http/src/main/java/http/exception/BadRequestException.java
// public class BadRequestException extends Exception{
//
// public BadRequestException(Throwable throwable) {
// super(throwable);
// }
// }
//
// Path: netty-http/src/main/java/http/message/DecodedSearchRequest.java
// public class DecodedSearchRequest {
// private final HttpRequest httpRequest;
// private final long orderNumber;
//
// private QueryMeta queryMeta;
//
// public DecodedSearchRequest(HttpRequest request, QueryMeta meta, long orderNumber) {
// this.httpRequest = request;
// this.queryMeta = meta;
// this.orderNumber = orderNumber;
// }
// public QueryMeta getQueryMeta() {
// return queryMeta;
// }
//
// public void setQueryMeta(QueryMeta queryMeta) {
// this.queryMeta = queryMeta;
// }
//
// public HttpRequest getHttpRequest() {
// return httpRequest;
// }
//
// public long getOrderNumber() {
// return orderNumber;
// }
//
// @Override
// public String toString() {
// return "DecodedSearchRequest{" +
// "httpRequest=" + httpRequest +
// ", orderNumber=" + orderNumber +
// ", queryMeta=" + queryMeta +
// '}';
// }
// }
//
// Path: netty-http/src/main/java/http/message/QueryMeta.java
// public class QueryMeta {
//
// private String orderBy;
// private HashMap<String, String> filters = new HashMap<String, String>();
//
// public HashMap addMeta(String type, String value) {
// filters.put(type, value);
// return filters;
// }
//
// public String getOrderBy() {
// return orderBy;
// }
//
// public void setOrderBy(String orderBy) {
// this.orderBy = orderBy;
// }
//
// public HashMap<String, String> getFilters() {
// return filters;
// }
//
// public void setFilters(HashMap<String, String> filters) {
// this.filters = filters;
// }
//
// @Override
// public String toString() {
// return "QueryMeta{" +
// "orderBy='" + orderBy + '\'' +
// ", filters=" + filters +
// '}';
// }
// }
// Path: netty-http/src/main/java/http/SearchQueryDecoder.java
import http.exception.BadRequestException;
import http.message.DecodedSearchRequest;
import http.message.QueryMeta;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.DecoderResult;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.QueryStringDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Map;
package http;
/**
* Created by i311352 on 2/13/2017.
*/
public class SearchQueryDecoder extends SimpleChannelInboundHandler<FullHttpRequest> {
private long orderNumber;
private static Logger logger = LoggerFactory.getLogger(SearchQueryDecoder.class);
public SearchQueryDecoder() {
super(false);
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest httpRequest) throws Exception {
DecoderResult result = httpRequest.decoderResult();
if (!result.isSuccess()) {
| throw new BadRequestException(result.cause());
|
compasses/elastic-rabbitmq | netty-http/src/main/java/http/SearchQueryDecoder.java | // Path: netty-http/src/main/java/http/exception/BadRequestException.java
// public class BadRequestException extends Exception{
//
// public BadRequestException(Throwable throwable) {
// super(throwable);
// }
// }
//
// Path: netty-http/src/main/java/http/message/DecodedSearchRequest.java
// public class DecodedSearchRequest {
// private final HttpRequest httpRequest;
// private final long orderNumber;
//
// private QueryMeta queryMeta;
//
// public DecodedSearchRequest(HttpRequest request, QueryMeta meta, long orderNumber) {
// this.httpRequest = request;
// this.queryMeta = meta;
// this.orderNumber = orderNumber;
// }
// public QueryMeta getQueryMeta() {
// return queryMeta;
// }
//
// public void setQueryMeta(QueryMeta queryMeta) {
// this.queryMeta = queryMeta;
// }
//
// public HttpRequest getHttpRequest() {
// return httpRequest;
// }
//
// public long getOrderNumber() {
// return orderNumber;
// }
//
// @Override
// public String toString() {
// return "DecodedSearchRequest{" +
// "httpRequest=" + httpRequest +
// ", orderNumber=" + orderNumber +
// ", queryMeta=" + queryMeta +
// '}';
// }
// }
//
// Path: netty-http/src/main/java/http/message/QueryMeta.java
// public class QueryMeta {
//
// private String orderBy;
// private HashMap<String, String> filters = new HashMap<String, String>();
//
// public HashMap addMeta(String type, String value) {
// filters.put(type, value);
// return filters;
// }
//
// public String getOrderBy() {
// return orderBy;
// }
//
// public void setOrderBy(String orderBy) {
// this.orderBy = orderBy;
// }
//
// public HashMap<String, String> getFilters() {
// return filters;
// }
//
// public void setFilters(HashMap<String, String> filters) {
// this.filters = filters;
// }
//
// @Override
// public String toString() {
// return "QueryMeta{" +
// "orderBy='" + orderBy + '\'' +
// ", filters=" + filters +
// '}';
// }
// }
| import http.exception.BadRequestException;
import http.message.DecodedSearchRequest;
import http.message.QueryMeta;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.DecoderResult;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.QueryStringDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Map;
| package http;
/**
* Created by i311352 on 2/13/2017.
*/
public class SearchQueryDecoder extends SimpleChannelInboundHandler<FullHttpRequest> {
private long orderNumber;
private static Logger logger = LoggerFactory.getLogger(SearchQueryDecoder.class);
public SearchQueryDecoder() {
super(false);
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest httpRequest) throws Exception {
DecoderResult result = httpRequest.decoderResult();
if (!result.isSuccess()) {
throw new BadRequestException(result.cause());
}
logger.info("Get search request: " + httpRequest.uri());
// only decode get path is enough
Map<String, List<String>> requestParameters;
QueryStringDecoder stringDecoder = new QueryStringDecoder(httpRequest.uri());
requestParameters = stringDecoder.parameters();
| // Path: netty-http/src/main/java/http/exception/BadRequestException.java
// public class BadRequestException extends Exception{
//
// public BadRequestException(Throwable throwable) {
// super(throwable);
// }
// }
//
// Path: netty-http/src/main/java/http/message/DecodedSearchRequest.java
// public class DecodedSearchRequest {
// private final HttpRequest httpRequest;
// private final long orderNumber;
//
// private QueryMeta queryMeta;
//
// public DecodedSearchRequest(HttpRequest request, QueryMeta meta, long orderNumber) {
// this.httpRequest = request;
// this.queryMeta = meta;
// this.orderNumber = orderNumber;
// }
// public QueryMeta getQueryMeta() {
// return queryMeta;
// }
//
// public void setQueryMeta(QueryMeta queryMeta) {
// this.queryMeta = queryMeta;
// }
//
// public HttpRequest getHttpRequest() {
// return httpRequest;
// }
//
// public long getOrderNumber() {
// return orderNumber;
// }
//
// @Override
// public String toString() {
// return "DecodedSearchRequest{" +
// "httpRequest=" + httpRequest +
// ", orderNumber=" + orderNumber +
// ", queryMeta=" + queryMeta +
// '}';
// }
// }
//
// Path: netty-http/src/main/java/http/message/QueryMeta.java
// public class QueryMeta {
//
// private String orderBy;
// private HashMap<String, String> filters = new HashMap<String, String>();
//
// public HashMap addMeta(String type, String value) {
// filters.put(type, value);
// return filters;
// }
//
// public String getOrderBy() {
// return orderBy;
// }
//
// public void setOrderBy(String orderBy) {
// this.orderBy = orderBy;
// }
//
// public HashMap<String, String> getFilters() {
// return filters;
// }
//
// public void setFilters(HashMap<String, String> filters) {
// this.filters = filters;
// }
//
// @Override
// public String toString() {
// return "QueryMeta{" +
// "orderBy='" + orderBy + '\'' +
// ", filters=" + filters +
// '}';
// }
// }
// Path: netty-http/src/main/java/http/SearchQueryDecoder.java
import http.exception.BadRequestException;
import http.message.DecodedSearchRequest;
import http.message.QueryMeta;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.DecoderResult;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.QueryStringDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Map;
package http;
/**
* Created by i311352 on 2/13/2017.
*/
public class SearchQueryDecoder extends SimpleChannelInboundHandler<FullHttpRequest> {
private long orderNumber;
private static Logger logger = LoggerFactory.getLogger(SearchQueryDecoder.class);
public SearchQueryDecoder() {
super(false);
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest httpRequest) throws Exception {
DecoderResult result = httpRequest.decoderResult();
if (!result.isSuccess()) {
throw new BadRequestException(result.cause());
}
logger.info("Get search request: " + httpRequest.uri());
// only decode get path is enough
Map<String, List<String>> requestParameters;
QueryStringDecoder stringDecoder = new QueryStringDecoder(httpRequest.uri());
requestParameters = stringDecoder.parameters();
| QueryMeta meta = new QueryMeta();
|
compasses/elastic-rabbitmq | netty-http/src/main/java/http/SearchQueryDecoder.java | // Path: netty-http/src/main/java/http/exception/BadRequestException.java
// public class BadRequestException extends Exception{
//
// public BadRequestException(Throwable throwable) {
// super(throwable);
// }
// }
//
// Path: netty-http/src/main/java/http/message/DecodedSearchRequest.java
// public class DecodedSearchRequest {
// private final HttpRequest httpRequest;
// private final long orderNumber;
//
// private QueryMeta queryMeta;
//
// public DecodedSearchRequest(HttpRequest request, QueryMeta meta, long orderNumber) {
// this.httpRequest = request;
// this.queryMeta = meta;
// this.orderNumber = orderNumber;
// }
// public QueryMeta getQueryMeta() {
// return queryMeta;
// }
//
// public void setQueryMeta(QueryMeta queryMeta) {
// this.queryMeta = queryMeta;
// }
//
// public HttpRequest getHttpRequest() {
// return httpRequest;
// }
//
// public long getOrderNumber() {
// return orderNumber;
// }
//
// @Override
// public String toString() {
// return "DecodedSearchRequest{" +
// "httpRequest=" + httpRequest +
// ", orderNumber=" + orderNumber +
// ", queryMeta=" + queryMeta +
// '}';
// }
// }
//
// Path: netty-http/src/main/java/http/message/QueryMeta.java
// public class QueryMeta {
//
// private String orderBy;
// private HashMap<String, String> filters = new HashMap<String, String>();
//
// public HashMap addMeta(String type, String value) {
// filters.put(type, value);
// return filters;
// }
//
// public String getOrderBy() {
// return orderBy;
// }
//
// public void setOrderBy(String orderBy) {
// this.orderBy = orderBy;
// }
//
// public HashMap<String, String> getFilters() {
// return filters;
// }
//
// public void setFilters(HashMap<String, String> filters) {
// this.filters = filters;
// }
//
// @Override
// public String toString() {
// return "QueryMeta{" +
// "orderBy='" + orderBy + '\'' +
// ", filters=" + filters +
// '}';
// }
// }
| import http.exception.BadRequestException;
import http.message.DecodedSearchRequest;
import http.message.QueryMeta;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.DecoderResult;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.QueryStringDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Map;
| @Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest httpRequest) throws Exception {
DecoderResult result = httpRequest.decoderResult();
if (!result.isSuccess()) {
throw new BadRequestException(result.cause());
}
logger.info("Get search request: " + httpRequest.uri());
// only decode get path is enough
Map<String, List<String>> requestParameters;
QueryStringDecoder stringDecoder = new QueryStringDecoder(httpRequest.uri());
requestParameters = stringDecoder.parameters();
QueryMeta meta = new QueryMeta();
for(Map.Entry<String, List<String>> entry : requestParameters.entrySet()) {
if (entry.getKey().equals("options[]")) {
// add filters
List<String> filters = entry.getValue();
filters.forEach(filter -> {
String[] typeVal = filter.split(":");
meta.addMeta(typeVal[0], typeVal[1]);
});
} else if (entry.getKey().equals("orderby")) {
meta.setOrderBy(entry.getValue().get(0));
} else {
logger.warn("Unknown query parameter, ignore it:" + entry.toString());
}
}
| // Path: netty-http/src/main/java/http/exception/BadRequestException.java
// public class BadRequestException extends Exception{
//
// public BadRequestException(Throwable throwable) {
// super(throwable);
// }
// }
//
// Path: netty-http/src/main/java/http/message/DecodedSearchRequest.java
// public class DecodedSearchRequest {
// private final HttpRequest httpRequest;
// private final long orderNumber;
//
// private QueryMeta queryMeta;
//
// public DecodedSearchRequest(HttpRequest request, QueryMeta meta, long orderNumber) {
// this.httpRequest = request;
// this.queryMeta = meta;
// this.orderNumber = orderNumber;
// }
// public QueryMeta getQueryMeta() {
// return queryMeta;
// }
//
// public void setQueryMeta(QueryMeta queryMeta) {
// this.queryMeta = queryMeta;
// }
//
// public HttpRequest getHttpRequest() {
// return httpRequest;
// }
//
// public long getOrderNumber() {
// return orderNumber;
// }
//
// @Override
// public String toString() {
// return "DecodedSearchRequest{" +
// "httpRequest=" + httpRequest +
// ", orderNumber=" + orderNumber +
// ", queryMeta=" + queryMeta +
// '}';
// }
// }
//
// Path: netty-http/src/main/java/http/message/QueryMeta.java
// public class QueryMeta {
//
// private String orderBy;
// private HashMap<String, String> filters = new HashMap<String, String>();
//
// public HashMap addMeta(String type, String value) {
// filters.put(type, value);
// return filters;
// }
//
// public String getOrderBy() {
// return orderBy;
// }
//
// public void setOrderBy(String orderBy) {
// this.orderBy = orderBy;
// }
//
// public HashMap<String, String> getFilters() {
// return filters;
// }
//
// public void setFilters(HashMap<String, String> filters) {
// this.filters = filters;
// }
//
// @Override
// public String toString() {
// return "QueryMeta{" +
// "orderBy='" + orderBy + '\'' +
// ", filters=" + filters +
// '}';
// }
// }
// Path: netty-http/src/main/java/http/SearchQueryDecoder.java
import http.exception.BadRequestException;
import http.message.DecodedSearchRequest;
import http.message.QueryMeta;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.DecoderResult;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.QueryStringDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Map;
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest httpRequest) throws Exception {
DecoderResult result = httpRequest.decoderResult();
if (!result.isSuccess()) {
throw new BadRequestException(result.cause());
}
logger.info("Get search request: " + httpRequest.uri());
// only decode get path is enough
Map<String, List<String>> requestParameters;
QueryStringDecoder stringDecoder = new QueryStringDecoder(httpRequest.uri());
requestParameters = stringDecoder.parameters();
QueryMeta meta = new QueryMeta();
for(Map.Entry<String, List<String>> entry : requestParameters.entrySet()) {
if (entry.getKey().equals("options[]")) {
// add filters
List<String> filters = entry.getValue();
filters.forEach(filter -> {
String[] typeVal = filter.split(":");
meta.addMeta(typeVal[0], typeVal[1]);
});
} else if (entry.getKey().equals("orderby")) {
meta.setOrderBy(entry.getValue().get(0));
} else {
logger.warn("Unknown query parameter, ignore it:" + entry.toString());
}
}
| DecodedSearchRequest searchRequest = new DecodedSearchRequest(httpRequest, meta, orderNumber++);
|
compasses/elastic-rabbitmq | rabbitmqservice/src/main/java/rabbitmq/ListenerJobBuilder.java | // Path: rabbitmqservice/src/main/java/sync/listener/ESMessageListener.java
// @Component
// public class ESMessageListener implements MessageListener {
// private static final Logger lightLogger = Logger.getLogger(ESMessageListener.class);
//
// private ESHandlerManager handlerManager = null;
// private ConfigurableApplicationContext context;
//
// private final CounterService counterService;
//
// private final GaugeService gaugeService;
//
// public ESMessageListener(ConfigurableApplicationContext context) {
// this.counterService = context.getBean("counterService", CounterService.class);
// this.gaugeService = context.getBean("gaugeService", GaugeService.class);
// this.context = context;
// //handlerManager.initHandler(context);
// }
//
// @Override
// public void onMessage(Message message) {
// if (handlerManager == null) {
// handlerManager = new ESHandlerManager();
// handlerManager.initHandler(context);
// }
//
// doWork(message);
// }
//
// protected void postHandle(Message message) {
// String messageId = String.valueOf(message.getMessageProperties()
// .getHeaders().get(MQMessageConst.H_MESSAGEID));
// String jobName = String.valueOf(message.getMessageProperties()
// .getHeaders().get(MQMessageConst.H_JOBNAME));
// }
//
// public void doWork(Message message) {
// String routingKey = message.getMessageProperties().getReceivedRoutingKey();
// Matcher m = ESConstants.ROUTINGKEY_PATTERN.matcher(routingKey);
// try {
// if (m.find() && m.groupCount() == 3) {
// ESHandleMessage esHandleMessage = new ESHandleMessage(Long.parseLong(m.group(3)),
// m.group(1), m.group(2), message.getBody());
// esHandleMessage.setEventGenerated(isGeneratedMessage(message));
// handleMsg(esHandleMessage);
// } else {
// lightLogger.warn("Message is invalid: " + routingKey);
// }
// } finally {
// lightLogger.info("Done");
// }
//
// }
//
// private boolean isGeneratedMessage(Message message) {
// return ObjectUtils.equals("EventGenerator", message.getMessageProperties().getHeaders().get("eventSource"));
// }
//
// private void handleMsg(ESHandleMessage message) {
// StopWatch stopWatch = new StopWatch();
// stopWatch.start();
// boolean successful = false;
//
// lightLogger.info("ES sync start on ESHandleMessage " + message.toString());
// ESHandler handler = null;
// try {
// handler = handlerManager.getHandler(message);
// if (handler == null) {
// lightLogger.info("Handler is null for message" + message.toString());
// return;
// }
//
// handler.onMessage(message);
//
// successful = true;
// } catch (Throwable t) {
// successful = false;
// throw t;
// } finally {
// stopWatch.stop();
// String metricName = message.getClass().getSimpleName() + "." + handler.getClass().getSimpleName();
// //counterService.increment(metricName + "." + (successful ? ".success" : "failed"));
// //gaugeService.submit(metricName, stopWatch.getTime());
// lightLogger.info("ES sync end on execTime[" + stopWatch.getTime() + "]");
// }
// }
//
// // @Override
// public String[] getRoutingKeys() {
// List<String> routingList = handlerManager.getRoutingKeyList();
// return routingList.toArray(new String[routingList.size()]);
// }
//
// public void setHandlerManager(ESHandlerManager handlerManager) {
// this.handlerManager = handlerManager;
// }
// }
| import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.jca.cci.connection.SingleConnectionFactory;
import sync.listener.ESMessageListener;
| package rabbitmq;
/**
* Created by I311352 on 12/28/2016.
*/
public class ListenerJobBuilder {
// just everything under default
public static MQListenerAdmin buildMQListenerAdmin(ConfigurableApplicationContext context) {
| // Path: rabbitmqservice/src/main/java/sync/listener/ESMessageListener.java
// @Component
// public class ESMessageListener implements MessageListener {
// private static final Logger lightLogger = Logger.getLogger(ESMessageListener.class);
//
// private ESHandlerManager handlerManager = null;
// private ConfigurableApplicationContext context;
//
// private final CounterService counterService;
//
// private final GaugeService gaugeService;
//
// public ESMessageListener(ConfigurableApplicationContext context) {
// this.counterService = context.getBean("counterService", CounterService.class);
// this.gaugeService = context.getBean("gaugeService", GaugeService.class);
// this.context = context;
// //handlerManager.initHandler(context);
// }
//
// @Override
// public void onMessage(Message message) {
// if (handlerManager == null) {
// handlerManager = new ESHandlerManager();
// handlerManager.initHandler(context);
// }
//
// doWork(message);
// }
//
// protected void postHandle(Message message) {
// String messageId = String.valueOf(message.getMessageProperties()
// .getHeaders().get(MQMessageConst.H_MESSAGEID));
// String jobName = String.valueOf(message.getMessageProperties()
// .getHeaders().get(MQMessageConst.H_JOBNAME));
// }
//
// public void doWork(Message message) {
// String routingKey = message.getMessageProperties().getReceivedRoutingKey();
// Matcher m = ESConstants.ROUTINGKEY_PATTERN.matcher(routingKey);
// try {
// if (m.find() && m.groupCount() == 3) {
// ESHandleMessage esHandleMessage = new ESHandleMessage(Long.parseLong(m.group(3)),
// m.group(1), m.group(2), message.getBody());
// esHandleMessage.setEventGenerated(isGeneratedMessage(message));
// handleMsg(esHandleMessage);
// } else {
// lightLogger.warn("Message is invalid: " + routingKey);
// }
// } finally {
// lightLogger.info("Done");
// }
//
// }
//
// private boolean isGeneratedMessage(Message message) {
// return ObjectUtils.equals("EventGenerator", message.getMessageProperties().getHeaders().get("eventSource"));
// }
//
// private void handleMsg(ESHandleMessage message) {
// StopWatch stopWatch = new StopWatch();
// stopWatch.start();
// boolean successful = false;
//
// lightLogger.info("ES sync start on ESHandleMessage " + message.toString());
// ESHandler handler = null;
// try {
// handler = handlerManager.getHandler(message);
// if (handler == null) {
// lightLogger.info("Handler is null for message" + message.toString());
// return;
// }
//
// handler.onMessage(message);
//
// successful = true;
// } catch (Throwable t) {
// successful = false;
// throw t;
// } finally {
// stopWatch.stop();
// String metricName = message.getClass().getSimpleName() + "." + handler.getClass().getSimpleName();
// //counterService.increment(metricName + "." + (successful ? ".success" : "failed"));
// //gaugeService.submit(metricName, stopWatch.getTime());
// lightLogger.info("ES sync end on execTime[" + stopWatch.getTime() + "]");
// }
// }
//
// // @Override
// public String[] getRoutingKeys() {
// List<String> routingList = handlerManager.getRoutingKeyList();
// return routingList.toArray(new String[routingList.size()]);
// }
//
// public void setHandlerManager(ESHandlerManager handlerManager) {
// this.handlerManager = handlerManager;
// }
// }
// Path: rabbitmqservice/src/main/java/rabbitmq/ListenerJobBuilder.java
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.jca.cci.connection.SingleConnectionFactory;
import sync.listener.ESMessageListener;
package rabbitmq;
/**
* Created by I311352 on 12/28/2016.
*/
public class ListenerJobBuilder {
// just everything under default
public static MQListenerAdmin buildMQListenerAdmin(ConfigurableApplicationContext context) {
| MessageListenerProxy listenerProxy = new MessageListenerProxy(new ESMessageListener(context),
|
compasses/elastic-rabbitmq | elasticservice/src/main/java/elasticsearch/searchservice/SearchServiceImpl.java | // Path: elasticservice/src/main/java/elasticsearch/searchservice/dsl/DSLGenerateService.java
// @Service
// public interface DSLGenerateService {
// String fromQueryParam(QueryParam param);
// }
//
// Path: elasticservice/src/main/java/elasticsearch/searchservice/models/CacheSearchService.java
// @Service
// public interface CacheSearchService {
// QueryResp query(String body);
// Integer count(String body);
// }
//
// Path: elasticservice/src/main/java/elasticsearch/searchservice/models/QueryParam.java
// public class QueryParam {
// private List<Meta> filter;
// private Collection collection;
// private String orderByField;
// private String orderByOrder;
// private Long channelId;
// private Integer pageSize;
// private Integer offSet;
// private Boolean isCount = Boolean.FALSE;
//
// public List<Meta> getFilter() {
// return filter;
// }
//
// public void setFilter(List<Meta> filter) {
// this.filter = filter;
// }
//
// public Collection getCollection() {
// return collection;
// }
//
// public void setCollection(Collection collection) {
// this.collection = collection;
// }
//
// public String getOrderByField() {
// return orderByField;
// }
//
// public void setOrderByField(String orderByField) {
// this.orderByField = orderByField;
// }
//
// public String getOrderByOrder() {
// return orderByOrder;
// }
//
// public void setOrderByOrder(String orderByOrder) {
// this.orderByOrder = orderByOrder;
// }
//
// public Integer getPageSize() {
// return pageSize;
// }
//
// public void setPageSize(Integer pageSize) {
// this.pageSize = pageSize;
// }
//
// public Integer getOffSet() {
// return offSet;
// }
//
// public void setOffSet(Integer offSet) {
// this.offSet = offSet;
// }
//
// public Long getChannelId() {
// return channelId;
// }
//
// public void setChannelId(Long channelId) {
// this.channelId = channelId;
// }
//
// public Boolean getCount() {
// return isCount;
// }
//
// public void setCount(Boolean count) {
// isCount = count;
// }
// }
//
// Path: elasticservice/src/main/java/elasticsearch/searchservice/models/QueryResp.java
// public class QueryResp {
// Long total;
// List<Long> productIds;
//
// public QueryResp() {
// }
//
// public QueryResp(Long total) {
// this.total = total;
// }
//
// public QueryResp(ESQueryResponse response) {
// total = response.getHit().getTotal();
// productIds = new ArrayList<>();
// for (Hits hitResult : response.getHit().getHits()) {
// JsonObject object = hitResult.getSource();
// Long id = object.get("id").getAsLong();
// productIds.add(id);
// }
// }
//
// public QueryResp(ESSearchResp resp) {
// total = resp.getHits().getTotal();
// productIds = new ArrayList<>();
// for (HitResult hitResult : resp.getHits().getHits()) {
// productIds.add(hitResult.get_source().getId());
// }
// }
//
// public Long getTotal() {
// return total;
// }
//
// public void setTotal(Long total) {
// this.total = total;
// }
//
// public List<Long> getProductIds() {
// return productIds;
// }
//
// public void setProductIds(List<Long> productIds) {
// this.productIds = productIds;
// }
// }
| import elasticsearch.searchservice.dsl.DSLGenerateService;
import elasticsearch.searchservice.models.CacheSearchService;
import elasticsearch.searchservice.models.QueryParam;
import elasticsearch.searchservice.models.QueryResp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
| package elasticsearch.searchservice;
/**
* Created by i311352 on 5/2/2017.
*/
@Service
public class SearchServiceImpl implements SearchService {
private static final Logger logger = LoggerFactory.getLogger(SearchServiceImpl.class);
@Autowired
| // Path: elasticservice/src/main/java/elasticsearch/searchservice/dsl/DSLGenerateService.java
// @Service
// public interface DSLGenerateService {
// String fromQueryParam(QueryParam param);
// }
//
// Path: elasticservice/src/main/java/elasticsearch/searchservice/models/CacheSearchService.java
// @Service
// public interface CacheSearchService {
// QueryResp query(String body);
// Integer count(String body);
// }
//
// Path: elasticservice/src/main/java/elasticsearch/searchservice/models/QueryParam.java
// public class QueryParam {
// private List<Meta> filter;
// private Collection collection;
// private String orderByField;
// private String orderByOrder;
// private Long channelId;
// private Integer pageSize;
// private Integer offSet;
// private Boolean isCount = Boolean.FALSE;
//
// public List<Meta> getFilter() {
// return filter;
// }
//
// public void setFilter(List<Meta> filter) {
// this.filter = filter;
// }
//
// public Collection getCollection() {
// return collection;
// }
//
// public void setCollection(Collection collection) {
// this.collection = collection;
// }
//
// public String getOrderByField() {
// return orderByField;
// }
//
// public void setOrderByField(String orderByField) {
// this.orderByField = orderByField;
// }
//
// public String getOrderByOrder() {
// return orderByOrder;
// }
//
// public void setOrderByOrder(String orderByOrder) {
// this.orderByOrder = orderByOrder;
// }
//
// public Integer getPageSize() {
// return pageSize;
// }
//
// public void setPageSize(Integer pageSize) {
// this.pageSize = pageSize;
// }
//
// public Integer getOffSet() {
// return offSet;
// }
//
// public void setOffSet(Integer offSet) {
// this.offSet = offSet;
// }
//
// public Long getChannelId() {
// return channelId;
// }
//
// public void setChannelId(Long channelId) {
// this.channelId = channelId;
// }
//
// public Boolean getCount() {
// return isCount;
// }
//
// public void setCount(Boolean count) {
// isCount = count;
// }
// }
//
// Path: elasticservice/src/main/java/elasticsearch/searchservice/models/QueryResp.java
// public class QueryResp {
// Long total;
// List<Long> productIds;
//
// public QueryResp() {
// }
//
// public QueryResp(Long total) {
// this.total = total;
// }
//
// public QueryResp(ESQueryResponse response) {
// total = response.getHit().getTotal();
// productIds = new ArrayList<>();
// for (Hits hitResult : response.getHit().getHits()) {
// JsonObject object = hitResult.getSource();
// Long id = object.get("id").getAsLong();
// productIds.add(id);
// }
// }
//
// public QueryResp(ESSearchResp resp) {
// total = resp.getHits().getTotal();
// productIds = new ArrayList<>();
// for (HitResult hitResult : resp.getHits().getHits()) {
// productIds.add(hitResult.get_source().getId());
// }
// }
//
// public Long getTotal() {
// return total;
// }
//
// public void setTotal(Long total) {
// this.total = total;
// }
//
// public List<Long> getProductIds() {
// return productIds;
// }
//
// public void setProductIds(List<Long> productIds) {
// this.productIds = productIds;
// }
// }
// Path: elasticservice/src/main/java/elasticsearch/searchservice/SearchServiceImpl.java
import elasticsearch.searchservice.dsl.DSLGenerateService;
import elasticsearch.searchservice.models.CacheSearchService;
import elasticsearch.searchservice.models.QueryParam;
import elasticsearch.searchservice.models.QueryResp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
package elasticsearch.searchservice;
/**
* Created by i311352 on 5/2/2017.
*/
@Service
public class SearchServiceImpl implements SearchService {
private static final Logger logger = LoggerFactory.getLogger(SearchServiceImpl.class);
@Autowired
| private CacheSearchService cacheSearchService;
|
compasses/elastic-rabbitmq | elasticservice/src/main/java/elasticsearch/searchservice/SearchServiceImpl.java | // Path: elasticservice/src/main/java/elasticsearch/searchservice/dsl/DSLGenerateService.java
// @Service
// public interface DSLGenerateService {
// String fromQueryParam(QueryParam param);
// }
//
// Path: elasticservice/src/main/java/elasticsearch/searchservice/models/CacheSearchService.java
// @Service
// public interface CacheSearchService {
// QueryResp query(String body);
// Integer count(String body);
// }
//
// Path: elasticservice/src/main/java/elasticsearch/searchservice/models/QueryParam.java
// public class QueryParam {
// private List<Meta> filter;
// private Collection collection;
// private String orderByField;
// private String orderByOrder;
// private Long channelId;
// private Integer pageSize;
// private Integer offSet;
// private Boolean isCount = Boolean.FALSE;
//
// public List<Meta> getFilter() {
// return filter;
// }
//
// public void setFilter(List<Meta> filter) {
// this.filter = filter;
// }
//
// public Collection getCollection() {
// return collection;
// }
//
// public void setCollection(Collection collection) {
// this.collection = collection;
// }
//
// public String getOrderByField() {
// return orderByField;
// }
//
// public void setOrderByField(String orderByField) {
// this.orderByField = orderByField;
// }
//
// public String getOrderByOrder() {
// return orderByOrder;
// }
//
// public void setOrderByOrder(String orderByOrder) {
// this.orderByOrder = orderByOrder;
// }
//
// public Integer getPageSize() {
// return pageSize;
// }
//
// public void setPageSize(Integer pageSize) {
// this.pageSize = pageSize;
// }
//
// public Integer getOffSet() {
// return offSet;
// }
//
// public void setOffSet(Integer offSet) {
// this.offSet = offSet;
// }
//
// public Long getChannelId() {
// return channelId;
// }
//
// public void setChannelId(Long channelId) {
// this.channelId = channelId;
// }
//
// public Boolean getCount() {
// return isCount;
// }
//
// public void setCount(Boolean count) {
// isCount = count;
// }
// }
//
// Path: elasticservice/src/main/java/elasticsearch/searchservice/models/QueryResp.java
// public class QueryResp {
// Long total;
// List<Long> productIds;
//
// public QueryResp() {
// }
//
// public QueryResp(Long total) {
// this.total = total;
// }
//
// public QueryResp(ESQueryResponse response) {
// total = response.getHit().getTotal();
// productIds = new ArrayList<>();
// for (Hits hitResult : response.getHit().getHits()) {
// JsonObject object = hitResult.getSource();
// Long id = object.get("id").getAsLong();
// productIds.add(id);
// }
// }
//
// public QueryResp(ESSearchResp resp) {
// total = resp.getHits().getTotal();
// productIds = new ArrayList<>();
// for (HitResult hitResult : resp.getHits().getHits()) {
// productIds.add(hitResult.get_source().getId());
// }
// }
//
// public Long getTotal() {
// return total;
// }
//
// public void setTotal(Long total) {
// this.total = total;
// }
//
// public List<Long> getProductIds() {
// return productIds;
// }
//
// public void setProductIds(List<Long> productIds) {
// this.productIds = productIds;
// }
// }
| import elasticsearch.searchservice.dsl.DSLGenerateService;
import elasticsearch.searchservice.models.CacheSearchService;
import elasticsearch.searchservice.models.QueryParam;
import elasticsearch.searchservice.models.QueryResp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
| package elasticsearch.searchservice;
/**
* Created by i311352 on 5/2/2017.
*/
@Service
public class SearchServiceImpl implements SearchService {
private static final Logger logger = LoggerFactory.getLogger(SearchServiceImpl.class);
@Autowired
private CacheSearchService cacheSearchService;
@Autowired
| // Path: elasticservice/src/main/java/elasticsearch/searchservice/dsl/DSLGenerateService.java
// @Service
// public interface DSLGenerateService {
// String fromQueryParam(QueryParam param);
// }
//
// Path: elasticservice/src/main/java/elasticsearch/searchservice/models/CacheSearchService.java
// @Service
// public interface CacheSearchService {
// QueryResp query(String body);
// Integer count(String body);
// }
//
// Path: elasticservice/src/main/java/elasticsearch/searchservice/models/QueryParam.java
// public class QueryParam {
// private List<Meta> filter;
// private Collection collection;
// private String orderByField;
// private String orderByOrder;
// private Long channelId;
// private Integer pageSize;
// private Integer offSet;
// private Boolean isCount = Boolean.FALSE;
//
// public List<Meta> getFilter() {
// return filter;
// }
//
// public void setFilter(List<Meta> filter) {
// this.filter = filter;
// }
//
// public Collection getCollection() {
// return collection;
// }
//
// public void setCollection(Collection collection) {
// this.collection = collection;
// }
//
// public String getOrderByField() {
// return orderByField;
// }
//
// public void setOrderByField(String orderByField) {
// this.orderByField = orderByField;
// }
//
// public String getOrderByOrder() {
// return orderByOrder;
// }
//
// public void setOrderByOrder(String orderByOrder) {
// this.orderByOrder = orderByOrder;
// }
//
// public Integer getPageSize() {
// return pageSize;
// }
//
// public void setPageSize(Integer pageSize) {
// this.pageSize = pageSize;
// }
//
// public Integer getOffSet() {
// return offSet;
// }
//
// public void setOffSet(Integer offSet) {
// this.offSet = offSet;
// }
//
// public Long getChannelId() {
// return channelId;
// }
//
// public void setChannelId(Long channelId) {
// this.channelId = channelId;
// }
//
// public Boolean getCount() {
// return isCount;
// }
//
// public void setCount(Boolean count) {
// isCount = count;
// }
// }
//
// Path: elasticservice/src/main/java/elasticsearch/searchservice/models/QueryResp.java
// public class QueryResp {
// Long total;
// List<Long> productIds;
//
// public QueryResp() {
// }
//
// public QueryResp(Long total) {
// this.total = total;
// }
//
// public QueryResp(ESQueryResponse response) {
// total = response.getHit().getTotal();
// productIds = new ArrayList<>();
// for (Hits hitResult : response.getHit().getHits()) {
// JsonObject object = hitResult.getSource();
// Long id = object.get("id").getAsLong();
// productIds.add(id);
// }
// }
//
// public QueryResp(ESSearchResp resp) {
// total = resp.getHits().getTotal();
// productIds = new ArrayList<>();
// for (HitResult hitResult : resp.getHits().getHits()) {
// productIds.add(hitResult.get_source().getId());
// }
// }
//
// public Long getTotal() {
// return total;
// }
//
// public void setTotal(Long total) {
// this.total = total;
// }
//
// public List<Long> getProductIds() {
// return productIds;
// }
//
// public void setProductIds(List<Long> productIds) {
// this.productIds = productIds;
// }
// }
// Path: elasticservice/src/main/java/elasticsearch/searchservice/SearchServiceImpl.java
import elasticsearch.searchservice.dsl.DSLGenerateService;
import elasticsearch.searchservice.models.CacheSearchService;
import elasticsearch.searchservice.models.QueryParam;
import elasticsearch.searchservice.models.QueryResp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
package elasticsearch.searchservice;
/**
* Created by i311352 on 5/2/2017.
*/
@Service
public class SearchServiceImpl implements SearchService {
private static final Logger logger = LoggerFactory.getLogger(SearchServiceImpl.class);
@Autowired
private CacheSearchService cacheSearchService;
@Autowired
| private DSLGenerateService dslGenerateService;
|
compasses/elastic-rabbitmq | elasticservice/src/main/java/elasticsearch/searchservice/SearchServiceImpl.java | // Path: elasticservice/src/main/java/elasticsearch/searchservice/dsl/DSLGenerateService.java
// @Service
// public interface DSLGenerateService {
// String fromQueryParam(QueryParam param);
// }
//
// Path: elasticservice/src/main/java/elasticsearch/searchservice/models/CacheSearchService.java
// @Service
// public interface CacheSearchService {
// QueryResp query(String body);
// Integer count(String body);
// }
//
// Path: elasticservice/src/main/java/elasticsearch/searchservice/models/QueryParam.java
// public class QueryParam {
// private List<Meta> filter;
// private Collection collection;
// private String orderByField;
// private String orderByOrder;
// private Long channelId;
// private Integer pageSize;
// private Integer offSet;
// private Boolean isCount = Boolean.FALSE;
//
// public List<Meta> getFilter() {
// return filter;
// }
//
// public void setFilter(List<Meta> filter) {
// this.filter = filter;
// }
//
// public Collection getCollection() {
// return collection;
// }
//
// public void setCollection(Collection collection) {
// this.collection = collection;
// }
//
// public String getOrderByField() {
// return orderByField;
// }
//
// public void setOrderByField(String orderByField) {
// this.orderByField = orderByField;
// }
//
// public String getOrderByOrder() {
// return orderByOrder;
// }
//
// public void setOrderByOrder(String orderByOrder) {
// this.orderByOrder = orderByOrder;
// }
//
// public Integer getPageSize() {
// return pageSize;
// }
//
// public void setPageSize(Integer pageSize) {
// this.pageSize = pageSize;
// }
//
// public Integer getOffSet() {
// return offSet;
// }
//
// public void setOffSet(Integer offSet) {
// this.offSet = offSet;
// }
//
// public Long getChannelId() {
// return channelId;
// }
//
// public void setChannelId(Long channelId) {
// this.channelId = channelId;
// }
//
// public Boolean getCount() {
// return isCount;
// }
//
// public void setCount(Boolean count) {
// isCount = count;
// }
// }
//
// Path: elasticservice/src/main/java/elasticsearch/searchservice/models/QueryResp.java
// public class QueryResp {
// Long total;
// List<Long> productIds;
//
// public QueryResp() {
// }
//
// public QueryResp(Long total) {
// this.total = total;
// }
//
// public QueryResp(ESQueryResponse response) {
// total = response.getHit().getTotal();
// productIds = new ArrayList<>();
// for (Hits hitResult : response.getHit().getHits()) {
// JsonObject object = hitResult.getSource();
// Long id = object.get("id").getAsLong();
// productIds.add(id);
// }
// }
//
// public QueryResp(ESSearchResp resp) {
// total = resp.getHits().getTotal();
// productIds = new ArrayList<>();
// for (HitResult hitResult : resp.getHits().getHits()) {
// productIds.add(hitResult.get_source().getId());
// }
// }
//
// public Long getTotal() {
// return total;
// }
//
// public void setTotal(Long total) {
// this.total = total;
// }
//
// public List<Long> getProductIds() {
// return productIds;
// }
//
// public void setProductIds(List<Long> productIds) {
// this.productIds = productIds;
// }
// }
| import elasticsearch.searchservice.dsl.DSLGenerateService;
import elasticsearch.searchservice.models.CacheSearchService;
import elasticsearch.searchservice.models.QueryParam;
import elasticsearch.searchservice.models.QueryResp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
| package elasticsearch.searchservice;
/**
* Created by i311352 on 5/2/2017.
*/
@Service
public class SearchServiceImpl implements SearchService {
private static final Logger logger = LoggerFactory.getLogger(SearchServiceImpl.class);
@Autowired
private CacheSearchService cacheSearchService;
@Autowired
private DSLGenerateService dslGenerateService;
@Override
| // Path: elasticservice/src/main/java/elasticsearch/searchservice/dsl/DSLGenerateService.java
// @Service
// public interface DSLGenerateService {
// String fromQueryParam(QueryParam param);
// }
//
// Path: elasticservice/src/main/java/elasticsearch/searchservice/models/CacheSearchService.java
// @Service
// public interface CacheSearchService {
// QueryResp query(String body);
// Integer count(String body);
// }
//
// Path: elasticservice/src/main/java/elasticsearch/searchservice/models/QueryParam.java
// public class QueryParam {
// private List<Meta> filter;
// private Collection collection;
// private String orderByField;
// private String orderByOrder;
// private Long channelId;
// private Integer pageSize;
// private Integer offSet;
// private Boolean isCount = Boolean.FALSE;
//
// public List<Meta> getFilter() {
// return filter;
// }
//
// public void setFilter(List<Meta> filter) {
// this.filter = filter;
// }
//
// public Collection getCollection() {
// return collection;
// }
//
// public void setCollection(Collection collection) {
// this.collection = collection;
// }
//
// public String getOrderByField() {
// return orderByField;
// }
//
// public void setOrderByField(String orderByField) {
// this.orderByField = orderByField;
// }
//
// public String getOrderByOrder() {
// return orderByOrder;
// }
//
// public void setOrderByOrder(String orderByOrder) {
// this.orderByOrder = orderByOrder;
// }
//
// public Integer getPageSize() {
// return pageSize;
// }
//
// public void setPageSize(Integer pageSize) {
// this.pageSize = pageSize;
// }
//
// public Integer getOffSet() {
// return offSet;
// }
//
// public void setOffSet(Integer offSet) {
// this.offSet = offSet;
// }
//
// public Long getChannelId() {
// return channelId;
// }
//
// public void setChannelId(Long channelId) {
// this.channelId = channelId;
// }
//
// public Boolean getCount() {
// return isCount;
// }
//
// public void setCount(Boolean count) {
// isCount = count;
// }
// }
//
// Path: elasticservice/src/main/java/elasticsearch/searchservice/models/QueryResp.java
// public class QueryResp {
// Long total;
// List<Long> productIds;
//
// public QueryResp() {
// }
//
// public QueryResp(Long total) {
// this.total = total;
// }
//
// public QueryResp(ESQueryResponse response) {
// total = response.getHit().getTotal();
// productIds = new ArrayList<>();
// for (Hits hitResult : response.getHit().getHits()) {
// JsonObject object = hitResult.getSource();
// Long id = object.get("id").getAsLong();
// productIds.add(id);
// }
// }
//
// public QueryResp(ESSearchResp resp) {
// total = resp.getHits().getTotal();
// productIds = new ArrayList<>();
// for (HitResult hitResult : resp.getHits().getHits()) {
// productIds.add(hitResult.get_source().getId());
// }
// }
//
// public Long getTotal() {
// return total;
// }
//
// public void setTotal(Long total) {
// this.total = total;
// }
//
// public List<Long> getProductIds() {
// return productIds;
// }
//
// public void setProductIds(List<Long> productIds) {
// this.productIds = productIds;
// }
// }
// Path: elasticservice/src/main/java/elasticsearch/searchservice/SearchServiceImpl.java
import elasticsearch.searchservice.dsl.DSLGenerateService;
import elasticsearch.searchservice.models.CacheSearchService;
import elasticsearch.searchservice.models.QueryParam;
import elasticsearch.searchservice.models.QueryResp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
package elasticsearch.searchservice;
/**
* Created by i311352 on 5/2/2017.
*/
@Service
public class SearchServiceImpl implements SearchService {
private static final Logger logger = LoggerFactory.getLogger(SearchServiceImpl.class);
@Autowired
private CacheSearchService cacheSearchService;
@Autowired
private DSLGenerateService dslGenerateService;
@Override
| public QueryResp doCount(QueryParam queryFromPHP) {
|
compasses/elastic-rabbitmq | elasticservice/src/main/java/elasticsearch/searchservice/SearchServiceImpl.java | // Path: elasticservice/src/main/java/elasticsearch/searchservice/dsl/DSLGenerateService.java
// @Service
// public interface DSLGenerateService {
// String fromQueryParam(QueryParam param);
// }
//
// Path: elasticservice/src/main/java/elasticsearch/searchservice/models/CacheSearchService.java
// @Service
// public interface CacheSearchService {
// QueryResp query(String body);
// Integer count(String body);
// }
//
// Path: elasticservice/src/main/java/elasticsearch/searchservice/models/QueryParam.java
// public class QueryParam {
// private List<Meta> filter;
// private Collection collection;
// private String orderByField;
// private String orderByOrder;
// private Long channelId;
// private Integer pageSize;
// private Integer offSet;
// private Boolean isCount = Boolean.FALSE;
//
// public List<Meta> getFilter() {
// return filter;
// }
//
// public void setFilter(List<Meta> filter) {
// this.filter = filter;
// }
//
// public Collection getCollection() {
// return collection;
// }
//
// public void setCollection(Collection collection) {
// this.collection = collection;
// }
//
// public String getOrderByField() {
// return orderByField;
// }
//
// public void setOrderByField(String orderByField) {
// this.orderByField = orderByField;
// }
//
// public String getOrderByOrder() {
// return orderByOrder;
// }
//
// public void setOrderByOrder(String orderByOrder) {
// this.orderByOrder = orderByOrder;
// }
//
// public Integer getPageSize() {
// return pageSize;
// }
//
// public void setPageSize(Integer pageSize) {
// this.pageSize = pageSize;
// }
//
// public Integer getOffSet() {
// return offSet;
// }
//
// public void setOffSet(Integer offSet) {
// this.offSet = offSet;
// }
//
// public Long getChannelId() {
// return channelId;
// }
//
// public void setChannelId(Long channelId) {
// this.channelId = channelId;
// }
//
// public Boolean getCount() {
// return isCount;
// }
//
// public void setCount(Boolean count) {
// isCount = count;
// }
// }
//
// Path: elasticservice/src/main/java/elasticsearch/searchservice/models/QueryResp.java
// public class QueryResp {
// Long total;
// List<Long> productIds;
//
// public QueryResp() {
// }
//
// public QueryResp(Long total) {
// this.total = total;
// }
//
// public QueryResp(ESQueryResponse response) {
// total = response.getHit().getTotal();
// productIds = new ArrayList<>();
// for (Hits hitResult : response.getHit().getHits()) {
// JsonObject object = hitResult.getSource();
// Long id = object.get("id").getAsLong();
// productIds.add(id);
// }
// }
//
// public QueryResp(ESSearchResp resp) {
// total = resp.getHits().getTotal();
// productIds = new ArrayList<>();
// for (HitResult hitResult : resp.getHits().getHits()) {
// productIds.add(hitResult.get_source().getId());
// }
// }
//
// public Long getTotal() {
// return total;
// }
//
// public void setTotal(Long total) {
// this.total = total;
// }
//
// public List<Long> getProductIds() {
// return productIds;
// }
//
// public void setProductIds(List<Long> productIds) {
// this.productIds = productIds;
// }
// }
| import elasticsearch.searchservice.dsl.DSLGenerateService;
import elasticsearch.searchservice.models.CacheSearchService;
import elasticsearch.searchservice.models.QueryParam;
import elasticsearch.searchservice.models.QueryResp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
| package elasticsearch.searchservice;
/**
* Created by i311352 on 5/2/2017.
*/
@Service
public class SearchServiceImpl implements SearchService {
private static final Logger logger = LoggerFactory.getLogger(SearchServiceImpl.class);
@Autowired
private CacheSearchService cacheSearchService;
@Autowired
private DSLGenerateService dslGenerateService;
@Override
| // Path: elasticservice/src/main/java/elasticsearch/searchservice/dsl/DSLGenerateService.java
// @Service
// public interface DSLGenerateService {
// String fromQueryParam(QueryParam param);
// }
//
// Path: elasticservice/src/main/java/elasticsearch/searchservice/models/CacheSearchService.java
// @Service
// public interface CacheSearchService {
// QueryResp query(String body);
// Integer count(String body);
// }
//
// Path: elasticservice/src/main/java/elasticsearch/searchservice/models/QueryParam.java
// public class QueryParam {
// private List<Meta> filter;
// private Collection collection;
// private String orderByField;
// private String orderByOrder;
// private Long channelId;
// private Integer pageSize;
// private Integer offSet;
// private Boolean isCount = Boolean.FALSE;
//
// public List<Meta> getFilter() {
// return filter;
// }
//
// public void setFilter(List<Meta> filter) {
// this.filter = filter;
// }
//
// public Collection getCollection() {
// return collection;
// }
//
// public void setCollection(Collection collection) {
// this.collection = collection;
// }
//
// public String getOrderByField() {
// return orderByField;
// }
//
// public void setOrderByField(String orderByField) {
// this.orderByField = orderByField;
// }
//
// public String getOrderByOrder() {
// return orderByOrder;
// }
//
// public void setOrderByOrder(String orderByOrder) {
// this.orderByOrder = orderByOrder;
// }
//
// public Integer getPageSize() {
// return pageSize;
// }
//
// public void setPageSize(Integer pageSize) {
// this.pageSize = pageSize;
// }
//
// public Integer getOffSet() {
// return offSet;
// }
//
// public void setOffSet(Integer offSet) {
// this.offSet = offSet;
// }
//
// public Long getChannelId() {
// return channelId;
// }
//
// public void setChannelId(Long channelId) {
// this.channelId = channelId;
// }
//
// public Boolean getCount() {
// return isCount;
// }
//
// public void setCount(Boolean count) {
// isCount = count;
// }
// }
//
// Path: elasticservice/src/main/java/elasticsearch/searchservice/models/QueryResp.java
// public class QueryResp {
// Long total;
// List<Long> productIds;
//
// public QueryResp() {
// }
//
// public QueryResp(Long total) {
// this.total = total;
// }
//
// public QueryResp(ESQueryResponse response) {
// total = response.getHit().getTotal();
// productIds = new ArrayList<>();
// for (Hits hitResult : response.getHit().getHits()) {
// JsonObject object = hitResult.getSource();
// Long id = object.get("id").getAsLong();
// productIds.add(id);
// }
// }
//
// public QueryResp(ESSearchResp resp) {
// total = resp.getHits().getTotal();
// productIds = new ArrayList<>();
// for (HitResult hitResult : resp.getHits().getHits()) {
// productIds.add(hitResult.get_source().getId());
// }
// }
//
// public Long getTotal() {
// return total;
// }
//
// public void setTotal(Long total) {
// this.total = total;
// }
//
// public List<Long> getProductIds() {
// return productIds;
// }
//
// public void setProductIds(List<Long> productIds) {
// this.productIds = productIds;
// }
// }
// Path: elasticservice/src/main/java/elasticsearch/searchservice/SearchServiceImpl.java
import elasticsearch.searchservice.dsl.DSLGenerateService;
import elasticsearch.searchservice.models.CacheSearchService;
import elasticsearch.searchservice.models.QueryParam;
import elasticsearch.searchservice.models.QueryResp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
package elasticsearch.searchservice;
/**
* Created by i311352 on 5/2/2017.
*/
@Service
public class SearchServiceImpl implements SearchService {
private static final Logger logger = LoggerFactory.getLogger(SearchServiceImpl.class);
@Autowired
private CacheSearchService cacheSearchService;
@Autowired
private DSLGenerateService dslGenerateService;
@Override
| public QueryResp doCount(QueryParam queryFromPHP) {
|
compasses/elastic-rabbitmq | netty-http/src/main/java/querydsl/TemplateGenerator.java | // Path: netty-http/src/main/java/http/elasticaction/SearchDSL.java
// @FunctionalInterface
// public interface SearchDSL<R> {
// R getDSL();
// }
//
// Path: netty-http/src/main/java/http/message/QueryMeta.java
// public class QueryMeta {
//
// private String orderBy;
// private HashMap<String, String> filters = new HashMap<String, String>();
//
// public HashMap addMeta(String type, String value) {
// filters.put(type, value);
// return filters;
// }
//
// public String getOrderBy() {
// return orderBy;
// }
//
// public void setOrderBy(String orderBy) {
// this.orderBy = orderBy;
// }
//
// public HashMap<String, String> getFilters() {
// return filters;
// }
//
// public void setFilters(HashMap<String, String> filters) {
// this.filters = filters;
// }
//
// @Override
// public String toString() {
// return "QueryMeta{" +
// "orderBy='" + orderBy + '\'' +
// ", filters=" + filters +
// '}';
// }
// }
| import http.elasticaction.SearchDSL;
import http.message.QueryMeta;
import org.jtwig.JtwigModel;
import org.jtwig.JtwigTemplate;
import org.jtwig.environment.DefaultEnvironmentConfiguration;
import org.jtwig.environment.Environment;
import org.jtwig.environment.EnvironmentConfiguration;
import org.jtwig.environment.EnvironmentFactory;
import org.jtwig.resource.reference.ResourceReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
| package querydsl;
/**
* Created by I311352 on 3/8/2017.
*/
public class TemplateGenerator implements SearchDSL<String> {
private final static Logger logger = LoggerFactory.getLogger(TemplateGenerator.class);
| // Path: netty-http/src/main/java/http/elasticaction/SearchDSL.java
// @FunctionalInterface
// public interface SearchDSL<R> {
// R getDSL();
// }
//
// Path: netty-http/src/main/java/http/message/QueryMeta.java
// public class QueryMeta {
//
// private String orderBy;
// private HashMap<String, String> filters = new HashMap<String, String>();
//
// public HashMap addMeta(String type, String value) {
// filters.put(type, value);
// return filters;
// }
//
// public String getOrderBy() {
// return orderBy;
// }
//
// public void setOrderBy(String orderBy) {
// this.orderBy = orderBy;
// }
//
// public HashMap<String, String> getFilters() {
// return filters;
// }
//
// public void setFilters(HashMap<String, String> filters) {
// this.filters = filters;
// }
//
// @Override
// public String toString() {
// return "QueryMeta{" +
// "orderBy='" + orderBy + '\'' +
// ", filters=" + filters +
// '}';
// }
// }
// Path: netty-http/src/main/java/querydsl/TemplateGenerator.java
import http.elasticaction.SearchDSL;
import http.message.QueryMeta;
import org.jtwig.JtwigModel;
import org.jtwig.JtwigTemplate;
import org.jtwig.environment.DefaultEnvironmentConfiguration;
import org.jtwig.environment.Environment;
import org.jtwig.environment.EnvironmentConfiguration;
import org.jtwig.environment.EnvironmentFactory;
import org.jtwig.resource.reference.ResourceReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
package querydsl;
/**
* Created by I311352 on 3/8/2017.
*/
public class TemplateGenerator implements SearchDSL<String> {
private final static Logger logger = LoggerFactory.getLogger(TemplateGenerator.class);
| private QueryMeta meta;
|
compasses/elastic-rabbitmq | generatedata/src/main/java/initdata/publish/MessagePublishService.java | // Path: generatedata/src/main/java/initdata/publish/model/Messages.java
// public class Messages {
// private Map<String, String> messageHeader;
// private List<MessagesDef> messages;
// public Map<String, String> getMessageHeader() {
// return messageHeader;
// }
//
// public void setMessageHeader(Map<String, String> messageHeader) {
// this.messageHeader = messageHeader;
// }
//
// public List<MessagesDef> getMessages() {
// return messages;
// }
//
// public void setMessages(List<MessagesDef> messages) {
// this.messages = messages;
// }
//
// class MessageHeader {
// @SerializedName("X-User-ID")
// private Long userId;
// @SerializedName("X-Employee-ID")
// private Long employeeId;
// @SerializedName("X-Tenant-ID")
// private Long tenantId;
//
// public Long getUserId() {
// return userId;
// }
//
// public void setUserId(Long userId) {
// this.userId = userId;
// }
//
// public Long getEmployeeId() {
// return employeeId;
// }
//
// public void setEmployeeId(Long employeeId) {
// this.employeeId = employeeId;
// }
//
// public Long getTenantId() {
// return tenantId;
// }
//
// public void setTenantId(Long tenantId) {
// this.tenantId = tenantId;
// }
//
// @Override
// public String toString() {
// return "MessageHeader{" +
// "userId=" + userId +
// ", employeeId=" + employeeId +
// ", tenantId=" + tenantId +
// '}';
// }
// }
// }
| import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import initdata.publish.model.Messages;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
| package initdata.publish;
/**
* Created by I311352 on 11/23/2016.
*/
@Service
public class MessagePublishService {
private static final Logger logger = Logger.getLogger(MessagePublishService.class);
private static final String EXCHANGE_NAME = "light-model-batch";
private static boolean USE_DEFAULT = true;
private static final String DEFAULT_RABBIT_PROPERTIES= "/rabbit/rabbitmq.properties";
private static final String DEFAULT_MESSAGE_SOURCE = "/messages/source.json";
private Channel channel;
private String rabbitProperties;
private String messageSource;
public MessagePublishService() {
this.rabbitProperties = DEFAULT_RABBIT_PROPERTIES;
this.messageSource = DEFAULT_MESSAGE_SOURCE;
}
public void publish() {
logger.info("Publish Configuration: rabbit.cfg:" + this.rabbitProperties +
" message source: " + this.messageSource);
if (!createChannel()) {
logger.error("Channel Create Failed, Do Nothing");
return;
}
logger.info("Creaet RabbitMQ Channel Success, Start to publish message");
try {
| // Path: generatedata/src/main/java/initdata/publish/model/Messages.java
// public class Messages {
// private Map<String, String> messageHeader;
// private List<MessagesDef> messages;
// public Map<String, String> getMessageHeader() {
// return messageHeader;
// }
//
// public void setMessageHeader(Map<String, String> messageHeader) {
// this.messageHeader = messageHeader;
// }
//
// public List<MessagesDef> getMessages() {
// return messages;
// }
//
// public void setMessages(List<MessagesDef> messages) {
// this.messages = messages;
// }
//
// class MessageHeader {
// @SerializedName("X-User-ID")
// private Long userId;
// @SerializedName("X-Employee-ID")
// private Long employeeId;
// @SerializedName("X-Tenant-ID")
// private Long tenantId;
//
// public Long getUserId() {
// return userId;
// }
//
// public void setUserId(Long userId) {
// this.userId = userId;
// }
//
// public Long getEmployeeId() {
// return employeeId;
// }
//
// public void setEmployeeId(Long employeeId) {
// this.employeeId = employeeId;
// }
//
// public Long getTenantId() {
// return tenantId;
// }
//
// public void setTenantId(Long tenantId) {
// this.tenantId = tenantId;
// }
//
// @Override
// public String toString() {
// return "MessageHeader{" +
// "userId=" + userId +
// ", employeeId=" + employeeId +
// ", tenantId=" + tenantId +
// '}';
// }
// }
// }
// Path: generatedata/src/main/java/initdata/publish/MessagePublishService.java
import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import initdata.publish.model.Messages;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
package initdata.publish;
/**
* Created by I311352 on 11/23/2016.
*/
@Service
public class MessagePublishService {
private static final Logger logger = Logger.getLogger(MessagePublishService.class);
private static final String EXCHANGE_NAME = "light-model-batch";
private static boolean USE_DEFAULT = true;
private static final String DEFAULT_RABBIT_PROPERTIES= "/rabbit/rabbitmq.properties";
private static final String DEFAULT_MESSAGE_SOURCE = "/messages/source.json";
private Channel channel;
private String rabbitProperties;
private String messageSource;
public MessagePublishService() {
this.rabbitProperties = DEFAULT_RABBIT_PROPERTIES;
this.messageSource = DEFAULT_MESSAGE_SOURCE;
}
public void publish() {
logger.info("Publish Configuration: rabbit.cfg:" + this.rabbitProperties +
" message source: " + this.messageSource);
if (!createChannel()) {
logger.error("Channel Create Failed, Do Nothing");
return;
}
logger.info("Creaet RabbitMQ Channel Success, Start to publish message");
try {
| Messages messages = loadMessages();
|
compasses/elastic-rabbitmq | elasticservice/src/main/java/elasticsearch/esapi/HotDocumentService.java | // Path: elasticservice/src/main/java/elasticsearch/esapi/resp/ESGetByIdResponse.java
// public class ESGetByIdResponse extends ESBaseResponse {
// private Boolean found;
// @SerializedName("_source")
// private JsonObject object;
//
// public Boolean getFound() {
// return found;
// }
//
// public void setFound(Boolean found) {
// this.found = found;
// }
//
// public JsonObject getObject() {
// return object;
// }
//
// public void setObject(JsonObject object) {
// this.object = object;
// }
//
// @Override
// public String toString() {
// return super.toString() + "ESGetByIdResponse{" +
// "found=" + found +
// ", object=" + object +
// '}';
// }
// }
//
// Path: elasticservice/src/main/java/elasticsearch/esapi/resp/ESSaveResponse.java
// public class ESSaveResponse extends ESBaseResponse {
// protected Boolean created;
// @SerializedName("_shards")
// protected JsonObject shards;
//
// public Boolean getCreated() {
// return created;
// }
//
// public void setCreated(Boolean created) {
// this.created = created;
// }
//
// public JsonObject getShards() {
// return shards;
// }
//
// public void setShards(JsonObject shards) {
// this.shards = shards;
// }
// }
//
// Path: elasticservice/src/main/java/elasticsearch/exception/ElasticVersionConflictException.java
// public class ElasticVersionConflictException extends RuntimeException {
// public ElasticVersionConflictException(String message) {
// super(message);
// }
//
// public ElasticVersionConflictException(String message, Throwable cause) {
// super(message, cause);
// }
// }
| import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import elasticsearch.esapi.resp.ESGetByIdResponse;
import elasticsearch.esapi.resp.ESSaveResponse;
import elasticsearch.exception.ElasticVersionConflictException;
import org.apache.commons.lang3.time.StopWatch;
import org.apache.http.HttpEntity;
import org.apache.http.entity.StringEntity;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.metrics.CounterService;
import org.springframework.boot.actuate.metrics.GaugeService;
import org.springframework.stereotype.Component;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.BiFunction;
| package elasticsearch.esapi;
/**
* Created by I311352 on 10/25/2016.
*/
/**
* Some document maybe processed by multi-thread, need take care for update conflict
* or override
*/
@Component
public class HotDocumentService {
private final static Logger logger = Logger.getLogger(HotDocumentService.class);
@Autowired
private DocumentService documentService;
@Autowired
private CounterService counterService;
@Autowired
private GaugeService gaugeService;
/**
* @param index
* @param type
* @param sourceId
* @param param depends on have the key of version
* @param newObj
* @param f ConflictHandleFunction
* @return
*/
| // Path: elasticservice/src/main/java/elasticsearch/esapi/resp/ESGetByIdResponse.java
// public class ESGetByIdResponse extends ESBaseResponse {
// private Boolean found;
// @SerializedName("_source")
// private JsonObject object;
//
// public Boolean getFound() {
// return found;
// }
//
// public void setFound(Boolean found) {
// this.found = found;
// }
//
// public JsonObject getObject() {
// return object;
// }
//
// public void setObject(JsonObject object) {
// this.object = object;
// }
//
// @Override
// public String toString() {
// return super.toString() + "ESGetByIdResponse{" +
// "found=" + found +
// ", object=" + object +
// '}';
// }
// }
//
// Path: elasticservice/src/main/java/elasticsearch/esapi/resp/ESSaveResponse.java
// public class ESSaveResponse extends ESBaseResponse {
// protected Boolean created;
// @SerializedName("_shards")
// protected JsonObject shards;
//
// public Boolean getCreated() {
// return created;
// }
//
// public void setCreated(Boolean created) {
// this.created = created;
// }
//
// public JsonObject getShards() {
// return shards;
// }
//
// public void setShards(JsonObject shards) {
// this.shards = shards;
// }
// }
//
// Path: elasticservice/src/main/java/elasticsearch/exception/ElasticVersionConflictException.java
// public class ElasticVersionConflictException extends RuntimeException {
// public ElasticVersionConflictException(String message) {
// super(message);
// }
//
// public ElasticVersionConflictException(String message, Throwable cause) {
// super(message, cause);
// }
// }
// Path: elasticservice/src/main/java/elasticsearch/esapi/HotDocumentService.java
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import elasticsearch.esapi.resp.ESGetByIdResponse;
import elasticsearch.esapi.resp.ESSaveResponse;
import elasticsearch.exception.ElasticVersionConflictException;
import org.apache.commons.lang3.time.StopWatch;
import org.apache.http.HttpEntity;
import org.apache.http.entity.StringEntity;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.metrics.CounterService;
import org.springframework.boot.actuate.metrics.GaugeService;
import org.springframework.stereotype.Component;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.BiFunction;
package elasticsearch.esapi;
/**
* Created by I311352 on 10/25/2016.
*/
/**
* Some document maybe processed by multi-thread, need take care for update conflict
* or override
*/
@Component
public class HotDocumentService {
private final static Logger logger = Logger.getLogger(HotDocumentService.class);
@Autowired
private DocumentService documentService;
@Autowired
private CounterService counterService;
@Autowired
private GaugeService gaugeService;
/**
* @param index
* @param type
* @param sourceId
* @param param depends on have the key of version
* @param newObj
* @param f ConflictHandleFunction
* @return
*/
| public ESSaveResponse update(String index, String type, Long sourceId, HashMap<String, String> param,
|
compasses/elastic-rabbitmq | elasticservice/src/main/java/elasticsearch/esapi/HotDocumentService.java | // Path: elasticservice/src/main/java/elasticsearch/esapi/resp/ESGetByIdResponse.java
// public class ESGetByIdResponse extends ESBaseResponse {
// private Boolean found;
// @SerializedName("_source")
// private JsonObject object;
//
// public Boolean getFound() {
// return found;
// }
//
// public void setFound(Boolean found) {
// this.found = found;
// }
//
// public JsonObject getObject() {
// return object;
// }
//
// public void setObject(JsonObject object) {
// this.object = object;
// }
//
// @Override
// public String toString() {
// return super.toString() + "ESGetByIdResponse{" +
// "found=" + found +
// ", object=" + object +
// '}';
// }
// }
//
// Path: elasticservice/src/main/java/elasticsearch/esapi/resp/ESSaveResponse.java
// public class ESSaveResponse extends ESBaseResponse {
// protected Boolean created;
// @SerializedName("_shards")
// protected JsonObject shards;
//
// public Boolean getCreated() {
// return created;
// }
//
// public void setCreated(Boolean created) {
// this.created = created;
// }
//
// public JsonObject getShards() {
// return shards;
// }
//
// public void setShards(JsonObject shards) {
// this.shards = shards;
// }
// }
//
// Path: elasticservice/src/main/java/elasticsearch/exception/ElasticVersionConflictException.java
// public class ElasticVersionConflictException extends RuntimeException {
// public ElasticVersionConflictException(String message) {
// super(message);
// }
//
// public ElasticVersionConflictException(String message, Throwable cause) {
// super(message, cause);
// }
// }
| import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import elasticsearch.esapi.resp.ESGetByIdResponse;
import elasticsearch.esapi.resp.ESSaveResponse;
import elasticsearch.exception.ElasticVersionConflictException;
import org.apache.commons.lang3.time.StopWatch;
import org.apache.http.HttpEntity;
import org.apache.http.entity.StringEntity;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.metrics.CounterService;
import org.springframework.boot.actuate.metrics.GaugeService;
import org.springframework.stereotype.Component;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.BiFunction;
| package elasticsearch.esapi;
/**
* Created by I311352 on 10/25/2016.
*/
/**
* Some document maybe processed by multi-thread, need take care for update conflict
* or override
*/
@Component
public class HotDocumentService {
private final static Logger logger = Logger.getLogger(HotDocumentService.class);
@Autowired
private DocumentService documentService;
@Autowired
private CounterService counterService;
@Autowired
private GaugeService gaugeService;
/**
* @param index
* @param type
* @param sourceId
* @param param depends on have the key of version
* @param newObj
* @param f ConflictHandleFunction
* @return
*/
public ESSaveResponse update(String index, String type, Long sourceId, HashMap<String, String> param,
JsonObject newObj, BiFunction<JsonObject, JsonObject, JsonObject> f) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
Status successful = Status.SUCCESS;
try {
//In case the arguments pollute
HashMap<String, String> localParam = new HashMap<>();
if (param != null) {
localParam.putAll(param);
}
if (localParam.get("version") != null && localParam.get("version").equals("-1")) {
localParam.remove("version");
return createSource(index, type, sourceId, localParam, newObj);
} else if (localParam.get("version") != null) {
logger.debug("do update with version" + localParam + " source=" + newObj.toString());
return updateOnInsert(index, type, sourceId, localParam, newObj);
} else {
| // Path: elasticservice/src/main/java/elasticsearch/esapi/resp/ESGetByIdResponse.java
// public class ESGetByIdResponse extends ESBaseResponse {
// private Boolean found;
// @SerializedName("_source")
// private JsonObject object;
//
// public Boolean getFound() {
// return found;
// }
//
// public void setFound(Boolean found) {
// this.found = found;
// }
//
// public JsonObject getObject() {
// return object;
// }
//
// public void setObject(JsonObject object) {
// this.object = object;
// }
//
// @Override
// public String toString() {
// return super.toString() + "ESGetByIdResponse{" +
// "found=" + found +
// ", object=" + object +
// '}';
// }
// }
//
// Path: elasticservice/src/main/java/elasticsearch/esapi/resp/ESSaveResponse.java
// public class ESSaveResponse extends ESBaseResponse {
// protected Boolean created;
// @SerializedName("_shards")
// protected JsonObject shards;
//
// public Boolean getCreated() {
// return created;
// }
//
// public void setCreated(Boolean created) {
// this.created = created;
// }
//
// public JsonObject getShards() {
// return shards;
// }
//
// public void setShards(JsonObject shards) {
// this.shards = shards;
// }
// }
//
// Path: elasticservice/src/main/java/elasticsearch/exception/ElasticVersionConflictException.java
// public class ElasticVersionConflictException extends RuntimeException {
// public ElasticVersionConflictException(String message) {
// super(message);
// }
//
// public ElasticVersionConflictException(String message, Throwable cause) {
// super(message, cause);
// }
// }
// Path: elasticservice/src/main/java/elasticsearch/esapi/HotDocumentService.java
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import elasticsearch.esapi.resp.ESGetByIdResponse;
import elasticsearch.esapi.resp.ESSaveResponse;
import elasticsearch.exception.ElasticVersionConflictException;
import org.apache.commons.lang3.time.StopWatch;
import org.apache.http.HttpEntity;
import org.apache.http.entity.StringEntity;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.metrics.CounterService;
import org.springframework.boot.actuate.metrics.GaugeService;
import org.springframework.stereotype.Component;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.BiFunction;
package elasticsearch.esapi;
/**
* Created by I311352 on 10/25/2016.
*/
/**
* Some document maybe processed by multi-thread, need take care for update conflict
* or override
*/
@Component
public class HotDocumentService {
private final static Logger logger = Logger.getLogger(HotDocumentService.class);
@Autowired
private DocumentService documentService;
@Autowired
private CounterService counterService;
@Autowired
private GaugeService gaugeService;
/**
* @param index
* @param type
* @param sourceId
* @param param depends on have the key of version
* @param newObj
* @param f ConflictHandleFunction
* @return
*/
public ESSaveResponse update(String index, String type, Long sourceId, HashMap<String, String> param,
JsonObject newObj, BiFunction<JsonObject, JsonObject, JsonObject> f) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
Status successful = Status.SUCCESS;
try {
//In case the arguments pollute
HashMap<String, String> localParam = new HashMap<>();
if (param != null) {
localParam.putAll(param);
}
if (localParam.get("version") != null && localParam.get("version").equals("-1")) {
localParam.remove("version");
return createSource(index, type, sourceId, localParam, newObj);
} else if (localParam.get("version") != null) {
logger.debug("do update with version" + localParam + " source=" + newObj.toString());
return updateOnInsert(index, type, sourceId, localParam, newObj);
} else {
| ESGetByIdResponse esResponse = documentService.loadSourceById(index, type, sourceId, localParam);
|
compasses/elastic-rabbitmq | elasticservice/src/main/java/elasticsearch/esapi/HotDocumentService.java | // Path: elasticservice/src/main/java/elasticsearch/esapi/resp/ESGetByIdResponse.java
// public class ESGetByIdResponse extends ESBaseResponse {
// private Boolean found;
// @SerializedName("_source")
// private JsonObject object;
//
// public Boolean getFound() {
// return found;
// }
//
// public void setFound(Boolean found) {
// this.found = found;
// }
//
// public JsonObject getObject() {
// return object;
// }
//
// public void setObject(JsonObject object) {
// this.object = object;
// }
//
// @Override
// public String toString() {
// return super.toString() + "ESGetByIdResponse{" +
// "found=" + found +
// ", object=" + object +
// '}';
// }
// }
//
// Path: elasticservice/src/main/java/elasticsearch/esapi/resp/ESSaveResponse.java
// public class ESSaveResponse extends ESBaseResponse {
// protected Boolean created;
// @SerializedName("_shards")
// protected JsonObject shards;
//
// public Boolean getCreated() {
// return created;
// }
//
// public void setCreated(Boolean created) {
// this.created = created;
// }
//
// public JsonObject getShards() {
// return shards;
// }
//
// public void setShards(JsonObject shards) {
// this.shards = shards;
// }
// }
//
// Path: elasticservice/src/main/java/elasticsearch/exception/ElasticVersionConflictException.java
// public class ElasticVersionConflictException extends RuntimeException {
// public ElasticVersionConflictException(String message) {
// super(message);
// }
//
// public ElasticVersionConflictException(String message, Throwable cause) {
// super(message, cause);
// }
// }
| import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import elasticsearch.esapi.resp.ESGetByIdResponse;
import elasticsearch.esapi.resp.ESSaveResponse;
import elasticsearch.exception.ElasticVersionConflictException;
import org.apache.commons.lang3.time.StopWatch;
import org.apache.http.HttpEntity;
import org.apache.http.entity.StringEntity;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.metrics.CounterService;
import org.springframework.boot.actuate.metrics.GaugeService;
import org.springframework.stereotype.Component;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.BiFunction;
| */
public ESSaveResponse update(String index, String type, Long sourceId, HashMap<String, String> param,
JsonObject newObj, BiFunction<JsonObject, JsonObject, JsonObject> f) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
Status successful = Status.SUCCESS;
try {
//In case the arguments pollute
HashMap<String, String> localParam = new HashMap<>();
if (param != null) {
localParam.putAll(param);
}
if (localParam.get("version") != null && localParam.get("version").equals("-1")) {
localParam.remove("version");
return createSource(index, type, sourceId, localParam, newObj);
} else if (localParam.get("version") != null) {
logger.debug("do update with version" + localParam + " source=" + newObj.toString());
return updateOnInsert(index, type, sourceId, localParam, newObj);
} else {
ESGetByIdResponse esResponse = documentService.loadSourceById(index, type, sourceId, localParam);
if (esResponse == null || esResponse.getFound() == false) {
return createSource(index, type, sourceId, localParam, newObj);
} else {
logger.debug("Retrieval source " + esResponse.toString());
localParam.put("version", esResponse.getVersion().toString());
return updateOnInsert(index, type, sourceId, localParam, newObj);
}
}
| // Path: elasticservice/src/main/java/elasticsearch/esapi/resp/ESGetByIdResponse.java
// public class ESGetByIdResponse extends ESBaseResponse {
// private Boolean found;
// @SerializedName("_source")
// private JsonObject object;
//
// public Boolean getFound() {
// return found;
// }
//
// public void setFound(Boolean found) {
// this.found = found;
// }
//
// public JsonObject getObject() {
// return object;
// }
//
// public void setObject(JsonObject object) {
// this.object = object;
// }
//
// @Override
// public String toString() {
// return super.toString() + "ESGetByIdResponse{" +
// "found=" + found +
// ", object=" + object +
// '}';
// }
// }
//
// Path: elasticservice/src/main/java/elasticsearch/esapi/resp/ESSaveResponse.java
// public class ESSaveResponse extends ESBaseResponse {
// protected Boolean created;
// @SerializedName("_shards")
// protected JsonObject shards;
//
// public Boolean getCreated() {
// return created;
// }
//
// public void setCreated(Boolean created) {
// this.created = created;
// }
//
// public JsonObject getShards() {
// return shards;
// }
//
// public void setShards(JsonObject shards) {
// this.shards = shards;
// }
// }
//
// Path: elasticservice/src/main/java/elasticsearch/exception/ElasticVersionConflictException.java
// public class ElasticVersionConflictException extends RuntimeException {
// public ElasticVersionConflictException(String message) {
// super(message);
// }
//
// public ElasticVersionConflictException(String message, Throwable cause) {
// super(message, cause);
// }
// }
// Path: elasticservice/src/main/java/elasticsearch/esapi/HotDocumentService.java
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import elasticsearch.esapi.resp.ESGetByIdResponse;
import elasticsearch.esapi.resp.ESSaveResponse;
import elasticsearch.exception.ElasticVersionConflictException;
import org.apache.commons.lang3.time.StopWatch;
import org.apache.http.HttpEntity;
import org.apache.http.entity.StringEntity;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.metrics.CounterService;
import org.springframework.boot.actuate.metrics.GaugeService;
import org.springframework.stereotype.Component;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.BiFunction;
*/
public ESSaveResponse update(String index, String type, Long sourceId, HashMap<String, String> param,
JsonObject newObj, BiFunction<JsonObject, JsonObject, JsonObject> f) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
Status successful = Status.SUCCESS;
try {
//In case the arguments pollute
HashMap<String, String> localParam = new HashMap<>();
if (param != null) {
localParam.putAll(param);
}
if (localParam.get("version") != null && localParam.get("version").equals("-1")) {
localParam.remove("version");
return createSource(index, type, sourceId, localParam, newObj);
} else if (localParam.get("version") != null) {
logger.debug("do update with version" + localParam + " source=" + newObj.toString());
return updateOnInsert(index, type, sourceId, localParam, newObj);
} else {
ESGetByIdResponse esResponse = documentService.loadSourceById(index, type, sourceId, localParam);
if (esResponse == null || esResponse.getFound() == false) {
return createSource(index, type, sourceId, localParam, newObj);
} else {
logger.debug("Retrieval source " + esResponse.toString());
localParam.put("version", esResponse.getVersion().toString());
return updateOnInsert(index, type, sourceId, localParam, newObj);
}
}
| } catch (ElasticVersionConflictException e) {
|
compasses/elastic-rabbitmq | netty-http/src/main/java/http/searchcommand/RestCommand.java | // Path: netty-http/src/main/java/http/elasticaction/RestRequest.java
// public class RestRequest {
// }
//
// Path: netty-http/src/main/java/http/elasticaction/SearchDSL.java
// @FunctionalInterface
// public interface SearchDSL<R> {
// R getDSL();
// }
//
// Path: netty-http/src/main/java/http/elasticaction/SearchDSLImpl.java
// public class SearchDSLImpl implements SearchDSL<QueryBuilder> {
//
// private final QueryMeta meta;
//
// public SearchDSLImpl(QueryMeta meta) {
// this.meta = meta;
// }
//
// @Override
// public QueryBuilder getDSL() {
// MatchAllQueryBuilder builders = matchAllQuery();
// return builders;
// }
// }
| import com.netflix.hystrix.*;
import http.elasticaction.RestRequest;
import http.elasticaction.SearchDSL;
import http.elasticaction.SearchDSLImpl;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.entity.StringEntity;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.index.query.QueryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.UUID;
| package http.searchcommand;
/**
* Created by i311352 on 2/16/2017.
*/
public class RestCommand extends HystrixCommand<char[]> {
private static final Logger LOGGER = LoggerFactory.getLogger(RestCommand.class);
private RestClient client;
| // Path: netty-http/src/main/java/http/elasticaction/RestRequest.java
// public class RestRequest {
// }
//
// Path: netty-http/src/main/java/http/elasticaction/SearchDSL.java
// @FunctionalInterface
// public interface SearchDSL<R> {
// R getDSL();
// }
//
// Path: netty-http/src/main/java/http/elasticaction/SearchDSLImpl.java
// public class SearchDSLImpl implements SearchDSL<QueryBuilder> {
//
// private final QueryMeta meta;
//
// public SearchDSLImpl(QueryMeta meta) {
// this.meta = meta;
// }
//
// @Override
// public QueryBuilder getDSL() {
// MatchAllQueryBuilder builders = matchAllQuery();
// return builders;
// }
// }
// Path: netty-http/src/main/java/http/searchcommand/RestCommand.java
import com.netflix.hystrix.*;
import http.elasticaction.RestRequest;
import http.elasticaction.SearchDSL;
import http.elasticaction.SearchDSLImpl;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.entity.StringEntity;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.index.query.QueryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.UUID;
package http.searchcommand;
/**
* Created by i311352 on 2/16/2017.
*/
public class RestCommand extends HystrixCommand<char[]> {
private static final Logger LOGGER = LoggerFactory.getLogger(RestCommand.class);
private RestClient client;
| private SearchDSL restRequest;
|
compasses/elastic-rabbitmq | app/src/main/java/ElasticRabbitApp.java | // Path: netty-http/src/main/java/http/Config.java
// public class Config {
// public Integer getBacklog() {
// return 1280;
// }
//
// public Integer getPort() {
// return 9999;
// }
//
// public Integer getClientMaxBodySize() {
// return 1024*1024*10;
// }
//
// public Integer getTaskThreadPoolSize() {
// return 0;
// }
//
// public Integer getEventLoopThreadCount() {
// return 10;
// }
// }
//
// Path: rabbitmqservice/src/main/java/rabbitmq/ListenerJobBuilder.java
// public class ListenerJobBuilder {
// // just everything under default
// public static MQListenerAdmin buildMQListenerAdmin(ConfigurableApplicationContext context) {
// MessageListenerProxy listenerProxy = new MessageListenerProxy(new ESMessageListener(context),
// "Elastic_Queue");
// return new MQListenerAdmin(getConnectionFactory(), listenerProxy);
// }
//
// public static ConnectionFactory getConnectionFactory() {
// CachingConnectionFactory connectionFactory = new CachingConnectionFactory("10.128.165.206");
// connectionFactory.setUsername("guest");
// connectionFactory.setPassword("guest");
// return connectionFactory;
// }
// }
//
// Path: rabbitmqservice/src/main/java/rabbitmq/MQListenerAdmin.java
// public class MQListenerAdmin {
// private static final Logger logger = Logger.getLogger(MQListenerAdmin.class);
// private final ConnectionFactory mqFactory;;
// private final RabbitAdmin amqpAdmin;
// private final SimpleMessageListenerContainer container;
// private Boolean startSucceeded = false;
// private Queue queue;
// private final MessageListener listener;
//
// public MQListenerAdmin(ConnectionFactory mqFactory, MessageListener listener) {
// container = new SimpleMessageListenerContainer();
// this.mqFactory = mqFactory;
// amqpAdmin = new RabbitAdmin(mqFactory);
// this.listener = listener;
// }
//
// public void start() {
// declareQueue();
//
// container.setAcknowledgeMode(AcknowledgeMode.AUTO);
// container.setAutoStartup(false);
// container.setChannelTransacted(false);
// container.setConcurrentConsumers(MQParsedConfig.conncurrentConsumers);
// container.setConnectionFactory(mqFactory);
// container.setPrefetchCount(1);
// container.setQueueNames(queue.getName());
// // container.setTransactionManager(new
// // RabbitTransactionManager(mqFactory));
// container.setMessageListener(listener);
// container.setDefaultRequeueRejected(true);
// container.start();
// startSucceeded = true;
// }
//
// private void declareQueue() {
// amqpAdmin.declareExchange(new TopicExchange(MQParsedConfig.exchangeName));
// queue = new Queue("ElasticRabbit");
// amqpAdmin.declareQueue(queue);
//
// logger.info("Using queue name:" + queue.getName());
//
// String[] routingKeys = MQParsedConfig.routingKeys;
// for (String routingKey : routingKeys) {
// amqpAdmin.declareBinding(new Binding(queue.getName(),
// Binding.DestinationType.QUEUE, MQParsedConfig.exchangeName, routingKey, null));
// }
// }
//
// }
| import http.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.Banner;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import rabbitmq.ListenerJobBuilder;
import rabbitmq.MQListenerAdmin;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReadWriteLock;
|
/**
* Created by I311352 on 12/28/2016.
*/
@SpringBootConfiguration
@EnableAutoConfiguration
@EnableHystrix
@EnableCircuitBreaker
@EnableHystrixDashboard
@ComponentScan({ "elasticsearch","rabbitmq", "sync"})
public class ElasticRabbitApp implements CommandLineRunner {
@Autowired
private ConfigurableApplicationContext context;
public static void main(String[] args) {
SpringApplication.run(ElasticRabbitApp.class, args);
}
@Override
public void run(String... args) throws Exception {
| // Path: netty-http/src/main/java/http/Config.java
// public class Config {
// public Integer getBacklog() {
// return 1280;
// }
//
// public Integer getPort() {
// return 9999;
// }
//
// public Integer getClientMaxBodySize() {
// return 1024*1024*10;
// }
//
// public Integer getTaskThreadPoolSize() {
// return 0;
// }
//
// public Integer getEventLoopThreadCount() {
// return 10;
// }
// }
//
// Path: rabbitmqservice/src/main/java/rabbitmq/ListenerJobBuilder.java
// public class ListenerJobBuilder {
// // just everything under default
// public static MQListenerAdmin buildMQListenerAdmin(ConfigurableApplicationContext context) {
// MessageListenerProxy listenerProxy = new MessageListenerProxy(new ESMessageListener(context),
// "Elastic_Queue");
// return new MQListenerAdmin(getConnectionFactory(), listenerProxy);
// }
//
// public static ConnectionFactory getConnectionFactory() {
// CachingConnectionFactory connectionFactory = new CachingConnectionFactory("10.128.165.206");
// connectionFactory.setUsername("guest");
// connectionFactory.setPassword("guest");
// return connectionFactory;
// }
// }
//
// Path: rabbitmqservice/src/main/java/rabbitmq/MQListenerAdmin.java
// public class MQListenerAdmin {
// private static final Logger logger = Logger.getLogger(MQListenerAdmin.class);
// private final ConnectionFactory mqFactory;;
// private final RabbitAdmin amqpAdmin;
// private final SimpleMessageListenerContainer container;
// private Boolean startSucceeded = false;
// private Queue queue;
// private final MessageListener listener;
//
// public MQListenerAdmin(ConnectionFactory mqFactory, MessageListener listener) {
// container = new SimpleMessageListenerContainer();
// this.mqFactory = mqFactory;
// amqpAdmin = new RabbitAdmin(mqFactory);
// this.listener = listener;
// }
//
// public void start() {
// declareQueue();
//
// container.setAcknowledgeMode(AcknowledgeMode.AUTO);
// container.setAutoStartup(false);
// container.setChannelTransacted(false);
// container.setConcurrentConsumers(MQParsedConfig.conncurrentConsumers);
// container.setConnectionFactory(mqFactory);
// container.setPrefetchCount(1);
// container.setQueueNames(queue.getName());
// // container.setTransactionManager(new
// // RabbitTransactionManager(mqFactory));
// container.setMessageListener(listener);
// container.setDefaultRequeueRejected(true);
// container.start();
// startSucceeded = true;
// }
//
// private void declareQueue() {
// amqpAdmin.declareExchange(new TopicExchange(MQParsedConfig.exchangeName));
// queue = new Queue("ElasticRabbit");
// amqpAdmin.declareQueue(queue);
//
// logger.info("Using queue name:" + queue.getName());
//
// String[] routingKeys = MQParsedConfig.routingKeys;
// for (String routingKey : routingKeys) {
// amqpAdmin.declareBinding(new Binding(queue.getName(),
// Binding.DestinationType.QUEUE, MQParsedConfig.exchangeName, routingKey, null));
// }
// }
//
// }
// Path: app/src/main/java/ElasticRabbitApp.java
import http.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.Banner;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import rabbitmq.ListenerJobBuilder;
import rabbitmq.MQListenerAdmin;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReadWriteLock;
/**
* Created by I311352 on 12/28/2016.
*/
@SpringBootConfiguration
@EnableAutoConfiguration
@EnableHystrix
@EnableCircuitBreaker
@EnableHystrixDashboard
@ComponentScan({ "elasticsearch","rabbitmq", "sync"})
public class ElasticRabbitApp implements CommandLineRunner {
@Autowired
private ConfigurableApplicationContext context;
public static void main(String[] args) {
SpringApplication.run(ElasticRabbitApp.class, args);
}
@Override
public void run(String... args) throws Exception {
| MQListenerAdmin listenerAdmin = ListenerJobBuilder.buildMQListenerAdmin(context);
|
compasses/elastic-rabbitmq | app/src/main/java/ElasticRabbitApp.java | // Path: netty-http/src/main/java/http/Config.java
// public class Config {
// public Integer getBacklog() {
// return 1280;
// }
//
// public Integer getPort() {
// return 9999;
// }
//
// public Integer getClientMaxBodySize() {
// return 1024*1024*10;
// }
//
// public Integer getTaskThreadPoolSize() {
// return 0;
// }
//
// public Integer getEventLoopThreadCount() {
// return 10;
// }
// }
//
// Path: rabbitmqservice/src/main/java/rabbitmq/ListenerJobBuilder.java
// public class ListenerJobBuilder {
// // just everything under default
// public static MQListenerAdmin buildMQListenerAdmin(ConfigurableApplicationContext context) {
// MessageListenerProxy listenerProxy = new MessageListenerProxy(new ESMessageListener(context),
// "Elastic_Queue");
// return new MQListenerAdmin(getConnectionFactory(), listenerProxy);
// }
//
// public static ConnectionFactory getConnectionFactory() {
// CachingConnectionFactory connectionFactory = new CachingConnectionFactory("10.128.165.206");
// connectionFactory.setUsername("guest");
// connectionFactory.setPassword("guest");
// return connectionFactory;
// }
// }
//
// Path: rabbitmqservice/src/main/java/rabbitmq/MQListenerAdmin.java
// public class MQListenerAdmin {
// private static final Logger logger = Logger.getLogger(MQListenerAdmin.class);
// private final ConnectionFactory mqFactory;;
// private final RabbitAdmin amqpAdmin;
// private final SimpleMessageListenerContainer container;
// private Boolean startSucceeded = false;
// private Queue queue;
// private final MessageListener listener;
//
// public MQListenerAdmin(ConnectionFactory mqFactory, MessageListener listener) {
// container = new SimpleMessageListenerContainer();
// this.mqFactory = mqFactory;
// amqpAdmin = new RabbitAdmin(mqFactory);
// this.listener = listener;
// }
//
// public void start() {
// declareQueue();
//
// container.setAcknowledgeMode(AcknowledgeMode.AUTO);
// container.setAutoStartup(false);
// container.setChannelTransacted(false);
// container.setConcurrentConsumers(MQParsedConfig.conncurrentConsumers);
// container.setConnectionFactory(mqFactory);
// container.setPrefetchCount(1);
// container.setQueueNames(queue.getName());
// // container.setTransactionManager(new
// // RabbitTransactionManager(mqFactory));
// container.setMessageListener(listener);
// container.setDefaultRequeueRejected(true);
// container.start();
// startSucceeded = true;
// }
//
// private void declareQueue() {
// amqpAdmin.declareExchange(new TopicExchange(MQParsedConfig.exchangeName));
// queue = new Queue("ElasticRabbit");
// amqpAdmin.declareQueue(queue);
//
// logger.info("Using queue name:" + queue.getName());
//
// String[] routingKeys = MQParsedConfig.routingKeys;
// for (String routingKey : routingKeys) {
// amqpAdmin.declareBinding(new Binding(queue.getName(),
// Binding.DestinationType.QUEUE, MQParsedConfig.exchangeName, routingKey, null));
// }
// }
//
// }
| import http.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.Banner;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import rabbitmq.ListenerJobBuilder;
import rabbitmq.MQListenerAdmin;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReadWriteLock;
|
/**
* Created by I311352 on 12/28/2016.
*/
@SpringBootConfiguration
@EnableAutoConfiguration
@EnableHystrix
@EnableCircuitBreaker
@EnableHystrixDashboard
@ComponentScan({ "elasticsearch","rabbitmq", "sync"})
public class ElasticRabbitApp implements CommandLineRunner {
@Autowired
private ConfigurableApplicationContext context;
public static void main(String[] args) {
SpringApplication.run(ElasticRabbitApp.class, args);
}
@Override
public void run(String... args) throws Exception {
| // Path: netty-http/src/main/java/http/Config.java
// public class Config {
// public Integer getBacklog() {
// return 1280;
// }
//
// public Integer getPort() {
// return 9999;
// }
//
// public Integer getClientMaxBodySize() {
// return 1024*1024*10;
// }
//
// public Integer getTaskThreadPoolSize() {
// return 0;
// }
//
// public Integer getEventLoopThreadCount() {
// return 10;
// }
// }
//
// Path: rabbitmqservice/src/main/java/rabbitmq/ListenerJobBuilder.java
// public class ListenerJobBuilder {
// // just everything under default
// public static MQListenerAdmin buildMQListenerAdmin(ConfigurableApplicationContext context) {
// MessageListenerProxy listenerProxy = new MessageListenerProxy(new ESMessageListener(context),
// "Elastic_Queue");
// return new MQListenerAdmin(getConnectionFactory(), listenerProxy);
// }
//
// public static ConnectionFactory getConnectionFactory() {
// CachingConnectionFactory connectionFactory = new CachingConnectionFactory("10.128.165.206");
// connectionFactory.setUsername("guest");
// connectionFactory.setPassword("guest");
// return connectionFactory;
// }
// }
//
// Path: rabbitmqservice/src/main/java/rabbitmq/MQListenerAdmin.java
// public class MQListenerAdmin {
// private static final Logger logger = Logger.getLogger(MQListenerAdmin.class);
// private final ConnectionFactory mqFactory;;
// private final RabbitAdmin amqpAdmin;
// private final SimpleMessageListenerContainer container;
// private Boolean startSucceeded = false;
// private Queue queue;
// private final MessageListener listener;
//
// public MQListenerAdmin(ConnectionFactory mqFactory, MessageListener listener) {
// container = new SimpleMessageListenerContainer();
// this.mqFactory = mqFactory;
// amqpAdmin = new RabbitAdmin(mqFactory);
// this.listener = listener;
// }
//
// public void start() {
// declareQueue();
//
// container.setAcknowledgeMode(AcknowledgeMode.AUTO);
// container.setAutoStartup(false);
// container.setChannelTransacted(false);
// container.setConcurrentConsumers(MQParsedConfig.conncurrentConsumers);
// container.setConnectionFactory(mqFactory);
// container.setPrefetchCount(1);
// container.setQueueNames(queue.getName());
// // container.setTransactionManager(new
// // RabbitTransactionManager(mqFactory));
// container.setMessageListener(listener);
// container.setDefaultRequeueRejected(true);
// container.start();
// startSucceeded = true;
// }
//
// private void declareQueue() {
// amqpAdmin.declareExchange(new TopicExchange(MQParsedConfig.exchangeName));
// queue = new Queue("ElasticRabbit");
// amqpAdmin.declareQueue(queue);
//
// logger.info("Using queue name:" + queue.getName());
//
// String[] routingKeys = MQParsedConfig.routingKeys;
// for (String routingKey : routingKeys) {
// amqpAdmin.declareBinding(new Binding(queue.getName(),
// Binding.DestinationType.QUEUE, MQParsedConfig.exchangeName, routingKey, null));
// }
// }
//
// }
// Path: app/src/main/java/ElasticRabbitApp.java
import http.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.Banner;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import rabbitmq.ListenerJobBuilder;
import rabbitmq.MQListenerAdmin;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReadWriteLock;
/**
* Created by I311352 on 12/28/2016.
*/
@SpringBootConfiguration
@EnableAutoConfiguration
@EnableHystrix
@EnableCircuitBreaker
@EnableHystrixDashboard
@ComponentScan({ "elasticsearch","rabbitmq", "sync"})
public class ElasticRabbitApp implements CommandLineRunner {
@Autowired
private ConfigurableApplicationContext context;
public static void main(String[] args) {
SpringApplication.run(ElasticRabbitApp.class, args);
}
@Override
public void run(String... args) throws Exception {
| MQListenerAdmin listenerAdmin = ListenerJobBuilder.buildMQListenerAdmin(context);
|
compasses/elastic-rabbitmq | elasticservice/src/main/java/elasticsearch/esapi/IndexService.java | // Path: elasticservice/src/main/java/elasticsearch/constant/ESConstants.java
// public class ESConstants {
// public static final String STORE_INDEX = "stores";
// public static final String PRODUCT_TYPE = "product";
// public static final String SKU_TYPE = "sku";
// public static final String PRODUCT_PROPERTY = "productproperty";
// public static final String CHANNEL_TYPE = "channels";
// public static final int SNIFFER_INTERVAL = 15000;
// public static final int RESTCLIENT_TIMEOUT = 20000; // 20s
//
//
// public static final Pattern ROUTINGKEY_PATTERN = Pattern.compile("([\\w\\.]+)\\.(\\w+)\\.(\\d+)");
//
// }
| import elasticsearch.constant.ESConstants;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.entity.StringEntity;
import org.apache.log4j.Logger;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Hashtable;
| package elasticsearch.esapi;
/**
* Created by I311352 on 9/30/2016.
*/
@Component
public class IndexService {
| // Path: elasticservice/src/main/java/elasticsearch/constant/ESConstants.java
// public class ESConstants {
// public static final String STORE_INDEX = "stores";
// public static final String PRODUCT_TYPE = "product";
// public static final String SKU_TYPE = "sku";
// public static final String PRODUCT_PROPERTY = "productproperty";
// public static final String CHANNEL_TYPE = "channels";
// public static final int SNIFFER_INTERVAL = 15000;
// public static final int RESTCLIENT_TIMEOUT = 20000; // 20s
//
//
// public static final Pattern ROUTINGKEY_PATTERN = Pattern.compile("([\\w\\.]+)\\.(\\w+)\\.(\\d+)");
//
// }
// Path: elasticservice/src/main/java/elasticsearch/esapi/IndexService.java
import elasticsearch.constant.ESConstants;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.entity.StringEntity;
import org.apache.log4j.Logger;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Hashtable;
package elasticsearch.esapi;
/**
* Created by I311352 on 9/30/2016.
*/
@Component
public class IndexService {
| private static final String CURRENT_INDEX_VERSION = ESConstants.STORE_INDEX + "_v1";
|
compasses/elastic-rabbitmq | elasticservice/src/main/java/elasticsearch/searchservice/SearchService.java | // Path: elasticservice/src/main/java/elasticsearch/searchservice/models/QueryParam.java
// public class QueryParam {
// private List<Meta> filter;
// private Collection collection;
// private String orderByField;
// private String orderByOrder;
// private Long channelId;
// private Integer pageSize;
// private Integer offSet;
// private Boolean isCount = Boolean.FALSE;
//
// public List<Meta> getFilter() {
// return filter;
// }
//
// public void setFilter(List<Meta> filter) {
// this.filter = filter;
// }
//
// public Collection getCollection() {
// return collection;
// }
//
// public void setCollection(Collection collection) {
// this.collection = collection;
// }
//
// public String getOrderByField() {
// return orderByField;
// }
//
// public void setOrderByField(String orderByField) {
// this.orderByField = orderByField;
// }
//
// public String getOrderByOrder() {
// return orderByOrder;
// }
//
// public void setOrderByOrder(String orderByOrder) {
// this.orderByOrder = orderByOrder;
// }
//
// public Integer getPageSize() {
// return pageSize;
// }
//
// public void setPageSize(Integer pageSize) {
// this.pageSize = pageSize;
// }
//
// public Integer getOffSet() {
// return offSet;
// }
//
// public void setOffSet(Integer offSet) {
// this.offSet = offSet;
// }
//
// public Long getChannelId() {
// return channelId;
// }
//
// public void setChannelId(Long channelId) {
// this.channelId = channelId;
// }
//
// public Boolean getCount() {
// return isCount;
// }
//
// public void setCount(Boolean count) {
// isCount = count;
// }
// }
//
// Path: elasticservice/src/main/java/elasticsearch/searchservice/models/QueryResp.java
// public class QueryResp {
// Long total;
// List<Long> productIds;
//
// public QueryResp() {
// }
//
// public QueryResp(Long total) {
// this.total = total;
// }
//
// public QueryResp(ESQueryResponse response) {
// total = response.getHit().getTotal();
// productIds = new ArrayList<>();
// for (Hits hitResult : response.getHit().getHits()) {
// JsonObject object = hitResult.getSource();
// Long id = object.get("id").getAsLong();
// productIds.add(id);
// }
// }
//
// public QueryResp(ESSearchResp resp) {
// total = resp.getHits().getTotal();
// productIds = new ArrayList<>();
// for (HitResult hitResult : resp.getHits().getHits()) {
// productIds.add(hitResult.get_source().getId());
// }
// }
//
// public Long getTotal() {
// return total;
// }
//
// public void setTotal(Long total) {
// this.total = total;
// }
//
// public List<Long> getProductIds() {
// return productIds;
// }
//
// public void setProductIds(List<Long> productIds) {
// this.productIds = productIds;
// }
// }
| import elasticsearch.searchservice.models.QueryParam;
import elasticsearch.searchservice.models.QueryResp;
import org.springframework.stereotype.Service;
| package elasticsearch.searchservice;
/**
* Created by i311352 on 5/2/2017.
*/
@Service
public interface SearchService {
| // Path: elasticservice/src/main/java/elasticsearch/searchservice/models/QueryParam.java
// public class QueryParam {
// private List<Meta> filter;
// private Collection collection;
// private String orderByField;
// private String orderByOrder;
// private Long channelId;
// private Integer pageSize;
// private Integer offSet;
// private Boolean isCount = Boolean.FALSE;
//
// public List<Meta> getFilter() {
// return filter;
// }
//
// public void setFilter(List<Meta> filter) {
// this.filter = filter;
// }
//
// public Collection getCollection() {
// return collection;
// }
//
// public void setCollection(Collection collection) {
// this.collection = collection;
// }
//
// public String getOrderByField() {
// return orderByField;
// }
//
// public void setOrderByField(String orderByField) {
// this.orderByField = orderByField;
// }
//
// public String getOrderByOrder() {
// return orderByOrder;
// }
//
// public void setOrderByOrder(String orderByOrder) {
// this.orderByOrder = orderByOrder;
// }
//
// public Integer getPageSize() {
// return pageSize;
// }
//
// public void setPageSize(Integer pageSize) {
// this.pageSize = pageSize;
// }
//
// public Integer getOffSet() {
// return offSet;
// }
//
// public void setOffSet(Integer offSet) {
// this.offSet = offSet;
// }
//
// public Long getChannelId() {
// return channelId;
// }
//
// public void setChannelId(Long channelId) {
// this.channelId = channelId;
// }
//
// public Boolean getCount() {
// return isCount;
// }
//
// public void setCount(Boolean count) {
// isCount = count;
// }
// }
//
// Path: elasticservice/src/main/java/elasticsearch/searchservice/models/QueryResp.java
// public class QueryResp {
// Long total;
// List<Long> productIds;
//
// public QueryResp() {
// }
//
// public QueryResp(Long total) {
// this.total = total;
// }
//
// public QueryResp(ESQueryResponse response) {
// total = response.getHit().getTotal();
// productIds = new ArrayList<>();
// for (Hits hitResult : response.getHit().getHits()) {
// JsonObject object = hitResult.getSource();
// Long id = object.get("id").getAsLong();
// productIds.add(id);
// }
// }
//
// public QueryResp(ESSearchResp resp) {
// total = resp.getHits().getTotal();
// productIds = new ArrayList<>();
// for (HitResult hitResult : resp.getHits().getHits()) {
// productIds.add(hitResult.get_source().getId());
// }
// }
//
// public Long getTotal() {
// return total;
// }
//
// public void setTotal(Long total) {
// this.total = total;
// }
//
// public List<Long> getProductIds() {
// return productIds;
// }
//
// public void setProductIds(List<Long> productIds) {
// this.productIds = productIds;
// }
// }
// Path: elasticservice/src/main/java/elasticsearch/searchservice/SearchService.java
import elasticsearch.searchservice.models.QueryParam;
import elasticsearch.searchservice.models.QueryResp;
import org.springframework.stereotype.Service;
package elasticsearch.searchservice;
/**
* Created by i311352 on 5/2/2017.
*/
@Service
public interface SearchService {
| QueryResp doSearch(QueryParam queryFromPHP);
|
compasses/elastic-rabbitmq | elasticservice/src/main/java/elasticsearch/searchservice/SearchService.java | // Path: elasticservice/src/main/java/elasticsearch/searchservice/models/QueryParam.java
// public class QueryParam {
// private List<Meta> filter;
// private Collection collection;
// private String orderByField;
// private String orderByOrder;
// private Long channelId;
// private Integer pageSize;
// private Integer offSet;
// private Boolean isCount = Boolean.FALSE;
//
// public List<Meta> getFilter() {
// return filter;
// }
//
// public void setFilter(List<Meta> filter) {
// this.filter = filter;
// }
//
// public Collection getCollection() {
// return collection;
// }
//
// public void setCollection(Collection collection) {
// this.collection = collection;
// }
//
// public String getOrderByField() {
// return orderByField;
// }
//
// public void setOrderByField(String orderByField) {
// this.orderByField = orderByField;
// }
//
// public String getOrderByOrder() {
// return orderByOrder;
// }
//
// public void setOrderByOrder(String orderByOrder) {
// this.orderByOrder = orderByOrder;
// }
//
// public Integer getPageSize() {
// return pageSize;
// }
//
// public void setPageSize(Integer pageSize) {
// this.pageSize = pageSize;
// }
//
// public Integer getOffSet() {
// return offSet;
// }
//
// public void setOffSet(Integer offSet) {
// this.offSet = offSet;
// }
//
// public Long getChannelId() {
// return channelId;
// }
//
// public void setChannelId(Long channelId) {
// this.channelId = channelId;
// }
//
// public Boolean getCount() {
// return isCount;
// }
//
// public void setCount(Boolean count) {
// isCount = count;
// }
// }
//
// Path: elasticservice/src/main/java/elasticsearch/searchservice/models/QueryResp.java
// public class QueryResp {
// Long total;
// List<Long> productIds;
//
// public QueryResp() {
// }
//
// public QueryResp(Long total) {
// this.total = total;
// }
//
// public QueryResp(ESQueryResponse response) {
// total = response.getHit().getTotal();
// productIds = new ArrayList<>();
// for (Hits hitResult : response.getHit().getHits()) {
// JsonObject object = hitResult.getSource();
// Long id = object.get("id").getAsLong();
// productIds.add(id);
// }
// }
//
// public QueryResp(ESSearchResp resp) {
// total = resp.getHits().getTotal();
// productIds = new ArrayList<>();
// for (HitResult hitResult : resp.getHits().getHits()) {
// productIds.add(hitResult.get_source().getId());
// }
// }
//
// public Long getTotal() {
// return total;
// }
//
// public void setTotal(Long total) {
// this.total = total;
// }
//
// public List<Long> getProductIds() {
// return productIds;
// }
//
// public void setProductIds(List<Long> productIds) {
// this.productIds = productIds;
// }
// }
| import elasticsearch.searchservice.models.QueryParam;
import elasticsearch.searchservice.models.QueryResp;
import org.springframework.stereotype.Service;
| package elasticsearch.searchservice;
/**
* Created by i311352 on 5/2/2017.
*/
@Service
public interface SearchService {
| // Path: elasticservice/src/main/java/elasticsearch/searchservice/models/QueryParam.java
// public class QueryParam {
// private List<Meta> filter;
// private Collection collection;
// private String orderByField;
// private String orderByOrder;
// private Long channelId;
// private Integer pageSize;
// private Integer offSet;
// private Boolean isCount = Boolean.FALSE;
//
// public List<Meta> getFilter() {
// return filter;
// }
//
// public void setFilter(List<Meta> filter) {
// this.filter = filter;
// }
//
// public Collection getCollection() {
// return collection;
// }
//
// public void setCollection(Collection collection) {
// this.collection = collection;
// }
//
// public String getOrderByField() {
// return orderByField;
// }
//
// public void setOrderByField(String orderByField) {
// this.orderByField = orderByField;
// }
//
// public String getOrderByOrder() {
// return orderByOrder;
// }
//
// public void setOrderByOrder(String orderByOrder) {
// this.orderByOrder = orderByOrder;
// }
//
// public Integer getPageSize() {
// return pageSize;
// }
//
// public void setPageSize(Integer pageSize) {
// this.pageSize = pageSize;
// }
//
// public Integer getOffSet() {
// return offSet;
// }
//
// public void setOffSet(Integer offSet) {
// this.offSet = offSet;
// }
//
// public Long getChannelId() {
// return channelId;
// }
//
// public void setChannelId(Long channelId) {
// this.channelId = channelId;
// }
//
// public Boolean getCount() {
// return isCount;
// }
//
// public void setCount(Boolean count) {
// isCount = count;
// }
// }
//
// Path: elasticservice/src/main/java/elasticsearch/searchservice/models/QueryResp.java
// public class QueryResp {
// Long total;
// List<Long> productIds;
//
// public QueryResp() {
// }
//
// public QueryResp(Long total) {
// this.total = total;
// }
//
// public QueryResp(ESQueryResponse response) {
// total = response.getHit().getTotal();
// productIds = new ArrayList<>();
// for (Hits hitResult : response.getHit().getHits()) {
// JsonObject object = hitResult.getSource();
// Long id = object.get("id").getAsLong();
// productIds.add(id);
// }
// }
//
// public QueryResp(ESSearchResp resp) {
// total = resp.getHits().getTotal();
// productIds = new ArrayList<>();
// for (HitResult hitResult : resp.getHits().getHits()) {
// productIds.add(hitResult.get_source().getId());
// }
// }
//
// public Long getTotal() {
// return total;
// }
//
// public void setTotal(Long total) {
// this.total = total;
// }
//
// public List<Long> getProductIds() {
// return productIds;
// }
//
// public void setProductIds(List<Long> productIds) {
// this.productIds = productIds;
// }
// }
// Path: elasticservice/src/main/java/elasticsearch/searchservice/SearchService.java
import elasticsearch.searchservice.models.QueryParam;
import elasticsearch.searchservice.models.QueryResp;
import org.springframework.stereotype.Service;
package elasticsearch.searchservice;
/**
* Created by i311352 on 5/2/2017.
*/
@Service
public interface SearchService {
| QueryResp doSearch(QueryParam queryFromPHP);
|
compasses/elastic-rabbitmq | netty-http/src/main/java/http/worker/SearchWorker.java | // Path: netty-http/src/main/java/http/searchcommand/SearchRequest.java
// public class SearchRequest implements Callable<char[]> {
// private static final Logger LOGGER = LoggerFactory.getLogger(RestCommand.class);
//
// RestCommand command;
// public SearchRequest(RestCommand command) {
// this.command = command;
// }
//
// @Override
// public char[] call() throws Exception {
// LOGGER.info("Start request: " + command.toString());
// return command.execute();
// }
// }
//
// Path: netty-http/src/main/java/http/worker/notifyexecutor/INotifyingFuture.java
// public interface INotifyingFuture<V> extends RunnableFuture<V> {
//
// /**
// * Sets this listener to a {@link INotifyingFuture}. When the future is done
// * or canceled the listener gets notified.<br>
// * @param listener
// * @param the executor that executes the shiet.
// */
// public void setListener(IFutureListener<V> listener, ExecutorService executor);
//
// /**
// * Sets this listener to a {@link INotifyingFuture}. When the future is done
// * or canceled the listener gets notified.<br>
// * <b>Attention</b>: Be aware of the fact that everything that is done in that
// * listener is executed in same thread as the original task that this listener listens
// * to. Only use this method when you are sure that no long running task is performed
// * by the listener. When you want the listener's tasks to be performed asynchronous
// * use {@link #setListener(IFutureListener, ExecutorService)} instead.
// * @param listener
// */
// public void setListener(IFutureListener<V> listener);
// }
//
// Path: netty-http/src/main/java/http/worker/notifyexecutor/SearchingFuture.java
// public class SearchingFuture<V> extends FutureTask<V> implements INotifyingFuture<V> {
//
// private static final ExecutorService DEFAULT_EXECUTOR = new SearchWorker(30, "SearchWorker", new LinkedBlockingDeque(100));;
//
// private IFutureListener<V> listener = null;
// private ExecutorService executor = null;
// private final AtomicBoolean executed = new AtomicBoolean();
//
// public SearchingFuture(Callable<V> callable) {
// super(callable);
// setExecutor(DEFAULT_EXECUTOR);
// }
//
// public SearchingFuture(Runnable runnable, V result) {
// super(runnable,result);
// setExecutor(DEFAULT_EXECUTOR);
// }
//
//
// @Override
// protected void done() {
// if(listener == null){
// return;
// }
// notifyListenerOnce();
// }
//
// /**
// * Atomically executes the task only one time.
// */
// protected void notifyListenerOnce(){
// if(!this.executed.getAndSet(true)){
// notifyListener();
// }
// }
//
// protected void notifyListener() {
// this.executor.submit(new TaskCompletionRunner<V>(delegateFuture(),this.listener));
// }
//
// /**
// * @return the future that was processed.
// */
// protected RunnableFuture<V> delegateFuture(){
// return this;
// }
//
// @Override
// public void setListener(IFutureListener<V> listener, ExecutorService executor) {
// setExecutor(executor);
// setListener(listener);
// }
//
// public void setExecutor(ExecutorService executor) {
// this.executor = executor;
// }
//
// @Override
// public void setListener(IFutureListener<V> listener) {
// this.listener = listener;
// /*
// * Probably the task was already executed. If so, call done() manually.
// */
// runWhenDone();
// }
//
// protected void runWhenDone(){
// if(isDone()){
// notifyListenerOnce();
// }
// }
//
// private static class TaskCompletionRunner<V> implements Runnable{
//
// private final IFutureListener<V> listener;
// private final RunnableFuture<V> future;
//
// public TaskCompletionRunner(RunnableFuture<V> future, IFutureListener<V> listener) {
// this.future = future;
// this.listener = listener;
// }
//
// @Override
// public void run() {
// if (this.future.isCancelled()) {
// this.listener.onCancel(this.future);
// } else {
// try {
// this.listener.onSuccess(this.future.get());
// } catch (InterruptedException e) {
// this.listener.onError(e, this.future);
// } catch (ExecutionException e) {
// this.listener.onError(e, this.future);
// }
// }
// }
// }
// }
| import http.searchcommand.SearchRequest;
import http.worker.notifyexecutor.INotifyingFuture;
import http.worker.notifyexecutor.SearchingFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
| package http.worker;
/**
* Created by i311352 on 2/20/2017.
*/
public class SearchWorker extends ThreadPoolExecutor {
private final static Logger logger = LoggerFactory.getLogger(SearchWorker.class);
private static SearchWorker instance;
public SearchWorker(int size, String name, BlockingQueue blockingQueue) {
super(size, size+5, 0L, TimeUnit.MILLISECONDS, blockingQueue, new WorkerThread(name));
}
@Override
protected void beforeExecute(Thread t, Runnable r) {
logger.info("start to exectue: " + t);
super.beforeExecute(t, r);
}
@Override
protected void afterExecute(Runnable r, Throwable t) {
super.afterExecute(r, t);
logger.info("after to exectue: " + t);
}
| // Path: netty-http/src/main/java/http/searchcommand/SearchRequest.java
// public class SearchRequest implements Callable<char[]> {
// private static final Logger LOGGER = LoggerFactory.getLogger(RestCommand.class);
//
// RestCommand command;
// public SearchRequest(RestCommand command) {
// this.command = command;
// }
//
// @Override
// public char[] call() throws Exception {
// LOGGER.info("Start request: " + command.toString());
// return command.execute();
// }
// }
//
// Path: netty-http/src/main/java/http/worker/notifyexecutor/INotifyingFuture.java
// public interface INotifyingFuture<V> extends RunnableFuture<V> {
//
// /**
// * Sets this listener to a {@link INotifyingFuture}. When the future is done
// * or canceled the listener gets notified.<br>
// * @param listener
// * @param the executor that executes the shiet.
// */
// public void setListener(IFutureListener<V> listener, ExecutorService executor);
//
// /**
// * Sets this listener to a {@link INotifyingFuture}. When the future is done
// * or canceled the listener gets notified.<br>
// * <b>Attention</b>: Be aware of the fact that everything that is done in that
// * listener is executed in same thread as the original task that this listener listens
// * to. Only use this method when you are sure that no long running task is performed
// * by the listener. When you want the listener's tasks to be performed asynchronous
// * use {@link #setListener(IFutureListener, ExecutorService)} instead.
// * @param listener
// */
// public void setListener(IFutureListener<V> listener);
// }
//
// Path: netty-http/src/main/java/http/worker/notifyexecutor/SearchingFuture.java
// public class SearchingFuture<V> extends FutureTask<V> implements INotifyingFuture<V> {
//
// private static final ExecutorService DEFAULT_EXECUTOR = new SearchWorker(30, "SearchWorker", new LinkedBlockingDeque(100));;
//
// private IFutureListener<V> listener = null;
// private ExecutorService executor = null;
// private final AtomicBoolean executed = new AtomicBoolean();
//
// public SearchingFuture(Callable<V> callable) {
// super(callable);
// setExecutor(DEFAULT_EXECUTOR);
// }
//
// public SearchingFuture(Runnable runnable, V result) {
// super(runnable,result);
// setExecutor(DEFAULT_EXECUTOR);
// }
//
//
// @Override
// protected void done() {
// if(listener == null){
// return;
// }
// notifyListenerOnce();
// }
//
// /**
// * Atomically executes the task only one time.
// */
// protected void notifyListenerOnce(){
// if(!this.executed.getAndSet(true)){
// notifyListener();
// }
// }
//
// protected void notifyListener() {
// this.executor.submit(new TaskCompletionRunner<V>(delegateFuture(),this.listener));
// }
//
// /**
// * @return the future that was processed.
// */
// protected RunnableFuture<V> delegateFuture(){
// return this;
// }
//
// @Override
// public void setListener(IFutureListener<V> listener, ExecutorService executor) {
// setExecutor(executor);
// setListener(listener);
// }
//
// public void setExecutor(ExecutorService executor) {
// this.executor = executor;
// }
//
// @Override
// public void setListener(IFutureListener<V> listener) {
// this.listener = listener;
// /*
// * Probably the task was already executed. If so, call done() manually.
// */
// runWhenDone();
// }
//
// protected void runWhenDone(){
// if(isDone()){
// notifyListenerOnce();
// }
// }
//
// private static class TaskCompletionRunner<V> implements Runnable{
//
// private final IFutureListener<V> listener;
// private final RunnableFuture<V> future;
//
// public TaskCompletionRunner(RunnableFuture<V> future, IFutureListener<V> listener) {
// this.future = future;
// this.listener = listener;
// }
//
// @Override
// public void run() {
// if (this.future.isCancelled()) {
// this.listener.onCancel(this.future);
// } else {
// try {
// this.listener.onSuccess(this.future.get());
// } catch (InterruptedException e) {
// this.listener.onError(e, this.future);
// } catch (ExecutionException e) {
// this.listener.onError(e, this.future);
// }
// }
// }
// }
// }
// Path: netty-http/src/main/java/http/worker/SearchWorker.java
import http.searchcommand.SearchRequest;
import http.worker.notifyexecutor.INotifyingFuture;
import http.worker.notifyexecutor.SearchingFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
package http.worker;
/**
* Created by i311352 on 2/20/2017.
*/
public class SearchWorker extends ThreadPoolExecutor {
private final static Logger logger = LoggerFactory.getLogger(SearchWorker.class);
private static SearchWorker instance;
public SearchWorker(int size, String name, BlockingQueue blockingQueue) {
super(size, size+5, 0L, TimeUnit.MILLISECONDS, blockingQueue, new WorkerThread(name));
}
@Override
protected void beforeExecute(Thread t, Runnable r) {
logger.info("start to exectue: " + t);
super.beforeExecute(t, r);
}
@Override
protected void afterExecute(Runnable r, Throwable t) {
super.afterExecute(r, t);
logger.info("after to exectue: " + t);
}
| public INotifyingFuture doSearch(SearchRequest request) {
|
compasses/elastic-rabbitmq | netty-http/src/main/java/http/worker/SearchWorker.java | // Path: netty-http/src/main/java/http/searchcommand/SearchRequest.java
// public class SearchRequest implements Callable<char[]> {
// private static final Logger LOGGER = LoggerFactory.getLogger(RestCommand.class);
//
// RestCommand command;
// public SearchRequest(RestCommand command) {
// this.command = command;
// }
//
// @Override
// public char[] call() throws Exception {
// LOGGER.info("Start request: " + command.toString());
// return command.execute();
// }
// }
//
// Path: netty-http/src/main/java/http/worker/notifyexecutor/INotifyingFuture.java
// public interface INotifyingFuture<V> extends RunnableFuture<V> {
//
// /**
// * Sets this listener to a {@link INotifyingFuture}. When the future is done
// * or canceled the listener gets notified.<br>
// * @param listener
// * @param the executor that executes the shiet.
// */
// public void setListener(IFutureListener<V> listener, ExecutorService executor);
//
// /**
// * Sets this listener to a {@link INotifyingFuture}. When the future is done
// * or canceled the listener gets notified.<br>
// * <b>Attention</b>: Be aware of the fact that everything that is done in that
// * listener is executed in same thread as the original task that this listener listens
// * to. Only use this method when you are sure that no long running task is performed
// * by the listener. When you want the listener's tasks to be performed asynchronous
// * use {@link #setListener(IFutureListener, ExecutorService)} instead.
// * @param listener
// */
// public void setListener(IFutureListener<V> listener);
// }
//
// Path: netty-http/src/main/java/http/worker/notifyexecutor/SearchingFuture.java
// public class SearchingFuture<V> extends FutureTask<V> implements INotifyingFuture<V> {
//
// private static final ExecutorService DEFAULT_EXECUTOR = new SearchWorker(30, "SearchWorker", new LinkedBlockingDeque(100));;
//
// private IFutureListener<V> listener = null;
// private ExecutorService executor = null;
// private final AtomicBoolean executed = new AtomicBoolean();
//
// public SearchingFuture(Callable<V> callable) {
// super(callable);
// setExecutor(DEFAULT_EXECUTOR);
// }
//
// public SearchingFuture(Runnable runnable, V result) {
// super(runnable,result);
// setExecutor(DEFAULT_EXECUTOR);
// }
//
//
// @Override
// protected void done() {
// if(listener == null){
// return;
// }
// notifyListenerOnce();
// }
//
// /**
// * Atomically executes the task only one time.
// */
// protected void notifyListenerOnce(){
// if(!this.executed.getAndSet(true)){
// notifyListener();
// }
// }
//
// protected void notifyListener() {
// this.executor.submit(new TaskCompletionRunner<V>(delegateFuture(),this.listener));
// }
//
// /**
// * @return the future that was processed.
// */
// protected RunnableFuture<V> delegateFuture(){
// return this;
// }
//
// @Override
// public void setListener(IFutureListener<V> listener, ExecutorService executor) {
// setExecutor(executor);
// setListener(listener);
// }
//
// public void setExecutor(ExecutorService executor) {
// this.executor = executor;
// }
//
// @Override
// public void setListener(IFutureListener<V> listener) {
// this.listener = listener;
// /*
// * Probably the task was already executed. If so, call done() manually.
// */
// runWhenDone();
// }
//
// protected void runWhenDone(){
// if(isDone()){
// notifyListenerOnce();
// }
// }
//
// private static class TaskCompletionRunner<V> implements Runnable{
//
// private final IFutureListener<V> listener;
// private final RunnableFuture<V> future;
//
// public TaskCompletionRunner(RunnableFuture<V> future, IFutureListener<V> listener) {
// this.future = future;
// this.listener = listener;
// }
//
// @Override
// public void run() {
// if (this.future.isCancelled()) {
// this.listener.onCancel(this.future);
// } else {
// try {
// this.listener.onSuccess(this.future.get());
// } catch (InterruptedException e) {
// this.listener.onError(e, this.future);
// } catch (ExecutionException e) {
// this.listener.onError(e, this.future);
// }
// }
// }
// }
// }
| import http.searchcommand.SearchRequest;
import http.worker.notifyexecutor.INotifyingFuture;
import http.worker.notifyexecutor.SearchingFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
| package http.worker;
/**
* Created by i311352 on 2/20/2017.
*/
public class SearchWorker extends ThreadPoolExecutor {
private final static Logger logger = LoggerFactory.getLogger(SearchWorker.class);
private static SearchWorker instance;
public SearchWorker(int size, String name, BlockingQueue blockingQueue) {
super(size, size+5, 0L, TimeUnit.MILLISECONDS, blockingQueue, new WorkerThread(name));
}
@Override
protected void beforeExecute(Thread t, Runnable r) {
logger.info("start to exectue: " + t);
super.beforeExecute(t, r);
}
@Override
protected void afterExecute(Runnable r, Throwable t) {
super.afterExecute(r, t);
logger.info("after to exectue: " + t);
}
| // Path: netty-http/src/main/java/http/searchcommand/SearchRequest.java
// public class SearchRequest implements Callable<char[]> {
// private static final Logger LOGGER = LoggerFactory.getLogger(RestCommand.class);
//
// RestCommand command;
// public SearchRequest(RestCommand command) {
// this.command = command;
// }
//
// @Override
// public char[] call() throws Exception {
// LOGGER.info("Start request: " + command.toString());
// return command.execute();
// }
// }
//
// Path: netty-http/src/main/java/http/worker/notifyexecutor/INotifyingFuture.java
// public interface INotifyingFuture<V> extends RunnableFuture<V> {
//
// /**
// * Sets this listener to a {@link INotifyingFuture}. When the future is done
// * or canceled the listener gets notified.<br>
// * @param listener
// * @param the executor that executes the shiet.
// */
// public void setListener(IFutureListener<V> listener, ExecutorService executor);
//
// /**
// * Sets this listener to a {@link INotifyingFuture}. When the future is done
// * or canceled the listener gets notified.<br>
// * <b>Attention</b>: Be aware of the fact that everything that is done in that
// * listener is executed in same thread as the original task that this listener listens
// * to. Only use this method when you are sure that no long running task is performed
// * by the listener. When you want the listener's tasks to be performed asynchronous
// * use {@link #setListener(IFutureListener, ExecutorService)} instead.
// * @param listener
// */
// public void setListener(IFutureListener<V> listener);
// }
//
// Path: netty-http/src/main/java/http/worker/notifyexecutor/SearchingFuture.java
// public class SearchingFuture<V> extends FutureTask<V> implements INotifyingFuture<V> {
//
// private static final ExecutorService DEFAULT_EXECUTOR = new SearchWorker(30, "SearchWorker", new LinkedBlockingDeque(100));;
//
// private IFutureListener<V> listener = null;
// private ExecutorService executor = null;
// private final AtomicBoolean executed = new AtomicBoolean();
//
// public SearchingFuture(Callable<V> callable) {
// super(callable);
// setExecutor(DEFAULT_EXECUTOR);
// }
//
// public SearchingFuture(Runnable runnable, V result) {
// super(runnable,result);
// setExecutor(DEFAULT_EXECUTOR);
// }
//
//
// @Override
// protected void done() {
// if(listener == null){
// return;
// }
// notifyListenerOnce();
// }
//
// /**
// * Atomically executes the task only one time.
// */
// protected void notifyListenerOnce(){
// if(!this.executed.getAndSet(true)){
// notifyListener();
// }
// }
//
// protected void notifyListener() {
// this.executor.submit(new TaskCompletionRunner<V>(delegateFuture(),this.listener));
// }
//
// /**
// * @return the future that was processed.
// */
// protected RunnableFuture<V> delegateFuture(){
// return this;
// }
//
// @Override
// public void setListener(IFutureListener<V> listener, ExecutorService executor) {
// setExecutor(executor);
// setListener(listener);
// }
//
// public void setExecutor(ExecutorService executor) {
// this.executor = executor;
// }
//
// @Override
// public void setListener(IFutureListener<V> listener) {
// this.listener = listener;
// /*
// * Probably the task was already executed. If so, call done() manually.
// */
// runWhenDone();
// }
//
// protected void runWhenDone(){
// if(isDone()){
// notifyListenerOnce();
// }
// }
//
// private static class TaskCompletionRunner<V> implements Runnable{
//
// private final IFutureListener<V> listener;
// private final RunnableFuture<V> future;
//
// public TaskCompletionRunner(RunnableFuture<V> future, IFutureListener<V> listener) {
// this.future = future;
// this.listener = listener;
// }
//
// @Override
// public void run() {
// if (this.future.isCancelled()) {
// this.listener.onCancel(this.future);
// } else {
// try {
// this.listener.onSuccess(this.future.get());
// } catch (InterruptedException e) {
// this.listener.onError(e, this.future);
// } catch (ExecutionException e) {
// this.listener.onError(e, this.future);
// }
// }
// }
// }
// }
// Path: netty-http/src/main/java/http/worker/SearchWorker.java
import http.searchcommand.SearchRequest;
import http.worker.notifyexecutor.INotifyingFuture;
import http.worker.notifyexecutor.SearchingFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
package http.worker;
/**
* Created by i311352 on 2/20/2017.
*/
public class SearchWorker extends ThreadPoolExecutor {
private final static Logger logger = LoggerFactory.getLogger(SearchWorker.class);
private static SearchWorker instance;
public SearchWorker(int size, String name, BlockingQueue blockingQueue) {
super(size, size+5, 0L, TimeUnit.MILLISECONDS, blockingQueue, new WorkerThread(name));
}
@Override
protected void beforeExecute(Thread t, Runnable r) {
logger.info("start to exectue: " + t);
super.beforeExecute(t, r);
}
@Override
protected void afterExecute(Runnable r, Throwable t) {
super.afterExecute(r, t);
logger.info("after to exectue: " + t);
}
| public INotifyingFuture doSearch(SearchRequest request) {
|
compasses/elastic-rabbitmq | elasticservice/src/main/java/elasticsearch/searchservice/models/QueryResp.java | // Path: elasticservice/src/main/java/elasticsearch/esapi/resp/ESQueryResponse.java
// public class ESQueryResponse {
// @SerializedName("_scroll_id")
// protected String scrollId;
//
// protected Long took;
//
// @SerializedName("timed_out")
// protected Boolean timeOut;
//
// @SerializedName("_shards")
// protected JsonObject shards;
//
// @SerializedName("hits")
// protected Hit hit;
//
// public Long getTook() {
// return took;
// }
//
// public void setTook(Long took) {
// this.took = took;
// }
//
// public Boolean getTimeOut() {
// return timeOut;
// }
//
// public void setTimeOut(Boolean timeOut) {
// this.timeOut = timeOut;
// }
//
// public JsonObject getShards() {
// return shards;
// }
//
// public void setShards(JsonObject shards) {
// this.shards = shards;
// }
//
// public Hit getHit() {
// return hit;
// }
//
// public void setHit(Hit hit) {
// this.hit = hit;
// }
//
// public String getScrollId() {
// return scrollId;
// }
//
// public void setScrollId(String scrollId) {
// this.scrollId = scrollId;
// }
//
// @Override
// public String toString() {
// return "ESQueryResponse{" +
// "scrollId='" + scrollId + '\'' +
// ", took=" + took +
// ", timeOut=" + timeOut +
// ", shards=" + shards +
// ", hit=" + hit +
// '}';
// }
// }
//
// Path: elasticservice/src/main/java/elasticsearch/esapi/resp/Hits.java
// public class Hits extends ESBaseResponse {
// @SerializedName("_score")
// private String score;
// @SerializedName("_source")
// private JsonObject source;
//
// public String getScore() {
// return score;
// }
//
// public void setScore(String score) {
// this.score = score;
// }
//
// public JsonObject getSource() {
// return source;
// }
//
// public void setSource(JsonObject source) {
// this.source = source;
// }
//
// @Override
// public String toString() {
// return "Hits{" +
// "index='" + index + '\'' +
// ", type='" + type + '\'' +
// ", id='" + id + '\'' +
// ", score='" + score + '\'' +
// ", routing='" + routing + '\'' +
// ", source=" + source +
// '}';
// }
// }
//
// Path: elasticservice/src/main/java/elasticsearch/searchservice/models/ESResp/ESSearchResp.java
// public class ESSearchResp {
// Hit hits;
//
//
// public Hit getHits() {
// return hits;
// }
//
// public void setHits(Hit hits) {
// this.hits = hits;
// }
// }
//
// Path: elasticservice/src/main/java/elasticsearch/searchservice/models/ESResp/HitResult.java
// public class HitResult {
// HitSource _source;
//
// public HitSource get_source() {
// return _source;
// }
//
// public void set_source(HitSource _source) {
// this._source = _source;
// }
// }
| import com.google.gson.JsonObject;
import elasticsearch.esapi.resp.ESQueryResponse;
import elasticsearch.esapi.resp.Hits;
import elasticsearch.searchservice.models.ESResp.ESSearchResp;
import elasticsearch.searchservice.models.ESResp.HitResult;
import java.util.ArrayList;
import java.util.List;
| package elasticsearch.searchservice.models;
/**
* Created by i311352 on 5/4/2017.
*/
public class QueryResp {
Long total;
List<Long> productIds;
public QueryResp() {
}
public QueryResp(Long total) {
this.total = total;
}
| // Path: elasticservice/src/main/java/elasticsearch/esapi/resp/ESQueryResponse.java
// public class ESQueryResponse {
// @SerializedName("_scroll_id")
// protected String scrollId;
//
// protected Long took;
//
// @SerializedName("timed_out")
// protected Boolean timeOut;
//
// @SerializedName("_shards")
// protected JsonObject shards;
//
// @SerializedName("hits")
// protected Hit hit;
//
// public Long getTook() {
// return took;
// }
//
// public void setTook(Long took) {
// this.took = took;
// }
//
// public Boolean getTimeOut() {
// return timeOut;
// }
//
// public void setTimeOut(Boolean timeOut) {
// this.timeOut = timeOut;
// }
//
// public JsonObject getShards() {
// return shards;
// }
//
// public void setShards(JsonObject shards) {
// this.shards = shards;
// }
//
// public Hit getHit() {
// return hit;
// }
//
// public void setHit(Hit hit) {
// this.hit = hit;
// }
//
// public String getScrollId() {
// return scrollId;
// }
//
// public void setScrollId(String scrollId) {
// this.scrollId = scrollId;
// }
//
// @Override
// public String toString() {
// return "ESQueryResponse{" +
// "scrollId='" + scrollId + '\'' +
// ", took=" + took +
// ", timeOut=" + timeOut +
// ", shards=" + shards +
// ", hit=" + hit +
// '}';
// }
// }
//
// Path: elasticservice/src/main/java/elasticsearch/esapi/resp/Hits.java
// public class Hits extends ESBaseResponse {
// @SerializedName("_score")
// private String score;
// @SerializedName("_source")
// private JsonObject source;
//
// public String getScore() {
// return score;
// }
//
// public void setScore(String score) {
// this.score = score;
// }
//
// public JsonObject getSource() {
// return source;
// }
//
// public void setSource(JsonObject source) {
// this.source = source;
// }
//
// @Override
// public String toString() {
// return "Hits{" +
// "index='" + index + '\'' +
// ", type='" + type + '\'' +
// ", id='" + id + '\'' +
// ", score='" + score + '\'' +
// ", routing='" + routing + '\'' +
// ", source=" + source +
// '}';
// }
// }
//
// Path: elasticservice/src/main/java/elasticsearch/searchservice/models/ESResp/ESSearchResp.java
// public class ESSearchResp {
// Hit hits;
//
//
// public Hit getHits() {
// return hits;
// }
//
// public void setHits(Hit hits) {
// this.hits = hits;
// }
// }
//
// Path: elasticservice/src/main/java/elasticsearch/searchservice/models/ESResp/HitResult.java
// public class HitResult {
// HitSource _source;
//
// public HitSource get_source() {
// return _source;
// }
//
// public void set_source(HitSource _source) {
// this._source = _source;
// }
// }
// Path: elasticservice/src/main/java/elasticsearch/searchservice/models/QueryResp.java
import com.google.gson.JsonObject;
import elasticsearch.esapi.resp.ESQueryResponse;
import elasticsearch.esapi.resp.Hits;
import elasticsearch.searchservice.models.ESResp.ESSearchResp;
import elasticsearch.searchservice.models.ESResp.HitResult;
import java.util.ArrayList;
import java.util.List;
package elasticsearch.searchservice.models;
/**
* Created by i311352 on 5/4/2017.
*/
public class QueryResp {
Long total;
List<Long> productIds;
public QueryResp() {
}
public QueryResp(Long total) {
this.total = total;
}
| public QueryResp(ESQueryResponse response) {
|
compasses/elastic-rabbitmq | elasticservice/src/main/java/elasticsearch/searchservice/models/QueryResp.java | // Path: elasticservice/src/main/java/elasticsearch/esapi/resp/ESQueryResponse.java
// public class ESQueryResponse {
// @SerializedName("_scroll_id")
// protected String scrollId;
//
// protected Long took;
//
// @SerializedName("timed_out")
// protected Boolean timeOut;
//
// @SerializedName("_shards")
// protected JsonObject shards;
//
// @SerializedName("hits")
// protected Hit hit;
//
// public Long getTook() {
// return took;
// }
//
// public void setTook(Long took) {
// this.took = took;
// }
//
// public Boolean getTimeOut() {
// return timeOut;
// }
//
// public void setTimeOut(Boolean timeOut) {
// this.timeOut = timeOut;
// }
//
// public JsonObject getShards() {
// return shards;
// }
//
// public void setShards(JsonObject shards) {
// this.shards = shards;
// }
//
// public Hit getHit() {
// return hit;
// }
//
// public void setHit(Hit hit) {
// this.hit = hit;
// }
//
// public String getScrollId() {
// return scrollId;
// }
//
// public void setScrollId(String scrollId) {
// this.scrollId = scrollId;
// }
//
// @Override
// public String toString() {
// return "ESQueryResponse{" +
// "scrollId='" + scrollId + '\'' +
// ", took=" + took +
// ", timeOut=" + timeOut +
// ", shards=" + shards +
// ", hit=" + hit +
// '}';
// }
// }
//
// Path: elasticservice/src/main/java/elasticsearch/esapi/resp/Hits.java
// public class Hits extends ESBaseResponse {
// @SerializedName("_score")
// private String score;
// @SerializedName("_source")
// private JsonObject source;
//
// public String getScore() {
// return score;
// }
//
// public void setScore(String score) {
// this.score = score;
// }
//
// public JsonObject getSource() {
// return source;
// }
//
// public void setSource(JsonObject source) {
// this.source = source;
// }
//
// @Override
// public String toString() {
// return "Hits{" +
// "index='" + index + '\'' +
// ", type='" + type + '\'' +
// ", id='" + id + '\'' +
// ", score='" + score + '\'' +
// ", routing='" + routing + '\'' +
// ", source=" + source +
// '}';
// }
// }
//
// Path: elasticservice/src/main/java/elasticsearch/searchservice/models/ESResp/ESSearchResp.java
// public class ESSearchResp {
// Hit hits;
//
//
// public Hit getHits() {
// return hits;
// }
//
// public void setHits(Hit hits) {
// this.hits = hits;
// }
// }
//
// Path: elasticservice/src/main/java/elasticsearch/searchservice/models/ESResp/HitResult.java
// public class HitResult {
// HitSource _source;
//
// public HitSource get_source() {
// return _source;
// }
//
// public void set_source(HitSource _source) {
// this._source = _source;
// }
// }
| import com.google.gson.JsonObject;
import elasticsearch.esapi.resp.ESQueryResponse;
import elasticsearch.esapi.resp.Hits;
import elasticsearch.searchservice.models.ESResp.ESSearchResp;
import elasticsearch.searchservice.models.ESResp.HitResult;
import java.util.ArrayList;
import java.util.List;
| package elasticsearch.searchservice.models;
/**
* Created by i311352 on 5/4/2017.
*/
public class QueryResp {
Long total;
List<Long> productIds;
public QueryResp() {
}
public QueryResp(Long total) {
this.total = total;
}
public QueryResp(ESQueryResponse response) {
total = response.getHit().getTotal();
productIds = new ArrayList<>();
| // Path: elasticservice/src/main/java/elasticsearch/esapi/resp/ESQueryResponse.java
// public class ESQueryResponse {
// @SerializedName("_scroll_id")
// protected String scrollId;
//
// protected Long took;
//
// @SerializedName("timed_out")
// protected Boolean timeOut;
//
// @SerializedName("_shards")
// protected JsonObject shards;
//
// @SerializedName("hits")
// protected Hit hit;
//
// public Long getTook() {
// return took;
// }
//
// public void setTook(Long took) {
// this.took = took;
// }
//
// public Boolean getTimeOut() {
// return timeOut;
// }
//
// public void setTimeOut(Boolean timeOut) {
// this.timeOut = timeOut;
// }
//
// public JsonObject getShards() {
// return shards;
// }
//
// public void setShards(JsonObject shards) {
// this.shards = shards;
// }
//
// public Hit getHit() {
// return hit;
// }
//
// public void setHit(Hit hit) {
// this.hit = hit;
// }
//
// public String getScrollId() {
// return scrollId;
// }
//
// public void setScrollId(String scrollId) {
// this.scrollId = scrollId;
// }
//
// @Override
// public String toString() {
// return "ESQueryResponse{" +
// "scrollId='" + scrollId + '\'' +
// ", took=" + took +
// ", timeOut=" + timeOut +
// ", shards=" + shards +
// ", hit=" + hit +
// '}';
// }
// }
//
// Path: elasticservice/src/main/java/elasticsearch/esapi/resp/Hits.java
// public class Hits extends ESBaseResponse {
// @SerializedName("_score")
// private String score;
// @SerializedName("_source")
// private JsonObject source;
//
// public String getScore() {
// return score;
// }
//
// public void setScore(String score) {
// this.score = score;
// }
//
// public JsonObject getSource() {
// return source;
// }
//
// public void setSource(JsonObject source) {
// this.source = source;
// }
//
// @Override
// public String toString() {
// return "Hits{" +
// "index='" + index + '\'' +
// ", type='" + type + '\'' +
// ", id='" + id + '\'' +
// ", score='" + score + '\'' +
// ", routing='" + routing + '\'' +
// ", source=" + source +
// '}';
// }
// }
//
// Path: elasticservice/src/main/java/elasticsearch/searchservice/models/ESResp/ESSearchResp.java
// public class ESSearchResp {
// Hit hits;
//
//
// public Hit getHits() {
// return hits;
// }
//
// public void setHits(Hit hits) {
// this.hits = hits;
// }
// }
//
// Path: elasticservice/src/main/java/elasticsearch/searchservice/models/ESResp/HitResult.java
// public class HitResult {
// HitSource _source;
//
// public HitSource get_source() {
// return _source;
// }
//
// public void set_source(HitSource _source) {
// this._source = _source;
// }
// }
// Path: elasticservice/src/main/java/elasticsearch/searchservice/models/QueryResp.java
import com.google.gson.JsonObject;
import elasticsearch.esapi.resp.ESQueryResponse;
import elasticsearch.esapi.resp.Hits;
import elasticsearch.searchservice.models.ESResp.ESSearchResp;
import elasticsearch.searchservice.models.ESResp.HitResult;
import java.util.ArrayList;
import java.util.List;
package elasticsearch.searchservice.models;
/**
* Created by i311352 on 5/4/2017.
*/
public class QueryResp {
Long total;
List<Long> productIds;
public QueryResp() {
}
public QueryResp(Long total) {
this.total = total;
}
public QueryResp(ESQueryResponse response) {
total = response.getHit().getTotal();
productIds = new ArrayList<>();
| for (Hits hitResult : response.getHit().getHits()) {
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.