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
jenkinsci/semantic-versioning-plugin
src/main/java/org/jenkinsci/plugins/SemanticVersioning/SemanticVersioningCallable.java
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/naming/NamingStrategy.java // public interface NamingStrategy extends Describable<NamingStrategy>, Serializable { // String exportNames(AppVersion current, Map<String, String> vars, boolean useBuildNumber, int buildNumber); // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/parsing/BuildDefinitionParser.java // public interface BuildDefinitionParser extends Describable<BuildDefinitionParser> { // AppVersion extractAppVersion(FilePath workspace, PrintStream logger) throws IOException, InvalidBuildFileFormatException; // }
import hudson.FilePath; import jenkins.security.MasterToSlaveCallable; import org.jenkinsci.plugins.SemanticVersioning.naming.NamingStrategy; import org.jenkinsci.plugins.SemanticVersioning.parsing.BuildDefinitionParser; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; import java.io.Serializable; import java.net.InetAddress; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map;
package org.jenkinsci.plugins.SemanticVersioning; public class SemanticVersioningCallable extends MasterToSlaveCallable<SemanticVersioningResult, IOException> implements Serializable { private static final long serialVersionUID = -2239554739563636620L; private String env; private boolean useBuildNumber; private FilePath workspace; private int buildNumber;
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/naming/NamingStrategy.java // public interface NamingStrategy extends Describable<NamingStrategy>, Serializable { // String exportNames(AppVersion current, Map<String, String> vars, boolean useBuildNumber, int buildNumber); // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/parsing/BuildDefinitionParser.java // public interface BuildDefinitionParser extends Describable<BuildDefinitionParser> { // AppVersion extractAppVersion(FilePath workspace, PrintStream logger) throws IOException, InvalidBuildFileFormatException; // } // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/SemanticVersioningCallable.java import hudson.FilePath; import jenkins.security.MasterToSlaveCallable; import org.jenkinsci.plugins.SemanticVersioning.naming.NamingStrategy; import org.jenkinsci.plugins.SemanticVersioning.parsing.BuildDefinitionParser; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; import java.io.Serializable; import java.net.InetAddress; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; package org.jenkinsci.plugins.SemanticVersioning; public class SemanticVersioningCallable extends MasterToSlaveCallable<SemanticVersioningResult, IOException> implements Serializable { private static final long serialVersionUID = -2239554739563636620L; private String env; private boolean useBuildNumber; private FilePath workspace; private int buildNumber;
private BuildDefinitionParser parser;
jenkinsci/semantic-versioning-plugin
src/main/java/org/jenkinsci/plugins/SemanticVersioning/SemanticVersioningCallable.java
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/naming/NamingStrategy.java // public interface NamingStrategy extends Describable<NamingStrategy>, Serializable { // String exportNames(AppVersion current, Map<String, String> vars, boolean useBuildNumber, int buildNumber); // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/parsing/BuildDefinitionParser.java // public interface BuildDefinitionParser extends Describable<BuildDefinitionParser> { // AppVersion extractAppVersion(FilePath workspace, PrintStream logger) throws IOException, InvalidBuildFileFormatException; // }
import hudson.FilePath; import jenkins.security.MasterToSlaveCallable; import org.jenkinsci.plugins.SemanticVersioning.naming.NamingStrategy; import org.jenkinsci.plugins.SemanticVersioning.parsing.BuildDefinitionParser; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; import java.io.Serializable; import java.net.InetAddress; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map;
package org.jenkinsci.plugins.SemanticVersioning; public class SemanticVersioningCallable extends MasterToSlaveCallable<SemanticVersioningResult, IOException> implements Serializable { private static final long serialVersionUID = -2239554739563636620L; private String env; private boolean useBuildNumber; private FilePath workspace; private int buildNumber; private BuildDefinitionParser parser;
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/naming/NamingStrategy.java // public interface NamingStrategy extends Describable<NamingStrategy>, Serializable { // String exportNames(AppVersion current, Map<String, String> vars, boolean useBuildNumber, int buildNumber); // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/parsing/BuildDefinitionParser.java // public interface BuildDefinitionParser extends Describable<BuildDefinitionParser> { // AppVersion extractAppVersion(FilePath workspace, PrintStream logger) throws IOException, InvalidBuildFileFormatException; // } // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/SemanticVersioningCallable.java import hudson.FilePath; import jenkins.security.MasterToSlaveCallable; import org.jenkinsci.plugins.SemanticVersioning.naming.NamingStrategy; import org.jenkinsci.plugins.SemanticVersioning.parsing.BuildDefinitionParser; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; import java.io.Serializable; import java.net.InetAddress; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; package org.jenkinsci.plugins.SemanticVersioning; public class SemanticVersioningCallable extends MasterToSlaveCallable<SemanticVersioningResult, IOException> implements Serializable { private static final long serialVersionUID = -2239554739563636620L; private String env; private boolean useBuildNumber; private FilePath workspace; private int buildNumber; private BuildDefinitionParser parser;
private NamingStrategy namingStrategy;
jenkinsci/semantic-versioning-plugin
src/main/java/org/jenkinsci/plugins/SemanticVersioning/parsing/NpmPackageParser.java
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/Messages.java // public class Messages { // public static final String SEMANTIC_VERSION_FILENAME = ".semanticVersion"; // public static final String DISPLAY_NAME = "Determine Semantic Version"; // public static final String SEMANTIC_VERSION_COLUMN_DISPLAY_NAME = "Semantic Version"; // public static final String UNKNOWN_VERSION = "Unknown"; // // public static class Parsers { // public static final String SBT_BUILD_SBT_PARSER = "SBT build.sbt parser"; // public static final String MAVEN_POM_PARSER = "Maven Pom Parser"; // public static final String SBT_BUILD_SCALA_PARSER = "SBT Build.scala Parser"; // public static final String BOWER_JSON_PARSER = "Bower bower.json Parser"; // public static final String NPM_JSON_PARSER = "NPM package.json Parser"; // public static final String COMPOSER_JSON_PARSER = "Composer composer.json Parser"; // } // // public static class ColumnDisplayStrategies { // public static final String LAST_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Successful Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_BUILD_VERSION_STRATEGY = "Show Last Successful Semantic Version"; // public static final String NA_STRATEGY = "Show 'N/A'"; // } // // public static class NamingStrategies { // public static final String NOOP_NAMING = "none"; // public static final String MAVEN_RELEASE_DEVELOPMENT = "Maven, release and development version"; // public static final String UNTOUCHED = "As found"; // public static final String UNTOUCHED_SNAPSHOT = "As found (-SNAPSHOT)"; // } // }
import hudson.Extension; import hudson.model.Descriptor; import org.jenkinsci.plugins.SemanticVersioning.Messages;
/* * The MIT License * * Copyright (c) 2014, Arne M. Størksen * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.jenkinsci.plugins.SemanticVersioning.parsing; @Extension public class NpmPackageParser extends JsonVersionParser { public NpmPackageParser() { super("package.json", "version"); } @SuppressWarnings("unchecked") public Descriptor<BuildDefinitionParser> getDescriptor() { return new AbstractSemanticParserDescription() { @Override public String getDisplayName() {
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/Messages.java // public class Messages { // public static final String SEMANTIC_VERSION_FILENAME = ".semanticVersion"; // public static final String DISPLAY_NAME = "Determine Semantic Version"; // public static final String SEMANTIC_VERSION_COLUMN_DISPLAY_NAME = "Semantic Version"; // public static final String UNKNOWN_VERSION = "Unknown"; // // public static class Parsers { // public static final String SBT_BUILD_SBT_PARSER = "SBT build.sbt parser"; // public static final String MAVEN_POM_PARSER = "Maven Pom Parser"; // public static final String SBT_BUILD_SCALA_PARSER = "SBT Build.scala Parser"; // public static final String BOWER_JSON_PARSER = "Bower bower.json Parser"; // public static final String NPM_JSON_PARSER = "NPM package.json Parser"; // public static final String COMPOSER_JSON_PARSER = "Composer composer.json Parser"; // } // // public static class ColumnDisplayStrategies { // public static final String LAST_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Successful Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_BUILD_VERSION_STRATEGY = "Show Last Successful Semantic Version"; // public static final String NA_STRATEGY = "Show 'N/A'"; // } // // public static class NamingStrategies { // public static final String NOOP_NAMING = "none"; // public static final String MAVEN_RELEASE_DEVELOPMENT = "Maven, release and development version"; // public static final String UNTOUCHED = "As found"; // public static final String UNTOUCHED_SNAPSHOT = "As found (-SNAPSHOT)"; // } // } // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/parsing/NpmPackageParser.java import hudson.Extension; import hudson.model.Descriptor; import org.jenkinsci.plugins.SemanticVersioning.Messages; /* * The MIT License * * Copyright (c) 2014, Arne M. Størksen * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.jenkinsci.plugins.SemanticVersioning.parsing; @Extension public class NpmPackageParser extends JsonVersionParser { public NpmPackageParser() { super("package.json", "version"); } @SuppressWarnings("unchecked") public Descriptor<BuildDefinitionParser> getDescriptor() { return new AbstractSemanticParserDescription() { @Override public String getDisplayName() {
return Messages.Parsers.NPM_JSON_PARSER;
jenkinsci/semantic-versioning-plugin
src/main/java/org/jenkinsci/plugins/SemanticVersioning/parsing/PomParser.java
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/AppVersion.java // public class AppVersion implements Serializable { // private static final String SNAPSHOT = "SNAPSHOT"; // private final int major; // private final int minor; // private final String original; // // private int build; // private final boolean isSnapshot; // public static final AppVersion EmptyVersion = new AppVersion(0, 0, 0, false, ""); // // public static AppVersion parse(String versionString) { // String[] parts = versionString.split("[\\.-]"); // // int major = Integer.parseInt(parts[0]); // int minor = Integer.parseInt(parts[1]); // // int build = -1; // boolean isSnapshot = false; // // if (parts.length == 3) { // if (parts[2].equals(SNAPSHOT)) { // isSnapshot = true; // } else { // build = Integer.parseInt(parts[2]); // } // } else if (parts.length == 4) { // build = Integer.parseInt(parts[2]); // isSnapshot = parts[3].equals(SNAPSHOT); // } // // return new AppVersion(major, minor, build, isSnapshot, versionString); // } // // private AppVersion(int major, int minor, int build, boolean isSnapshot, String original) { // this.major = major; // this.minor = minor; // // this.isSnapshot = isSnapshot; // this.build = build; // this.original = original; // } // // public int getMajor() { // return major; // } // // public int getMinor() { // return minor; // } // // public String getOriginal() { // return this.original; // } // // public boolean isSnapshot() { // return isSnapshot; // } // // public void setBuild(int build) { // this.build = build; // } // // public int getBuild() { // return build; // } // // public String toJsonString() { // return String.format( // "{ \"major\": %d, \"minor\": %d, \"build\": %d, \"isSnapshot\": %b, \"originalString\": \"%s\" }", // this.major, // this.minor, // this.build, // this.isSnapshot, // this.original); // } // // @Override // public String toString() { // String version = String.format("%s.%s", major, minor); // if(build > -1) { // version += "." + build; // } // if (isSnapshot) { // version += "-" + SNAPSHOT; // } // return version; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/InvalidBuildFileFormatException.java // public class InvalidBuildFileFormatException extends Exception { // private static final long serialVersionUID = 1L; // // public InvalidBuildFileFormatException(String message) { // super(message); // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/Messages.java // public class Messages { // public static final String SEMANTIC_VERSION_FILENAME = ".semanticVersion"; // public static final String DISPLAY_NAME = "Determine Semantic Version"; // public static final String SEMANTIC_VERSION_COLUMN_DISPLAY_NAME = "Semantic Version"; // public static final String UNKNOWN_VERSION = "Unknown"; // // public static class Parsers { // public static final String SBT_BUILD_SBT_PARSER = "SBT build.sbt parser"; // public static final String MAVEN_POM_PARSER = "Maven Pom Parser"; // public static final String SBT_BUILD_SCALA_PARSER = "SBT Build.scala Parser"; // public static final String BOWER_JSON_PARSER = "Bower bower.json Parser"; // public static final String NPM_JSON_PARSER = "NPM package.json Parser"; // public static final String COMPOSER_JSON_PARSER = "Composer composer.json Parser"; // } // // public static class ColumnDisplayStrategies { // public static final String LAST_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Successful Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_BUILD_VERSION_STRATEGY = "Show Last Successful Semantic Version"; // public static final String NA_STRATEGY = "Show 'N/A'"; // } // // public static class NamingStrategies { // public static final String NOOP_NAMING = "none"; // public static final String MAVEN_RELEASE_DEVELOPMENT = "Maven, release and development version"; // public static final String UNTOUCHED = "As found"; // public static final String UNTOUCHED_SNAPSHOT = "As found (-SNAPSHOT)"; // } // }
import org.jenkinsci.plugins.SemanticVersioning.AppVersion; import org.jenkinsci.plugins.SemanticVersioning.InvalidBuildFileFormatException; import org.jenkinsci.plugins.SemanticVersioning.Messages; import org.jenkinsci.remoting.RoleChecker; import org.w3c.dom.Document; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.*; import java.io.File; import java.io.IOException; import java.io.PrintStream; import hudson.Extension; import hudson.FilePath; import hudson.FilePath.FileCallable; import hudson.model.Descriptor; import hudson.remoting.VirtualChannel;
} catch (SAXException e) { throw new InterruptedException(pom .getAbsolutePath() + " is not a valid POM file."); } catch (ParserConfigurationException e) { throw new InterruptedException(pom .getAbsolutePath() + " is not a valid POM file."); } } public void checkRoles(RoleChecker arg0) throws SecurityException { } }); } catch (InterruptedException e) { throw new InvalidBuildFileFormatException(e.getMessage()); } return pomDocument; } @SuppressWarnings("unchecked") public Descriptor<BuildDefinitionParser> getDescriptor() { return new AbstractSemanticParserDescription() { @Override public String getDisplayName() {
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/AppVersion.java // public class AppVersion implements Serializable { // private static final String SNAPSHOT = "SNAPSHOT"; // private final int major; // private final int minor; // private final String original; // // private int build; // private final boolean isSnapshot; // public static final AppVersion EmptyVersion = new AppVersion(0, 0, 0, false, ""); // // public static AppVersion parse(String versionString) { // String[] parts = versionString.split("[\\.-]"); // // int major = Integer.parseInt(parts[0]); // int minor = Integer.parseInt(parts[1]); // // int build = -1; // boolean isSnapshot = false; // // if (parts.length == 3) { // if (parts[2].equals(SNAPSHOT)) { // isSnapshot = true; // } else { // build = Integer.parseInt(parts[2]); // } // } else if (parts.length == 4) { // build = Integer.parseInt(parts[2]); // isSnapshot = parts[3].equals(SNAPSHOT); // } // // return new AppVersion(major, minor, build, isSnapshot, versionString); // } // // private AppVersion(int major, int minor, int build, boolean isSnapshot, String original) { // this.major = major; // this.minor = minor; // // this.isSnapshot = isSnapshot; // this.build = build; // this.original = original; // } // // public int getMajor() { // return major; // } // // public int getMinor() { // return minor; // } // // public String getOriginal() { // return this.original; // } // // public boolean isSnapshot() { // return isSnapshot; // } // // public void setBuild(int build) { // this.build = build; // } // // public int getBuild() { // return build; // } // // public String toJsonString() { // return String.format( // "{ \"major\": %d, \"minor\": %d, \"build\": %d, \"isSnapshot\": %b, \"originalString\": \"%s\" }", // this.major, // this.minor, // this.build, // this.isSnapshot, // this.original); // } // // @Override // public String toString() { // String version = String.format("%s.%s", major, minor); // if(build > -1) { // version += "." + build; // } // if (isSnapshot) { // version += "-" + SNAPSHOT; // } // return version; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/InvalidBuildFileFormatException.java // public class InvalidBuildFileFormatException extends Exception { // private static final long serialVersionUID = 1L; // // public InvalidBuildFileFormatException(String message) { // super(message); // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/Messages.java // public class Messages { // public static final String SEMANTIC_VERSION_FILENAME = ".semanticVersion"; // public static final String DISPLAY_NAME = "Determine Semantic Version"; // public static final String SEMANTIC_VERSION_COLUMN_DISPLAY_NAME = "Semantic Version"; // public static final String UNKNOWN_VERSION = "Unknown"; // // public static class Parsers { // public static final String SBT_BUILD_SBT_PARSER = "SBT build.sbt parser"; // public static final String MAVEN_POM_PARSER = "Maven Pom Parser"; // public static final String SBT_BUILD_SCALA_PARSER = "SBT Build.scala Parser"; // public static final String BOWER_JSON_PARSER = "Bower bower.json Parser"; // public static final String NPM_JSON_PARSER = "NPM package.json Parser"; // public static final String COMPOSER_JSON_PARSER = "Composer composer.json Parser"; // } // // public static class ColumnDisplayStrategies { // public static final String LAST_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Successful Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_BUILD_VERSION_STRATEGY = "Show Last Successful Semantic Version"; // public static final String NA_STRATEGY = "Show 'N/A'"; // } // // public static class NamingStrategies { // public static final String NOOP_NAMING = "none"; // public static final String MAVEN_RELEASE_DEVELOPMENT = "Maven, release and development version"; // public static final String UNTOUCHED = "As found"; // public static final String UNTOUCHED_SNAPSHOT = "As found (-SNAPSHOT)"; // } // } // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/parsing/PomParser.java import org.jenkinsci.plugins.SemanticVersioning.AppVersion; import org.jenkinsci.plugins.SemanticVersioning.InvalidBuildFileFormatException; import org.jenkinsci.plugins.SemanticVersioning.Messages; import org.jenkinsci.remoting.RoleChecker; import org.w3c.dom.Document; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.*; import java.io.File; import java.io.IOException; import java.io.PrintStream; import hudson.Extension; import hudson.FilePath; import hudson.FilePath.FileCallable; import hudson.model.Descriptor; import hudson.remoting.VirtualChannel; } catch (SAXException e) { throw new InterruptedException(pom .getAbsolutePath() + " is not a valid POM file."); } catch (ParserConfigurationException e) { throw new InterruptedException(pom .getAbsolutePath() + " is not a valid POM file."); } } public void checkRoles(RoleChecker arg0) throws SecurityException { } }); } catch (InterruptedException e) { throw new InvalidBuildFileFormatException(e.getMessage()); } return pomDocument; } @SuppressWarnings("unchecked") public Descriptor<BuildDefinitionParser> getDescriptor() { return new AbstractSemanticParserDescription() { @Override public String getDisplayName() {
return Messages.Parsers.MAVEN_POM_PARSER;
jenkinsci/semantic-versioning-plugin
src/main/java/org/jenkinsci/plugins/SemanticVersioning/naming/UntouchedNamingStrategy.java
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/AppVersion.java // public class AppVersion implements Serializable { // private static final String SNAPSHOT = "SNAPSHOT"; // private final int major; // private final int minor; // private final String original; // // private int build; // private final boolean isSnapshot; // public static final AppVersion EmptyVersion = new AppVersion(0, 0, 0, false, ""); // // public static AppVersion parse(String versionString) { // String[] parts = versionString.split("[\\.-]"); // // int major = Integer.parseInt(parts[0]); // int minor = Integer.parseInt(parts[1]); // // int build = -1; // boolean isSnapshot = false; // // if (parts.length == 3) { // if (parts[2].equals(SNAPSHOT)) { // isSnapshot = true; // } else { // build = Integer.parseInt(parts[2]); // } // } else if (parts.length == 4) { // build = Integer.parseInt(parts[2]); // isSnapshot = parts[3].equals(SNAPSHOT); // } // // return new AppVersion(major, minor, build, isSnapshot, versionString); // } // // private AppVersion(int major, int minor, int build, boolean isSnapshot, String original) { // this.major = major; // this.minor = minor; // // this.isSnapshot = isSnapshot; // this.build = build; // this.original = original; // } // // public int getMajor() { // return major; // } // // public int getMinor() { // return minor; // } // // public String getOriginal() { // return this.original; // } // // public boolean isSnapshot() { // return isSnapshot; // } // // public void setBuild(int build) { // this.build = build; // } // // public int getBuild() { // return build; // } // // public String toJsonString() { // return String.format( // "{ \"major\": %d, \"minor\": %d, \"build\": %d, \"isSnapshot\": %b, \"originalString\": \"%s\" }", // this.major, // this.minor, // this.build, // this.isSnapshot, // this.original); // } // // @Override // public String toString() { // String version = String.format("%s.%s", major, minor); // if(build > -1) { // version += "." + build; // } // if (isSnapshot) { // version += "-" + SNAPSHOT; // } // return version; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/Messages.java // public class Messages { // public static final String SEMANTIC_VERSION_FILENAME = ".semanticVersion"; // public static final String DISPLAY_NAME = "Determine Semantic Version"; // public static final String SEMANTIC_VERSION_COLUMN_DISPLAY_NAME = "Semantic Version"; // public static final String UNKNOWN_VERSION = "Unknown"; // // public static class Parsers { // public static final String SBT_BUILD_SBT_PARSER = "SBT build.sbt parser"; // public static final String MAVEN_POM_PARSER = "Maven Pom Parser"; // public static final String SBT_BUILD_SCALA_PARSER = "SBT Build.scala Parser"; // public static final String BOWER_JSON_PARSER = "Bower bower.json Parser"; // public static final String NPM_JSON_PARSER = "NPM package.json Parser"; // public static final String COMPOSER_JSON_PARSER = "Composer composer.json Parser"; // } // // public static class ColumnDisplayStrategies { // public static final String LAST_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Successful Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_BUILD_VERSION_STRATEGY = "Show Last Successful Semantic Version"; // public static final String NA_STRATEGY = "Show 'N/A'"; // } // // public static class NamingStrategies { // public static final String NOOP_NAMING = "none"; // public static final String MAVEN_RELEASE_DEVELOPMENT = "Maven, release and development version"; // public static final String UNTOUCHED = "As found"; // public static final String UNTOUCHED_SNAPSHOT = "As found (-SNAPSHOT)"; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/parsing/AbstractSemanticParserDescription.java // public abstract class AbstractSemanticParserDescription extends hudson.model.Descriptor { // @Override // public abstract String getDisplayName(); // }
import hudson.Extension; import hudson.model.Descriptor; import java.io.Serializable; import java.util.Map; import java.util.logging.Logger; import org.jenkinsci.plugins.SemanticVersioning.AppVersion; import org.jenkinsci.plugins.SemanticVersioning.Messages; import org.jenkinsci.plugins.SemanticVersioning.parsing.AbstractSemanticParserDescription;
package org.jenkinsci.plugins.SemanticVersioning.naming; @Extension public class UntouchedNamingStrategy implements NamingStrategy, Serializable {
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/AppVersion.java // public class AppVersion implements Serializable { // private static final String SNAPSHOT = "SNAPSHOT"; // private final int major; // private final int minor; // private final String original; // // private int build; // private final boolean isSnapshot; // public static final AppVersion EmptyVersion = new AppVersion(0, 0, 0, false, ""); // // public static AppVersion parse(String versionString) { // String[] parts = versionString.split("[\\.-]"); // // int major = Integer.parseInt(parts[0]); // int minor = Integer.parseInt(parts[1]); // // int build = -1; // boolean isSnapshot = false; // // if (parts.length == 3) { // if (parts[2].equals(SNAPSHOT)) { // isSnapshot = true; // } else { // build = Integer.parseInt(parts[2]); // } // } else if (parts.length == 4) { // build = Integer.parseInt(parts[2]); // isSnapshot = parts[3].equals(SNAPSHOT); // } // // return new AppVersion(major, minor, build, isSnapshot, versionString); // } // // private AppVersion(int major, int minor, int build, boolean isSnapshot, String original) { // this.major = major; // this.minor = minor; // // this.isSnapshot = isSnapshot; // this.build = build; // this.original = original; // } // // public int getMajor() { // return major; // } // // public int getMinor() { // return minor; // } // // public String getOriginal() { // return this.original; // } // // public boolean isSnapshot() { // return isSnapshot; // } // // public void setBuild(int build) { // this.build = build; // } // // public int getBuild() { // return build; // } // // public String toJsonString() { // return String.format( // "{ \"major\": %d, \"minor\": %d, \"build\": %d, \"isSnapshot\": %b, \"originalString\": \"%s\" }", // this.major, // this.minor, // this.build, // this.isSnapshot, // this.original); // } // // @Override // public String toString() { // String version = String.format("%s.%s", major, minor); // if(build > -1) { // version += "." + build; // } // if (isSnapshot) { // version += "-" + SNAPSHOT; // } // return version; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/Messages.java // public class Messages { // public static final String SEMANTIC_VERSION_FILENAME = ".semanticVersion"; // public static final String DISPLAY_NAME = "Determine Semantic Version"; // public static final String SEMANTIC_VERSION_COLUMN_DISPLAY_NAME = "Semantic Version"; // public static final String UNKNOWN_VERSION = "Unknown"; // // public static class Parsers { // public static final String SBT_BUILD_SBT_PARSER = "SBT build.sbt parser"; // public static final String MAVEN_POM_PARSER = "Maven Pom Parser"; // public static final String SBT_BUILD_SCALA_PARSER = "SBT Build.scala Parser"; // public static final String BOWER_JSON_PARSER = "Bower bower.json Parser"; // public static final String NPM_JSON_PARSER = "NPM package.json Parser"; // public static final String COMPOSER_JSON_PARSER = "Composer composer.json Parser"; // } // // public static class ColumnDisplayStrategies { // public static final String LAST_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Successful Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_BUILD_VERSION_STRATEGY = "Show Last Successful Semantic Version"; // public static final String NA_STRATEGY = "Show 'N/A'"; // } // // public static class NamingStrategies { // public static final String NOOP_NAMING = "none"; // public static final String MAVEN_RELEASE_DEVELOPMENT = "Maven, release and development version"; // public static final String UNTOUCHED = "As found"; // public static final String UNTOUCHED_SNAPSHOT = "As found (-SNAPSHOT)"; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/parsing/AbstractSemanticParserDescription.java // public abstract class AbstractSemanticParserDescription extends hudson.model.Descriptor { // @Override // public abstract String getDisplayName(); // } // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/naming/UntouchedNamingStrategy.java import hudson.Extension; import hudson.model.Descriptor; import java.io.Serializable; import java.util.Map; import java.util.logging.Logger; import org.jenkinsci.plugins.SemanticVersioning.AppVersion; import org.jenkinsci.plugins.SemanticVersioning.Messages; import org.jenkinsci.plugins.SemanticVersioning.parsing.AbstractSemanticParserDescription; package org.jenkinsci.plugins.SemanticVersioning.naming; @Extension public class UntouchedNamingStrategy implements NamingStrategy, Serializable {
private static Logger logger = Logger.getLogger(String.valueOf(AppVersion.class));
jenkinsci/semantic-versioning-plugin
src/main/java/org/jenkinsci/plugins/SemanticVersioning/naming/UntouchedNamingStrategy.java
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/AppVersion.java // public class AppVersion implements Serializable { // private static final String SNAPSHOT = "SNAPSHOT"; // private final int major; // private final int minor; // private final String original; // // private int build; // private final boolean isSnapshot; // public static final AppVersion EmptyVersion = new AppVersion(0, 0, 0, false, ""); // // public static AppVersion parse(String versionString) { // String[] parts = versionString.split("[\\.-]"); // // int major = Integer.parseInt(parts[0]); // int minor = Integer.parseInt(parts[1]); // // int build = -1; // boolean isSnapshot = false; // // if (parts.length == 3) { // if (parts[2].equals(SNAPSHOT)) { // isSnapshot = true; // } else { // build = Integer.parseInt(parts[2]); // } // } else if (parts.length == 4) { // build = Integer.parseInt(parts[2]); // isSnapshot = parts[3].equals(SNAPSHOT); // } // // return new AppVersion(major, minor, build, isSnapshot, versionString); // } // // private AppVersion(int major, int minor, int build, boolean isSnapshot, String original) { // this.major = major; // this.minor = minor; // // this.isSnapshot = isSnapshot; // this.build = build; // this.original = original; // } // // public int getMajor() { // return major; // } // // public int getMinor() { // return minor; // } // // public String getOriginal() { // return this.original; // } // // public boolean isSnapshot() { // return isSnapshot; // } // // public void setBuild(int build) { // this.build = build; // } // // public int getBuild() { // return build; // } // // public String toJsonString() { // return String.format( // "{ \"major\": %d, \"minor\": %d, \"build\": %d, \"isSnapshot\": %b, \"originalString\": \"%s\" }", // this.major, // this.minor, // this.build, // this.isSnapshot, // this.original); // } // // @Override // public String toString() { // String version = String.format("%s.%s", major, minor); // if(build > -1) { // version += "." + build; // } // if (isSnapshot) { // version += "-" + SNAPSHOT; // } // return version; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/Messages.java // public class Messages { // public static final String SEMANTIC_VERSION_FILENAME = ".semanticVersion"; // public static final String DISPLAY_NAME = "Determine Semantic Version"; // public static final String SEMANTIC_VERSION_COLUMN_DISPLAY_NAME = "Semantic Version"; // public static final String UNKNOWN_VERSION = "Unknown"; // // public static class Parsers { // public static final String SBT_BUILD_SBT_PARSER = "SBT build.sbt parser"; // public static final String MAVEN_POM_PARSER = "Maven Pom Parser"; // public static final String SBT_BUILD_SCALA_PARSER = "SBT Build.scala Parser"; // public static final String BOWER_JSON_PARSER = "Bower bower.json Parser"; // public static final String NPM_JSON_PARSER = "NPM package.json Parser"; // public static final String COMPOSER_JSON_PARSER = "Composer composer.json Parser"; // } // // public static class ColumnDisplayStrategies { // public static final String LAST_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Successful Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_BUILD_VERSION_STRATEGY = "Show Last Successful Semantic Version"; // public static final String NA_STRATEGY = "Show 'N/A'"; // } // // public static class NamingStrategies { // public static final String NOOP_NAMING = "none"; // public static final String MAVEN_RELEASE_DEVELOPMENT = "Maven, release and development version"; // public static final String UNTOUCHED = "As found"; // public static final String UNTOUCHED_SNAPSHOT = "As found (-SNAPSHOT)"; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/parsing/AbstractSemanticParserDescription.java // public abstract class AbstractSemanticParserDescription extends hudson.model.Descriptor { // @Override // public abstract String getDisplayName(); // }
import hudson.Extension; import hudson.model.Descriptor; import java.io.Serializable; import java.util.Map; import java.util.logging.Logger; import org.jenkinsci.plugins.SemanticVersioning.AppVersion; import org.jenkinsci.plugins.SemanticVersioning.Messages; import org.jenkinsci.plugins.SemanticVersioning.parsing.AbstractSemanticParserDescription;
package org.jenkinsci.plugins.SemanticVersioning.naming; @Extension public class UntouchedNamingStrategy implements NamingStrategy, Serializable { private static Logger logger = Logger.getLogger(String.valueOf(AppVersion.class)); public Descriptor<NamingStrategy> getDescriptor() {
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/AppVersion.java // public class AppVersion implements Serializable { // private static final String SNAPSHOT = "SNAPSHOT"; // private final int major; // private final int minor; // private final String original; // // private int build; // private final boolean isSnapshot; // public static final AppVersion EmptyVersion = new AppVersion(0, 0, 0, false, ""); // // public static AppVersion parse(String versionString) { // String[] parts = versionString.split("[\\.-]"); // // int major = Integer.parseInt(parts[0]); // int minor = Integer.parseInt(parts[1]); // // int build = -1; // boolean isSnapshot = false; // // if (parts.length == 3) { // if (parts[2].equals(SNAPSHOT)) { // isSnapshot = true; // } else { // build = Integer.parseInt(parts[2]); // } // } else if (parts.length == 4) { // build = Integer.parseInt(parts[2]); // isSnapshot = parts[3].equals(SNAPSHOT); // } // // return new AppVersion(major, minor, build, isSnapshot, versionString); // } // // private AppVersion(int major, int minor, int build, boolean isSnapshot, String original) { // this.major = major; // this.minor = minor; // // this.isSnapshot = isSnapshot; // this.build = build; // this.original = original; // } // // public int getMajor() { // return major; // } // // public int getMinor() { // return minor; // } // // public String getOriginal() { // return this.original; // } // // public boolean isSnapshot() { // return isSnapshot; // } // // public void setBuild(int build) { // this.build = build; // } // // public int getBuild() { // return build; // } // // public String toJsonString() { // return String.format( // "{ \"major\": %d, \"minor\": %d, \"build\": %d, \"isSnapshot\": %b, \"originalString\": \"%s\" }", // this.major, // this.minor, // this.build, // this.isSnapshot, // this.original); // } // // @Override // public String toString() { // String version = String.format("%s.%s", major, minor); // if(build > -1) { // version += "." + build; // } // if (isSnapshot) { // version += "-" + SNAPSHOT; // } // return version; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/Messages.java // public class Messages { // public static final String SEMANTIC_VERSION_FILENAME = ".semanticVersion"; // public static final String DISPLAY_NAME = "Determine Semantic Version"; // public static final String SEMANTIC_VERSION_COLUMN_DISPLAY_NAME = "Semantic Version"; // public static final String UNKNOWN_VERSION = "Unknown"; // // public static class Parsers { // public static final String SBT_BUILD_SBT_PARSER = "SBT build.sbt parser"; // public static final String MAVEN_POM_PARSER = "Maven Pom Parser"; // public static final String SBT_BUILD_SCALA_PARSER = "SBT Build.scala Parser"; // public static final String BOWER_JSON_PARSER = "Bower bower.json Parser"; // public static final String NPM_JSON_PARSER = "NPM package.json Parser"; // public static final String COMPOSER_JSON_PARSER = "Composer composer.json Parser"; // } // // public static class ColumnDisplayStrategies { // public static final String LAST_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Successful Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_BUILD_VERSION_STRATEGY = "Show Last Successful Semantic Version"; // public static final String NA_STRATEGY = "Show 'N/A'"; // } // // public static class NamingStrategies { // public static final String NOOP_NAMING = "none"; // public static final String MAVEN_RELEASE_DEVELOPMENT = "Maven, release and development version"; // public static final String UNTOUCHED = "As found"; // public static final String UNTOUCHED_SNAPSHOT = "As found (-SNAPSHOT)"; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/parsing/AbstractSemanticParserDescription.java // public abstract class AbstractSemanticParserDescription extends hudson.model.Descriptor { // @Override // public abstract String getDisplayName(); // } // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/naming/UntouchedNamingStrategy.java import hudson.Extension; import hudson.model.Descriptor; import java.io.Serializable; import java.util.Map; import java.util.logging.Logger; import org.jenkinsci.plugins.SemanticVersioning.AppVersion; import org.jenkinsci.plugins.SemanticVersioning.Messages; import org.jenkinsci.plugins.SemanticVersioning.parsing.AbstractSemanticParserDescription; package org.jenkinsci.plugins.SemanticVersioning.naming; @Extension public class UntouchedNamingStrategy implements NamingStrategy, Serializable { private static Logger logger = Logger.getLogger(String.valueOf(AppVersion.class)); public Descriptor<NamingStrategy> getDescriptor() {
return new AbstractSemanticParserDescription() {
jenkinsci/semantic-versioning-plugin
src/main/java/org/jenkinsci/plugins/SemanticVersioning/naming/UntouchedNamingStrategy.java
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/AppVersion.java // public class AppVersion implements Serializable { // private static final String SNAPSHOT = "SNAPSHOT"; // private final int major; // private final int minor; // private final String original; // // private int build; // private final boolean isSnapshot; // public static final AppVersion EmptyVersion = new AppVersion(0, 0, 0, false, ""); // // public static AppVersion parse(String versionString) { // String[] parts = versionString.split("[\\.-]"); // // int major = Integer.parseInt(parts[0]); // int minor = Integer.parseInt(parts[1]); // // int build = -1; // boolean isSnapshot = false; // // if (parts.length == 3) { // if (parts[2].equals(SNAPSHOT)) { // isSnapshot = true; // } else { // build = Integer.parseInt(parts[2]); // } // } else if (parts.length == 4) { // build = Integer.parseInt(parts[2]); // isSnapshot = parts[3].equals(SNAPSHOT); // } // // return new AppVersion(major, minor, build, isSnapshot, versionString); // } // // private AppVersion(int major, int minor, int build, boolean isSnapshot, String original) { // this.major = major; // this.minor = minor; // // this.isSnapshot = isSnapshot; // this.build = build; // this.original = original; // } // // public int getMajor() { // return major; // } // // public int getMinor() { // return minor; // } // // public String getOriginal() { // return this.original; // } // // public boolean isSnapshot() { // return isSnapshot; // } // // public void setBuild(int build) { // this.build = build; // } // // public int getBuild() { // return build; // } // // public String toJsonString() { // return String.format( // "{ \"major\": %d, \"minor\": %d, \"build\": %d, \"isSnapshot\": %b, \"originalString\": \"%s\" }", // this.major, // this.minor, // this.build, // this.isSnapshot, // this.original); // } // // @Override // public String toString() { // String version = String.format("%s.%s", major, minor); // if(build > -1) { // version += "." + build; // } // if (isSnapshot) { // version += "-" + SNAPSHOT; // } // return version; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/Messages.java // public class Messages { // public static final String SEMANTIC_VERSION_FILENAME = ".semanticVersion"; // public static final String DISPLAY_NAME = "Determine Semantic Version"; // public static final String SEMANTIC_VERSION_COLUMN_DISPLAY_NAME = "Semantic Version"; // public static final String UNKNOWN_VERSION = "Unknown"; // // public static class Parsers { // public static final String SBT_BUILD_SBT_PARSER = "SBT build.sbt parser"; // public static final String MAVEN_POM_PARSER = "Maven Pom Parser"; // public static final String SBT_BUILD_SCALA_PARSER = "SBT Build.scala Parser"; // public static final String BOWER_JSON_PARSER = "Bower bower.json Parser"; // public static final String NPM_JSON_PARSER = "NPM package.json Parser"; // public static final String COMPOSER_JSON_PARSER = "Composer composer.json Parser"; // } // // public static class ColumnDisplayStrategies { // public static final String LAST_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Successful Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_BUILD_VERSION_STRATEGY = "Show Last Successful Semantic Version"; // public static final String NA_STRATEGY = "Show 'N/A'"; // } // // public static class NamingStrategies { // public static final String NOOP_NAMING = "none"; // public static final String MAVEN_RELEASE_DEVELOPMENT = "Maven, release and development version"; // public static final String UNTOUCHED = "As found"; // public static final String UNTOUCHED_SNAPSHOT = "As found (-SNAPSHOT)"; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/parsing/AbstractSemanticParserDescription.java // public abstract class AbstractSemanticParserDescription extends hudson.model.Descriptor { // @Override // public abstract String getDisplayName(); // }
import hudson.Extension; import hudson.model.Descriptor; import java.io.Serializable; import java.util.Map; import java.util.logging.Logger; import org.jenkinsci.plugins.SemanticVersioning.AppVersion; import org.jenkinsci.plugins.SemanticVersioning.Messages; import org.jenkinsci.plugins.SemanticVersioning.parsing.AbstractSemanticParserDescription;
package org.jenkinsci.plugins.SemanticVersioning.naming; @Extension public class UntouchedNamingStrategy implements NamingStrategy, Serializable { private static Logger logger = Logger.getLogger(String.valueOf(AppVersion.class)); public Descriptor<NamingStrategy> getDescriptor() { return new AbstractSemanticParserDescription() { @Override public String getDisplayName() {
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/AppVersion.java // public class AppVersion implements Serializable { // private static final String SNAPSHOT = "SNAPSHOT"; // private final int major; // private final int minor; // private final String original; // // private int build; // private final boolean isSnapshot; // public static final AppVersion EmptyVersion = new AppVersion(0, 0, 0, false, ""); // // public static AppVersion parse(String versionString) { // String[] parts = versionString.split("[\\.-]"); // // int major = Integer.parseInt(parts[0]); // int minor = Integer.parseInt(parts[1]); // // int build = -1; // boolean isSnapshot = false; // // if (parts.length == 3) { // if (parts[2].equals(SNAPSHOT)) { // isSnapshot = true; // } else { // build = Integer.parseInt(parts[2]); // } // } else if (parts.length == 4) { // build = Integer.parseInt(parts[2]); // isSnapshot = parts[3].equals(SNAPSHOT); // } // // return new AppVersion(major, minor, build, isSnapshot, versionString); // } // // private AppVersion(int major, int minor, int build, boolean isSnapshot, String original) { // this.major = major; // this.minor = minor; // // this.isSnapshot = isSnapshot; // this.build = build; // this.original = original; // } // // public int getMajor() { // return major; // } // // public int getMinor() { // return minor; // } // // public String getOriginal() { // return this.original; // } // // public boolean isSnapshot() { // return isSnapshot; // } // // public void setBuild(int build) { // this.build = build; // } // // public int getBuild() { // return build; // } // // public String toJsonString() { // return String.format( // "{ \"major\": %d, \"minor\": %d, \"build\": %d, \"isSnapshot\": %b, \"originalString\": \"%s\" }", // this.major, // this.minor, // this.build, // this.isSnapshot, // this.original); // } // // @Override // public String toString() { // String version = String.format("%s.%s", major, minor); // if(build > -1) { // version += "." + build; // } // if (isSnapshot) { // version += "-" + SNAPSHOT; // } // return version; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/Messages.java // public class Messages { // public static final String SEMANTIC_VERSION_FILENAME = ".semanticVersion"; // public static final String DISPLAY_NAME = "Determine Semantic Version"; // public static final String SEMANTIC_VERSION_COLUMN_DISPLAY_NAME = "Semantic Version"; // public static final String UNKNOWN_VERSION = "Unknown"; // // public static class Parsers { // public static final String SBT_BUILD_SBT_PARSER = "SBT build.sbt parser"; // public static final String MAVEN_POM_PARSER = "Maven Pom Parser"; // public static final String SBT_BUILD_SCALA_PARSER = "SBT Build.scala Parser"; // public static final String BOWER_JSON_PARSER = "Bower bower.json Parser"; // public static final String NPM_JSON_PARSER = "NPM package.json Parser"; // public static final String COMPOSER_JSON_PARSER = "Composer composer.json Parser"; // } // // public static class ColumnDisplayStrategies { // public static final String LAST_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Successful Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_BUILD_VERSION_STRATEGY = "Show Last Successful Semantic Version"; // public static final String NA_STRATEGY = "Show 'N/A'"; // } // // public static class NamingStrategies { // public static final String NOOP_NAMING = "none"; // public static final String MAVEN_RELEASE_DEVELOPMENT = "Maven, release and development version"; // public static final String UNTOUCHED = "As found"; // public static final String UNTOUCHED_SNAPSHOT = "As found (-SNAPSHOT)"; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/parsing/AbstractSemanticParserDescription.java // public abstract class AbstractSemanticParserDescription extends hudson.model.Descriptor { // @Override // public abstract String getDisplayName(); // } // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/naming/UntouchedNamingStrategy.java import hudson.Extension; import hudson.model.Descriptor; import java.io.Serializable; import java.util.Map; import java.util.logging.Logger; import org.jenkinsci.plugins.SemanticVersioning.AppVersion; import org.jenkinsci.plugins.SemanticVersioning.Messages; import org.jenkinsci.plugins.SemanticVersioning.parsing.AbstractSemanticParserDescription; package org.jenkinsci.plugins.SemanticVersioning.naming; @Extension public class UntouchedNamingStrategy implements NamingStrategy, Serializable { private static Logger logger = Logger.getLogger(String.valueOf(AppVersion.class)); public Descriptor<NamingStrategy> getDescriptor() { return new AbstractSemanticParserDescription() { @Override public String getDisplayName() {
return Messages.NamingStrategies.UNTOUCHED;
jenkinsci/semantic-versioning-plugin
src/main/java/org/jenkinsci/plugins/SemanticVersioning/columnDisplay/LastSuccessfulJenkinsBuildNumberStrategy.java
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/Messages.java // public class Messages { // public static final String SEMANTIC_VERSION_FILENAME = ".semanticVersion"; // public static final String DISPLAY_NAME = "Determine Semantic Version"; // public static final String SEMANTIC_VERSION_COLUMN_DISPLAY_NAME = "Semantic Version"; // public static final String UNKNOWN_VERSION = "Unknown"; // // public static class Parsers { // public static final String SBT_BUILD_SBT_PARSER = "SBT build.sbt parser"; // public static final String MAVEN_POM_PARSER = "Maven Pom Parser"; // public static final String SBT_BUILD_SCALA_PARSER = "SBT Build.scala Parser"; // public static final String BOWER_JSON_PARSER = "Bower bower.json Parser"; // public static final String NPM_JSON_PARSER = "NPM package.json Parser"; // public static final String COMPOSER_JSON_PARSER = "Composer composer.json Parser"; // } // // public static class ColumnDisplayStrategies { // public static final String LAST_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Successful Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_BUILD_VERSION_STRATEGY = "Show Last Successful Semantic Version"; // public static final String NA_STRATEGY = "Show 'N/A'"; // } // // public static class NamingStrategies { // public static final String NOOP_NAMING = "none"; // public static final String MAVEN_RELEASE_DEVELOPMENT = "Maven, release and development version"; // public static final String UNTOUCHED = "As found"; // public static final String UNTOUCHED_SNAPSHOT = "As found (-SNAPSHOT)"; // } // }
import hudson.Extension; import hudson.model.Descriptor; import hudson.model.Job; import org.jenkinsci.plugins.SemanticVersioning.Messages;
/* * The MIT License * * Copyright (c) 2014, Steve Wagner * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.jenkinsci.plugins.SemanticVersioning.columnDisplay; @Extension public class LastSuccessfulJenkinsBuildNumberStrategy extends AbstractColumnDisplayStrategy { public String getDisplayString(Job job) { return Integer.toString(job.getLastSuccessfulBuild().getNumber()); } @SuppressWarnings("unchecked") public Descriptor<ColumnDisplayStrategy> getDescriptor() { return new AbstractDisplayStrategyDescription() { @Override public String getDisplayName() {
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/Messages.java // public class Messages { // public static final String SEMANTIC_VERSION_FILENAME = ".semanticVersion"; // public static final String DISPLAY_NAME = "Determine Semantic Version"; // public static final String SEMANTIC_VERSION_COLUMN_DISPLAY_NAME = "Semantic Version"; // public static final String UNKNOWN_VERSION = "Unknown"; // // public static class Parsers { // public static final String SBT_BUILD_SBT_PARSER = "SBT build.sbt parser"; // public static final String MAVEN_POM_PARSER = "Maven Pom Parser"; // public static final String SBT_BUILD_SCALA_PARSER = "SBT Build.scala Parser"; // public static final String BOWER_JSON_PARSER = "Bower bower.json Parser"; // public static final String NPM_JSON_PARSER = "NPM package.json Parser"; // public static final String COMPOSER_JSON_PARSER = "Composer composer.json Parser"; // } // // public static class ColumnDisplayStrategies { // public static final String LAST_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Successful Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_BUILD_VERSION_STRATEGY = "Show Last Successful Semantic Version"; // public static final String NA_STRATEGY = "Show 'N/A'"; // } // // public static class NamingStrategies { // public static final String NOOP_NAMING = "none"; // public static final String MAVEN_RELEASE_DEVELOPMENT = "Maven, release and development version"; // public static final String UNTOUCHED = "As found"; // public static final String UNTOUCHED_SNAPSHOT = "As found (-SNAPSHOT)"; // } // } // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/columnDisplay/LastSuccessfulJenkinsBuildNumberStrategy.java import hudson.Extension; import hudson.model.Descriptor; import hudson.model.Job; import org.jenkinsci.plugins.SemanticVersioning.Messages; /* * The MIT License * * Copyright (c) 2014, Steve Wagner * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.jenkinsci.plugins.SemanticVersioning.columnDisplay; @Extension public class LastSuccessfulJenkinsBuildNumberStrategy extends AbstractColumnDisplayStrategy { public String getDisplayString(Job job) { return Integer.toString(job.getLastSuccessfulBuild().getNumber()); } @SuppressWarnings("unchecked") public Descriptor<ColumnDisplayStrategy> getDescriptor() { return new AbstractDisplayStrategyDescription() { @Override public String getDisplayName() {
return Messages.ColumnDisplayStrategies.LAST_SUCCESSFUL_JENKINS_BUILD_NUMBER_STRATEGY;
jenkinsci/semantic-versioning-plugin
src/main/java/org/jenkinsci/plugins/SemanticVersioning/columnDisplay/NotApplicableStrategy.java
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/Messages.java // public class Messages { // public static final String SEMANTIC_VERSION_FILENAME = ".semanticVersion"; // public static final String DISPLAY_NAME = "Determine Semantic Version"; // public static final String SEMANTIC_VERSION_COLUMN_DISPLAY_NAME = "Semantic Version"; // public static final String UNKNOWN_VERSION = "Unknown"; // // public static class Parsers { // public static final String SBT_BUILD_SBT_PARSER = "SBT build.sbt parser"; // public static final String MAVEN_POM_PARSER = "Maven Pom Parser"; // public static final String SBT_BUILD_SCALA_PARSER = "SBT Build.scala Parser"; // public static final String BOWER_JSON_PARSER = "Bower bower.json Parser"; // public static final String NPM_JSON_PARSER = "NPM package.json Parser"; // public static final String COMPOSER_JSON_PARSER = "Composer composer.json Parser"; // } // // public static class ColumnDisplayStrategies { // public static final String LAST_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Successful Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_BUILD_VERSION_STRATEGY = "Show Last Successful Semantic Version"; // public static final String NA_STRATEGY = "Show 'N/A'"; // } // // public static class NamingStrategies { // public static final String NOOP_NAMING = "none"; // public static final String MAVEN_RELEASE_DEVELOPMENT = "Maven, release and development version"; // public static final String UNTOUCHED = "As found"; // public static final String UNTOUCHED_SNAPSHOT = "As found (-SNAPSHOT)"; // } // }
import hudson.Extension; import hudson.model.Descriptor; import hudson.model.Job; import org.jenkinsci.plugins.SemanticVersioning.Messages;
/* * The MIT License * * Copyright (c) 2014, Steve Wagner * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.jenkinsci.plugins.SemanticVersioning.columnDisplay; @Extension public class NotApplicableStrategy extends AbstractColumnDisplayStrategy { public String getDisplayString(Job job) { return "N/A"; } @SuppressWarnings("unchecked") public Descriptor<ColumnDisplayStrategy> getDescriptor() { return new AbstractDisplayStrategyDescription() { @Override public String getDisplayName() {
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/Messages.java // public class Messages { // public static final String SEMANTIC_VERSION_FILENAME = ".semanticVersion"; // public static final String DISPLAY_NAME = "Determine Semantic Version"; // public static final String SEMANTIC_VERSION_COLUMN_DISPLAY_NAME = "Semantic Version"; // public static final String UNKNOWN_VERSION = "Unknown"; // // public static class Parsers { // public static final String SBT_BUILD_SBT_PARSER = "SBT build.sbt parser"; // public static final String MAVEN_POM_PARSER = "Maven Pom Parser"; // public static final String SBT_BUILD_SCALA_PARSER = "SBT Build.scala Parser"; // public static final String BOWER_JSON_PARSER = "Bower bower.json Parser"; // public static final String NPM_JSON_PARSER = "NPM package.json Parser"; // public static final String COMPOSER_JSON_PARSER = "Composer composer.json Parser"; // } // // public static class ColumnDisplayStrategies { // public static final String LAST_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Successful Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_BUILD_VERSION_STRATEGY = "Show Last Successful Semantic Version"; // public static final String NA_STRATEGY = "Show 'N/A'"; // } // // public static class NamingStrategies { // public static final String NOOP_NAMING = "none"; // public static final String MAVEN_RELEASE_DEVELOPMENT = "Maven, release and development version"; // public static final String UNTOUCHED = "As found"; // public static final String UNTOUCHED_SNAPSHOT = "As found (-SNAPSHOT)"; // } // } // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/columnDisplay/NotApplicableStrategy.java import hudson.Extension; import hudson.model.Descriptor; import hudson.model.Job; import org.jenkinsci.plugins.SemanticVersioning.Messages; /* * The MIT License * * Copyright (c) 2014, Steve Wagner * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.jenkinsci.plugins.SemanticVersioning.columnDisplay; @Extension public class NotApplicableStrategy extends AbstractColumnDisplayStrategy { public String getDisplayString(Job job) { return "N/A"; } @SuppressWarnings("unchecked") public Descriptor<ColumnDisplayStrategy> getDescriptor() { return new AbstractDisplayStrategyDescription() { @Override public String getDisplayName() {
return Messages.ColumnDisplayStrategies.NA_STRATEGY;
jenkinsci/semantic-versioning-plugin
src/main/java/org/jenkinsci/plugins/SemanticVersioning/parsing/ComposerParser.java
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/Messages.java // public class Messages { // public static final String SEMANTIC_VERSION_FILENAME = ".semanticVersion"; // public static final String DISPLAY_NAME = "Determine Semantic Version"; // public static final String SEMANTIC_VERSION_COLUMN_DISPLAY_NAME = "Semantic Version"; // public static final String UNKNOWN_VERSION = "Unknown"; // // public static class Parsers { // public static final String SBT_BUILD_SBT_PARSER = "SBT build.sbt parser"; // public static final String MAVEN_POM_PARSER = "Maven Pom Parser"; // public static final String SBT_BUILD_SCALA_PARSER = "SBT Build.scala Parser"; // public static final String BOWER_JSON_PARSER = "Bower bower.json Parser"; // public static final String NPM_JSON_PARSER = "NPM package.json Parser"; // public static final String COMPOSER_JSON_PARSER = "Composer composer.json Parser"; // } // // public static class ColumnDisplayStrategies { // public static final String LAST_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Successful Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_BUILD_VERSION_STRATEGY = "Show Last Successful Semantic Version"; // public static final String NA_STRATEGY = "Show 'N/A'"; // } // // public static class NamingStrategies { // public static final String NOOP_NAMING = "none"; // public static final String MAVEN_RELEASE_DEVELOPMENT = "Maven, release and development version"; // public static final String UNTOUCHED = "As found"; // public static final String UNTOUCHED_SNAPSHOT = "As found (-SNAPSHOT)"; // } // }
import hudson.Extension; import hudson.model.Descriptor; import org.jenkinsci.plugins.SemanticVersioning.Messages;
/* * The MIT License * * Copyright (c) 2014, Arne M. Størksen * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.jenkinsci.plugins.SemanticVersioning.parsing; @Extension public class ComposerParser extends JsonVersionParser { public ComposerParser() { super("composer.json", "version"); } @SuppressWarnings("unchecked") public Descriptor<BuildDefinitionParser> getDescriptor() { return new AbstractSemanticParserDescription() { @Override public String getDisplayName() {
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/Messages.java // public class Messages { // public static final String SEMANTIC_VERSION_FILENAME = ".semanticVersion"; // public static final String DISPLAY_NAME = "Determine Semantic Version"; // public static final String SEMANTIC_VERSION_COLUMN_DISPLAY_NAME = "Semantic Version"; // public static final String UNKNOWN_VERSION = "Unknown"; // // public static class Parsers { // public static final String SBT_BUILD_SBT_PARSER = "SBT build.sbt parser"; // public static final String MAVEN_POM_PARSER = "Maven Pom Parser"; // public static final String SBT_BUILD_SCALA_PARSER = "SBT Build.scala Parser"; // public static final String BOWER_JSON_PARSER = "Bower bower.json Parser"; // public static final String NPM_JSON_PARSER = "NPM package.json Parser"; // public static final String COMPOSER_JSON_PARSER = "Composer composer.json Parser"; // } // // public static class ColumnDisplayStrategies { // public static final String LAST_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Successful Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_BUILD_VERSION_STRATEGY = "Show Last Successful Semantic Version"; // public static final String NA_STRATEGY = "Show 'N/A'"; // } // // public static class NamingStrategies { // public static final String NOOP_NAMING = "none"; // public static final String MAVEN_RELEASE_DEVELOPMENT = "Maven, release and development version"; // public static final String UNTOUCHED = "As found"; // public static final String UNTOUCHED_SNAPSHOT = "As found (-SNAPSHOT)"; // } // } // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/parsing/ComposerParser.java import hudson.Extension; import hudson.model.Descriptor; import org.jenkinsci.plugins.SemanticVersioning.Messages; /* * The MIT License * * Copyright (c) 2014, Arne M. Størksen * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.jenkinsci.plugins.SemanticVersioning.parsing; @Extension public class ComposerParser extends JsonVersionParser { public ComposerParser() { super("composer.json", "version"); } @SuppressWarnings("unchecked") public Descriptor<BuildDefinitionParser> getDescriptor() { return new AbstractSemanticParserDescription() { @Override public String getDisplayName() {
return Messages.Parsers.COMPOSER_JSON_PARSER;
jenkinsci/semantic-versioning-plugin
src/main/java/org/jenkinsci/plugins/SemanticVersioning/naming/UntouchedSnapshotNamingStrategy.java
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/AppVersion.java // public class AppVersion implements Serializable { // private static final String SNAPSHOT = "SNAPSHOT"; // private final int major; // private final int minor; // private final String original; // // private int build; // private final boolean isSnapshot; // public static final AppVersion EmptyVersion = new AppVersion(0, 0, 0, false, ""); // // public static AppVersion parse(String versionString) { // String[] parts = versionString.split("[\\.-]"); // // int major = Integer.parseInt(parts[0]); // int minor = Integer.parseInt(parts[1]); // // int build = -1; // boolean isSnapshot = false; // // if (parts.length == 3) { // if (parts[2].equals(SNAPSHOT)) { // isSnapshot = true; // } else { // build = Integer.parseInt(parts[2]); // } // } else if (parts.length == 4) { // build = Integer.parseInt(parts[2]); // isSnapshot = parts[3].equals(SNAPSHOT); // } // // return new AppVersion(major, minor, build, isSnapshot, versionString); // } // // private AppVersion(int major, int minor, int build, boolean isSnapshot, String original) { // this.major = major; // this.minor = minor; // // this.isSnapshot = isSnapshot; // this.build = build; // this.original = original; // } // // public int getMajor() { // return major; // } // // public int getMinor() { // return minor; // } // // public String getOriginal() { // return this.original; // } // // public boolean isSnapshot() { // return isSnapshot; // } // // public void setBuild(int build) { // this.build = build; // } // // public int getBuild() { // return build; // } // // public String toJsonString() { // return String.format( // "{ \"major\": %d, \"minor\": %d, \"build\": %d, \"isSnapshot\": %b, \"originalString\": \"%s\" }", // this.major, // this.minor, // this.build, // this.isSnapshot, // this.original); // } // // @Override // public String toString() { // String version = String.format("%s.%s", major, minor); // if(build > -1) { // version += "." + build; // } // if (isSnapshot) { // version += "-" + SNAPSHOT; // } // return version; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/Messages.java // public class Messages { // public static final String SEMANTIC_VERSION_FILENAME = ".semanticVersion"; // public static final String DISPLAY_NAME = "Determine Semantic Version"; // public static final String SEMANTIC_VERSION_COLUMN_DISPLAY_NAME = "Semantic Version"; // public static final String UNKNOWN_VERSION = "Unknown"; // // public static class Parsers { // public static final String SBT_BUILD_SBT_PARSER = "SBT build.sbt parser"; // public static final String MAVEN_POM_PARSER = "Maven Pom Parser"; // public static final String SBT_BUILD_SCALA_PARSER = "SBT Build.scala Parser"; // public static final String BOWER_JSON_PARSER = "Bower bower.json Parser"; // public static final String NPM_JSON_PARSER = "NPM package.json Parser"; // public static final String COMPOSER_JSON_PARSER = "Composer composer.json Parser"; // } // // public static class ColumnDisplayStrategies { // public static final String LAST_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Successful Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_BUILD_VERSION_STRATEGY = "Show Last Successful Semantic Version"; // public static final String NA_STRATEGY = "Show 'N/A'"; // } // // public static class NamingStrategies { // public static final String NOOP_NAMING = "none"; // public static final String MAVEN_RELEASE_DEVELOPMENT = "Maven, release and development version"; // public static final String UNTOUCHED = "As found"; // public static final String UNTOUCHED_SNAPSHOT = "As found (-SNAPSHOT)"; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/parsing/AbstractSemanticParserDescription.java // public abstract class AbstractSemanticParserDescription extends hudson.model.Descriptor { // @Override // public abstract String getDisplayName(); // }
import hudson.Extension; import hudson.model.Descriptor; import java.io.Serializable; import java.util.Map; import java.util.logging.Logger; import org.jenkinsci.plugins.SemanticVersioning.AppVersion; import org.jenkinsci.plugins.SemanticVersioning.Messages; import org.jenkinsci.plugins.SemanticVersioning.parsing.AbstractSemanticParserDescription;
package org.jenkinsci.plugins.SemanticVersioning.naming; @Extension public class UntouchedSnapshotNamingStrategy implements NamingStrategy, Serializable {
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/AppVersion.java // public class AppVersion implements Serializable { // private static final String SNAPSHOT = "SNAPSHOT"; // private final int major; // private final int minor; // private final String original; // // private int build; // private final boolean isSnapshot; // public static final AppVersion EmptyVersion = new AppVersion(0, 0, 0, false, ""); // // public static AppVersion parse(String versionString) { // String[] parts = versionString.split("[\\.-]"); // // int major = Integer.parseInt(parts[0]); // int minor = Integer.parseInt(parts[1]); // // int build = -1; // boolean isSnapshot = false; // // if (parts.length == 3) { // if (parts[2].equals(SNAPSHOT)) { // isSnapshot = true; // } else { // build = Integer.parseInt(parts[2]); // } // } else if (parts.length == 4) { // build = Integer.parseInt(parts[2]); // isSnapshot = parts[3].equals(SNAPSHOT); // } // // return new AppVersion(major, minor, build, isSnapshot, versionString); // } // // private AppVersion(int major, int minor, int build, boolean isSnapshot, String original) { // this.major = major; // this.minor = minor; // // this.isSnapshot = isSnapshot; // this.build = build; // this.original = original; // } // // public int getMajor() { // return major; // } // // public int getMinor() { // return minor; // } // // public String getOriginal() { // return this.original; // } // // public boolean isSnapshot() { // return isSnapshot; // } // // public void setBuild(int build) { // this.build = build; // } // // public int getBuild() { // return build; // } // // public String toJsonString() { // return String.format( // "{ \"major\": %d, \"minor\": %d, \"build\": %d, \"isSnapshot\": %b, \"originalString\": \"%s\" }", // this.major, // this.minor, // this.build, // this.isSnapshot, // this.original); // } // // @Override // public String toString() { // String version = String.format("%s.%s", major, minor); // if(build > -1) { // version += "." + build; // } // if (isSnapshot) { // version += "-" + SNAPSHOT; // } // return version; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/Messages.java // public class Messages { // public static final String SEMANTIC_VERSION_FILENAME = ".semanticVersion"; // public static final String DISPLAY_NAME = "Determine Semantic Version"; // public static final String SEMANTIC_VERSION_COLUMN_DISPLAY_NAME = "Semantic Version"; // public static final String UNKNOWN_VERSION = "Unknown"; // // public static class Parsers { // public static final String SBT_BUILD_SBT_PARSER = "SBT build.sbt parser"; // public static final String MAVEN_POM_PARSER = "Maven Pom Parser"; // public static final String SBT_BUILD_SCALA_PARSER = "SBT Build.scala Parser"; // public static final String BOWER_JSON_PARSER = "Bower bower.json Parser"; // public static final String NPM_JSON_PARSER = "NPM package.json Parser"; // public static final String COMPOSER_JSON_PARSER = "Composer composer.json Parser"; // } // // public static class ColumnDisplayStrategies { // public static final String LAST_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Successful Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_BUILD_VERSION_STRATEGY = "Show Last Successful Semantic Version"; // public static final String NA_STRATEGY = "Show 'N/A'"; // } // // public static class NamingStrategies { // public static final String NOOP_NAMING = "none"; // public static final String MAVEN_RELEASE_DEVELOPMENT = "Maven, release and development version"; // public static final String UNTOUCHED = "As found"; // public static final String UNTOUCHED_SNAPSHOT = "As found (-SNAPSHOT)"; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/parsing/AbstractSemanticParserDescription.java // public abstract class AbstractSemanticParserDescription extends hudson.model.Descriptor { // @Override // public abstract String getDisplayName(); // } // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/naming/UntouchedSnapshotNamingStrategy.java import hudson.Extension; import hudson.model.Descriptor; import java.io.Serializable; import java.util.Map; import java.util.logging.Logger; import org.jenkinsci.plugins.SemanticVersioning.AppVersion; import org.jenkinsci.plugins.SemanticVersioning.Messages; import org.jenkinsci.plugins.SemanticVersioning.parsing.AbstractSemanticParserDescription; package org.jenkinsci.plugins.SemanticVersioning.naming; @Extension public class UntouchedSnapshotNamingStrategy implements NamingStrategy, Serializable {
private static Logger logger = Logger.getLogger(String.valueOf(AppVersion.class));
jenkinsci/semantic-versioning-plugin
src/main/java/org/jenkinsci/plugins/SemanticVersioning/naming/UntouchedSnapshotNamingStrategy.java
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/AppVersion.java // public class AppVersion implements Serializable { // private static final String SNAPSHOT = "SNAPSHOT"; // private final int major; // private final int minor; // private final String original; // // private int build; // private final boolean isSnapshot; // public static final AppVersion EmptyVersion = new AppVersion(0, 0, 0, false, ""); // // public static AppVersion parse(String versionString) { // String[] parts = versionString.split("[\\.-]"); // // int major = Integer.parseInt(parts[0]); // int minor = Integer.parseInt(parts[1]); // // int build = -1; // boolean isSnapshot = false; // // if (parts.length == 3) { // if (parts[2].equals(SNAPSHOT)) { // isSnapshot = true; // } else { // build = Integer.parseInt(parts[2]); // } // } else if (parts.length == 4) { // build = Integer.parseInt(parts[2]); // isSnapshot = parts[3].equals(SNAPSHOT); // } // // return new AppVersion(major, minor, build, isSnapshot, versionString); // } // // private AppVersion(int major, int minor, int build, boolean isSnapshot, String original) { // this.major = major; // this.minor = minor; // // this.isSnapshot = isSnapshot; // this.build = build; // this.original = original; // } // // public int getMajor() { // return major; // } // // public int getMinor() { // return minor; // } // // public String getOriginal() { // return this.original; // } // // public boolean isSnapshot() { // return isSnapshot; // } // // public void setBuild(int build) { // this.build = build; // } // // public int getBuild() { // return build; // } // // public String toJsonString() { // return String.format( // "{ \"major\": %d, \"minor\": %d, \"build\": %d, \"isSnapshot\": %b, \"originalString\": \"%s\" }", // this.major, // this.minor, // this.build, // this.isSnapshot, // this.original); // } // // @Override // public String toString() { // String version = String.format("%s.%s", major, minor); // if(build > -1) { // version += "." + build; // } // if (isSnapshot) { // version += "-" + SNAPSHOT; // } // return version; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/Messages.java // public class Messages { // public static final String SEMANTIC_VERSION_FILENAME = ".semanticVersion"; // public static final String DISPLAY_NAME = "Determine Semantic Version"; // public static final String SEMANTIC_VERSION_COLUMN_DISPLAY_NAME = "Semantic Version"; // public static final String UNKNOWN_VERSION = "Unknown"; // // public static class Parsers { // public static final String SBT_BUILD_SBT_PARSER = "SBT build.sbt parser"; // public static final String MAVEN_POM_PARSER = "Maven Pom Parser"; // public static final String SBT_BUILD_SCALA_PARSER = "SBT Build.scala Parser"; // public static final String BOWER_JSON_PARSER = "Bower bower.json Parser"; // public static final String NPM_JSON_PARSER = "NPM package.json Parser"; // public static final String COMPOSER_JSON_PARSER = "Composer composer.json Parser"; // } // // public static class ColumnDisplayStrategies { // public static final String LAST_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Successful Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_BUILD_VERSION_STRATEGY = "Show Last Successful Semantic Version"; // public static final String NA_STRATEGY = "Show 'N/A'"; // } // // public static class NamingStrategies { // public static final String NOOP_NAMING = "none"; // public static final String MAVEN_RELEASE_DEVELOPMENT = "Maven, release and development version"; // public static final String UNTOUCHED = "As found"; // public static final String UNTOUCHED_SNAPSHOT = "As found (-SNAPSHOT)"; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/parsing/AbstractSemanticParserDescription.java // public abstract class AbstractSemanticParserDescription extends hudson.model.Descriptor { // @Override // public abstract String getDisplayName(); // }
import hudson.Extension; import hudson.model.Descriptor; import java.io.Serializable; import java.util.Map; import java.util.logging.Logger; import org.jenkinsci.plugins.SemanticVersioning.AppVersion; import org.jenkinsci.plugins.SemanticVersioning.Messages; import org.jenkinsci.plugins.SemanticVersioning.parsing.AbstractSemanticParserDescription;
package org.jenkinsci.plugins.SemanticVersioning.naming; @Extension public class UntouchedSnapshotNamingStrategy implements NamingStrategy, Serializable { private static Logger logger = Logger.getLogger(String.valueOf(AppVersion.class)); public Descriptor<NamingStrategy> getDescriptor() {
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/AppVersion.java // public class AppVersion implements Serializable { // private static final String SNAPSHOT = "SNAPSHOT"; // private final int major; // private final int minor; // private final String original; // // private int build; // private final boolean isSnapshot; // public static final AppVersion EmptyVersion = new AppVersion(0, 0, 0, false, ""); // // public static AppVersion parse(String versionString) { // String[] parts = versionString.split("[\\.-]"); // // int major = Integer.parseInt(parts[0]); // int minor = Integer.parseInt(parts[1]); // // int build = -1; // boolean isSnapshot = false; // // if (parts.length == 3) { // if (parts[2].equals(SNAPSHOT)) { // isSnapshot = true; // } else { // build = Integer.parseInt(parts[2]); // } // } else if (parts.length == 4) { // build = Integer.parseInt(parts[2]); // isSnapshot = parts[3].equals(SNAPSHOT); // } // // return new AppVersion(major, minor, build, isSnapshot, versionString); // } // // private AppVersion(int major, int minor, int build, boolean isSnapshot, String original) { // this.major = major; // this.minor = minor; // // this.isSnapshot = isSnapshot; // this.build = build; // this.original = original; // } // // public int getMajor() { // return major; // } // // public int getMinor() { // return minor; // } // // public String getOriginal() { // return this.original; // } // // public boolean isSnapshot() { // return isSnapshot; // } // // public void setBuild(int build) { // this.build = build; // } // // public int getBuild() { // return build; // } // // public String toJsonString() { // return String.format( // "{ \"major\": %d, \"minor\": %d, \"build\": %d, \"isSnapshot\": %b, \"originalString\": \"%s\" }", // this.major, // this.minor, // this.build, // this.isSnapshot, // this.original); // } // // @Override // public String toString() { // String version = String.format("%s.%s", major, minor); // if(build > -1) { // version += "." + build; // } // if (isSnapshot) { // version += "-" + SNAPSHOT; // } // return version; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/Messages.java // public class Messages { // public static final String SEMANTIC_VERSION_FILENAME = ".semanticVersion"; // public static final String DISPLAY_NAME = "Determine Semantic Version"; // public static final String SEMANTIC_VERSION_COLUMN_DISPLAY_NAME = "Semantic Version"; // public static final String UNKNOWN_VERSION = "Unknown"; // // public static class Parsers { // public static final String SBT_BUILD_SBT_PARSER = "SBT build.sbt parser"; // public static final String MAVEN_POM_PARSER = "Maven Pom Parser"; // public static final String SBT_BUILD_SCALA_PARSER = "SBT Build.scala Parser"; // public static final String BOWER_JSON_PARSER = "Bower bower.json Parser"; // public static final String NPM_JSON_PARSER = "NPM package.json Parser"; // public static final String COMPOSER_JSON_PARSER = "Composer composer.json Parser"; // } // // public static class ColumnDisplayStrategies { // public static final String LAST_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Successful Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_BUILD_VERSION_STRATEGY = "Show Last Successful Semantic Version"; // public static final String NA_STRATEGY = "Show 'N/A'"; // } // // public static class NamingStrategies { // public static final String NOOP_NAMING = "none"; // public static final String MAVEN_RELEASE_DEVELOPMENT = "Maven, release and development version"; // public static final String UNTOUCHED = "As found"; // public static final String UNTOUCHED_SNAPSHOT = "As found (-SNAPSHOT)"; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/parsing/AbstractSemanticParserDescription.java // public abstract class AbstractSemanticParserDescription extends hudson.model.Descriptor { // @Override // public abstract String getDisplayName(); // } // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/naming/UntouchedSnapshotNamingStrategy.java import hudson.Extension; import hudson.model.Descriptor; import java.io.Serializable; import java.util.Map; import java.util.logging.Logger; import org.jenkinsci.plugins.SemanticVersioning.AppVersion; import org.jenkinsci.plugins.SemanticVersioning.Messages; import org.jenkinsci.plugins.SemanticVersioning.parsing.AbstractSemanticParserDescription; package org.jenkinsci.plugins.SemanticVersioning.naming; @Extension public class UntouchedSnapshotNamingStrategy implements NamingStrategy, Serializable { private static Logger logger = Logger.getLogger(String.valueOf(AppVersion.class)); public Descriptor<NamingStrategy> getDescriptor() {
return new AbstractSemanticParserDescription() {
jenkinsci/semantic-versioning-plugin
src/main/java/org/jenkinsci/plugins/SemanticVersioning/naming/UntouchedSnapshotNamingStrategy.java
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/AppVersion.java // public class AppVersion implements Serializable { // private static final String SNAPSHOT = "SNAPSHOT"; // private final int major; // private final int minor; // private final String original; // // private int build; // private final boolean isSnapshot; // public static final AppVersion EmptyVersion = new AppVersion(0, 0, 0, false, ""); // // public static AppVersion parse(String versionString) { // String[] parts = versionString.split("[\\.-]"); // // int major = Integer.parseInt(parts[0]); // int minor = Integer.parseInt(parts[1]); // // int build = -1; // boolean isSnapshot = false; // // if (parts.length == 3) { // if (parts[2].equals(SNAPSHOT)) { // isSnapshot = true; // } else { // build = Integer.parseInt(parts[2]); // } // } else if (parts.length == 4) { // build = Integer.parseInt(parts[2]); // isSnapshot = parts[3].equals(SNAPSHOT); // } // // return new AppVersion(major, minor, build, isSnapshot, versionString); // } // // private AppVersion(int major, int minor, int build, boolean isSnapshot, String original) { // this.major = major; // this.minor = minor; // // this.isSnapshot = isSnapshot; // this.build = build; // this.original = original; // } // // public int getMajor() { // return major; // } // // public int getMinor() { // return minor; // } // // public String getOriginal() { // return this.original; // } // // public boolean isSnapshot() { // return isSnapshot; // } // // public void setBuild(int build) { // this.build = build; // } // // public int getBuild() { // return build; // } // // public String toJsonString() { // return String.format( // "{ \"major\": %d, \"minor\": %d, \"build\": %d, \"isSnapshot\": %b, \"originalString\": \"%s\" }", // this.major, // this.minor, // this.build, // this.isSnapshot, // this.original); // } // // @Override // public String toString() { // String version = String.format("%s.%s", major, minor); // if(build > -1) { // version += "." + build; // } // if (isSnapshot) { // version += "-" + SNAPSHOT; // } // return version; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/Messages.java // public class Messages { // public static final String SEMANTIC_VERSION_FILENAME = ".semanticVersion"; // public static final String DISPLAY_NAME = "Determine Semantic Version"; // public static final String SEMANTIC_VERSION_COLUMN_DISPLAY_NAME = "Semantic Version"; // public static final String UNKNOWN_VERSION = "Unknown"; // // public static class Parsers { // public static final String SBT_BUILD_SBT_PARSER = "SBT build.sbt parser"; // public static final String MAVEN_POM_PARSER = "Maven Pom Parser"; // public static final String SBT_BUILD_SCALA_PARSER = "SBT Build.scala Parser"; // public static final String BOWER_JSON_PARSER = "Bower bower.json Parser"; // public static final String NPM_JSON_PARSER = "NPM package.json Parser"; // public static final String COMPOSER_JSON_PARSER = "Composer composer.json Parser"; // } // // public static class ColumnDisplayStrategies { // public static final String LAST_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Successful Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_BUILD_VERSION_STRATEGY = "Show Last Successful Semantic Version"; // public static final String NA_STRATEGY = "Show 'N/A'"; // } // // public static class NamingStrategies { // public static final String NOOP_NAMING = "none"; // public static final String MAVEN_RELEASE_DEVELOPMENT = "Maven, release and development version"; // public static final String UNTOUCHED = "As found"; // public static final String UNTOUCHED_SNAPSHOT = "As found (-SNAPSHOT)"; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/parsing/AbstractSemanticParserDescription.java // public abstract class AbstractSemanticParserDescription extends hudson.model.Descriptor { // @Override // public abstract String getDisplayName(); // }
import hudson.Extension; import hudson.model.Descriptor; import java.io.Serializable; import java.util.Map; import java.util.logging.Logger; import org.jenkinsci.plugins.SemanticVersioning.AppVersion; import org.jenkinsci.plugins.SemanticVersioning.Messages; import org.jenkinsci.plugins.SemanticVersioning.parsing.AbstractSemanticParserDescription;
package org.jenkinsci.plugins.SemanticVersioning.naming; @Extension public class UntouchedSnapshotNamingStrategy implements NamingStrategy, Serializable { private static Logger logger = Logger.getLogger(String.valueOf(AppVersion.class)); public Descriptor<NamingStrategy> getDescriptor() { return new AbstractSemanticParserDescription() { @Override public String getDisplayName() {
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/AppVersion.java // public class AppVersion implements Serializable { // private static final String SNAPSHOT = "SNAPSHOT"; // private final int major; // private final int minor; // private final String original; // // private int build; // private final boolean isSnapshot; // public static final AppVersion EmptyVersion = new AppVersion(0, 0, 0, false, ""); // // public static AppVersion parse(String versionString) { // String[] parts = versionString.split("[\\.-]"); // // int major = Integer.parseInt(parts[0]); // int minor = Integer.parseInt(parts[1]); // // int build = -1; // boolean isSnapshot = false; // // if (parts.length == 3) { // if (parts[2].equals(SNAPSHOT)) { // isSnapshot = true; // } else { // build = Integer.parseInt(parts[2]); // } // } else if (parts.length == 4) { // build = Integer.parseInt(parts[2]); // isSnapshot = parts[3].equals(SNAPSHOT); // } // // return new AppVersion(major, minor, build, isSnapshot, versionString); // } // // private AppVersion(int major, int minor, int build, boolean isSnapshot, String original) { // this.major = major; // this.minor = minor; // // this.isSnapshot = isSnapshot; // this.build = build; // this.original = original; // } // // public int getMajor() { // return major; // } // // public int getMinor() { // return minor; // } // // public String getOriginal() { // return this.original; // } // // public boolean isSnapshot() { // return isSnapshot; // } // // public void setBuild(int build) { // this.build = build; // } // // public int getBuild() { // return build; // } // // public String toJsonString() { // return String.format( // "{ \"major\": %d, \"minor\": %d, \"build\": %d, \"isSnapshot\": %b, \"originalString\": \"%s\" }", // this.major, // this.minor, // this.build, // this.isSnapshot, // this.original); // } // // @Override // public String toString() { // String version = String.format("%s.%s", major, minor); // if(build > -1) { // version += "." + build; // } // if (isSnapshot) { // version += "-" + SNAPSHOT; // } // return version; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/Messages.java // public class Messages { // public static final String SEMANTIC_VERSION_FILENAME = ".semanticVersion"; // public static final String DISPLAY_NAME = "Determine Semantic Version"; // public static final String SEMANTIC_VERSION_COLUMN_DISPLAY_NAME = "Semantic Version"; // public static final String UNKNOWN_VERSION = "Unknown"; // // public static class Parsers { // public static final String SBT_BUILD_SBT_PARSER = "SBT build.sbt parser"; // public static final String MAVEN_POM_PARSER = "Maven Pom Parser"; // public static final String SBT_BUILD_SCALA_PARSER = "SBT Build.scala Parser"; // public static final String BOWER_JSON_PARSER = "Bower bower.json Parser"; // public static final String NPM_JSON_PARSER = "NPM package.json Parser"; // public static final String COMPOSER_JSON_PARSER = "Composer composer.json Parser"; // } // // public static class ColumnDisplayStrategies { // public static final String LAST_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Successful Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_BUILD_VERSION_STRATEGY = "Show Last Successful Semantic Version"; // public static final String NA_STRATEGY = "Show 'N/A'"; // } // // public static class NamingStrategies { // public static final String NOOP_NAMING = "none"; // public static final String MAVEN_RELEASE_DEVELOPMENT = "Maven, release and development version"; // public static final String UNTOUCHED = "As found"; // public static final String UNTOUCHED_SNAPSHOT = "As found (-SNAPSHOT)"; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/parsing/AbstractSemanticParserDescription.java // public abstract class AbstractSemanticParserDescription extends hudson.model.Descriptor { // @Override // public abstract String getDisplayName(); // } // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/naming/UntouchedSnapshotNamingStrategy.java import hudson.Extension; import hudson.model.Descriptor; import java.io.Serializable; import java.util.Map; import java.util.logging.Logger; import org.jenkinsci.plugins.SemanticVersioning.AppVersion; import org.jenkinsci.plugins.SemanticVersioning.Messages; import org.jenkinsci.plugins.SemanticVersioning.parsing.AbstractSemanticParserDescription; package org.jenkinsci.plugins.SemanticVersioning.naming; @Extension public class UntouchedSnapshotNamingStrategy implements NamingStrategy, Serializable { private static Logger logger = Logger.getLogger(String.valueOf(AppVersion.class)); public Descriptor<NamingStrategy> getDescriptor() { return new AbstractSemanticParserDescription() { @Override public String getDisplayName() {
return Messages.NamingStrategies.UNTOUCHED_SNAPSHOT;
jenkinsci/semantic-versioning-plugin
src/main/java/org/jenkinsci/plugins/SemanticVersioning/parsing/BuildScalaParser.java
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/AppVersion.java // public class AppVersion implements Serializable { // private static final String SNAPSHOT = "SNAPSHOT"; // private final int major; // private final int minor; // private final String original; // // private int build; // private final boolean isSnapshot; // public static final AppVersion EmptyVersion = new AppVersion(0, 0, 0, false, ""); // // public static AppVersion parse(String versionString) { // String[] parts = versionString.split("[\\.-]"); // // int major = Integer.parseInt(parts[0]); // int minor = Integer.parseInt(parts[1]); // // int build = -1; // boolean isSnapshot = false; // // if (parts.length == 3) { // if (parts[2].equals(SNAPSHOT)) { // isSnapshot = true; // } else { // build = Integer.parseInt(parts[2]); // } // } else if (parts.length == 4) { // build = Integer.parseInt(parts[2]); // isSnapshot = parts[3].equals(SNAPSHOT); // } // // return new AppVersion(major, minor, build, isSnapshot, versionString); // } // // private AppVersion(int major, int minor, int build, boolean isSnapshot, String original) { // this.major = major; // this.minor = minor; // // this.isSnapshot = isSnapshot; // this.build = build; // this.original = original; // } // // public int getMajor() { // return major; // } // // public int getMinor() { // return minor; // } // // public String getOriginal() { // return this.original; // } // // public boolean isSnapshot() { // return isSnapshot; // } // // public void setBuild(int build) { // this.build = build; // } // // public int getBuild() { // return build; // } // // public String toJsonString() { // return String.format( // "{ \"major\": %d, \"minor\": %d, \"build\": %d, \"isSnapshot\": %b, \"originalString\": \"%s\" }", // this.major, // this.minor, // this.build, // this.isSnapshot, // this.original); // } // // @Override // public String toString() { // String version = String.format("%s.%s", major, minor); // if(build > -1) { // version += "." + build; // } // if (isSnapshot) { // version += "-" + SNAPSHOT; // } // return version; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/InvalidBuildFileFormatException.java // public class InvalidBuildFileFormatException extends Exception { // private static final long serialVersionUID = 1L; // // public InvalidBuildFileFormatException(String message) { // super(message); // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/Messages.java // public class Messages { // public static final String SEMANTIC_VERSION_FILENAME = ".semanticVersion"; // public static final String DISPLAY_NAME = "Determine Semantic Version"; // public static final String SEMANTIC_VERSION_COLUMN_DISPLAY_NAME = "Semantic Version"; // public static final String UNKNOWN_VERSION = "Unknown"; // // public static class Parsers { // public static final String SBT_BUILD_SBT_PARSER = "SBT build.sbt parser"; // public static final String MAVEN_POM_PARSER = "Maven Pom Parser"; // public static final String SBT_BUILD_SCALA_PARSER = "SBT Build.scala Parser"; // public static final String BOWER_JSON_PARSER = "Bower bower.json Parser"; // public static final String NPM_JSON_PARSER = "NPM package.json Parser"; // public static final String COMPOSER_JSON_PARSER = "Composer composer.json Parser"; // } // // public static class ColumnDisplayStrategies { // public static final String LAST_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Successful Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_BUILD_VERSION_STRATEGY = "Show Last Successful Semantic Version"; // public static final String NA_STRATEGY = "Show 'N/A'"; // } // // public static class NamingStrategies { // public static final String NOOP_NAMING = "none"; // public static final String MAVEN_RELEASE_DEVELOPMENT = "Maven, release and development version"; // public static final String UNTOUCHED = "As found"; // public static final String UNTOUCHED_SNAPSHOT = "As found (-SNAPSHOT)"; // } // }
import org.apache.commons.io.FileUtils; import org.jenkinsci.plugins.SemanticVersioning.AppVersion; import org.jenkinsci.plugins.SemanticVersioning.InvalidBuildFileFormatException; import org.jenkinsci.plugins.SemanticVersioning.Messages; import hudson.Extension; import hudson.FilePath; import hudson.model.Descriptor; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintStream; import java.util.regex.Matcher; import java.util.regex.Pattern;
if(extendsBuild.matcher(content).find()) { String version; Pattern pattern = Pattern.compile("val\\s*appVersion\\s*=\\s*\"([^\"]*)\"", Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(content); boolean found = matcher.find(); if(found) { version = matcher.toMatchResult().group(1); } else { throw new InvalidBuildFileFormatException("No version information found in " + BUILD_DEFINITION_FILENAME); } return AppVersion.parse(version); } else { throw new InvalidBuildFileFormatException("'" + BUILD_DEFINITION_FILENAME + "' is not a valid build definition file."); } } else { throw new FileNotFoundException("'" + BUILD_DEFINITION_FILENAME + "' was not found."); } } @SuppressWarnings("unchecked") public Descriptor<BuildDefinitionParser> getDescriptor() { return new AbstractSemanticParserDescription() { @Override public String getDisplayName() {
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/AppVersion.java // public class AppVersion implements Serializable { // private static final String SNAPSHOT = "SNAPSHOT"; // private final int major; // private final int minor; // private final String original; // // private int build; // private final boolean isSnapshot; // public static final AppVersion EmptyVersion = new AppVersion(0, 0, 0, false, ""); // // public static AppVersion parse(String versionString) { // String[] parts = versionString.split("[\\.-]"); // // int major = Integer.parseInt(parts[0]); // int minor = Integer.parseInt(parts[1]); // // int build = -1; // boolean isSnapshot = false; // // if (parts.length == 3) { // if (parts[2].equals(SNAPSHOT)) { // isSnapshot = true; // } else { // build = Integer.parseInt(parts[2]); // } // } else if (parts.length == 4) { // build = Integer.parseInt(parts[2]); // isSnapshot = parts[3].equals(SNAPSHOT); // } // // return new AppVersion(major, minor, build, isSnapshot, versionString); // } // // private AppVersion(int major, int minor, int build, boolean isSnapshot, String original) { // this.major = major; // this.minor = minor; // // this.isSnapshot = isSnapshot; // this.build = build; // this.original = original; // } // // public int getMajor() { // return major; // } // // public int getMinor() { // return minor; // } // // public String getOriginal() { // return this.original; // } // // public boolean isSnapshot() { // return isSnapshot; // } // // public void setBuild(int build) { // this.build = build; // } // // public int getBuild() { // return build; // } // // public String toJsonString() { // return String.format( // "{ \"major\": %d, \"minor\": %d, \"build\": %d, \"isSnapshot\": %b, \"originalString\": \"%s\" }", // this.major, // this.minor, // this.build, // this.isSnapshot, // this.original); // } // // @Override // public String toString() { // String version = String.format("%s.%s", major, minor); // if(build > -1) { // version += "." + build; // } // if (isSnapshot) { // version += "-" + SNAPSHOT; // } // return version; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/InvalidBuildFileFormatException.java // public class InvalidBuildFileFormatException extends Exception { // private static final long serialVersionUID = 1L; // // public InvalidBuildFileFormatException(String message) { // super(message); // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/Messages.java // public class Messages { // public static final String SEMANTIC_VERSION_FILENAME = ".semanticVersion"; // public static final String DISPLAY_NAME = "Determine Semantic Version"; // public static final String SEMANTIC_VERSION_COLUMN_DISPLAY_NAME = "Semantic Version"; // public static final String UNKNOWN_VERSION = "Unknown"; // // public static class Parsers { // public static final String SBT_BUILD_SBT_PARSER = "SBT build.sbt parser"; // public static final String MAVEN_POM_PARSER = "Maven Pom Parser"; // public static final String SBT_BUILD_SCALA_PARSER = "SBT Build.scala Parser"; // public static final String BOWER_JSON_PARSER = "Bower bower.json Parser"; // public static final String NPM_JSON_PARSER = "NPM package.json Parser"; // public static final String COMPOSER_JSON_PARSER = "Composer composer.json Parser"; // } // // public static class ColumnDisplayStrategies { // public static final String LAST_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Successful Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_BUILD_VERSION_STRATEGY = "Show Last Successful Semantic Version"; // public static final String NA_STRATEGY = "Show 'N/A'"; // } // // public static class NamingStrategies { // public static final String NOOP_NAMING = "none"; // public static final String MAVEN_RELEASE_DEVELOPMENT = "Maven, release and development version"; // public static final String UNTOUCHED = "As found"; // public static final String UNTOUCHED_SNAPSHOT = "As found (-SNAPSHOT)"; // } // } // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/parsing/BuildScalaParser.java import org.apache.commons.io.FileUtils; import org.jenkinsci.plugins.SemanticVersioning.AppVersion; import org.jenkinsci.plugins.SemanticVersioning.InvalidBuildFileFormatException; import org.jenkinsci.plugins.SemanticVersioning.Messages; import hudson.Extension; import hudson.FilePath; import hudson.model.Descriptor; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintStream; import java.util.regex.Matcher; import java.util.regex.Pattern; if(extendsBuild.matcher(content).find()) { String version; Pattern pattern = Pattern.compile("val\\s*appVersion\\s*=\\s*\"([^\"]*)\"", Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(content); boolean found = matcher.find(); if(found) { version = matcher.toMatchResult().group(1); } else { throw new InvalidBuildFileFormatException("No version information found in " + BUILD_DEFINITION_FILENAME); } return AppVersion.parse(version); } else { throw new InvalidBuildFileFormatException("'" + BUILD_DEFINITION_FILENAME + "' is not a valid build definition file."); } } else { throw new FileNotFoundException("'" + BUILD_DEFINITION_FILENAME + "' was not found."); } } @SuppressWarnings("unchecked") public Descriptor<BuildDefinitionParser> getDescriptor() { return new AbstractSemanticParserDescription() { @Override public String getDisplayName() {
return Messages.Parsers.SBT_BUILD_SCALA_PARSER;
jenkinsci/semantic-versioning-plugin
src/main/java/org/jenkinsci/plugins/SemanticVersioning/naming/NoopNamingStrategy.java
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/AppVersion.java // public class AppVersion implements Serializable { // private static final String SNAPSHOT = "SNAPSHOT"; // private final int major; // private final int minor; // private final String original; // // private int build; // private final boolean isSnapshot; // public static final AppVersion EmptyVersion = new AppVersion(0, 0, 0, false, ""); // // public static AppVersion parse(String versionString) { // String[] parts = versionString.split("[\\.-]"); // // int major = Integer.parseInt(parts[0]); // int minor = Integer.parseInt(parts[1]); // // int build = -1; // boolean isSnapshot = false; // // if (parts.length == 3) { // if (parts[2].equals(SNAPSHOT)) { // isSnapshot = true; // } else { // build = Integer.parseInt(parts[2]); // } // } else if (parts.length == 4) { // build = Integer.parseInt(parts[2]); // isSnapshot = parts[3].equals(SNAPSHOT); // } // // return new AppVersion(major, minor, build, isSnapshot, versionString); // } // // private AppVersion(int major, int minor, int build, boolean isSnapshot, String original) { // this.major = major; // this.minor = minor; // // this.isSnapshot = isSnapshot; // this.build = build; // this.original = original; // } // // public int getMajor() { // return major; // } // // public int getMinor() { // return minor; // } // // public String getOriginal() { // return this.original; // } // // public boolean isSnapshot() { // return isSnapshot; // } // // public void setBuild(int build) { // this.build = build; // } // // public int getBuild() { // return build; // } // // public String toJsonString() { // return String.format( // "{ \"major\": %d, \"minor\": %d, \"build\": %d, \"isSnapshot\": %b, \"originalString\": \"%s\" }", // this.major, // this.minor, // this.build, // this.isSnapshot, // this.original); // } // // @Override // public String toString() { // String version = String.format("%s.%s", major, minor); // if(build > -1) { // version += "." + build; // } // if (isSnapshot) { // version += "-" + SNAPSHOT; // } // return version; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/Messages.java // public class Messages { // public static final String SEMANTIC_VERSION_FILENAME = ".semanticVersion"; // public static final String DISPLAY_NAME = "Determine Semantic Version"; // public static final String SEMANTIC_VERSION_COLUMN_DISPLAY_NAME = "Semantic Version"; // public static final String UNKNOWN_VERSION = "Unknown"; // // public static class Parsers { // public static final String SBT_BUILD_SBT_PARSER = "SBT build.sbt parser"; // public static final String MAVEN_POM_PARSER = "Maven Pom Parser"; // public static final String SBT_BUILD_SCALA_PARSER = "SBT Build.scala Parser"; // public static final String BOWER_JSON_PARSER = "Bower bower.json Parser"; // public static final String NPM_JSON_PARSER = "NPM package.json Parser"; // public static final String COMPOSER_JSON_PARSER = "Composer composer.json Parser"; // } // // public static class ColumnDisplayStrategies { // public static final String LAST_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Successful Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_BUILD_VERSION_STRATEGY = "Show Last Successful Semantic Version"; // public static final String NA_STRATEGY = "Show 'N/A'"; // } // // public static class NamingStrategies { // public static final String NOOP_NAMING = "none"; // public static final String MAVEN_RELEASE_DEVELOPMENT = "Maven, release and development version"; // public static final String UNTOUCHED = "As found"; // public static final String UNTOUCHED_SNAPSHOT = "As found (-SNAPSHOT)"; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/parsing/AbstractSemanticParserDescription.java // public abstract class AbstractSemanticParserDescription extends hudson.model.Descriptor { // @Override // public abstract String getDisplayName(); // }
import hudson.Extension; import hudson.model.Descriptor; import java.io.Serializable; import java.util.Map; import java.util.logging.Logger; import org.jenkinsci.plugins.SemanticVersioning.AppVersion; import org.jenkinsci.plugins.SemanticVersioning.Messages; import org.jenkinsci.plugins.SemanticVersioning.parsing.AbstractSemanticParserDescription;
package org.jenkinsci.plugins.SemanticVersioning.naming; @Extension public class NoopNamingStrategy implements NamingStrategy, Serializable {
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/AppVersion.java // public class AppVersion implements Serializable { // private static final String SNAPSHOT = "SNAPSHOT"; // private final int major; // private final int minor; // private final String original; // // private int build; // private final boolean isSnapshot; // public static final AppVersion EmptyVersion = new AppVersion(0, 0, 0, false, ""); // // public static AppVersion parse(String versionString) { // String[] parts = versionString.split("[\\.-]"); // // int major = Integer.parseInt(parts[0]); // int minor = Integer.parseInt(parts[1]); // // int build = -1; // boolean isSnapshot = false; // // if (parts.length == 3) { // if (parts[2].equals(SNAPSHOT)) { // isSnapshot = true; // } else { // build = Integer.parseInt(parts[2]); // } // } else if (parts.length == 4) { // build = Integer.parseInt(parts[2]); // isSnapshot = parts[3].equals(SNAPSHOT); // } // // return new AppVersion(major, minor, build, isSnapshot, versionString); // } // // private AppVersion(int major, int minor, int build, boolean isSnapshot, String original) { // this.major = major; // this.minor = minor; // // this.isSnapshot = isSnapshot; // this.build = build; // this.original = original; // } // // public int getMajor() { // return major; // } // // public int getMinor() { // return minor; // } // // public String getOriginal() { // return this.original; // } // // public boolean isSnapshot() { // return isSnapshot; // } // // public void setBuild(int build) { // this.build = build; // } // // public int getBuild() { // return build; // } // // public String toJsonString() { // return String.format( // "{ \"major\": %d, \"minor\": %d, \"build\": %d, \"isSnapshot\": %b, \"originalString\": \"%s\" }", // this.major, // this.minor, // this.build, // this.isSnapshot, // this.original); // } // // @Override // public String toString() { // String version = String.format("%s.%s", major, minor); // if(build > -1) { // version += "." + build; // } // if (isSnapshot) { // version += "-" + SNAPSHOT; // } // return version; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/Messages.java // public class Messages { // public static final String SEMANTIC_VERSION_FILENAME = ".semanticVersion"; // public static final String DISPLAY_NAME = "Determine Semantic Version"; // public static final String SEMANTIC_VERSION_COLUMN_DISPLAY_NAME = "Semantic Version"; // public static final String UNKNOWN_VERSION = "Unknown"; // // public static class Parsers { // public static final String SBT_BUILD_SBT_PARSER = "SBT build.sbt parser"; // public static final String MAVEN_POM_PARSER = "Maven Pom Parser"; // public static final String SBT_BUILD_SCALA_PARSER = "SBT Build.scala Parser"; // public static final String BOWER_JSON_PARSER = "Bower bower.json Parser"; // public static final String NPM_JSON_PARSER = "NPM package.json Parser"; // public static final String COMPOSER_JSON_PARSER = "Composer composer.json Parser"; // } // // public static class ColumnDisplayStrategies { // public static final String LAST_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Successful Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_BUILD_VERSION_STRATEGY = "Show Last Successful Semantic Version"; // public static final String NA_STRATEGY = "Show 'N/A'"; // } // // public static class NamingStrategies { // public static final String NOOP_NAMING = "none"; // public static final String MAVEN_RELEASE_DEVELOPMENT = "Maven, release and development version"; // public static final String UNTOUCHED = "As found"; // public static final String UNTOUCHED_SNAPSHOT = "As found (-SNAPSHOT)"; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/parsing/AbstractSemanticParserDescription.java // public abstract class AbstractSemanticParserDescription extends hudson.model.Descriptor { // @Override // public abstract String getDisplayName(); // } // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/naming/NoopNamingStrategy.java import hudson.Extension; import hudson.model.Descriptor; import java.io.Serializable; import java.util.Map; import java.util.logging.Logger; import org.jenkinsci.plugins.SemanticVersioning.AppVersion; import org.jenkinsci.plugins.SemanticVersioning.Messages; import org.jenkinsci.plugins.SemanticVersioning.parsing.AbstractSemanticParserDescription; package org.jenkinsci.plugins.SemanticVersioning.naming; @Extension public class NoopNamingStrategy implements NamingStrategy, Serializable {
private static Logger logger = Logger.getLogger(String.valueOf(AppVersion.class));
jenkinsci/semantic-versioning-plugin
src/main/java/org/jenkinsci/plugins/SemanticVersioning/naming/NoopNamingStrategy.java
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/AppVersion.java // public class AppVersion implements Serializable { // private static final String SNAPSHOT = "SNAPSHOT"; // private final int major; // private final int minor; // private final String original; // // private int build; // private final boolean isSnapshot; // public static final AppVersion EmptyVersion = new AppVersion(0, 0, 0, false, ""); // // public static AppVersion parse(String versionString) { // String[] parts = versionString.split("[\\.-]"); // // int major = Integer.parseInt(parts[0]); // int minor = Integer.parseInt(parts[1]); // // int build = -1; // boolean isSnapshot = false; // // if (parts.length == 3) { // if (parts[2].equals(SNAPSHOT)) { // isSnapshot = true; // } else { // build = Integer.parseInt(parts[2]); // } // } else if (parts.length == 4) { // build = Integer.parseInt(parts[2]); // isSnapshot = parts[3].equals(SNAPSHOT); // } // // return new AppVersion(major, minor, build, isSnapshot, versionString); // } // // private AppVersion(int major, int minor, int build, boolean isSnapshot, String original) { // this.major = major; // this.minor = minor; // // this.isSnapshot = isSnapshot; // this.build = build; // this.original = original; // } // // public int getMajor() { // return major; // } // // public int getMinor() { // return minor; // } // // public String getOriginal() { // return this.original; // } // // public boolean isSnapshot() { // return isSnapshot; // } // // public void setBuild(int build) { // this.build = build; // } // // public int getBuild() { // return build; // } // // public String toJsonString() { // return String.format( // "{ \"major\": %d, \"minor\": %d, \"build\": %d, \"isSnapshot\": %b, \"originalString\": \"%s\" }", // this.major, // this.minor, // this.build, // this.isSnapshot, // this.original); // } // // @Override // public String toString() { // String version = String.format("%s.%s", major, minor); // if(build > -1) { // version += "." + build; // } // if (isSnapshot) { // version += "-" + SNAPSHOT; // } // return version; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/Messages.java // public class Messages { // public static final String SEMANTIC_VERSION_FILENAME = ".semanticVersion"; // public static final String DISPLAY_NAME = "Determine Semantic Version"; // public static final String SEMANTIC_VERSION_COLUMN_DISPLAY_NAME = "Semantic Version"; // public static final String UNKNOWN_VERSION = "Unknown"; // // public static class Parsers { // public static final String SBT_BUILD_SBT_PARSER = "SBT build.sbt parser"; // public static final String MAVEN_POM_PARSER = "Maven Pom Parser"; // public static final String SBT_BUILD_SCALA_PARSER = "SBT Build.scala Parser"; // public static final String BOWER_JSON_PARSER = "Bower bower.json Parser"; // public static final String NPM_JSON_PARSER = "NPM package.json Parser"; // public static final String COMPOSER_JSON_PARSER = "Composer composer.json Parser"; // } // // public static class ColumnDisplayStrategies { // public static final String LAST_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Successful Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_BUILD_VERSION_STRATEGY = "Show Last Successful Semantic Version"; // public static final String NA_STRATEGY = "Show 'N/A'"; // } // // public static class NamingStrategies { // public static final String NOOP_NAMING = "none"; // public static final String MAVEN_RELEASE_DEVELOPMENT = "Maven, release and development version"; // public static final String UNTOUCHED = "As found"; // public static final String UNTOUCHED_SNAPSHOT = "As found (-SNAPSHOT)"; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/parsing/AbstractSemanticParserDescription.java // public abstract class AbstractSemanticParserDescription extends hudson.model.Descriptor { // @Override // public abstract String getDisplayName(); // }
import hudson.Extension; import hudson.model.Descriptor; import java.io.Serializable; import java.util.Map; import java.util.logging.Logger; import org.jenkinsci.plugins.SemanticVersioning.AppVersion; import org.jenkinsci.plugins.SemanticVersioning.Messages; import org.jenkinsci.plugins.SemanticVersioning.parsing.AbstractSemanticParserDescription;
package org.jenkinsci.plugins.SemanticVersioning.naming; @Extension public class NoopNamingStrategy implements NamingStrategy, Serializable { private static Logger logger = Logger.getLogger(String.valueOf(AppVersion.class)); public Descriptor<NamingStrategy> getDescriptor() {
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/AppVersion.java // public class AppVersion implements Serializable { // private static final String SNAPSHOT = "SNAPSHOT"; // private final int major; // private final int minor; // private final String original; // // private int build; // private final boolean isSnapshot; // public static final AppVersion EmptyVersion = new AppVersion(0, 0, 0, false, ""); // // public static AppVersion parse(String versionString) { // String[] parts = versionString.split("[\\.-]"); // // int major = Integer.parseInt(parts[0]); // int minor = Integer.parseInt(parts[1]); // // int build = -1; // boolean isSnapshot = false; // // if (parts.length == 3) { // if (parts[2].equals(SNAPSHOT)) { // isSnapshot = true; // } else { // build = Integer.parseInt(parts[2]); // } // } else if (parts.length == 4) { // build = Integer.parseInt(parts[2]); // isSnapshot = parts[3].equals(SNAPSHOT); // } // // return new AppVersion(major, minor, build, isSnapshot, versionString); // } // // private AppVersion(int major, int minor, int build, boolean isSnapshot, String original) { // this.major = major; // this.minor = minor; // // this.isSnapshot = isSnapshot; // this.build = build; // this.original = original; // } // // public int getMajor() { // return major; // } // // public int getMinor() { // return minor; // } // // public String getOriginal() { // return this.original; // } // // public boolean isSnapshot() { // return isSnapshot; // } // // public void setBuild(int build) { // this.build = build; // } // // public int getBuild() { // return build; // } // // public String toJsonString() { // return String.format( // "{ \"major\": %d, \"minor\": %d, \"build\": %d, \"isSnapshot\": %b, \"originalString\": \"%s\" }", // this.major, // this.minor, // this.build, // this.isSnapshot, // this.original); // } // // @Override // public String toString() { // String version = String.format("%s.%s", major, minor); // if(build > -1) { // version += "." + build; // } // if (isSnapshot) { // version += "-" + SNAPSHOT; // } // return version; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/Messages.java // public class Messages { // public static final String SEMANTIC_VERSION_FILENAME = ".semanticVersion"; // public static final String DISPLAY_NAME = "Determine Semantic Version"; // public static final String SEMANTIC_VERSION_COLUMN_DISPLAY_NAME = "Semantic Version"; // public static final String UNKNOWN_VERSION = "Unknown"; // // public static class Parsers { // public static final String SBT_BUILD_SBT_PARSER = "SBT build.sbt parser"; // public static final String MAVEN_POM_PARSER = "Maven Pom Parser"; // public static final String SBT_BUILD_SCALA_PARSER = "SBT Build.scala Parser"; // public static final String BOWER_JSON_PARSER = "Bower bower.json Parser"; // public static final String NPM_JSON_PARSER = "NPM package.json Parser"; // public static final String COMPOSER_JSON_PARSER = "Composer composer.json Parser"; // } // // public static class ColumnDisplayStrategies { // public static final String LAST_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Successful Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_BUILD_VERSION_STRATEGY = "Show Last Successful Semantic Version"; // public static final String NA_STRATEGY = "Show 'N/A'"; // } // // public static class NamingStrategies { // public static final String NOOP_NAMING = "none"; // public static final String MAVEN_RELEASE_DEVELOPMENT = "Maven, release and development version"; // public static final String UNTOUCHED = "As found"; // public static final String UNTOUCHED_SNAPSHOT = "As found (-SNAPSHOT)"; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/parsing/AbstractSemanticParserDescription.java // public abstract class AbstractSemanticParserDescription extends hudson.model.Descriptor { // @Override // public abstract String getDisplayName(); // } // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/naming/NoopNamingStrategy.java import hudson.Extension; import hudson.model.Descriptor; import java.io.Serializable; import java.util.Map; import java.util.logging.Logger; import org.jenkinsci.plugins.SemanticVersioning.AppVersion; import org.jenkinsci.plugins.SemanticVersioning.Messages; import org.jenkinsci.plugins.SemanticVersioning.parsing.AbstractSemanticParserDescription; package org.jenkinsci.plugins.SemanticVersioning.naming; @Extension public class NoopNamingStrategy implements NamingStrategy, Serializable { private static Logger logger = Logger.getLogger(String.valueOf(AppVersion.class)); public Descriptor<NamingStrategy> getDescriptor() {
return new AbstractSemanticParserDescription() {
jenkinsci/semantic-versioning-plugin
src/main/java/org/jenkinsci/plugins/SemanticVersioning/naming/NoopNamingStrategy.java
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/AppVersion.java // public class AppVersion implements Serializable { // private static final String SNAPSHOT = "SNAPSHOT"; // private final int major; // private final int minor; // private final String original; // // private int build; // private final boolean isSnapshot; // public static final AppVersion EmptyVersion = new AppVersion(0, 0, 0, false, ""); // // public static AppVersion parse(String versionString) { // String[] parts = versionString.split("[\\.-]"); // // int major = Integer.parseInt(parts[0]); // int minor = Integer.parseInt(parts[1]); // // int build = -1; // boolean isSnapshot = false; // // if (parts.length == 3) { // if (parts[2].equals(SNAPSHOT)) { // isSnapshot = true; // } else { // build = Integer.parseInt(parts[2]); // } // } else if (parts.length == 4) { // build = Integer.parseInt(parts[2]); // isSnapshot = parts[3].equals(SNAPSHOT); // } // // return new AppVersion(major, minor, build, isSnapshot, versionString); // } // // private AppVersion(int major, int minor, int build, boolean isSnapshot, String original) { // this.major = major; // this.minor = minor; // // this.isSnapshot = isSnapshot; // this.build = build; // this.original = original; // } // // public int getMajor() { // return major; // } // // public int getMinor() { // return minor; // } // // public String getOriginal() { // return this.original; // } // // public boolean isSnapshot() { // return isSnapshot; // } // // public void setBuild(int build) { // this.build = build; // } // // public int getBuild() { // return build; // } // // public String toJsonString() { // return String.format( // "{ \"major\": %d, \"minor\": %d, \"build\": %d, \"isSnapshot\": %b, \"originalString\": \"%s\" }", // this.major, // this.minor, // this.build, // this.isSnapshot, // this.original); // } // // @Override // public String toString() { // String version = String.format("%s.%s", major, minor); // if(build > -1) { // version += "." + build; // } // if (isSnapshot) { // version += "-" + SNAPSHOT; // } // return version; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/Messages.java // public class Messages { // public static final String SEMANTIC_VERSION_FILENAME = ".semanticVersion"; // public static final String DISPLAY_NAME = "Determine Semantic Version"; // public static final String SEMANTIC_VERSION_COLUMN_DISPLAY_NAME = "Semantic Version"; // public static final String UNKNOWN_VERSION = "Unknown"; // // public static class Parsers { // public static final String SBT_BUILD_SBT_PARSER = "SBT build.sbt parser"; // public static final String MAVEN_POM_PARSER = "Maven Pom Parser"; // public static final String SBT_BUILD_SCALA_PARSER = "SBT Build.scala Parser"; // public static final String BOWER_JSON_PARSER = "Bower bower.json Parser"; // public static final String NPM_JSON_PARSER = "NPM package.json Parser"; // public static final String COMPOSER_JSON_PARSER = "Composer composer.json Parser"; // } // // public static class ColumnDisplayStrategies { // public static final String LAST_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Successful Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_BUILD_VERSION_STRATEGY = "Show Last Successful Semantic Version"; // public static final String NA_STRATEGY = "Show 'N/A'"; // } // // public static class NamingStrategies { // public static final String NOOP_NAMING = "none"; // public static final String MAVEN_RELEASE_DEVELOPMENT = "Maven, release and development version"; // public static final String UNTOUCHED = "As found"; // public static final String UNTOUCHED_SNAPSHOT = "As found (-SNAPSHOT)"; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/parsing/AbstractSemanticParserDescription.java // public abstract class AbstractSemanticParserDescription extends hudson.model.Descriptor { // @Override // public abstract String getDisplayName(); // }
import hudson.Extension; import hudson.model.Descriptor; import java.io.Serializable; import java.util.Map; import java.util.logging.Logger; import org.jenkinsci.plugins.SemanticVersioning.AppVersion; import org.jenkinsci.plugins.SemanticVersioning.Messages; import org.jenkinsci.plugins.SemanticVersioning.parsing.AbstractSemanticParserDescription;
package org.jenkinsci.plugins.SemanticVersioning.naming; @Extension public class NoopNamingStrategy implements NamingStrategy, Serializable { private static Logger logger = Logger.getLogger(String.valueOf(AppVersion.class)); public Descriptor<NamingStrategy> getDescriptor() { return new AbstractSemanticParserDescription() { @Override public String getDisplayName() {
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/AppVersion.java // public class AppVersion implements Serializable { // private static final String SNAPSHOT = "SNAPSHOT"; // private final int major; // private final int minor; // private final String original; // // private int build; // private final boolean isSnapshot; // public static final AppVersion EmptyVersion = new AppVersion(0, 0, 0, false, ""); // // public static AppVersion parse(String versionString) { // String[] parts = versionString.split("[\\.-]"); // // int major = Integer.parseInt(parts[0]); // int minor = Integer.parseInt(parts[1]); // // int build = -1; // boolean isSnapshot = false; // // if (parts.length == 3) { // if (parts[2].equals(SNAPSHOT)) { // isSnapshot = true; // } else { // build = Integer.parseInt(parts[2]); // } // } else if (parts.length == 4) { // build = Integer.parseInt(parts[2]); // isSnapshot = parts[3].equals(SNAPSHOT); // } // // return new AppVersion(major, minor, build, isSnapshot, versionString); // } // // private AppVersion(int major, int minor, int build, boolean isSnapshot, String original) { // this.major = major; // this.minor = minor; // // this.isSnapshot = isSnapshot; // this.build = build; // this.original = original; // } // // public int getMajor() { // return major; // } // // public int getMinor() { // return minor; // } // // public String getOriginal() { // return this.original; // } // // public boolean isSnapshot() { // return isSnapshot; // } // // public void setBuild(int build) { // this.build = build; // } // // public int getBuild() { // return build; // } // // public String toJsonString() { // return String.format( // "{ \"major\": %d, \"minor\": %d, \"build\": %d, \"isSnapshot\": %b, \"originalString\": \"%s\" }", // this.major, // this.minor, // this.build, // this.isSnapshot, // this.original); // } // // @Override // public String toString() { // String version = String.format("%s.%s", major, minor); // if(build > -1) { // version += "." + build; // } // if (isSnapshot) { // version += "-" + SNAPSHOT; // } // return version; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/Messages.java // public class Messages { // public static final String SEMANTIC_VERSION_FILENAME = ".semanticVersion"; // public static final String DISPLAY_NAME = "Determine Semantic Version"; // public static final String SEMANTIC_VERSION_COLUMN_DISPLAY_NAME = "Semantic Version"; // public static final String UNKNOWN_VERSION = "Unknown"; // // public static class Parsers { // public static final String SBT_BUILD_SBT_PARSER = "SBT build.sbt parser"; // public static final String MAVEN_POM_PARSER = "Maven Pom Parser"; // public static final String SBT_BUILD_SCALA_PARSER = "SBT Build.scala Parser"; // public static final String BOWER_JSON_PARSER = "Bower bower.json Parser"; // public static final String NPM_JSON_PARSER = "NPM package.json Parser"; // public static final String COMPOSER_JSON_PARSER = "Composer composer.json Parser"; // } // // public static class ColumnDisplayStrategies { // public static final String LAST_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Successful Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_BUILD_VERSION_STRATEGY = "Show Last Successful Semantic Version"; // public static final String NA_STRATEGY = "Show 'N/A'"; // } // // public static class NamingStrategies { // public static final String NOOP_NAMING = "none"; // public static final String MAVEN_RELEASE_DEVELOPMENT = "Maven, release and development version"; // public static final String UNTOUCHED = "As found"; // public static final String UNTOUCHED_SNAPSHOT = "As found (-SNAPSHOT)"; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/parsing/AbstractSemanticParserDescription.java // public abstract class AbstractSemanticParserDescription extends hudson.model.Descriptor { // @Override // public abstract String getDisplayName(); // } // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/naming/NoopNamingStrategy.java import hudson.Extension; import hudson.model.Descriptor; import java.io.Serializable; import java.util.Map; import java.util.logging.Logger; import org.jenkinsci.plugins.SemanticVersioning.AppVersion; import org.jenkinsci.plugins.SemanticVersioning.Messages; import org.jenkinsci.plugins.SemanticVersioning.parsing.AbstractSemanticParserDescription; package org.jenkinsci.plugins.SemanticVersioning.naming; @Extension public class NoopNamingStrategy implements NamingStrategy, Serializable { private static Logger logger = Logger.getLogger(String.valueOf(AppVersion.class)); public Descriptor<NamingStrategy> getDescriptor() { return new AbstractSemanticParserDescription() { @Override public String getDisplayName() {
return Messages.NamingStrategies.NOOP_NAMING;
jenkinsci/semantic-versioning-plugin
src/main/java/org/jenkinsci/plugins/SemanticVersioning/columnDisplay/LastJenkinsBuildNumberStrategy.java
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/Messages.java // public class Messages { // public static final String SEMANTIC_VERSION_FILENAME = ".semanticVersion"; // public static final String DISPLAY_NAME = "Determine Semantic Version"; // public static final String SEMANTIC_VERSION_COLUMN_DISPLAY_NAME = "Semantic Version"; // public static final String UNKNOWN_VERSION = "Unknown"; // // public static class Parsers { // public static final String SBT_BUILD_SBT_PARSER = "SBT build.sbt parser"; // public static final String MAVEN_POM_PARSER = "Maven Pom Parser"; // public static final String SBT_BUILD_SCALA_PARSER = "SBT Build.scala Parser"; // public static final String BOWER_JSON_PARSER = "Bower bower.json Parser"; // public static final String NPM_JSON_PARSER = "NPM package.json Parser"; // public static final String COMPOSER_JSON_PARSER = "Composer composer.json Parser"; // } // // public static class ColumnDisplayStrategies { // public static final String LAST_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Successful Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_BUILD_VERSION_STRATEGY = "Show Last Successful Semantic Version"; // public static final String NA_STRATEGY = "Show 'N/A'"; // } // // public static class NamingStrategies { // public static final String NOOP_NAMING = "none"; // public static final String MAVEN_RELEASE_DEVELOPMENT = "Maven, release and development version"; // public static final String UNTOUCHED = "As found"; // public static final String UNTOUCHED_SNAPSHOT = "As found (-SNAPSHOT)"; // } // }
import hudson.Extension; import hudson.model.Descriptor; import hudson.model.Job; import org.jenkinsci.plugins.SemanticVersioning.Messages;
/* * The MIT License * * Copyright (c) 2014, Steve Wagner * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.jenkinsci.plugins.SemanticVersioning.columnDisplay; @Extension public class LastJenkinsBuildNumberStrategy extends AbstractColumnDisplayStrategy { public String getDisplayString(Job job) { return Integer.toString(job.getLastBuild().getNumber()); } @SuppressWarnings("unchecked") public Descriptor<ColumnDisplayStrategy> getDescriptor() { return new AbstractDisplayStrategyDescription() { @Override public String getDisplayName() {
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/Messages.java // public class Messages { // public static final String SEMANTIC_VERSION_FILENAME = ".semanticVersion"; // public static final String DISPLAY_NAME = "Determine Semantic Version"; // public static final String SEMANTIC_VERSION_COLUMN_DISPLAY_NAME = "Semantic Version"; // public static final String UNKNOWN_VERSION = "Unknown"; // // public static class Parsers { // public static final String SBT_BUILD_SBT_PARSER = "SBT build.sbt parser"; // public static final String MAVEN_POM_PARSER = "Maven Pom Parser"; // public static final String SBT_BUILD_SCALA_PARSER = "SBT Build.scala Parser"; // public static final String BOWER_JSON_PARSER = "Bower bower.json Parser"; // public static final String NPM_JSON_PARSER = "NPM package.json Parser"; // public static final String COMPOSER_JSON_PARSER = "Composer composer.json Parser"; // } // // public static class ColumnDisplayStrategies { // public static final String LAST_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Successful Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_BUILD_VERSION_STRATEGY = "Show Last Successful Semantic Version"; // public static final String NA_STRATEGY = "Show 'N/A'"; // } // // public static class NamingStrategies { // public static final String NOOP_NAMING = "none"; // public static final String MAVEN_RELEASE_DEVELOPMENT = "Maven, release and development version"; // public static final String UNTOUCHED = "As found"; // public static final String UNTOUCHED_SNAPSHOT = "As found (-SNAPSHOT)"; // } // } // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/columnDisplay/LastJenkinsBuildNumberStrategy.java import hudson.Extension; import hudson.model.Descriptor; import hudson.model.Job; import org.jenkinsci.plugins.SemanticVersioning.Messages; /* * The MIT License * * Copyright (c) 2014, Steve Wagner * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.jenkinsci.plugins.SemanticVersioning.columnDisplay; @Extension public class LastJenkinsBuildNumberStrategy extends AbstractColumnDisplayStrategy { public String getDisplayString(Job job) { return Integer.toString(job.getLastBuild().getNumber()); } @SuppressWarnings("unchecked") public Descriptor<ColumnDisplayStrategy> getDescriptor() { return new AbstractDisplayStrategyDescription() { @Override public String getDisplayName() {
return Messages.ColumnDisplayStrategies.LAST_JENKINS_BUILD_NUMBER_STRATEGY;
jenkinsci/semantic-versioning-plugin
src/main/java/org/jenkinsci/plugins/SemanticVersioning/SemanticVersioningBuilder.java
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/naming/NamingStrategy.java // public interface NamingStrategy extends Describable<NamingStrategy>, Serializable { // String exportNames(AppVersion current, Map<String, String> vars, boolean useBuildNumber, int buildNumber); // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/naming/NoopNamingStrategy.java // @Extension // public class NoopNamingStrategy implements NamingStrategy, Serializable { // // private static Logger logger = Logger.getLogger(String.valueOf(AppVersion.class)); // // public Descriptor<NamingStrategy> getDescriptor() { // return new AbstractSemanticParserDescription() { // // @Override // public String getDisplayName() { // // return Messages.NamingStrategies.NOOP_NAMING; // } // }; // } // // public String exportNames(AppVersion current, Map<String,String> vars, boolean useBuildNumber, int buildNumber) { // // it's called "noop", d'oh! // logger.info("SemanticVersioningProcessor::getAppVersion -> not setting anything (NOOP): " + current.toJsonString()); // return current.toString(); // } // // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/parsing/BuildDefinitionParser.java // public interface BuildDefinitionParser extends Describable<BuildDefinitionParser> { // AppVersion extractAppVersion(FilePath workspace, PrintStream logger) throws IOException, InvalidBuildFileFormatException; // }
import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.model.BuildListener; import hudson.model.TaskListener; import hudson.model.AbstractBuild; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.BuildStepMonitor; import hudson.tasks.Builder; import hudson.util.ListBoxModel; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.util.HashMap; import jenkins.model.Jenkins; import net.sf.json.JSONObject; import org.apache.commons.io.FileUtils; import org.jenkinsci.plugins.SemanticVersioning.naming.NamingStrategy; import org.jenkinsci.plugins.SemanticVersioning.naming.NoopNamingStrategy; import org.jenkinsci.plugins.SemanticVersioning.parsing.BuildDefinitionParser; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.StaplerRequest;
/* * The MIT License * * Copyright (c) 2014, Steve Wagner * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.jenkinsci.plugins.SemanticVersioning; public class SemanticVersioningBuilder extends Builder { private BuildDefinitionParser parser;
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/naming/NamingStrategy.java // public interface NamingStrategy extends Describable<NamingStrategy>, Serializable { // String exportNames(AppVersion current, Map<String, String> vars, boolean useBuildNumber, int buildNumber); // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/naming/NoopNamingStrategy.java // @Extension // public class NoopNamingStrategy implements NamingStrategy, Serializable { // // private static Logger logger = Logger.getLogger(String.valueOf(AppVersion.class)); // // public Descriptor<NamingStrategy> getDescriptor() { // return new AbstractSemanticParserDescription() { // // @Override // public String getDisplayName() { // // return Messages.NamingStrategies.NOOP_NAMING; // } // }; // } // // public String exportNames(AppVersion current, Map<String,String> vars, boolean useBuildNumber, int buildNumber) { // // it's called "noop", d'oh! // logger.info("SemanticVersioningProcessor::getAppVersion -> not setting anything (NOOP): " + current.toJsonString()); // return current.toString(); // } // // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/parsing/BuildDefinitionParser.java // public interface BuildDefinitionParser extends Describable<BuildDefinitionParser> { // AppVersion extractAppVersion(FilePath workspace, PrintStream logger) throws IOException, InvalidBuildFileFormatException; // } // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/SemanticVersioningBuilder.java import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.model.BuildListener; import hudson.model.TaskListener; import hudson.model.AbstractBuild; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.BuildStepMonitor; import hudson.tasks.Builder; import hudson.util.ListBoxModel; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.util.HashMap; import jenkins.model.Jenkins; import net.sf.json.JSONObject; import org.apache.commons.io.FileUtils; import org.jenkinsci.plugins.SemanticVersioning.naming.NamingStrategy; import org.jenkinsci.plugins.SemanticVersioning.naming.NoopNamingStrategy; import org.jenkinsci.plugins.SemanticVersioning.parsing.BuildDefinitionParser; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.StaplerRequest; /* * The MIT License * * Copyright (c) 2014, Steve Wagner * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.jenkinsci.plugins.SemanticVersioning; public class SemanticVersioningBuilder extends Builder { private BuildDefinitionParser parser;
private NamingStrategy namingStrategy = new NoopNamingStrategy();
jenkinsci/semantic-versioning-plugin
src/main/java/org/jenkinsci/plugins/SemanticVersioning/SemanticVersioningBuilder.java
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/naming/NamingStrategy.java // public interface NamingStrategy extends Describable<NamingStrategy>, Serializable { // String exportNames(AppVersion current, Map<String, String> vars, boolean useBuildNumber, int buildNumber); // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/naming/NoopNamingStrategy.java // @Extension // public class NoopNamingStrategy implements NamingStrategy, Serializable { // // private static Logger logger = Logger.getLogger(String.valueOf(AppVersion.class)); // // public Descriptor<NamingStrategy> getDescriptor() { // return new AbstractSemanticParserDescription() { // // @Override // public String getDisplayName() { // // return Messages.NamingStrategies.NOOP_NAMING; // } // }; // } // // public String exportNames(AppVersion current, Map<String,String> vars, boolean useBuildNumber, int buildNumber) { // // it's called "noop", d'oh! // logger.info("SemanticVersioningProcessor::getAppVersion -> not setting anything (NOOP): " + current.toJsonString()); // return current.toString(); // } // // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/parsing/BuildDefinitionParser.java // public interface BuildDefinitionParser extends Describable<BuildDefinitionParser> { // AppVersion extractAppVersion(FilePath workspace, PrintStream logger) throws IOException, InvalidBuildFileFormatException; // }
import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.model.BuildListener; import hudson.model.TaskListener; import hudson.model.AbstractBuild; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.BuildStepMonitor; import hudson.tasks.Builder; import hudson.util.ListBoxModel; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.util.HashMap; import jenkins.model.Jenkins; import net.sf.json.JSONObject; import org.apache.commons.io.FileUtils; import org.jenkinsci.plugins.SemanticVersioning.naming.NamingStrategy; import org.jenkinsci.plugins.SemanticVersioning.naming.NoopNamingStrategy; import org.jenkinsci.plugins.SemanticVersioning.parsing.BuildDefinitionParser; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.StaplerRequest;
/* * The MIT License * * Copyright (c) 2014, Steve Wagner * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.jenkinsci.plugins.SemanticVersioning; public class SemanticVersioningBuilder extends Builder { private BuildDefinitionParser parser;
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/naming/NamingStrategy.java // public interface NamingStrategy extends Describable<NamingStrategy>, Serializable { // String exportNames(AppVersion current, Map<String, String> vars, boolean useBuildNumber, int buildNumber); // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/naming/NoopNamingStrategy.java // @Extension // public class NoopNamingStrategy implements NamingStrategy, Serializable { // // private static Logger logger = Logger.getLogger(String.valueOf(AppVersion.class)); // // public Descriptor<NamingStrategy> getDescriptor() { // return new AbstractSemanticParserDescription() { // // @Override // public String getDisplayName() { // // return Messages.NamingStrategies.NOOP_NAMING; // } // }; // } // // public String exportNames(AppVersion current, Map<String,String> vars, boolean useBuildNumber, int buildNumber) { // // it's called "noop", d'oh! // logger.info("SemanticVersioningProcessor::getAppVersion -> not setting anything (NOOP): " + current.toJsonString()); // return current.toString(); // } // // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/parsing/BuildDefinitionParser.java // public interface BuildDefinitionParser extends Describable<BuildDefinitionParser> { // AppVersion extractAppVersion(FilePath workspace, PrintStream logger) throws IOException, InvalidBuildFileFormatException; // } // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/SemanticVersioningBuilder.java import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.model.BuildListener; import hudson.model.TaskListener; import hudson.model.AbstractBuild; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.BuildStepMonitor; import hudson.tasks.Builder; import hudson.util.ListBoxModel; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.util.HashMap; import jenkins.model.Jenkins; import net.sf.json.JSONObject; import org.apache.commons.io.FileUtils; import org.jenkinsci.plugins.SemanticVersioning.naming.NamingStrategy; import org.jenkinsci.plugins.SemanticVersioning.naming.NoopNamingStrategy; import org.jenkinsci.plugins.SemanticVersioning.parsing.BuildDefinitionParser; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.StaplerRequest; /* * The MIT License * * Copyright (c) 2014, Steve Wagner * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.jenkinsci.plugins.SemanticVersioning; public class SemanticVersioningBuilder extends Builder { private BuildDefinitionParser parser;
private NamingStrategy namingStrategy = new NoopNamingStrategy();
jenkinsci/semantic-versioning-plugin
src/main/java/org/jenkinsci/plugins/SemanticVersioning/parsing/JsonVersionParser.java
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/AppVersion.java // public class AppVersion implements Serializable { // private static final String SNAPSHOT = "SNAPSHOT"; // private final int major; // private final int minor; // private final String original; // // private int build; // private final boolean isSnapshot; // public static final AppVersion EmptyVersion = new AppVersion(0, 0, 0, false, ""); // // public static AppVersion parse(String versionString) { // String[] parts = versionString.split("[\\.-]"); // // int major = Integer.parseInt(parts[0]); // int minor = Integer.parseInt(parts[1]); // // int build = -1; // boolean isSnapshot = false; // // if (parts.length == 3) { // if (parts[2].equals(SNAPSHOT)) { // isSnapshot = true; // } else { // build = Integer.parseInt(parts[2]); // } // } else if (parts.length == 4) { // build = Integer.parseInt(parts[2]); // isSnapshot = parts[3].equals(SNAPSHOT); // } // // return new AppVersion(major, minor, build, isSnapshot, versionString); // } // // private AppVersion(int major, int minor, int build, boolean isSnapshot, String original) { // this.major = major; // this.minor = minor; // // this.isSnapshot = isSnapshot; // this.build = build; // this.original = original; // } // // public int getMajor() { // return major; // } // // public int getMinor() { // return minor; // } // // public String getOriginal() { // return this.original; // } // // public boolean isSnapshot() { // return isSnapshot; // } // // public void setBuild(int build) { // this.build = build; // } // // public int getBuild() { // return build; // } // // public String toJsonString() { // return String.format( // "{ \"major\": %d, \"minor\": %d, \"build\": %d, \"isSnapshot\": %b, \"originalString\": \"%s\" }", // this.major, // this.minor, // this.build, // this.isSnapshot, // this.original); // } // // @Override // public String toString() { // String version = String.format("%s.%s", major, minor); // if(build > -1) { // version += "." + build; // } // if (isSnapshot) { // version += "-" + SNAPSHOT; // } // return version; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/InvalidBuildFileFormatException.java // public class InvalidBuildFileFormatException extends Exception { // private static final long serialVersionUID = 1L; // // public InvalidBuildFileFormatException(String message) { // super(message); // } // }
import org.jenkinsci.plugins.SemanticVersioning.AppVersion; import org.jenkinsci.plugins.SemanticVersioning.InvalidBuildFileFormatException; import hudson.FilePath; import net.sf.json.JSONObject; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintStream; import org.apache.commons.io.FileUtils;
/* * The MIT License * * Copyright (c) 2014, Arne M. Størksen * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.jenkinsci.plugins.SemanticVersioning.parsing; public abstract class JsonVersionParser extends AbstractBuildDefinitionParser { private final String filepath; private final String jsonpathVersion; protected JsonVersionParser(String filepath, String jsonpathVersion) { this.filepath = filepath; this.jsonpathVersion = jsonpathVersion; }
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/AppVersion.java // public class AppVersion implements Serializable { // private static final String SNAPSHOT = "SNAPSHOT"; // private final int major; // private final int minor; // private final String original; // // private int build; // private final boolean isSnapshot; // public static final AppVersion EmptyVersion = new AppVersion(0, 0, 0, false, ""); // // public static AppVersion parse(String versionString) { // String[] parts = versionString.split("[\\.-]"); // // int major = Integer.parseInt(parts[0]); // int minor = Integer.parseInt(parts[1]); // // int build = -1; // boolean isSnapshot = false; // // if (parts.length == 3) { // if (parts[2].equals(SNAPSHOT)) { // isSnapshot = true; // } else { // build = Integer.parseInt(parts[2]); // } // } else if (parts.length == 4) { // build = Integer.parseInt(parts[2]); // isSnapshot = parts[3].equals(SNAPSHOT); // } // // return new AppVersion(major, minor, build, isSnapshot, versionString); // } // // private AppVersion(int major, int minor, int build, boolean isSnapshot, String original) { // this.major = major; // this.minor = minor; // // this.isSnapshot = isSnapshot; // this.build = build; // this.original = original; // } // // public int getMajor() { // return major; // } // // public int getMinor() { // return minor; // } // // public String getOriginal() { // return this.original; // } // // public boolean isSnapshot() { // return isSnapshot; // } // // public void setBuild(int build) { // this.build = build; // } // // public int getBuild() { // return build; // } // // public String toJsonString() { // return String.format( // "{ \"major\": %d, \"minor\": %d, \"build\": %d, \"isSnapshot\": %b, \"originalString\": \"%s\" }", // this.major, // this.minor, // this.build, // this.isSnapshot, // this.original); // } // // @Override // public String toString() { // String version = String.format("%s.%s", major, minor); // if(build > -1) { // version += "." + build; // } // if (isSnapshot) { // version += "-" + SNAPSHOT; // } // return version; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/InvalidBuildFileFormatException.java // public class InvalidBuildFileFormatException extends Exception { // private static final long serialVersionUID = 1L; // // public InvalidBuildFileFormatException(String message) { // super(message); // } // } // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/parsing/JsonVersionParser.java import org.jenkinsci.plugins.SemanticVersioning.AppVersion; import org.jenkinsci.plugins.SemanticVersioning.InvalidBuildFileFormatException; import hudson.FilePath; import net.sf.json.JSONObject; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintStream; import org.apache.commons.io.FileUtils; /* * The MIT License * * Copyright (c) 2014, Arne M. Størksen * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.jenkinsci.plugins.SemanticVersioning.parsing; public abstract class JsonVersionParser extends AbstractBuildDefinitionParser { private final String filepath; private final String jsonpathVersion; protected JsonVersionParser(String filepath, String jsonpathVersion) { this.filepath = filepath; this.jsonpathVersion = jsonpathVersion; }
public AppVersion extractAppVersion(FilePath workspace, PrintStream logger) throws IOException, InvalidBuildFileFormatException {
jenkinsci/semantic-versioning-plugin
src/main/java/org/jenkinsci/plugins/SemanticVersioning/parsing/JsonVersionParser.java
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/AppVersion.java // public class AppVersion implements Serializable { // private static final String SNAPSHOT = "SNAPSHOT"; // private final int major; // private final int minor; // private final String original; // // private int build; // private final boolean isSnapshot; // public static final AppVersion EmptyVersion = new AppVersion(0, 0, 0, false, ""); // // public static AppVersion parse(String versionString) { // String[] parts = versionString.split("[\\.-]"); // // int major = Integer.parseInt(parts[0]); // int minor = Integer.parseInt(parts[1]); // // int build = -1; // boolean isSnapshot = false; // // if (parts.length == 3) { // if (parts[2].equals(SNAPSHOT)) { // isSnapshot = true; // } else { // build = Integer.parseInt(parts[2]); // } // } else if (parts.length == 4) { // build = Integer.parseInt(parts[2]); // isSnapshot = parts[3].equals(SNAPSHOT); // } // // return new AppVersion(major, minor, build, isSnapshot, versionString); // } // // private AppVersion(int major, int minor, int build, boolean isSnapshot, String original) { // this.major = major; // this.minor = minor; // // this.isSnapshot = isSnapshot; // this.build = build; // this.original = original; // } // // public int getMajor() { // return major; // } // // public int getMinor() { // return minor; // } // // public String getOriginal() { // return this.original; // } // // public boolean isSnapshot() { // return isSnapshot; // } // // public void setBuild(int build) { // this.build = build; // } // // public int getBuild() { // return build; // } // // public String toJsonString() { // return String.format( // "{ \"major\": %d, \"minor\": %d, \"build\": %d, \"isSnapshot\": %b, \"originalString\": \"%s\" }", // this.major, // this.minor, // this.build, // this.isSnapshot, // this.original); // } // // @Override // public String toString() { // String version = String.format("%s.%s", major, minor); // if(build > -1) { // version += "." + build; // } // if (isSnapshot) { // version += "-" + SNAPSHOT; // } // return version; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/InvalidBuildFileFormatException.java // public class InvalidBuildFileFormatException extends Exception { // private static final long serialVersionUID = 1L; // // public InvalidBuildFileFormatException(String message) { // super(message); // } // }
import org.jenkinsci.plugins.SemanticVersioning.AppVersion; import org.jenkinsci.plugins.SemanticVersioning.InvalidBuildFileFormatException; import hudson.FilePath; import net.sf.json.JSONObject; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintStream; import org.apache.commons.io.FileUtils;
/* * The MIT License * * Copyright (c) 2014, Arne M. Størksen * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.jenkinsci.plugins.SemanticVersioning.parsing; public abstract class JsonVersionParser extends AbstractBuildDefinitionParser { private final String filepath; private final String jsonpathVersion; protected JsonVersionParser(String filepath, String jsonpathVersion) { this.filepath = filepath; this.jsonpathVersion = jsonpathVersion; }
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/AppVersion.java // public class AppVersion implements Serializable { // private static final String SNAPSHOT = "SNAPSHOT"; // private final int major; // private final int minor; // private final String original; // // private int build; // private final boolean isSnapshot; // public static final AppVersion EmptyVersion = new AppVersion(0, 0, 0, false, ""); // // public static AppVersion parse(String versionString) { // String[] parts = versionString.split("[\\.-]"); // // int major = Integer.parseInt(parts[0]); // int minor = Integer.parseInt(parts[1]); // // int build = -1; // boolean isSnapshot = false; // // if (parts.length == 3) { // if (parts[2].equals(SNAPSHOT)) { // isSnapshot = true; // } else { // build = Integer.parseInt(parts[2]); // } // } else if (parts.length == 4) { // build = Integer.parseInt(parts[2]); // isSnapshot = parts[3].equals(SNAPSHOT); // } // // return new AppVersion(major, minor, build, isSnapshot, versionString); // } // // private AppVersion(int major, int minor, int build, boolean isSnapshot, String original) { // this.major = major; // this.minor = minor; // // this.isSnapshot = isSnapshot; // this.build = build; // this.original = original; // } // // public int getMajor() { // return major; // } // // public int getMinor() { // return minor; // } // // public String getOriginal() { // return this.original; // } // // public boolean isSnapshot() { // return isSnapshot; // } // // public void setBuild(int build) { // this.build = build; // } // // public int getBuild() { // return build; // } // // public String toJsonString() { // return String.format( // "{ \"major\": %d, \"minor\": %d, \"build\": %d, \"isSnapshot\": %b, \"originalString\": \"%s\" }", // this.major, // this.minor, // this.build, // this.isSnapshot, // this.original); // } // // @Override // public String toString() { // String version = String.format("%s.%s", major, minor); // if(build > -1) { // version += "." + build; // } // if (isSnapshot) { // version += "-" + SNAPSHOT; // } // return version; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/InvalidBuildFileFormatException.java // public class InvalidBuildFileFormatException extends Exception { // private static final long serialVersionUID = 1L; // // public InvalidBuildFileFormatException(String message) { // super(message); // } // } // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/parsing/JsonVersionParser.java import org.jenkinsci.plugins.SemanticVersioning.AppVersion; import org.jenkinsci.plugins.SemanticVersioning.InvalidBuildFileFormatException; import hudson.FilePath; import net.sf.json.JSONObject; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintStream; import org.apache.commons.io.FileUtils; /* * The MIT License * * Copyright (c) 2014, Arne M. Størksen * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.jenkinsci.plugins.SemanticVersioning.parsing; public abstract class JsonVersionParser extends AbstractBuildDefinitionParser { private final String filepath; private final String jsonpathVersion; protected JsonVersionParser(String filepath, String jsonpathVersion) { this.filepath = filepath; this.jsonpathVersion = jsonpathVersion; }
public AppVersion extractAppVersion(FilePath workspace, PrintStream logger) throws IOException, InvalidBuildFileFormatException {
jenkinsci/semantic-versioning-plugin
src/main/java/org/jenkinsci/plugins/SemanticVersioning/naming/MavenReleaseNamingStrategy.java
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/AppVersion.java // public class AppVersion implements Serializable { // private static final String SNAPSHOT = "SNAPSHOT"; // private final int major; // private final int minor; // private final String original; // // private int build; // private final boolean isSnapshot; // public static final AppVersion EmptyVersion = new AppVersion(0, 0, 0, false, ""); // // public static AppVersion parse(String versionString) { // String[] parts = versionString.split("[\\.-]"); // // int major = Integer.parseInt(parts[0]); // int minor = Integer.parseInt(parts[1]); // // int build = -1; // boolean isSnapshot = false; // // if (parts.length == 3) { // if (parts[2].equals(SNAPSHOT)) { // isSnapshot = true; // } else { // build = Integer.parseInt(parts[2]); // } // } else if (parts.length == 4) { // build = Integer.parseInt(parts[2]); // isSnapshot = parts[3].equals(SNAPSHOT); // } // // return new AppVersion(major, minor, build, isSnapshot, versionString); // } // // private AppVersion(int major, int minor, int build, boolean isSnapshot, String original) { // this.major = major; // this.minor = minor; // // this.isSnapshot = isSnapshot; // this.build = build; // this.original = original; // } // // public int getMajor() { // return major; // } // // public int getMinor() { // return minor; // } // // public String getOriginal() { // return this.original; // } // // public boolean isSnapshot() { // return isSnapshot; // } // // public void setBuild(int build) { // this.build = build; // } // // public int getBuild() { // return build; // } // // public String toJsonString() { // return String.format( // "{ \"major\": %d, \"minor\": %d, \"build\": %d, \"isSnapshot\": %b, \"originalString\": \"%s\" }", // this.major, // this.minor, // this.build, // this.isSnapshot, // this.original); // } // // @Override // public String toString() { // String version = String.format("%s.%s", major, minor); // if(build > -1) { // version += "." + build; // } // if (isSnapshot) { // version += "-" + SNAPSHOT; // } // return version; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/Messages.java // public class Messages { // public static final String SEMANTIC_VERSION_FILENAME = ".semanticVersion"; // public static final String DISPLAY_NAME = "Determine Semantic Version"; // public static final String SEMANTIC_VERSION_COLUMN_DISPLAY_NAME = "Semantic Version"; // public static final String UNKNOWN_VERSION = "Unknown"; // // public static class Parsers { // public static final String SBT_BUILD_SBT_PARSER = "SBT build.sbt parser"; // public static final String MAVEN_POM_PARSER = "Maven Pom Parser"; // public static final String SBT_BUILD_SCALA_PARSER = "SBT Build.scala Parser"; // public static final String BOWER_JSON_PARSER = "Bower bower.json Parser"; // public static final String NPM_JSON_PARSER = "NPM package.json Parser"; // public static final String COMPOSER_JSON_PARSER = "Composer composer.json Parser"; // } // // public static class ColumnDisplayStrategies { // public static final String LAST_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Successful Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_BUILD_VERSION_STRATEGY = "Show Last Successful Semantic Version"; // public static final String NA_STRATEGY = "Show 'N/A'"; // } // // public static class NamingStrategies { // public static final String NOOP_NAMING = "none"; // public static final String MAVEN_RELEASE_DEVELOPMENT = "Maven, release and development version"; // public static final String UNTOUCHED = "As found"; // public static final String UNTOUCHED_SNAPSHOT = "As found (-SNAPSHOT)"; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/parsing/AbstractSemanticParserDescription.java // public abstract class AbstractSemanticParserDescription extends hudson.model.Descriptor { // @Override // public abstract String getDisplayName(); // }
import java.io.Serializable; import java.util.Map; import java.util.logging.Logger; import hudson.Extension; import hudson.model.Descriptor; import org.jenkinsci.plugins.SemanticVersioning.AppVersion; import org.jenkinsci.plugins.SemanticVersioning.Messages; import org.jenkinsci.plugins.SemanticVersioning.parsing.AbstractSemanticParserDescription;
package org.jenkinsci.plugins.SemanticVersioning.naming; @Extension public class MavenReleaseNamingStrategy implements NamingStrategy, Serializable {
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/AppVersion.java // public class AppVersion implements Serializable { // private static final String SNAPSHOT = "SNAPSHOT"; // private final int major; // private final int minor; // private final String original; // // private int build; // private final boolean isSnapshot; // public static final AppVersion EmptyVersion = new AppVersion(0, 0, 0, false, ""); // // public static AppVersion parse(String versionString) { // String[] parts = versionString.split("[\\.-]"); // // int major = Integer.parseInt(parts[0]); // int minor = Integer.parseInt(parts[1]); // // int build = -1; // boolean isSnapshot = false; // // if (parts.length == 3) { // if (parts[2].equals(SNAPSHOT)) { // isSnapshot = true; // } else { // build = Integer.parseInt(parts[2]); // } // } else if (parts.length == 4) { // build = Integer.parseInt(parts[2]); // isSnapshot = parts[3].equals(SNAPSHOT); // } // // return new AppVersion(major, minor, build, isSnapshot, versionString); // } // // private AppVersion(int major, int minor, int build, boolean isSnapshot, String original) { // this.major = major; // this.minor = minor; // // this.isSnapshot = isSnapshot; // this.build = build; // this.original = original; // } // // public int getMajor() { // return major; // } // // public int getMinor() { // return minor; // } // // public String getOriginal() { // return this.original; // } // // public boolean isSnapshot() { // return isSnapshot; // } // // public void setBuild(int build) { // this.build = build; // } // // public int getBuild() { // return build; // } // // public String toJsonString() { // return String.format( // "{ \"major\": %d, \"minor\": %d, \"build\": %d, \"isSnapshot\": %b, \"originalString\": \"%s\" }", // this.major, // this.minor, // this.build, // this.isSnapshot, // this.original); // } // // @Override // public String toString() { // String version = String.format("%s.%s", major, minor); // if(build > -1) { // version += "." + build; // } // if (isSnapshot) { // version += "-" + SNAPSHOT; // } // return version; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/Messages.java // public class Messages { // public static final String SEMANTIC_VERSION_FILENAME = ".semanticVersion"; // public static final String DISPLAY_NAME = "Determine Semantic Version"; // public static final String SEMANTIC_VERSION_COLUMN_DISPLAY_NAME = "Semantic Version"; // public static final String UNKNOWN_VERSION = "Unknown"; // // public static class Parsers { // public static final String SBT_BUILD_SBT_PARSER = "SBT build.sbt parser"; // public static final String MAVEN_POM_PARSER = "Maven Pom Parser"; // public static final String SBT_BUILD_SCALA_PARSER = "SBT Build.scala Parser"; // public static final String BOWER_JSON_PARSER = "Bower bower.json Parser"; // public static final String NPM_JSON_PARSER = "NPM package.json Parser"; // public static final String COMPOSER_JSON_PARSER = "Composer composer.json Parser"; // } // // public static class ColumnDisplayStrategies { // public static final String LAST_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Successful Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_BUILD_VERSION_STRATEGY = "Show Last Successful Semantic Version"; // public static final String NA_STRATEGY = "Show 'N/A'"; // } // // public static class NamingStrategies { // public static final String NOOP_NAMING = "none"; // public static final String MAVEN_RELEASE_DEVELOPMENT = "Maven, release and development version"; // public static final String UNTOUCHED = "As found"; // public static final String UNTOUCHED_SNAPSHOT = "As found (-SNAPSHOT)"; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/parsing/AbstractSemanticParserDescription.java // public abstract class AbstractSemanticParserDescription extends hudson.model.Descriptor { // @Override // public abstract String getDisplayName(); // } // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/naming/MavenReleaseNamingStrategy.java import java.io.Serializable; import java.util.Map; import java.util.logging.Logger; import hudson.Extension; import hudson.model.Descriptor; import org.jenkinsci.plugins.SemanticVersioning.AppVersion; import org.jenkinsci.plugins.SemanticVersioning.Messages; import org.jenkinsci.plugins.SemanticVersioning.parsing.AbstractSemanticParserDescription; package org.jenkinsci.plugins.SemanticVersioning.naming; @Extension public class MavenReleaseNamingStrategy implements NamingStrategy, Serializable {
private static Logger logger = Logger.getLogger(String.valueOf(AppVersion.class));
jenkinsci/semantic-versioning-plugin
src/main/java/org/jenkinsci/plugins/SemanticVersioning/naming/MavenReleaseNamingStrategy.java
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/AppVersion.java // public class AppVersion implements Serializable { // private static final String SNAPSHOT = "SNAPSHOT"; // private final int major; // private final int minor; // private final String original; // // private int build; // private final boolean isSnapshot; // public static final AppVersion EmptyVersion = new AppVersion(0, 0, 0, false, ""); // // public static AppVersion parse(String versionString) { // String[] parts = versionString.split("[\\.-]"); // // int major = Integer.parseInt(parts[0]); // int minor = Integer.parseInt(parts[1]); // // int build = -1; // boolean isSnapshot = false; // // if (parts.length == 3) { // if (parts[2].equals(SNAPSHOT)) { // isSnapshot = true; // } else { // build = Integer.parseInt(parts[2]); // } // } else if (parts.length == 4) { // build = Integer.parseInt(parts[2]); // isSnapshot = parts[3].equals(SNAPSHOT); // } // // return new AppVersion(major, minor, build, isSnapshot, versionString); // } // // private AppVersion(int major, int minor, int build, boolean isSnapshot, String original) { // this.major = major; // this.minor = minor; // // this.isSnapshot = isSnapshot; // this.build = build; // this.original = original; // } // // public int getMajor() { // return major; // } // // public int getMinor() { // return minor; // } // // public String getOriginal() { // return this.original; // } // // public boolean isSnapshot() { // return isSnapshot; // } // // public void setBuild(int build) { // this.build = build; // } // // public int getBuild() { // return build; // } // // public String toJsonString() { // return String.format( // "{ \"major\": %d, \"minor\": %d, \"build\": %d, \"isSnapshot\": %b, \"originalString\": \"%s\" }", // this.major, // this.minor, // this.build, // this.isSnapshot, // this.original); // } // // @Override // public String toString() { // String version = String.format("%s.%s", major, minor); // if(build > -1) { // version += "." + build; // } // if (isSnapshot) { // version += "-" + SNAPSHOT; // } // return version; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/Messages.java // public class Messages { // public static final String SEMANTIC_VERSION_FILENAME = ".semanticVersion"; // public static final String DISPLAY_NAME = "Determine Semantic Version"; // public static final String SEMANTIC_VERSION_COLUMN_DISPLAY_NAME = "Semantic Version"; // public static final String UNKNOWN_VERSION = "Unknown"; // // public static class Parsers { // public static final String SBT_BUILD_SBT_PARSER = "SBT build.sbt parser"; // public static final String MAVEN_POM_PARSER = "Maven Pom Parser"; // public static final String SBT_BUILD_SCALA_PARSER = "SBT Build.scala Parser"; // public static final String BOWER_JSON_PARSER = "Bower bower.json Parser"; // public static final String NPM_JSON_PARSER = "NPM package.json Parser"; // public static final String COMPOSER_JSON_PARSER = "Composer composer.json Parser"; // } // // public static class ColumnDisplayStrategies { // public static final String LAST_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Successful Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_BUILD_VERSION_STRATEGY = "Show Last Successful Semantic Version"; // public static final String NA_STRATEGY = "Show 'N/A'"; // } // // public static class NamingStrategies { // public static final String NOOP_NAMING = "none"; // public static final String MAVEN_RELEASE_DEVELOPMENT = "Maven, release and development version"; // public static final String UNTOUCHED = "As found"; // public static final String UNTOUCHED_SNAPSHOT = "As found (-SNAPSHOT)"; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/parsing/AbstractSemanticParserDescription.java // public abstract class AbstractSemanticParserDescription extends hudson.model.Descriptor { // @Override // public abstract String getDisplayName(); // }
import java.io.Serializable; import java.util.Map; import java.util.logging.Logger; import hudson.Extension; import hudson.model.Descriptor; import org.jenkinsci.plugins.SemanticVersioning.AppVersion; import org.jenkinsci.plugins.SemanticVersioning.Messages; import org.jenkinsci.plugins.SemanticVersioning.parsing.AbstractSemanticParserDescription;
package org.jenkinsci.plugins.SemanticVersioning.naming; @Extension public class MavenReleaseNamingStrategy implements NamingStrategy, Serializable { private static Logger logger = Logger.getLogger(String.valueOf(AppVersion.class)); public Descriptor<NamingStrategy> getDescriptor() {
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/AppVersion.java // public class AppVersion implements Serializable { // private static final String SNAPSHOT = "SNAPSHOT"; // private final int major; // private final int minor; // private final String original; // // private int build; // private final boolean isSnapshot; // public static final AppVersion EmptyVersion = new AppVersion(0, 0, 0, false, ""); // // public static AppVersion parse(String versionString) { // String[] parts = versionString.split("[\\.-]"); // // int major = Integer.parseInt(parts[0]); // int minor = Integer.parseInt(parts[1]); // // int build = -1; // boolean isSnapshot = false; // // if (parts.length == 3) { // if (parts[2].equals(SNAPSHOT)) { // isSnapshot = true; // } else { // build = Integer.parseInt(parts[2]); // } // } else if (parts.length == 4) { // build = Integer.parseInt(parts[2]); // isSnapshot = parts[3].equals(SNAPSHOT); // } // // return new AppVersion(major, minor, build, isSnapshot, versionString); // } // // private AppVersion(int major, int minor, int build, boolean isSnapshot, String original) { // this.major = major; // this.minor = minor; // // this.isSnapshot = isSnapshot; // this.build = build; // this.original = original; // } // // public int getMajor() { // return major; // } // // public int getMinor() { // return minor; // } // // public String getOriginal() { // return this.original; // } // // public boolean isSnapshot() { // return isSnapshot; // } // // public void setBuild(int build) { // this.build = build; // } // // public int getBuild() { // return build; // } // // public String toJsonString() { // return String.format( // "{ \"major\": %d, \"minor\": %d, \"build\": %d, \"isSnapshot\": %b, \"originalString\": \"%s\" }", // this.major, // this.minor, // this.build, // this.isSnapshot, // this.original); // } // // @Override // public String toString() { // String version = String.format("%s.%s", major, minor); // if(build > -1) { // version += "." + build; // } // if (isSnapshot) { // version += "-" + SNAPSHOT; // } // return version; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/Messages.java // public class Messages { // public static final String SEMANTIC_VERSION_FILENAME = ".semanticVersion"; // public static final String DISPLAY_NAME = "Determine Semantic Version"; // public static final String SEMANTIC_VERSION_COLUMN_DISPLAY_NAME = "Semantic Version"; // public static final String UNKNOWN_VERSION = "Unknown"; // // public static class Parsers { // public static final String SBT_BUILD_SBT_PARSER = "SBT build.sbt parser"; // public static final String MAVEN_POM_PARSER = "Maven Pom Parser"; // public static final String SBT_BUILD_SCALA_PARSER = "SBT Build.scala Parser"; // public static final String BOWER_JSON_PARSER = "Bower bower.json Parser"; // public static final String NPM_JSON_PARSER = "NPM package.json Parser"; // public static final String COMPOSER_JSON_PARSER = "Composer composer.json Parser"; // } // // public static class ColumnDisplayStrategies { // public static final String LAST_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Successful Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_BUILD_VERSION_STRATEGY = "Show Last Successful Semantic Version"; // public static final String NA_STRATEGY = "Show 'N/A'"; // } // // public static class NamingStrategies { // public static final String NOOP_NAMING = "none"; // public static final String MAVEN_RELEASE_DEVELOPMENT = "Maven, release and development version"; // public static final String UNTOUCHED = "As found"; // public static final String UNTOUCHED_SNAPSHOT = "As found (-SNAPSHOT)"; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/parsing/AbstractSemanticParserDescription.java // public abstract class AbstractSemanticParserDescription extends hudson.model.Descriptor { // @Override // public abstract String getDisplayName(); // } // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/naming/MavenReleaseNamingStrategy.java import java.io.Serializable; import java.util.Map; import java.util.logging.Logger; import hudson.Extension; import hudson.model.Descriptor; import org.jenkinsci.plugins.SemanticVersioning.AppVersion; import org.jenkinsci.plugins.SemanticVersioning.Messages; import org.jenkinsci.plugins.SemanticVersioning.parsing.AbstractSemanticParserDescription; package org.jenkinsci.plugins.SemanticVersioning.naming; @Extension public class MavenReleaseNamingStrategy implements NamingStrategy, Serializable { private static Logger logger = Logger.getLogger(String.valueOf(AppVersion.class)); public Descriptor<NamingStrategy> getDescriptor() {
return new AbstractSemanticParserDescription() {
jenkinsci/semantic-versioning-plugin
src/main/java/org/jenkinsci/plugins/SemanticVersioning/naming/MavenReleaseNamingStrategy.java
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/AppVersion.java // public class AppVersion implements Serializable { // private static final String SNAPSHOT = "SNAPSHOT"; // private final int major; // private final int minor; // private final String original; // // private int build; // private final boolean isSnapshot; // public static final AppVersion EmptyVersion = new AppVersion(0, 0, 0, false, ""); // // public static AppVersion parse(String versionString) { // String[] parts = versionString.split("[\\.-]"); // // int major = Integer.parseInt(parts[0]); // int minor = Integer.parseInt(parts[1]); // // int build = -1; // boolean isSnapshot = false; // // if (parts.length == 3) { // if (parts[2].equals(SNAPSHOT)) { // isSnapshot = true; // } else { // build = Integer.parseInt(parts[2]); // } // } else if (parts.length == 4) { // build = Integer.parseInt(parts[2]); // isSnapshot = parts[3].equals(SNAPSHOT); // } // // return new AppVersion(major, minor, build, isSnapshot, versionString); // } // // private AppVersion(int major, int minor, int build, boolean isSnapshot, String original) { // this.major = major; // this.minor = minor; // // this.isSnapshot = isSnapshot; // this.build = build; // this.original = original; // } // // public int getMajor() { // return major; // } // // public int getMinor() { // return minor; // } // // public String getOriginal() { // return this.original; // } // // public boolean isSnapshot() { // return isSnapshot; // } // // public void setBuild(int build) { // this.build = build; // } // // public int getBuild() { // return build; // } // // public String toJsonString() { // return String.format( // "{ \"major\": %d, \"minor\": %d, \"build\": %d, \"isSnapshot\": %b, \"originalString\": \"%s\" }", // this.major, // this.minor, // this.build, // this.isSnapshot, // this.original); // } // // @Override // public String toString() { // String version = String.format("%s.%s", major, minor); // if(build > -1) { // version += "." + build; // } // if (isSnapshot) { // version += "-" + SNAPSHOT; // } // return version; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/Messages.java // public class Messages { // public static final String SEMANTIC_VERSION_FILENAME = ".semanticVersion"; // public static final String DISPLAY_NAME = "Determine Semantic Version"; // public static final String SEMANTIC_VERSION_COLUMN_DISPLAY_NAME = "Semantic Version"; // public static final String UNKNOWN_VERSION = "Unknown"; // // public static class Parsers { // public static final String SBT_BUILD_SBT_PARSER = "SBT build.sbt parser"; // public static final String MAVEN_POM_PARSER = "Maven Pom Parser"; // public static final String SBT_BUILD_SCALA_PARSER = "SBT Build.scala Parser"; // public static final String BOWER_JSON_PARSER = "Bower bower.json Parser"; // public static final String NPM_JSON_PARSER = "NPM package.json Parser"; // public static final String COMPOSER_JSON_PARSER = "Composer composer.json Parser"; // } // // public static class ColumnDisplayStrategies { // public static final String LAST_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Successful Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_BUILD_VERSION_STRATEGY = "Show Last Successful Semantic Version"; // public static final String NA_STRATEGY = "Show 'N/A'"; // } // // public static class NamingStrategies { // public static final String NOOP_NAMING = "none"; // public static final String MAVEN_RELEASE_DEVELOPMENT = "Maven, release and development version"; // public static final String UNTOUCHED = "As found"; // public static final String UNTOUCHED_SNAPSHOT = "As found (-SNAPSHOT)"; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/parsing/AbstractSemanticParserDescription.java // public abstract class AbstractSemanticParserDescription extends hudson.model.Descriptor { // @Override // public abstract String getDisplayName(); // }
import java.io.Serializable; import java.util.Map; import java.util.logging.Logger; import hudson.Extension; import hudson.model.Descriptor; import org.jenkinsci.plugins.SemanticVersioning.AppVersion; import org.jenkinsci.plugins.SemanticVersioning.Messages; import org.jenkinsci.plugins.SemanticVersioning.parsing.AbstractSemanticParserDescription;
package org.jenkinsci.plugins.SemanticVersioning.naming; @Extension public class MavenReleaseNamingStrategy implements NamingStrategy, Serializable { private static Logger logger = Logger.getLogger(String.valueOf(AppVersion.class)); public Descriptor<NamingStrategy> getDescriptor() { return new AbstractSemanticParserDescription() { @Override public String getDisplayName() {
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/AppVersion.java // public class AppVersion implements Serializable { // private static final String SNAPSHOT = "SNAPSHOT"; // private final int major; // private final int minor; // private final String original; // // private int build; // private final boolean isSnapshot; // public static final AppVersion EmptyVersion = new AppVersion(0, 0, 0, false, ""); // // public static AppVersion parse(String versionString) { // String[] parts = versionString.split("[\\.-]"); // // int major = Integer.parseInt(parts[0]); // int minor = Integer.parseInt(parts[1]); // // int build = -1; // boolean isSnapshot = false; // // if (parts.length == 3) { // if (parts[2].equals(SNAPSHOT)) { // isSnapshot = true; // } else { // build = Integer.parseInt(parts[2]); // } // } else if (parts.length == 4) { // build = Integer.parseInt(parts[2]); // isSnapshot = parts[3].equals(SNAPSHOT); // } // // return new AppVersion(major, minor, build, isSnapshot, versionString); // } // // private AppVersion(int major, int minor, int build, boolean isSnapshot, String original) { // this.major = major; // this.minor = minor; // // this.isSnapshot = isSnapshot; // this.build = build; // this.original = original; // } // // public int getMajor() { // return major; // } // // public int getMinor() { // return minor; // } // // public String getOriginal() { // return this.original; // } // // public boolean isSnapshot() { // return isSnapshot; // } // // public void setBuild(int build) { // this.build = build; // } // // public int getBuild() { // return build; // } // // public String toJsonString() { // return String.format( // "{ \"major\": %d, \"minor\": %d, \"build\": %d, \"isSnapshot\": %b, \"originalString\": \"%s\" }", // this.major, // this.minor, // this.build, // this.isSnapshot, // this.original); // } // // @Override // public String toString() { // String version = String.format("%s.%s", major, minor); // if(build > -1) { // version += "." + build; // } // if (isSnapshot) { // version += "-" + SNAPSHOT; // } // return version; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/Messages.java // public class Messages { // public static final String SEMANTIC_VERSION_FILENAME = ".semanticVersion"; // public static final String DISPLAY_NAME = "Determine Semantic Version"; // public static final String SEMANTIC_VERSION_COLUMN_DISPLAY_NAME = "Semantic Version"; // public static final String UNKNOWN_VERSION = "Unknown"; // // public static class Parsers { // public static final String SBT_BUILD_SBT_PARSER = "SBT build.sbt parser"; // public static final String MAVEN_POM_PARSER = "Maven Pom Parser"; // public static final String SBT_BUILD_SCALA_PARSER = "SBT Build.scala Parser"; // public static final String BOWER_JSON_PARSER = "Bower bower.json Parser"; // public static final String NPM_JSON_PARSER = "NPM package.json Parser"; // public static final String COMPOSER_JSON_PARSER = "Composer composer.json Parser"; // } // // public static class ColumnDisplayStrategies { // public static final String LAST_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Successful Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_BUILD_VERSION_STRATEGY = "Show Last Successful Semantic Version"; // public static final String NA_STRATEGY = "Show 'N/A'"; // } // // public static class NamingStrategies { // public static final String NOOP_NAMING = "none"; // public static final String MAVEN_RELEASE_DEVELOPMENT = "Maven, release and development version"; // public static final String UNTOUCHED = "As found"; // public static final String UNTOUCHED_SNAPSHOT = "As found (-SNAPSHOT)"; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/parsing/AbstractSemanticParserDescription.java // public abstract class AbstractSemanticParserDescription extends hudson.model.Descriptor { // @Override // public abstract String getDisplayName(); // } // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/naming/MavenReleaseNamingStrategy.java import java.io.Serializable; import java.util.Map; import java.util.logging.Logger; import hudson.Extension; import hudson.model.Descriptor; import org.jenkinsci.plugins.SemanticVersioning.AppVersion; import org.jenkinsci.plugins.SemanticVersioning.Messages; import org.jenkinsci.plugins.SemanticVersioning.parsing.AbstractSemanticParserDescription; package org.jenkinsci.plugins.SemanticVersioning.naming; @Extension public class MavenReleaseNamingStrategy implements NamingStrategy, Serializable { private static Logger logger = Logger.getLogger(String.valueOf(AppVersion.class)); public Descriptor<NamingStrategy> getDescriptor() { return new AbstractSemanticParserDescription() { @Override public String getDisplayName() {
return Messages.NamingStrategies.MAVEN_RELEASE_DEVELOPMENT;
jenkinsci/semantic-versioning-plugin
src/main/java/org/jenkinsci/plugins/SemanticVersioning/parsing/BowerParser.java
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/Messages.java // public class Messages { // public static final String SEMANTIC_VERSION_FILENAME = ".semanticVersion"; // public static final String DISPLAY_NAME = "Determine Semantic Version"; // public static final String SEMANTIC_VERSION_COLUMN_DISPLAY_NAME = "Semantic Version"; // public static final String UNKNOWN_VERSION = "Unknown"; // // public static class Parsers { // public static final String SBT_BUILD_SBT_PARSER = "SBT build.sbt parser"; // public static final String MAVEN_POM_PARSER = "Maven Pom Parser"; // public static final String SBT_BUILD_SCALA_PARSER = "SBT Build.scala Parser"; // public static final String BOWER_JSON_PARSER = "Bower bower.json Parser"; // public static final String NPM_JSON_PARSER = "NPM package.json Parser"; // public static final String COMPOSER_JSON_PARSER = "Composer composer.json Parser"; // } // // public static class ColumnDisplayStrategies { // public static final String LAST_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Successful Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_BUILD_VERSION_STRATEGY = "Show Last Successful Semantic Version"; // public static final String NA_STRATEGY = "Show 'N/A'"; // } // // public static class NamingStrategies { // public static final String NOOP_NAMING = "none"; // public static final String MAVEN_RELEASE_DEVELOPMENT = "Maven, release and development version"; // public static final String UNTOUCHED = "As found"; // public static final String UNTOUCHED_SNAPSHOT = "As found (-SNAPSHOT)"; // } // }
import hudson.Extension; import hudson.model.Descriptor; import org.jenkinsci.plugins.SemanticVersioning.Messages;
/* * The MIT License * * Copyright (c) 2014, Arne M. Størksen * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.jenkinsci.plugins.SemanticVersioning.parsing; @Extension public class BowerParser extends JsonVersionParser { public BowerParser() { super("bower.json", "version"); } @SuppressWarnings("unchecked") public Descriptor<BuildDefinitionParser> getDescriptor() { return new AbstractSemanticParserDescription() { @Override public String getDisplayName() {
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/Messages.java // public class Messages { // public static final String SEMANTIC_VERSION_FILENAME = ".semanticVersion"; // public static final String DISPLAY_NAME = "Determine Semantic Version"; // public static final String SEMANTIC_VERSION_COLUMN_DISPLAY_NAME = "Semantic Version"; // public static final String UNKNOWN_VERSION = "Unknown"; // // public static class Parsers { // public static final String SBT_BUILD_SBT_PARSER = "SBT build.sbt parser"; // public static final String MAVEN_POM_PARSER = "Maven Pom Parser"; // public static final String SBT_BUILD_SCALA_PARSER = "SBT Build.scala Parser"; // public static final String BOWER_JSON_PARSER = "Bower bower.json Parser"; // public static final String NPM_JSON_PARSER = "NPM package.json Parser"; // public static final String COMPOSER_JSON_PARSER = "Composer composer.json Parser"; // } // // public static class ColumnDisplayStrategies { // public static final String LAST_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Successful Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_BUILD_VERSION_STRATEGY = "Show Last Successful Semantic Version"; // public static final String NA_STRATEGY = "Show 'N/A'"; // } // // public static class NamingStrategies { // public static final String NOOP_NAMING = "none"; // public static final String MAVEN_RELEASE_DEVELOPMENT = "Maven, release and development version"; // public static final String UNTOUCHED = "As found"; // public static final String UNTOUCHED_SNAPSHOT = "As found (-SNAPSHOT)"; // } // } // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/parsing/BowerParser.java import hudson.Extension; import hudson.model.Descriptor; import org.jenkinsci.plugins.SemanticVersioning.Messages; /* * The MIT License * * Copyright (c) 2014, Arne M. Størksen * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.jenkinsci.plugins.SemanticVersioning.parsing; @Extension public class BowerParser extends JsonVersionParser { public BowerParser() { super("bower.json", "version"); } @SuppressWarnings("unchecked") public Descriptor<BuildDefinitionParser> getDescriptor() { return new AbstractSemanticParserDescription() { @Override public String getDisplayName() {
return Messages.Parsers.BOWER_JSON_PARSER;
jenkinsci/semantic-versioning-plugin
src/main/java/org/jenkinsci/plugins/SemanticVersioning/SemanticVersionColumn.java
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/columnDisplay/AbstractColumnDisplayStrategy.java // public abstract class AbstractColumnDisplayStrategy extends ExtensionPoint implements ColumnDisplayStrategy { // public static ExtensionList<ColumnDisplayStrategy> getStrategies() { // return Jenkins.getActiveInstance().getExtensionList(ColumnDisplayStrategy.class); // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/columnDisplay/ColumnDisplayStrategy.java // public interface ColumnDisplayStrategy extends Describable<ColumnDisplayStrategy> { // String getDisplayString(Job job); // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/columnDisplay/LastSuccessfulBuildStrategy.java // @Extension // public class LastSuccessfulBuildStrategy extends AbstractColumnDisplayStrategy { // // private static Logger logger = Logger.getLogger(String.valueOf(AppVersion.class)); // // public String getDisplayString(Job job) { // String semanticVersion = null; // Run run = job.getLastSuccessfulBuild(); // if (run == null) { // logger.info("LastSuccessfulBuildStrategy::getDisplayString -> last successful build not found."); // semanticVersion = Messages.UNKNOWN_VERSION; // } else { // String filename = run.getRootDir() + "/" + Messages.SEMANTIC_VERSION_FILENAME; // logger.info("LastSuccessfulBuildStrategy::getDisplayString -> last successful build found. Filename -> " + filename); // File file = new File(filename); // if (file.exists()) { // try { // semanticVersion = FileUtils.readFileToString(file); // logger.info("LastSuccessfulBuildStrategy::getDisplayString -> read semantic version from file -> " + semanticVersion); // } catch (IOException e) { // logger.severe(e.toString()); // } // } else { // logger.info("LastSuccessfulBuildStrategy::getDisplayString -> semanticVersion file not found."); // semanticVersion = Messages.UNKNOWN_VERSION; // } // } // // return semanticVersion; // } // // @SuppressWarnings("unchecked") // public Descriptor<ColumnDisplayStrategy> getDescriptor() { // return new AbstractDisplayStrategyDescription() { // @Override // public String getDisplayName() { // return Messages.ColumnDisplayStrategies.LAST_SUCCESSFUL_BUILD_VERSION_STRATEGY; // } // }; // } // }
import hudson.views.ListViewColumnDescriptor; import jenkins.model.Jenkins; import net.sf.json.JSONObject; import org.apache.commons.lang.StringUtils; import org.jenkinsci.plugins.SemanticVersioning.columnDisplay.AbstractColumnDisplayStrategy; import org.jenkinsci.plugins.SemanticVersioning.columnDisplay.ColumnDisplayStrategy; import org.jenkinsci.plugins.SemanticVersioning.columnDisplay.LastSuccessfulBuildStrategy; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.StaplerRequest; import java.io.IOException; import java.util.logging.Logger; import hudson.Extension; import hudson.ExtensionList; import hudson.model.Descriptor; import hudson.model.Job; import hudson.util.ListBoxModel; import hudson.views.ListViewColumn;
/* * The MIT License * * Copyright (c) 2014, Steve Wagner * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.jenkinsci.plugins.SemanticVersioning; public class SemanticVersionColumn extends ListViewColumn { private static Logger logger = Logger.getLogger(String.valueOf(AppVersion.class));
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/columnDisplay/AbstractColumnDisplayStrategy.java // public abstract class AbstractColumnDisplayStrategy extends ExtensionPoint implements ColumnDisplayStrategy { // public static ExtensionList<ColumnDisplayStrategy> getStrategies() { // return Jenkins.getActiveInstance().getExtensionList(ColumnDisplayStrategy.class); // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/columnDisplay/ColumnDisplayStrategy.java // public interface ColumnDisplayStrategy extends Describable<ColumnDisplayStrategy> { // String getDisplayString(Job job); // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/columnDisplay/LastSuccessfulBuildStrategy.java // @Extension // public class LastSuccessfulBuildStrategy extends AbstractColumnDisplayStrategy { // // private static Logger logger = Logger.getLogger(String.valueOf(AppVersion.class)); // // public String getDisplayString(Job job) { // String semanticVersion = null; // Run run = job.getLastSuccessfulBuild(); // if (run == null) { // logger.info("LastSuccessfulBuildStrategy::getDisplayString -> last successful build not found."); // semanticVersion = Messages.UNKNOWN_VERSION; // } else { // String filename = run.getRootDir() + "/" + Messages.SEMANTIC_VERSION_FILENAME; // logger.info("LastSuccessfulBuildStrategy::getDisplayString -> last successful build found. Filename -> " + filename); // File file = new File(filename); // if (file.exists()) { // try { // semanticVersion = FileUtils.readFileToString(file); // logger.info("LastSuccessfulBuildStrategy::getDisplayString -> read semantic version from file -> " + semanticVersion); // } catch (IOException e) { // logger.severe(e.toString()); // } // } else { // logger.info("LastSuccessfulBuildStrategy::getDisplayString -> semanticVersion file not found."); // semanticVersion = Messages.UNKNOWN_VERSION; // } // } // // return semanticVersion; // } // // @SuppressWarnings("unchecked") // public Descriptor<ColumnDisplayStrategy> getDescriptor() { // return new AbstractDisplayStrategyDescription() { // @Override // public String getDisplayName() { // return Messages.ColumnDisplayStrategies.LAST_SUCCESSFUL_BUILD_VERSION_STRATEGY; // } // }; // } // } // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/SemanticVersionColumn.java import hudson.views.ListViewColumnDescriptor; import jenkins.model.Jenkins; import net.sf.json.JSONObject; import org.apache.commons.lang.StringUtils; import org.jenkinsci.plugins.SemanticVersioning.columnDisplay.AbstractColumnDisplayStrategy; import org.jenkinsci.plugins.SemanticVersioning.columnDisplay.ColumnDisplayStrategy; import org.jenkinsci.plugins.SemanticVersioning.columnDisplay.LastSuccessfulBuildStrategy; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.StaplerRequest; import java.io.IOException; import java.util.logging.Logger; import hudson.Extension; import hudson.ExtensionList; import hudson.model.Descriptor; import hudson.model.Job; import hudson.util.ListBoxModel; import hudson.views.ListViewColumn; /* * The MIT License * * Copyright (c) 2014, Steve Wagner * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.jenkinsci.plugins.SemanticVersioning; public class SemanticVersionColumn extends ListViewColumn { private static Logger logger = Logger.getLogger(String.valueOf(AppVersion.class));
private ColumnDisplayStrategy displayStrategy;
jenkinsci/semantic-versioning-plugin
src/main/java/org/jenkinsci/plugins/SemanticVersioning/SemanticVersionColumn.java
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/columnDisplay/AbstractColumnDisplayStrategy.java // public abstract class AbstractColumnDisplayStrategy extends ExtensionPoint implements ColumnDisplayStrategy { // public static ExtensionList<ColumnDisplayStrategy> getStrategies() { // return Jenkins.getActiveInstance().getExtensionList(ColumnDisplayStrategy.class); // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/columnDisplay/ColumnDisplayStrategy.java // public interface ColumnDisplayStrategy extends Describable<ColumnDisplayStrategy> { // String getDisplayString(Job job); // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/columnDisplay/LastSuccessfulBuildStrategy.java // @Extension // public class LastSuccessfulBuildStrategy extends AbstractColumnDisplayStrategy { // // private static Logger logger = Logger.getLogger(String.valueOf(AppVersion.class)); // // public String getDisplayString(Job job) { // String semanticVersion = null; // Run run = job.getLastSuccessfulBuild(); // if (run == null) { // logger.info("LastSuccessfulBuildStrategy::getDisplayString -> last successful build not found."); // semanticVersion = Messages.UNKNOWN_VERSION; // } else { // String filename = run.getRootDir() + "/" + Messages.SEMANTIC_VERSION_FILENAME; // logger.info("LastSuccessfulBuildStrategy::getDisplayString -> last successful build found. Filename -> " + filename); // File file = new File(filename); // if (file.exists()) { // try { // semanticVersion = FileUtils.readFileToString(file); // logger.info("LastSuccessfulBuildStrategy::getDisplayString -> read semantic version from file -> " + semanticVersion); // } catch (IOException e) { // logger.severe(e.toString()); // } // } else { // logger.info("LastSuccessfulBuildStrategy::getDisplayString -> semanticVersion file not found."); // semanticVersion = Messages.UNKNOWN_VERSION; // } // } // // return semanticVersion; // } // // @SuppressWarnings("unchecked") // public Descriptor<ColumnDisplayStrategy> getDescriptor() { // return new AbstractDisplayStrategyDescription() { // @Override // public String getDisplayName() { // return Messages.ColumnDisplayStrategies.LAST_SUCCESSFUL_BUILD_VERSION_STRATEGY; // } // }; // } // }
import hudson.views.ListViewColumnDescriptor; import jenkins.model.Jenkins; import net.sf.json.JSONObject; import org.apache.commons.lang.StringUtils; import org.jenkinsci.plugins.SemanticVersioning.columnDisplay.AbstractColumnDisplayStrategy; import org.jenkinsci.plugins.SemanticVersioning.columnDisplay.ColumnDisplayStrategy; import org.jenkinsci.plugins.SemanticVersioning.columnDisplay.LastSuccessfulBuildStrategy; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.StaplerRequest; import java.io.IOException; import java.util.logging.Logger; import hudson.Extension; import hudson.ExtensionList; import hudson.model.Descriptor; import hudson.model.Job; import hudson.util.ListBoxModel; import hudson.views.ListViewColumn;
/* * The MIT License * * Copyright (c) 2014, Steve Wagner * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.jenkinsci.plugins.SemanticVersioning; public class SemanticVersionColumn extends ListViewColumn { private static Logger logger = Logger.getLogger(String.valueOf(AppVersion.class)); private ColumnDisplayStrategy displayStrategy; @DataBoundConstructor public SemanticVersionColumn(String displayStrategyName) { try { this.displayStrategy = (ColumnDisplayStrategy) Jenkins.getActiveInstance().getExtensionList(displayStrategyName).iterator().next(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public static final Descriptor<ListViewColumn> descriptor = new SemanticVersionColumnDescriptor(); public String getDisplayStrategy() { return this.displayStrategy.getClass().getCanonicalName(); } public String getSemanticVersion(Job job) throws IOException, InterruptedException { ColumnDisplayStrategy strategy; if(job==null || job.getLastBuild()==null || job.getLastBuild().getResult()==null) { return "-"; } if(job.getLastBuild().getResult().ordinal == 0) {
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/columnDisplay/AbstractColumnDisplayStrategy.java // public abstract class AbstractColumnDisplayStrategy extends ExtensionPoint implements ColumnDisplayStrategy { // public static ExtensionList<ColumnDisplayStrategy> getStrategies() { // return Jenkins.getActiveInstance().getExtensionList(ColumnDisplayStrategy.class); // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/columnDisplay/ColumnDisplayStrategy.java // public interface ColumnDisplayStrategy extends Describable<ColumnDisplayStrategy> { // String getDisplayString(Job job); // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/columnDisplay/LastSuccessfulBuildStrategy.java // @Extension // public class LastSuccessfulBuildStrategy extends AbstractColumnDisplayStrategy { // // private static Logger logger = Logger.getLogger(String.valueOf(AppVersion.class)); // // public String getDisplayString(Job job) { // String semanticVersion = null; // Run run = job.getLastSuccessfulBuild(); // if (run == null) { // logger.info("LastSuccessfulBuildStrategy::getDisplayString -> last successful build not found."); // semanticVersion = Messages.UNKNOWN_VERSION; // } else { // String filename = run.getRootDir() + "/" + Messages.SEMANTIC_VERSION_FILENAME; // logger.info("LastSuccessfulBuildStrategy::getDisplayString -> last successful build found. Filename -> " + filename); // File file = new File(filename); // if (file.exists()) { // try { // semanticVersion = FileUtils.readFileToString(file); // logger.info("LastSuccessfulBuildStrategy::getDisplayString -> read semantic version from file -> " + semanticVersion); // } catch (IOException e) { // logger.severe(e.toString()); // } // } else { // logger.info("LastSuccessfulBuildStrategy::getDisplayString -> semanticVersion file not found."); // semanticVersion = Messages.UNKNOWN_VERSION; // } // } // // return semanticVersion; // } // // @SuppressWarnings("unchecked") // public Descriptor<ColumnDisplayStrategy> getDescriptor() { // return new AbstractDisplayStrategyDescription() { // @Override // public String getDisplayName() { // return Messages.ColumnDisplayStrategies.LAST_SUCCESSFUL_BUILD_VERSION_STRATEGY; // } // }; // } // } // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/SemanticVersionColumn.java import hudson.views.ListViewColumnDescriptor; import jenkins.model.Jenkins; import net.sf.json.JSONObject; import org.apache.commons.lang.StringUtils; import org.jenkinsci.plugins.SemanticVersioning.columnDisplay.AbstractColumnDisplayStrategy; import org.jenkinsci.plugins.SemanticVersioning.columnDisplay.ColumnDisplayStrategy; import org.jenkinsci.plugins.SemanticVersioning.columnDisplay.LastSuccessfulBuildStrategy; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.StaplerRequest; import java.io.IOException; import java.util.logging.Logger; import hudson.Extension; import hudson.ExtensionList; import hudson.model.Descriptor; import hudson.model.Job; import hudson.util.ListBoxModel; import hudson.views.ListViewColumn; /* * The MIT License * * Copyright (c) 2014, Steve Wagner * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.jenkinsci.plugins.SemanticVersioning; public class SemanticVersionColumn extends ListViewColumn { private static Logger logger = Logger.getLogger(String.valueOf(AppVersion.class)); private ColumnDisplayStrategy displayStrategy; @DataBoundConstructor public SemanticVersionColumn(String displayStrategyName) { try { this.displayStrategy = (ColumnDisplayStrategy) Jenkins.getActiveInstance().getExtensionList(displayStrategyName).iterator().next(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public static final Descriptor<ListViewColumn> descriptor = new SemanticVersionColumnDescriptor(); public String getDisplayStrategy() { return this.displayStrategy.getClass().getCanonicalName(); } public String getSemanticVersion(Job job) throws IOException, InterruptedException { ColumnDisplayStrategy strategy; if(job==null || job.getLastBuild()==null || job.getLastBuild().getResult()==null) { return "-"; } if(job.getLastBuild().getResult().ordinal == 0) {
strategy = new LastSuccessfulBuildStrategy();
jenkinsci/semantic-versioning-plugin
src/main/java/org/jenkinsci/plugins/SemanticVersioning/SemanticVersionColumn.java
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/columnDisplay/AbstractColumnDisplayStrategy.java // public abstract class AbstractColumnDisplayStrategy extends ExtensionPoint implements ColumnDisplayStrategy { // public static ExtensionList<ColumnDisplayStrategy> getStrategies() { // return Jenkins.getActiveInstance().getExtensionList(ColumnDisplayStrategy.class); // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/columnDisplay/ColumnDisplayStrategy.java // public interface ColumnDisplayStrategy extends Describable<ColumnDisplayStrategy> { // String getDisplayString(Job job); // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/columnDisplay/LastSuccessfulBuildStrategy.java // @Extension // public class LastSuccessfulBuildStrategy extends AbstractColumnDisplayStrategy { // // private static Logger logger = Logger.getLogger(String.valueOf(AppVersion.class)); // // public String getDisplayString(Job job) { // String semanticVersion = null; // Run run = job.getLastSuccessfulBuild(); // if (run == null) { // logger.info("LastSuccessfulBuildStrategy::getDisplayString -> last successful build not found."); // semanticVersion = Messages.UNKNOWN_VERSION; // } else { // String filename = run.getRootDir() + "/" + Messages.SEMANTIC_VERSION_FILENAME; // logger.info("LastSuccessfulBuildStrategy::getDisplayString -> last successful build found. Filename -> " + filename); // File file = new File(filename); // if (file.exists()) { // try { // semanticVersion = FileUtils.readFileToString(file); // logger.info("LastSuccessfulBuildStrategy::getDisplayString -> read semantic version from file -> " + semanticVersion); // } catch (IOException e) { // logger.severe(e.toString()); // } // } else { // logger.info("LastSuccessfulBuildStrategy::getDisplayString -> semanticVersion file not found."); // semanticVersion = Messages.UNKNOWN_VERSION; // } // } // // return semanticVersion; // } // // @SuppressWarnings("unchecked") // public Descriptor<ColumnDisplayStrategy> getDescriptor() { // return new AbstractDisplayStrategyDescription() { // @Override // public String getDisplayName() { // return Messages.ColumnDisplayStrategies.LAST_SUCCESSFUL_BUILD_VERSION_STRATEGY; // } // }; // } // }
import hudson.views.ListViewColumnDescriptor; import jenkins.model.Jenkins; import net.sf.json.JSONObject; import org.apache.commons.lang.StringUtils; import org.jenkinsci.plugins.SemanticVersioning.columnDisplay.AbstractColumnDisplayStrategy; import org.jenkinsci.plugins.SemanticVersioning.columnDisplay.ColumnDisplayStrategy; import org.jenkinsci.plugins.SemanticVersioning.columnDisplay.LastSuccessfulBuildStrategy; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.StaplerRequest; import java.io.IOException; import java.util.logging.Logger; import hudson.Extension; import hudson.ExtensionList; import hudson.model.Descriptor; import hudson.model.Job; import hudson.util.ListBoxModel; import hudson.views.ListViewColumn;
public String getSemanticVersion(Job job) throws IOException, InterruptedException { ColumnDisplayStrategy strategy; if(job==null || job.getLastBuild()==null || job.getLastBuild().getResult()==null) { return "-"; } if(job.getLastBuild().getResult().ordinal == 0) { strategy = new LastSuccessfulBuildStrategy(); } else { strategy = this.displayStrategy; } return strategy.getDisplayString(job); } @Extension(ordinal = 1.5) public static class SemanticVersionColumnDescriptor extends ListViewColumnDescriptor { @Override public boolean shownByDefault() { return false; } @Override public ListViewColumn newInstance(StaplerRequest req, JSONObject formData) throws FormException { String strategy = formData == null ? null : formData.optString("displayStrategy"); return new SemanticVersionColumn(StringUtils.defaultIfBlank(strategy, LastSuccessfulBuildStrategy.class.getCanonicalName())); } public ListBoxModel doFillDisplayStrategyItems() { ListBoxModel columnDisplayStrategies = new ListBoxModel();
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/columnDisplay/AbstractColumnDisplayStrategy.java // public abstract class AbstractColumnDisplayStrategy extends ExtensionPoint implements ColumnDisplayStrategy { // public static ExtensionList<ColumnDisplayStrategy> getStrategies() { // return Jenkins.getActiveInstance().getExtensionList(ColumnDisplayStrategy.class); // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/columnDisplay/ColumnDisplayStrategy.java // public interface ColumnDisplayStrategy extends Describable<ColumnDisplayStrategy> { // String getDisplayString(Job job); // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/columnDisplay/LastSuccessfulBuildStrategy.java // @Extension // public class LastSuccessfulBuildStrategy extends AbstractColumnDisplayStrategy { // // private static Logger logger = Logger.getLogger(String.valueOf(AppVersion.class)); // // public String getDisplayString(Job job) { // String semanticVersion = null; // Run run = job.getLastSuccessfulBuild(); // if (run == null) { // logger.info("LastSuccessfulBuildStrategy::getDisplayString -> last successful build not found."); // semanticVersion = Messages.UNKNOWN_VERSION; // } else { // String filename = run.getRootDir() + "/" + Messages.SEMANTIC_VERSION_FILENAME; // logger.info("LastSuccessfulBuildStrategy::getDisplayString -> last successful build found. Filename -> " + filename); // File file = new File(filename); // if (file.exists()) { // try { // semanticVersion = FileUtils.readFileToString(file); // logger.info("LastSuccessfulBuildStrategy::getDisplayString -> read semantic version from file -> " + semanticVersion); // } catch (IOException e) { // logger.severe(e.toString()); // } // } else { // logger.info("LastSuccessfulBuildStrategy::getDisplayString -> semanticVersion file not found."); // semanticVersion = Messages.UNKNOWN_VERSION; // } // } // // return semanticVersion; // } // // @SuppressWarnings("unchecked") // public Descriptor<ColumnDisplayStrategy> getDescriptor() { // return new AbstractDisplayStrategyDescription() { // @Override // public String getDisplayName() { // return Messages.ColumnDisplayStrategies.LAST_SUCCESSFUL_BUILD_VERSION_STRATEGY; // } // }; // } // } // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/SemanticVersionColumn.java import hudson.views.ListViewColumnDescriptor; import jenkins.model.Jenkins; import net.sf.json.JSONObject; import org.apache.commons.lang.StringUtils; import org.jenkinsci.plugins.SemanticVersioning.columnDisplay.AbstractColumnDisplayStrategy; import org.jenkinsci.plugins.SemanticVersioning.columnDisplay.ColumnDisplayStrategy; import org.jenkinsci.plugins.SemanticVersioning.columnDisplay.LastSuccessfulBuildStrategy; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.StaplerRequest; import java.io.IOException; import java.util.logging.Logger; import hudson.Extension; import hudson.ExtensionList; import hudson.model.Descriptor; import hudson.model.Job; import hudson.util.ListBoxModel; import hudson.views.ListViewColumn; public String getSemanticVersion(Job job) throws IOException, InterruptedException { ColumnDisplayStrategy strategy; if(job==null || job.getLastBuild()==null || job.getLastBuild().getResult()==null) { return "-"; } if(job.getLastBuild().getResult().ordinal == 0) { strategy = new LastSuccessfulBuildStrategy(); } else { strategy = this.displayStrategy; } return strategy.getDisplayString(job); } @Extension(ordinal = 1.5) public static class SemanticVersionColumnDescriptor extends ListViewColumnDescriptor { @Override public boolean shownByDefault() { return false; } @Override public ListViewColumn newInstance(StaplerRequest req, JSONObject formData) throws FormException { String strategy = formData == null ? null : formData.optString("displayStrategy"); return new SemanticVersionColumn(StringUtils.defaultIfBlank(strategy, LastSuccessfulBuildStrategy.class.getCanonicalName())); } public ListBoxModel doFillDisplayStrategyItems() { ListBoxModel columnDisplayStrategies = new ListBoxModel();
ExtensionList<ColumnDisplayStrategy> extensionList = AbstractColumnDisplayStrategy.getStrategies();
jenkinsci/semantic-versioning-plugin
src/main/java/org/jenkinsci/plugins/SemanticVersioning/columnDisplay/LastSuccessfulBuildStrategy.java
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/AppVersion.java // public class AppVersion implements Serializable { // private static final String SNAPSHOT = "SNAPSHOT"; // private final int major; // private final int minor; // private final String original; // // private int build; // private final boolean isSnapshot; // public static final AppVersion EmptyVersion = new AppVersion(0, 0, 0, false, ""); // // public static AppVersion parse(String versionString) { // String[] parts = versionString.split("[\\.-]"); // // int major = Integer.parseInt(parts[0]); // int minor = Integer.parseInt(parts[1]); // // int build = -1; // boolean isSnapshot = false; // // if (parts.length == 3) { // if (parts[2].equals(SNAPSHOT)) { // isSnapshot = true; // } else { // build = Integer.parseInt(parts[2]); // } // } else if (parts.length == 4) { // build = Integer.parseInt(parts[2]); // isSnapshot = parts[3].equals(SNAPSHOT); // } // // return new AppVersion(major, minor, build, isSnapshot, versionString); // } // // private AppVersion(int major, int minor, int build, boolean isSnapshot, String original) { // this.major = major; // this.minor = minor; // // this.isSnapshot = isSnapshot; // this.build = build; // this.original = original; // } // // public int getMajor() { // return major; // } // // public int getMinor() { // return minor; // } // // public String getOriginal() { // return this.original; // } // // public boolean isSnapshot() { // return isSnapshot; // } // // public void setBuild(int build) { // this.build = build; // } // // public int getBuild() { // return build; // } // // public String toJsonString() { // return String.format( // "{ \"major\": %d, \"minor\": %d, \"build\": %d, \"isSnapshot\": %b, \"originalString\": \"%s\" }", // this.major, // this.minor, // this.build, // this.isSnapshot, // this.original); // } // // @Override // public String toString() { // String version = String.format("%s.%s", major, minor); // if(build > -1) { // version += "." + build; // } // if (isSnapshot) { // version += "-" + SNAPSHOT; // } // return version; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/Messages.java // public class Messages { // public static final String SEMANTIC_VERSION_FILENAME = ".semanticVersion"; // public static final String DISPLAY_NAME = "Determine Semantic Version"; // public static final String SEMANTIC_VERSION_COLUMN_DISPLAY_NAME = "Semantic Version"; // public static final String UNKNOWN_VERSION = "Unknown"; // // public static class Parsers { // public static final String SBT_BUILD_SBT_PARSER = "SBT build.sbt parser"; // public static final String MAVEN_POM_PARSER = "Maven Pom Parser"; // public static final String SBT_BUILD_SCALA_PARSER = "SBT Build.scala Parser"; // public static final String BOWER_JSON_PARSER = "Bower bower.json Parser"; // public static final String NPM_JSON_PARSER = "NPM package.json Parser"; // public static final String COMPOSER_JSON_PARSER = "Composer composer.json Parser"; // } // // public static class ColumnDisplayStrategies { // public static final String LAST_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Successful Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_BUILD_VERSION_STRATEGY = "Show Last Successful Semantic Version"; // public static final String NA_STRATEGY = "Show 'N/A'"; // } // // public static class NamingStrategies { // public static final String NOOP_NAMING = "none"; // public static final String MAVEN_RELEASE_DEVELOPMENT = "Maven, release and development version"; // public static final String UNTOUCHED = "As found"; // public static final String UNTOUCHED_SNAPSHOT = "As found (-SNAPSHOT)"; // } // }
import org.jenkinsci.plugins.SemanticVersioning.Messages; import java.io.File; import java.io.IOException; import java.util.logging.Logger; import hudson.Extension; import hudson.model.Descriptor; import hudson.model.Job; import hudson.model.Run; import org.apache.commons.io.FileUtils; import org.jenkinsci.plugins.SemanticVersioning.AppVersion;
/* * The MIT License * * Copyright (c) 2014, Steve Wagner * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.jenkinsci.plugins.SemanticVersioning.columnDisplay; @Extension public class LastSuccessfulBuildStrategy extends AbstractColumnDisplayStrategy {
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/AppVersion.java // public class AppVersion implements Serializable { // private static final String SNAPSHOT = "SNAPSHOT"; // private final int major; // private final int minor; // private final String original; // // private int build; // private final boolean isSnapshot; // public static final AppVersion EmptyVersion = new AppVersion(0, 0, 0, false, ""); // // public static AppVersion parse(String versionString) { // String[] parts = versionString.split("[\\.-]"); // // int major = Integer.parseInt(parts[0]); // int minor = Integer.parseInt(parts[1]); // // int build = -1; // boolean isSnapshot = false; // // if (parts.length == 3) { // if (parts[2].equals(SNAPSHOT)) { // isSnapshot = true; // } else { // build = Integer.parseInt(parts[2]); // } // } else if (parts.length == 4) { // build = Integer.parseInt(parts[2]); // isSnapshot = parts[3].equals(SNAPSHOT); // } // // return new AppVersion(major, minor, build, isSnapshot, versionString); // } // // private AppVersion(int major, int minor, int build, boolean isSnapshot, String original) { // this.major = major; // this.minor = minor; // // this.isSnapshot = isSnapshot; // this.build = build; // this.original = original; // } // // public int getMajor() { // return major; // } // // public int getMinor() { // return minor; // } // // public String getOriginal() { // return this.original; // } // // public boolean isSnapshot() { // return isSnapshot; // } // // public void setBuild(int build) { // this.build = build; // } // // public int getBuild() { // return build; // } // // public String toJsonString() { // return String.format( // "{ \"major\": %d, \"minor\": %d, \"build\": %d, \"isSnapshot\": %b, \"originalString\": \"%s\" }", // this.major, // this.minor, // this.build, // this.isSnapshot, // this.original); // } // // @Override // public String toString() { // String version = String.format("%s.%s", major, minor); // if(build > -1) { // version += "." + build; // } // if (isSnapshot) { // version += "-" + SNAPSHOT; // } // return version; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/Messages.java // public class Messages { // public static final String SEMANTIC_VERSION_FILENAME = ".semanticVersion"; // public static final String DISPLAY_NAME = "Determine Semantic Version"; // public static final String SEMANTIC_VERSION_COLUMN_DISPLAY_NAME = "Semantic Version"; // public static final String UNKNOWN_VERSION = "Unknown"; // // public static class Parsers { // public static final String SBT_BUILD_SBT_PARSER = "SBT build.sbt parser"; // public static final String MAVEN_POM_PARSER = "Maven Pom Parser"; // public static final String SBT_BUILD_SCALA_PARSER = "SBT Build.scala Parser"; // public static final String BOWER_JSON_PARSER = "Bower bower.json Parser"; // public static final String NPM_JSON_PARSER = "NPM package.json Parser"; // public static final String COMPOSER_JSON_PARSER = "Composer composer.json Parser"; // } // // public static class ColumnDisplayStrategies { // public static final String LAST_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Successful Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_BUILD_VERSION_STRATEGY = "Show Last Successful Semantic Version"; // public static final String NA_STRATEGY = "Show 'N/A'"; // } // // public static class NamingStrategies { // public static final String NOOP_NAMING = "none"; // public static final String MAVEN_RELEASE_DEVELOPMENT = "Maven, release and development version"; // public static final String UNTOUCHED = "As found"; // public static final String UNTOUCHED_SNAPSHOT = "As found (-SNAPSHOT)"; // } // } // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/columnDisplay/LastSuccessfulBuildStrategy.java import org.jenkinsci.plugins.SemanticVersioning.Messages; import java.io.File; import java.io.IOException; import java.util.logging.Logger; import hudson.Extension; import hudson.model.Descriptor; import hudson.model.Job; import hudson.model.Run; import org.apache.commons.io.FileUtils; import org.jenkinsci.plugins.SemanticVersioning.AppVersion; /* * The MIT License * * Copyright (c) 2014, Steve Wagner * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.jenkinsci.plugins.SemanticVersioning.columnDisplay; @Extension public class LastSuccessfulBuildStrategy extends AbstractColumnDisplayStrategy {
private static Logger logger = Logger.getLogger(String.valueOf(AppVersion.class));
jenkinsci/semantic-versioning-plugin
src/main/java/org/jenkinsci/plugins/SemanticVersioning/columnDisplay/LastSuccessfulBuildStrategy.java
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/AppVersion.java // public class AppVersion implements Serializable { // private static final String SNAPSHOT = "SNAPSHOT"; // private final int major; // private final int minor; // private final String original; // // private int build; // private final boolean isSnapshot; // public static final AppVersion EmptyVersion = new AppVersion(0, 0, 0, false, ""); // // public static AppVersion parse(String versionString) { // String[] parts = versionString.split("[\\.-]"); // // int major = Integer.parseInt(parts[0]); // int minor = Integer.parseInt(parts[1]); // // int build = -1; // boolean isSnapshot = false; // // if (parts.length == 3) { // if (parts[2].equals(SNAPSHOT)) { // isSnapshot = true; // } else { // build = Integer.parseInt(parts[2]); // } // } else if (parts.length == 4) { // build = Integer.parseInt(parts[2]); // isSnapshot = parts[3].equals(SNAPSHOT); // } // // return new AppVersion(major, minor, build, isSnapshot, versionString); // } // // private AppVersion(int major, int minor, int build, boolean isSnapshot, String original) { // this.major = major; // this.minor = minor; // // this.isSnapshot = isSnapshot; // this.build = build; // this.original = original; // } // // public int getMajor() { // return major; // } // // public int getMinor() { // return minor; // } // // public String getOriginal() { // return this.original; // } // // public boolean isSnapshot() { // return isSnapshot; // } // // public void setBuild(int build) { // this.build = build; // } // // public int getBuild() { // return build; // } // // public String toJsonString() { // return String.format( // "{ \"major\": %d, \"minor\": %d, \"build\": %d, \"isSnapshot\": %b, \"originalString\": \"%s\" }", // this.major, // this.minor, // this.build, // this.isSnapshot, // this.original); // } // // @Override // public String toString() { // String version = String.format("%s.%s", major, minor); // if(build > -1) { // version += "." + build; // } // if (isSnapshot) { // version += "-" + SNAPSHOT; // } // return version; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/Messages.java // public class Messages { // public static final String SEMANTIC_VERSION_FILENAME = ".semanticVersion"; // public static final String DISPLAY_NAME = "Determine Semantic Version"; // public static final String SEMANTIC_VERSION_COLUMN_DISPLAY_NAME = "Semantic Version"; // public static final String UNKNOWN_VERSION = "Unknown"; // // public static class Parsers { // public static final String SBT_BUILD_SBT_PARSER = "SBT build.sbt parser"; // public static final String MAVEN_POM_PARSER = "Maven Pom Parser"; // public static final String SBT_BUILD_SCALA_PARSER = "SBT Build.scala Parser"; // public static final String BOWER_JSON_PARSER = "Bower bower.json Parser"; // public static final String NPM_JSON_PARSER = "NPM package.json Parser"; // public static final String COMPOSER_JSON_PARSER = "Composer composer.json Parser"; // } // // public static class ColumnDisplayStrategies { // public static final String LAST_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Successful Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_BUILD_VERSION_STRATEGY = "Show Last Successful Semantic Version"; // public static final String NA_STRATEGY = "Show 'N/A'"; // } // // public static class NamingStrategies { // public static final String NOOP_NAMING = "none"; // public static final String MAVEN_RELEASE_DEVELOPMENT = "Maven, release and development version"; // public static final String UNTOUCHED = "As found"; // public static final String UNTOUCHED_SNAPSHOT = "As found (-SNAPSHOT)"; // } // }
import org.jenkinsci.plugins.SemanticVersioning.Messages; import java.io.File; import java.io.IOException; import java.util.logging.Logger; import hudson.Extension; import hudson.model.Descriptor; import hudson.model.Job; import hudson.model.Run; import org.apache.commons.io.FileUtils; import org.jenkinsci.plugins.SemanticVersioning.AppVersion;
/* * The MIT License * * Copyright (c) 2014, Steve Wagner * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.jenkinsci.plugins.SemanticVersioning.columnDisplay; @Extension public class LastSuccessfulBuildStrategy extends AbstractColumnDisplayStrategy { private static Logger logger = Logger.getLogger(String.valueOf(AppVersion.class)); public String getDisplayString(Job job) { String semanticVersion = null; Run run = job.getLastSuccessfulBuild(); if (run == null) { logger.info("LastSuccessfulBuildStrategy::getDisplayString -> last successful build not found.");
// Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/AppVersion.java // public class AppVersion implements Serializable { // private static final String SNAPSHOT = "SNAPSHOT"; // private final int major; // private final int minor; // private final String original; // // private int build; // private final boolean isSnapshot; // public static final AppVersion EmptyVersion = new AppVersion(0, 0, 0, false, ""); // // public static AppVersion parse(String versionString) { // String[] parts = versionString.split("[\\.-]"); // // int major = Integer.parseInt(parts[0]); // int minor = Integer.parseInt(parts[1]); // // int build = -1; // boolean isSnapshot = false; // // if (parts.length == 3) { // if (parts[2].equals(SNAPSHOT)) { // isSnapshot = true; // } else { // build = Integer.parseInt(parts[2]); // } // } else if (parts.length == 4) { // build = Integer.parseInt(parts[2]); // isSnapshot = parts[3].equals(SNAPSHOT); // } // // return new AppVersion(major, minor, build, isSnapshot, versionString); // } // // private AppVersion(int major, int minor, int build, boolean isSnapshot, String original) { // this.major = major; // this.minor = minor; // // this.isSnapshot = isSnapshot; // this.build = build; // this.original = original; // } // // public int getMajor() { // return major; // } // // public int getMinor() { // return minor; // } // // public String getOriginal() { // return this.original; // } // // public boolean isSnapshot() { // return isSnapshot; // } // // public void setBuild(int build) { // this.build = build; // } // // public int getBuild() { // return build; // } // // public String toJsonString() { // return String.format( // "{ \"major\": %d, \"minor\": %d, \"build\": %d, \"isSnapshot\": %b, \"originalString\": \"%s\" }", // this.major, // this.minor, // this.build, // this.isSnapshot, // this.original); // } // // @Override // public String toString() { // String version = String.format("%s.%s", major, minor); // if(build > -1) { // version += "." + build; // } // if (isSnapshot) { // version += "-" + SNAPSHOT; // } // return version; // } // } // // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/Messages.java // public class Messages { // public static final String SEMANTIC_VERSION_FILENAME = ".semanticVersion"; // public static final String DISPLAY_NAME = "Determine Semantic Version"; // public static final String SEMANTIC_VERSION_COLUMN_DISPLAY_NAME = "Semantic Version"; // public static final String UNKNOWN_VERSION = "Unknown"; // // public static class Parsers { // public static final String SBT_BUILD_SBT_PARSER = "SBT build.sbt parser"; // public static final String MAVEN_POM_PARSER = "Maven Pom Parser"; // public static final String SBT_BUILD_SCALA_PARSER = "SBT Build.scala Parser"; // public static final String BOWER_JSON_PARSER = "Bower bower.json Parser"; // public static final String NPM_JSON_PARSER = "NPM package.json Parser"; // public static final String COMPOSER_JSON_PARSER = "Composer composer.json Parser"; // } // // public static class ColumnDisplayStrategies { // public static final String LAST_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_JENKINS_BUILD_NUMBER_STRATEGY = "Show Last Successful Jenkins Build Number"; // public static final String LAST_SUCCESSFUL_BUILD_VERSION_STRATEGY = "Show Last Successful Semantic Version"; // public static final String NA_STRATEGY = "Show 'N/A'"; // } // // public static class NamingStrategies { // public static final String NOOP_NAMING = "none"; // public static final String MAVEN_RELEASE_DEVELOPMENT = "Maven, release and development version"; // public static final String UNTOUCHED = "As found"; // public static final String UNTOUCHED_SNAPSHOT = "As found (-SNAPSHOT)"; // } // } // Path: src/main/java/org/jenkinsci/plugins/SemanticVersioning/columnDisplay/LastSuccessfulBuildStrategy.java import org.jenkinsci.plugins.SemanticVersioning.Messages; import java.io.File; import java.io.IOException; import java.util.logging.Logger; import hudson.Extension; import hudson.model.Descriptor; import hudson.model.Job; import hudson.model.Run; import org.apache.commons.io.FileUtils; import org.jenkinsci.plugins.SemanticVersioning.AppVersion; /* * The MIT License * * Copyright (c) 2014, Steve Wagner * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.jenkinsci.plugins.SemanticVersioning.columnDisplay; @Extension public class LastSuccessfulBuildStrategy extends AbstractColumnDisplayStrategy { private static Logger logger = Logger.getLogger(String.valueOf(AppVersion.class)); public String getDisplayString(Job job) { String semanticVersion = null; Run run = job.getLastSuccessfulBuild(); if (run == null) { logger.info("LastSuccessfulBuildStrategy::getDisplayString -> last successful build not found.");
semanticVersion = Messages.UNKNOWN_VERSION;
PedroCarrillo/Expense-Tracker-App
ExpenseTracker/app/src/main/java/com/pedrocarrillo/expensetracker/adapters/CategoriesAdapter.java
// Path: ExpenseTracker/app/src/main/java/com/pedrocarrillo/expensetracker/custom/BaseViewHolder.java // public abstract class BaseViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener { // // protected RecyclerClickListener onRecyclerClickListener; // // public interface RecyclerClickListener { // void onClick(RecyclerView.ViewHolder vh, int position); // void onLongClick(RecyclerView.ViewHolder vh, int position); // } // // public BaseViewHolder(View v, RecyclerClickListener onRecyclerClickListener ) { // super(v); // this.onRecyclerClickListener = onRecyclerClickListener; // v.setOnClickListener(this); // v.setOnLongClickListener(this); // } // // @Override // public void onClick(View v) { // if (onRecyclerClickListener != null) onRecyclerClickListener.onClick(this, getAdapterPosition()); // } // // @Override // public boolean onLongClick(View v) { // if (onRecyclerClickListener != null) onRecyclerClickListener.onLongClick(this, getAdapterPosition()); // return true; // } // // } // // Path: ExpenseTracker/app/src/main/java/com/pedrocarrillo/expensetracker/entities/Category.java // public class Category extends RealmObject { // // @PrimaryKey // private String id; // // private String name; // private int type; // private RealmList<Expense> expenses; // // public Category() { // } // // public Category(String name, @IExpensesType int type) { // this.name = name; // this.type = type; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public int getType() { // return type; // } // // public void setType(int type) { // this.type = type; // } // // public RealmList<Expense> getExpenses() { // return expenses; // } // // public void setExpenses(RealmList<Expense> expenses) { // this.expenses = expenses; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public static List<Category> getCategoriesIncome() { // return getCategoriesForType(IExpensesType.MODE_INCOME); // } // // public static List<Category> getCategoriesExpense() { // return getCategoriesForType(IExpensesType.MODE_EXPENSES); // } // // public static List<Category> getCategoriesForType(@IExpensesType int type){ // return RealmManager.getInstance().getRealmInstance().where(Category.class) // .equalTo("type", type) // .findAll(); // } // // }
import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.TextView; import com.pedrocarrillo.expensetracker.ExpenseTrackerApp; import com.pedrocarrillo.expensetracker.R; import com.pedrocarrillo.expensetracker.custom.BaseViewHolder; import com.pedrocarrillo.expensetracker.entities.Category; import java.util.List;
package com.pedrocarrillo.expensetracker.adapters; /** * Created by pcarrillo on 17/09/2015. */ public class CategoriesAdapter extends BaseRecyclerViewAdapter<CategoriesAdapter.CategoryViewHolder> { private List<Category> mCategoryList; private int lastPosition = -1;
// Path: ExpenseTracker/app/src/main/java/com/pedrocarrillo/expensetracker/custom/BaseViewHolder.java // public abstract class BaseViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener { // // protected RecyclerClickListener onRecyclerClickListener; // // public interface RecyclerClickListener { // void onClick(RecyclerView.ViewHolder vh, int position); // void onLongClick(RecyclerView.ViewHolder vh, int position); // } // // public BaseViewHolder(View v, RecyclerClickListener onRecyclerClickListener ) { // super(v); // this.onRecyclerClickListener = onRecyclerClickListener; // v.setOnClickListener(this); // v.setOnLongClickListener(this); // } // // @Override // public void onClick(View v) { // if (onRecyclerClickListener != null) onRecyclerClickListener.onClick(this, getAdapterPosition()); // } // // @Override // public boolean onLongClick(View v) { // if (onRecyclerClickListener != null) onRecyclerClickListener.onLongClick(this, getAdapterPosition()); // return true; // } // // } // // Path: ExpenseTracker/app/src/main/java/com/pedrocarrillo/expensetracker/entities/Category.java // public class Category extends RealmObject { // // @PrimaryKey // private String id; // // private String name; // private int type; // private RealmList<Expense> expenses; // // public Category() { // } // // public Category(String name, @IExpensesType int type) { // this.name = name; // this.type = type; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public int getType() { // return type; // } // // public void setType(int type) { // this.type = type; // } // // public RealmList<Expense> getExpenses() { // return expenses; // } // // public void setExpenses(RealmList<Expense> expenses) { // this.expenses = expenses; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public static List<Category> getCategoriesIncome() { // return getCategoriesForType(IExpensesType.MODE_INCOME); // } // // public static List<Category> getCategoriesExpense() { // return getCategoriesForType(IExpensesType.MODE_EXPENSES); // } // // public static List<Category> getCategoriesForType(@IExpensesType int type){ // return RealmManager.getInstance().getRealmInstance().where(Category.class) // .equalTo("type", type) // .findAll(); // } // // } // Path: ExpenseTracker/app/src/main/java/com/pedrocarrillo/expensetracker/adapters/CategoriesAdapter.java import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.TextView; import com.pedrocarrillo.expensetracker.ExpenseTrackerApp; import com.pedrocarrillo.expensetracker.R; import com.pedrocarrillo.expensetracker.custom.BaseViewHolder; import com.pedrocarrillo.expensetracker.entities.Category; import java.util.List; package com.pedrocarrillo.expensetracker.adapters; /** * Created by pcarrillo on 17/09/2015. */ public class CategoriesAdapter extends BaseRecyclerViewAdapter<CategoriesAdapter.CategoryViewHolder> { private List<Category> mCategoryList; private int lastPosition = -1;
private BaseViewHolder.RecyclerClickListener onRecyclerClickListener;
PedroCarrillo/Expense-Tracker-App
ExpenseTracker/app/src/main/java/com/pedrocarrillo/expensetracker/receivers/AlarmsSystemBooted.java
// Path: ExpenseTracker/app/src/main/java/com/pedrocarrillo/expensetracker/entities/Reminder.java // public class Reminder extends RealmObject { // // @PrimaryKey // private String id; // // private String name; // private boolean state; // private int day; // private Date date; // private Date createdAt; // // public Reminder() {} // // public Reminder(String name, int day, boolean state, Date date) { // this.name = name; // this.day = day; // this.state = state; // this.date = date; // this.createdAt = new Date(); // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public boolean isState() { // return state; // } // // public void setState(boolean state) { // this.state = state; // } // // public Date getDate() { // return date; // } // // public void setDate(Date date) { // this.date = date; // } // // public int getDay() { // return day; // } // // public void setDay(int day) { // this.day = day; // } // // public Date getCreatedAt() { // return createdAt; // } // // public void setCreatedAt(Date createdAt) { // this.createdAt = createdAt; // } // // public static List<Reminder> getReminders() { // return RealmManager.getInstance().getRealmInstance().where(Reminder.class).findAll(); // } // // public static void saveNewReminder(String name, int daySelected, boolean state, Date timeSelected) { // Reminder reminder = new Reminder(name, daySelected, true, timeSelected); // RealmManager.getInstance().save(reminder, Reminder.class); // setReminder(reminder); // } // // public static void setReminder(Reminder reminder) { // Calendar alarmCalendar = Calendar.getInstance(); // Calendar reminderDate = Calendar.getInstance(); // reminderDate.setTime(reminder.getDate()); // if (reminder.getDay() <= alarmCalendar.get(Calendar.DAY_OF_MONTH) || !DateUtils.isToday(reminder.getCreatedAt())) { // alarmCalendar.setTime(DateUtils.getLastDateOfCurrentMonth()); // } // alarmCalendar.set(Calendar.DATE, reminder.getDay()); // alarmCalendar.set(Calendar.HOUR_OF_DAY, reminderDate.get(Calendar.HOUR_OF_DAY)); // alarmCalendar.set(Calendar.MINUTE, reminderDate.get(Calendar.MINUTE)); // // AlarmManager alarmMgr = (AlarmManager) ExpenseTrackerApp.getContext().getSystemService(Context.ALARM_SERVICE); // Intent intent = new Intent(ExpenseTrackerApp.getContext(), AlarmReceiver.class); // intent.putExtra(NewReminderFragment.REMINDER_ID_KEY, reminder.getId()); // // PendingIntent alarmIntent = PendingIntent.getBroadcast(ExpenseTrackerApp.getContext(), (int) reminder.getCreatedAt().getTime(), intent, 0); // alarmMgr.set(AlarmManager.RTC_WAKEUP, alarmCalendar.getTimeInMillis(), alarmIntent); // // } // // public static void cancelReminder(Reminder reminder) { // AlarmManager alarmMgr = (AlarmManager) ExpenseTrackerApp.getContext().getSystemService(Context.ALARM_SERVICE); // Intent intent = new Intent(ExpenseTrackerApp.getContext(), AlarmReceiver.class); // intent.putExtra(NewReminderFragment.REMINDER_ID_KEY, reminder.getId()); // PendingIntent alarmIntent = PendingIntent.getBroadcast(ExpenseTrackerApp.getContext(), (int) reminder.getCreatedAt().getTime(), intent, 0); // alarmMgr.cancel(alarmIntent); // } // // public static void updateReminder(Reminder reminder, boolean checked) { // Reminder reminderToUpdate = new Reminder(reminder.getName(), reminder.getDay(), checked, reminder.getDate()); // reminderToUpdate.setCreatedAt(reminder.getCreatedAt()); // reminderToUpdate.setId(reminder.getId()); // RealmManager.getInstance().update(reminderToUpdate); // if (checked) { // setReminder(reminder); // } else { // cancelReminder(reminder); // } // } // // public static void eraseReminder(Reminder reminder) { // if (reminder.isState()) { // cancelReminder(reminder); // } // RealmManager.getInstance().delete(reminder); // } // // public static void eraseReminders(List<Reminder> reminderList) { // for (Reminder reminder : reminderList) { // if (reminder.isState()) { // cancelReminder(reminder); // } // } // RealmManager.getInstance().delete(reminderList); // } // }
import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import com.pedrocarrillo.expensetracker.entities.Reminder;
package com.pedrocarrillo.expensetracker.receivers; /** * Created by Pedro on 9/27/2015. */ public class AlarmsSystemBooted extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
// Path: ExpenseTracker/app/src/main/java/com/pedrocarrillo/expensetracker/entities/Reminder.java // public class Reminder extends RealmObject { // // @PrimaryKey // private String id; // // private String name; // private boolean state; // private int day; // private Date date; // private Date createdAt; // // public Reminder() {} // // public Reminder(String name, int day, boolean state, Date date) { // this.name = name; // this.day = day; // this.state = state; // this.date = date; // this.createdAt = new Date(); // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public boolean isState() { // return state; // } // // public void setState(boolean state) { // this.state = state; // } // // public Date getDate() { // return date; // } // // public void setDate(Date date) { // this.date = date; // } // // public int getDay() { // return day; // } // // public void setDay(int day) { // this.day = day; // } // // public Date getCreatedAt() { // return createdAt; // } // // public void setCreatedAt(Date createdAt) { // this.createdAt = createdAt; // } // // public static List<Reminder> getReminders() { // return RealmManager.getInstance().getRealmInstance().where(Reminder.class).findAll(); // } // // public static void saveNewReminder(String name, int daySelected, boolean state, Date timeSelected) { // Reminder reminder = new Reminder(name, daySelected, true, timeSelected); // RealmManager.getInstance().save(reminder, Reminder.class); // setReminder(reminder); // } // // public static void setReminder(Reminder reminder) { // Calendar alarmCalendar = Calendar.getInstance(); // Calendar reminderDate = Calendar.getInstance(); // reminderDate.setTime(reminder.getDate()); // if (reminder.getDay() <= alarmCalendar.get(Calendar.DAY_OF_MONTH) || !DateUtils.isToday(reminder.getCreatedAt())) { // alarmCalendar.setTime(DateUtils.getLastDateOfCurrentMonth()); // } // alarmCalendar.set(Calendar.DATE, reminder.getDay()); // alarmCalendar.set(Calendar.HOUR_OF_DAY, reminderDate.get(Calendar.HOUR_OF_DAY)); // alarmCalendar.set(Calendar.MINUTE, reminderDate.get(Calendar.MINUTE)); // // AlarmManager alarmMgr = (AlarmManager) ExpenseTrackerApp.getContext().getSystemService(Context.ALARM_SERVICE); // Intent intent = new Intent(ExpenseTrackerApp.getContext(), AlarmReceiver.class); // intent.putExtra(NewReminderFragment.REMINDER_ID_KEY, reminder.getId()); // // PendingIntent alarmIntent = PendingIntent.getBroadcast(ExpenseTrackerApp.getContext(), (int) reminder.getCreatedAt().getTime(), intent, 0); // alarmMgr.set(AlarmManager.RTC_WAKEUP, alarmCalendar.getTimeInMillis(), alarmIntent); // // } // // public static void cancelReminder(Reminder reminder) { // AlarmManager alarmMgr = (AlarmManager) ExpenseTrackerApp.getContext().getSystemService(Context.ALARM_SERVICE); // Intent intent = new Intent(ExpenseTrackerApp.getContext(), AlarmReceiver.class); // intent.putExtra(NewReminderFragment.REMINDER_ID_KEY, reminder.getId()); // PendingIntent alarmIntent = PendingIntent.getBroadcast(ExpenseTrackerApp.getContext(), (int) reminder.getCreatedAt().getTime(), intent, 0); // alarmMgr.cancel(alarmIntent); // } // // public static void updateReminder(Reminder reminder, boolean checked) { // Reminder reminderToUpdate = new Reminder(reminder.getName(), reminder.getDay(), checked, reminder.getDate()); // reminderToUpdate.setCreatedAt(reminder.getCreatedAt()); // reminderToUpdate.setId(reminder.getId()); // RealmManager.getInstance().update(reminderToUpdate); // if (checked) { // setReminder(reminder); // } else { // cancelReminder(reminder); // } // } // // public static void eraseReminder(Reminder reminder) { // if (reminder.isState()) { // cancelReminder(reminder); // } // RealmManager.getInstance().delete(reminder); // } // // public static void eraseReminders(List<Reminder> reminderList) { // for (Reminder reminder : reminderList) { // if (reminder.isState()) { // cancelReminder(reminder); // } // } // RealmManager.getInstance().delete(reminderList); // } // } // Path: ExpenseTracker/app/src/main/java/com/pedrocarrillo/expensetracker/receivers/AlarmsSystemBooted.java import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import com.pedrocarrillo.expensetracker.entities.Reminder; package com.pedrocarrillo.expensetracker.receivers; /** * Created by Pedro on 9/27/2015. */ public class AlarmsSystemBooted extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
for (Reminder reminder : Reminder.getReminders()) {
PedroCarrillo/Expense-Tracker-App
ExpenseTracker/app/src/main/java/com/pedrocarrillo/expensetracker/adapters/WelcomePagerAdapter.java
// Path: ExpenseTracker/app/src/main/java/com/pedrocarrillo/expensetracker/ui/Login/WelcomePage.java // public class WelcomePage extends Fragment { // // final static String LAYOUT_ID = "layoutid"; // // public static WelcomePage newInstance(int layoutId) { // WelcomePage pane = new WelcomePage(); // Bundle args = new Bundle(); // args.putInt(LAYOUT_ID, layoutId); // pane.setArguments(args); // return pane; // } // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(getArguments().getInt(LAYOUT_ID, -1), container, false); // } // // }
import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import com.pedrocarrillo.expensetracker.R; import com.pedrocarrillo.expensetracker.ui.login.WelcomePage;
package com.pedrocarrillo.expensetracker.adapters; /** * Created by Pedro on 15/9/2015. */ public class WelcomePagerAdapter extends FragmentStatePagerAdapter { private static final int NUM_PAGES = 3; public WelcomePagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) {
// Path: ExpenseTracker/app/src/main/java/com/pedrocarrillo/expensetracker/ui/Login/WelcomePage.java // public class WelcomePage extends Fragment { // // final static String LAYOUT_ID = "layoutid"; // // public static WelcomePage newInstance(int layoutId) { // WelcomePage pane = new WelcomePage(); // Bundle args = new Bundle(); // args.putInt(LAYOUT_ID, layoutId); // pane.setArguments(args); // return pane; // } // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(getArguments().getInt(LAYOUT_ID, -1), container, false); // } // // } // Path: ExpenseTracker/app/src/main/java/com/pedrocarrillo/expensetracker/adapters/WelcomePagerAdapter.java import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import com.pedrocarrillo.expensetracker.R; import com.pedrocarrillo.expensetracker.ui.login.WelcomePage; package com.pedrocarrillo.expensetracker.adapters; /** * Created by Pedro on 15/9/2015. */ public class WelcomePagerAdapter extends FragmentStatePagerAdapter { private static final int NUM_PAGES = 3; public WelcomePagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) {
WelcomePage tp = null;
PedroCarrillo/Expense-Tracker-App
ExpenseTracker/app/src/main/java/com/pedrocarrillo/expensetracker/adapters/BaseExpenseRecyclerViewAdapter.java
// Path: ExpenseTracker/app/src/main/java/com/pedrocarrillo/expensetracker/utils/ExpensesManager.java // public class ExpensesManager { // // private List<Expense> mExpensesList = new ArrayList<>(); // private SparseBooleanArray mSelectedExpensesItems = new SparseBooleanArray(); // // private static ExpensesManager ourInstance = new ExpensesManager(); // // public static ExpensesManager getInstance() { // return ourInstance; // } // // private ExpensesManager() { // } // // public void setExpensesList(Date dateFrom, Date dateTo, @IExpensesType int type, Category category) { // mExpensesList = Expense.getExpensesList(dateFrom, dateTo, type, category); // resetSelectedItems(); // } // // public void setExpensesListByDateMode(@IDateMode int mCurrentDateMode) { // switch (mCurrentDateMode) { // case IDateMode.MODE_TODAY: // mExpensesList = Expense.getTodayExpenses(); // break; // case IDateMode.MODE_WEEK: // mExpensesList = Expense.getWeekExpenses(); // break; // case IDateMode.MODE_MONTH: // mExpensesList = Expense.getMonthExpenses(); // break; // } // } // // public List<Expense> getExpensesList() { // return mExpensesList; // } // // public SparseBooleanArray getSelectedExpensesItems() { // return mSelectedExpensesItems; // } // // public void resetSelectedItems() { // mSelectedExpensesItems.clear(); // } // // public List<Integer> getSelectedExpensesIndex() { // List<Integer> items = new ArrayList<>(mSelectedExpensesItems.size()); // for (int i = 0; i < mSelectedExpensesItems.size(); ++i) { // items.add(mSelectedExpensesItems.keyAt(i)); // } // return items; // } // // public void eraseSelectedExpenses() { // boolean isToday = false; // List<Expense> expensesToDelete = new ArrayList<>(); // for (int position : getSelectedExpensesIndex()) { // Expense expense = mExpensesList.get(position); // expensesToDelete.add(expense); // Date expenseDate = expense.getDate(); // // update widget if the expense is created today // if (DateUtils.isToday(expenseDate)) { // isToday = true; // } // } // if (isToday) { // Intent i = new Intent(ExpenseTrackerApp.getContext(), ExpensesWidgetProvider.class); // i.setAction(ExpensesWidgetService.UPDATE_WIDGET); // ExpenseTrackerApp.getContext().sendBroadcast(i); // } // RealmManager.getInstance().delete(expensesToDelete); // } // // public void setSelectedItems(SparseBooleanArray selectedItems) { // this.mSelectedExpensesItems = selectedItems; // } // // }
import android.support.v7.widget.RecyclerView; import android.util.SparseBooleanArray; import com.pedrocarrillo.expensetracker.utils.ExpensesManager; import java.util.ArrayList; import java.util.List;
package com.pedrocarrillo.expensetracker.adapters; /** * Created by pcarrillo on 21/10/2015. */ abstract class BaseExpenseRecyclerViewAdapter<VH extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<VH> { /** * Indicates if the item at position position is selected * @param position Position of the item to check * @return true if the item is selected, false otherwise */ public boolean isSelected(int position) { return getSelectedItems().contains(position); } /** * Toggle the selection status of the item at a given position * @param position Position of the item to toggle the selection status for */ public void toggleSelection(int position) {
// Path: ExpenseTracker/app/src/main/java/com/pedrocarrillo/expensetracker/utils/ExpensesManager.java // public class ExpensesManager { // // private List<Expense> mExpensesList = new ArrayList<>(); // private SparseBooleanArray mSelectedExpensesItems = new SparseBooleanArray(); // // private static ExpensesManager ourInstance = new ExpensesManager(); // // public static ExpensesManager getInstance() { // return ourInstance; // } // // private ExpensesManager() { // } // // public void setExpensesList(Date dateFrom, Date dateTo, @IExpensesType int type, Category category) { // mExpensesList = Expense.getExpensesList(dateFrom, dateTo, type, category); // resetSelectedItems(); // } // // public void setExpensesListByDateMode(@IDateMode int mCurrentDateMode) { // switch (mCurrentDateMode) { // case IDateMode.MODE_TODAY: // mExpensesList = Expense.getTodayExpenses(); // break; // case IDateMode.MODE_WEEK: // mExpensesList = Expense.getWeekExpenses(); // break; // case IDateMode.MODE_MONTH: // mExpensesList = Expense.getMonthExpenses(); // break; // } // } // // public List<Expense> getExpensesList() { // return mExpensesList; // } // // public SparseBooleanArray getSelectedExpensesItems() { // return mSelectedExpensesItems; // } // // public void resetSelectedItems() { // mSelectedExpensesItems.clear(); // } // // public List<Integer> getSelectedExpensesIndex() { // List<Integer> items = new ArrayList<>(mSelectedExpensesItems.size()); // for (int i = 0; i < mSelectedExpensesItems.size(); ++i) { // items.add(mSelectedExpensesItems.keyAt(i)); // } // return items; // } // // public void eraseSelectedExpenses() { // boolean isToday = false; // List<Expense> expensesToDelete = new ArrayList<>(); // for (int position : getSelectedExpensesIndex()) { // Expense expense = mExpensesList.get(position); // expensesToDelete.add(expense); // Date expenseDate = expense.getDate(); // // update widget if the expense is created today // if (DateUtils.isToday(expenseDate)) { // isToday = true; // } // } // if (isToday) { // Intent i = new Intent(ExpenseTrackerApp.getContext(), ExpensesWidgetProvider.class); // i.setAction(ExpensesWidgetService.UPDATE_WIDGET); // ExpenseTrackerApp.getContext().sendBroadcast(i); // } // RealmManager.getInstance().delete(expensesToDelete); // } // // public void setSelectedItems(SparseBooleanArray selectedItems) { // this.mSelectedExpensesItems = selectedItems; // } // // } // Path: ExpenseTracker/app/src/main/java/com/pedrocarrillo/expensetracker/adapters/BaseExpenseRecyclerViewAdapter.java import android.support.v7.widget.RecyclerView; import android.util.SparseBooleanArray; import com.pedrocarrillo.expensetracker.utils.ExpensesManager; import java.util.ArrayList; import java.util.List; package com.pedrocarrillo.expensetracker.adapters; /** * Created by pcarrillo on 21/10/2015. */ abstract class BaseExpenseRecyclerViewAdapter<VH extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<VH> { /** * Indicates if the item at position position is selected * @param position Position of the item to check * @return true if the item is selected, false otherwise */ public boolean isSelected(int position) { return getSelectedItems().contains(position); } /** * Toggle the selection status of the item at a given position * @param position Position of the item to toggle the selection status for */ public void toggleSelection(int position) {
if (ExpensesManager.getInstance().getSelectedExpensesItems().get(position, false)) {
PedroCarrillo/Expense-Tracker-App
ExpenseTracker/app/src/main/java/com/pedrocarrillo/expensetracker/utils/FileManager.java
// Path: ExpenseTracker/app/src/main/java/com/pedrocarrillo/expensetracker/interfaces/FileGeneratorParser.java // public interface FileGeneratorParser { // // String generateFileContent(); // // }
import android.os.Environment; import android.util.Log; import com.pedrocarrillo.expensetracker.interfaces.FileGeneratorParser; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Date;
package com.pedrocarrillo.expensetracker.utils; /** * Created by pedrocarrillo on 3/20/16. */ public class FileManager { public static String getFileName() { return "Expense tracker "+(new Date().toString()); }
// Path: ExpenseTracker/app/src/main/java/com/pedrocarrillo/expensetracker/interfaces/FileGeneratorParser.java // public interface FileGeneratorParser { // // String generateFileContent(); // // } // Path: ExpenseTracker/app/src/main/java/com/pedrocarrillo/expensetracker/utils/FileManager.java import android.os.Environment; import android.util.Log; import com.pedrocarrillo.expensetracker.interfaces.FileGeneratorParser; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Date; package com.pedrocarrillo.expensetracker.utils; /** * Created by pedrocarrillo on 3/20/16. */ public class FileManager { public static String getFileName() { return "Expense tracker "+(new Date().toString()); }
public static final File generateFile(FileGeneratorParser fileGeneratorParser) {
PedroCarrillo/Expense-Tracker-App
ExpenseTracker/app/src/main/java/com/pedrocarrillo/expensetracker/entities/Category.java
// Path: ExpenseTracker/app/src/main/java/com/pedrocarrillo/expensetracker/utils/RealmManager.java // public class RealmManager { // // private Realm realm; // // private static RealmManager ourInstance = new RealmManager(); // // public static RealmManager getInstance() { // return ourInstance; // } // // public RealmManager(){ // realm = Realm.getInstance(ExpenseTrackerApp.getContext()); // } // // public Realm getRealmInstance() { // return realm; // } // // public <E extends RealmObject> void update(final E object) { // realm.executeTransaction(new Realm.Transaction() { // @Override // public void execute(Realm realm) { // realm.copyToRealmOrUpdate(object); // } // }); // } // // public <E extends RealmObject> void update(final Iterable<E> object) { // realm.executeTransaction(new Realm.Transaction() { // @Override // public void execute(Realm realm) { // realm.copyToRealmOrUpdate(object); // } // }); // } // // public <E extends RealmObject> void save(final E object, final Class<E> clazz) { // realm.executeTransaction(new Realm.Transaction() { // @Override // public void execute(Realm realm) { // checkDuplicateUUID(object, clazz); // realm.copyToRealmOrUpdate(object); // } // }); // } // // public <E extends RealmObject> void delete(final Iterable<E> objects){ // realm.executeTransaction(new Realm.Transaction() { // @Override // public void execute(Realm realm) { // if (objects == null) { // return; // } // for (E object : objects) { // if (object instanceof Category) { // Category category = (Category) object; // RealmResults<Expense> expenseList = Expense.getExpensesPerCategory(category); // for (int i = expenseList.size()-1; i >= 0; i--) { // expenseList.get(i).removeFromRealm(); // } // } // object.removeFromRealm(); // } // } // }); // } // // public <E extends RealmObject> void delete(final E object){ // realm.executeTransaction(new Realm.Transaction() { // @Override // public void execute(Realm realm) { // if (object instanceof Category) { // Category category = (Category) object; // RealmResults<Expense> expenseList = Expense.getExpensesPerCategory(category); // for (int i = expenseList.size()-1; i >= 0; i--) { // expenseList.get(i).removeFromRealm(); // } // } // object.removeFromRealm(); // } // }); // } // // public <E extends RealmObject> RealmObject findById(Class<E> clazz, String id) { // return realm.where(clazz).equalTo("id", id).findFirst(); // } // // public <E extends RealmObject> void checkDuplicateUUID(E object, Class<E> clazz) { // boolean repeated = true; // while (repeated) { // String id = UUID.randomUUID().toString(); // RealmObject realmObject = findById(clazz, id); // if ( realmObject == null ) { // if (object instanceof Expense) { // ((Expense)object).setId(id); // } else if (object instanceof Category){ // ((Category)object).setId(id); // } else { // ((Reminder)object).setId(id); // } // repeated = false; // } // } // } // // }
import com.pedrocarrillo.expensetracker.interfaces.IExpensesType; import com.pedrocarrillo.expensetracker.utils.RealmManager; import java.util.List; import io.realm.RealmList; import io.realm.RealmObject; import io.realm.RealmResults; import io.realm.annotations.PrimaryKey;
public void setType(int type) { this.type = type; } public RealmList<Expense> getExpenses() { return expenses; } public void setExpenses(RealmList<Expense> expenses) { this.expenses = expenses; } public String getId() { return id; } public void setId(String id) { this.id = id; } public static List<Category> getCategoriesIncome() { return getCategoriesForType(IExpensesType.MODE_INCOME); } public static List<Category> getCategoriesExpense() { return getCategoriesForType(IExpensesType.MODE_EXPENSES); } public static List<Category> getCategoriesForType(@IExpensesType int type){
// Path: ExpenseTracker/app/src/main/java/com/pedrocarrillo/expensetracker/utils/RealmManager.java // public class RealmManager { // // private Realm realm; // // private static RealmManager ourInstance = new RealmManager(); // // public static RealmManager getInstance() { // return ourInstance; // } // // public RealmManager(){ // realm = Realm.getInstance(ExpenseTrackerApp.getContext()); // } // // public Realm getRealmInstance() { // return realm; // } // // public <E extends RealmObject> void update(final E object) { // realm.executeTransaction(new Realm.Transaction() { // @Override // public void execute(Realm realm) { // realm.copyToRealmOrUpdate(object); // } // }); // } // // public <E extends RealmObject> void update(final Iterable<E> object) { // realm.executeTransaction(new Realm.Transaction() { // @Override // public void execute(Realm realm) { // realm.copyToRealmOrUpdate(object); // } // }); // } // // public <E extends RealmObject> void save(final E object, final Class<E> clazz) { // realm.executeTransaction(new Realm.Transaction() { // @Override // public void execute(Realm realm) { // checkDuplicateUUID(object, clazz); // realm.copyToRealmOrUpdate(object); // } // }); // } // // public <E extends RealmObject> void delete(final Iterable<E> objects){ // realm.executeTransaction(new Realm.Transaction() { // @Override // public void execute(Realm realm) { // if (objects == null) { // return; // } // for (E object : objects) { // if (object instanceof Category) { // Category category = (Category) object; // RealmResults<Expense> expenseList = Expense.getExpensesPerCategory(category); // for (int i = expenseList.size()-1; i >= 0; i--) { // expenseList.get(i).removeFromRealm(); // } // } // object.removeFromRealm(); // } // } // }); // } // // public <E extends RealmObject> void delete(final E object){ // realm.executeTransaction(new Realm.Transaction() { // @Override // public void execute(Realm realm) { // if (object instanceof Category) { // Category category = (Category) object; // RealmResults<Expense> expenseList = Expense.getExpensesPerCategory(category); // for (int i = expenseList.size()-1; i >= 0; i--) { // expenseList.get(i).removeFromRealm(); // } // } // object.removeFromRealm(); // } // }); // } // // public <E extends RealmObject> RealmObject findById(Class<E> clazz, String id) { // return realm.where(clazz).equalTo("id", id).findFirst(); // } // // public <E extends RealmObject> void checkDuplicateUUID(E object, Class<E> clazz) { // boolean repeated = true; // while (repeated) { // String id = UUID.randomUUID().toString(); // RealmObject realmObject = findById(clazz, id); // if ( realmObject == null ) { // if (object instanceof Expense) { // ((Expense)object).setId(id); // } else if (object instanceof Category){ // ((Category)object).setId(id); // } else { // ((Reminder)object).setId(id); // } // repeated = false; // } // } // } // // } // Path: ExpenseTracker/app/src/main/java/com/pedrocarrillo/expensetracker/entities/Category.java import com.pedrocarrillo.expensetracker.interfaces.IExpensesType; import com.pedrocarrillo.expensetracker.utils.RealmManager; import java.util.List; import io.realm.RealmList; import io.realm.RealmObject; import io.realm.RealmResults; import io.realm.annotations.PrimaryKey; public void setType(int type) { this.type = type; } public RealmList<Expense> getExpenses() { return expenses; } public void setExpenses(RealmList<Expense> expenses) { this.expenses = expenses; } public String getId() { return id; } public void setId(String id) { this.id = id; } public static List<Category> getCategoriesIncome() { return getCategoriesForType(IExpensesType.MODE_INCOME); } public static List<Category> getCategoriesExpense() { return getCategoriesForType(IExpensesType.MODE_EXPENSES); } public static List<Category> getCategoriesForType(@IExpensesType int type){
return RealmManager.getInstance().getRealmInstance().where(Category.class)
diffplug/matconsolectl
src/matlabcontrol/MatlabProxyFactoryOptions.java
// Path: src/matlabcontrol/MatlabProxyFactory.java // public interface CopyPasteCallback { // /** // * The given code should be copy-pasted into MATLAB. // */ // void copyPaste(String matlabCmdsToConnect); // }
import java.io.Writer; import java.util.concurrent.atomic.AtomicLong; import matlabcontrol.MatlabProxyFactory.CopyPasteCallback; import java.io.File;
/* * Code licensed under new-style BSD (see LICENSE). * All code up to tags/original: Copyright (c) 2013, Joshua Kaplan * All code after tags/original: Copyright (c) 2016, DiffPlug */ package matlabcontrol; /** * Options that configure how a factory operates. Use a {@link Builder} to create an instance of this class. * <br><br> * This class is unconditionally thread-safe. * * @see MatlabProxyFactory#MatlabProxyFactory(matlabcontrol.MatlabProxyFactoryOptions) * @since 4.0.0 * @author <a href="mailto:nonother@gmail.com">Joshua Kaplan</a> */ public class MatlabProxyFactoryOptions { private final String _matlabLocation; private final File _startingDirectory; private final boolean _hidden; private final boolean _usePreviouslyControlled; private final boolean _osgiClassloaderFriendly;
// Path: src/matlabcontrol/MatlabProxyFactory.java // public interface CopyPasteCallback { // /** // * The given code should be copy-pasted into MATLAB. // */ // void copyPaste(String matlabCmdsToConnect); // } // Path: src/matlabcontrol/MatlabProxyFactoryOptions.java import java.io.Writer; import java.util.concurrent.atomic.AtomicLong; import matlabcontrol.MatlabProxyFactory.CopyPasteCallback; import java.io.File; /* * Code licensed under new-style BSD (see LICENSE). * All code up to tags/original: Copyright (c) 2013, Joshua Kaplan * All code after tags/original: Copyright (c) 2016, DiffPlug */ package matlabcontrol; /** * Options that configure how a factory operates. Use a {@link Builder} to create an instance of this class. * <br><br> * This class is unconditionally thread-safe. * * @see MatlabProxyFactory#MatlabProxyFactory(matlabcontrol.MatlabProxyFactoryOptions) * @since 4.0.0 * @author <a href="mailto:nonother@gmail.com">Joshua Kaplan</a> */ public class MatlabProxyFactoryOptions { private final String _matlabLocation; private final File _startingDirectory; private final boolean _hidden; private final boolean _usePreviouslyControlled; private final boolean _osgiClassloaderFriendly;
private final CopyPasteCallback _copyPasteCallback;
diffplug/matconsolectl
src/matlabcontrol/LocalMatlabProxyFactory.java
// Path: src/matlabcontrol/MatlabProxy.java // public static interface Identifier { // /** // * Returns {@code true} if {@code other} is equal to this identifier, {@code false} otherwise. // * // * @param other // * @return // */ // @Override // public boolean equals(Object other); // // /** // * Returns a hash code which conforms to the {@code hashCode} contract defined in {@link Object#hashCode()}. // * // * @return // */ // @Override // public int hashCode(); // } // // Path: src/matlabcontrol/MatlabProxyFactory.java // public static interface Request { // /** // * The identifier of the proxy associated with this request. If the proxy is created, then its identifier // * accessible via {@link MatlabProxy#getIdentifier()} will return {@code true} when tested for equivalence with // * the identifier returned by this method using {@link Identifier#equals(java.lang.Object)}. // * // * @return proxy's identifier // */ // public Identifier getProxyIdentifer(); // // /** // * Attempts to cancel the request. If the request has already been completed or cannot successfully be canceled // * then {@code false} will be returned, otherwise {@code true} will be returned. If the request has already been // * successfully canceled then this method will have no effect and {@code true} will be returned. // * // * @return if successfully cancelled // */ // public boolean cancel(); // // /** // * If the request has been successfully cancelled. // * // * @return if successfully cancelled // */ // public boolean isCancelled(); // // /** // * Returns {@code true} if the proxy has been created. // * // * @return if the proxy has been created // */ // public boolean isCompleted(); // } // // Path: src/matlabcontrol/MatlabProxyFactory.java // public static interface RequestCallback { // /** // * Called when the proxy has been created. Because requests have no timeout, there is no guarantee that this // * method will ever be called. // * // * @param proxy // */ // public void proxyCreated(MatlabProxy proxy); // }
import matlabcontrol.MatlabProxy.Identifier; import matlabcontrol.MatlabProxyFactory.Request; import matlabcontrol.MatlabProxyFactory.RequestCallback; import java.util.concurrent.atomic.AtomicInteger;
/* * Code licensed under new-style BSD (see LICENSE). * All code up to tags/original: Copyright (c) 2013, Joshua Kaplan * All code after tags/original: Copyright (c) 2016, DiffPlug */ package matlabcontrol; /** * Creates local instances of {@link MatlabProxy}. * * @since 4.0.0 * * @author <a href="mailto:nonother@gmail.com">Joshua Kaplan</a> */ class LocalMatlabProxyFactory implements ProxyFactory { public LocalMatlabProxyFactory(MatlabProxyFactoryOptions options) {} @Override public LocalMatlabProxy getProxy() throws MatlabConnectionException { JMIValidator.validateJMIMethods(); return new LocalMatlabProxy(new LocalIdentifier()); } @Override
// Path: src/matlabcontrol/MatlabProxy.java // public static interface Identifier { // /** // * Returns {@code true} if {@code other} is equal to this identifier, {@code false} otherwise. // * // * @param other // * @return // */ // @Override // public boolean equals(Object other); // // /** // * Returns a hash code which conforms to the {@code hashCode} contract defined in {@link Object#hashCode()}. // * // * @return // */ // @Override // public int hashCode(); // } // // Path: src/matlabcontrol/MatlabProxyFactory.java // public static interface Request { // /** // * The identifier of the proxy associated with this request. If the proxy is created, then its identifier // * accessible via {@link MatlabProxy#getIdentifier()} will return {@code true} when tested for equivalence with // * the identifier returned by this method using {@link Identifier#equals(java.lang.Object)}. // * // * @return proxy's identifier // */ // public Identifier getProxyIdentifer(); // // /** // * Attempts to cancel the request. If the request has already been completed or cannot successfully be canceled // * then {@code false} will be returned, otherwise {@code true} will be returned. If the request has already been // * successfully canceled then this method will have no effect and {@code true} will be returned. // * // * @return if successfully cancelled // */ // public boolean cancel(); // // /** // * If the request has been successfully cancelled. // * // * @return if successfully cancelled // */ // public boolean isCancelled(); // // /** // * Returns {@code true} if the proxy has been created. // * // * @return if the proxy has been created // */ // public boolean isCompleted(); // } // // Path: src/matlabcontrol/MatlabProxyFactory.java // public static interface RequestCallback { // /** // * Called when the proxy has been created. Because requests have no timeout, there is no guarantee that this // * method will ever be called. // * // * @param proxy // */ // public void proxyCreated(MatlabProxy proxy); // } // Path: src/matlabcontrol/LocalMatlabProxyFactory.java import matlabcontrol.MatlabProxy.Identifier; import matlabcontrol.MatlabProxyFactory.Request; import matlabcontrol.MatlabProxyFactory.RequestCallback; import java.util.concurrent.atomic.AtomicInteger; /* * Code licensed under new-style BSD (see LICENSE). * All code up to tags/original: Copyright (c) 2013, Joshua Kaplan * All code after tags/original: Copyright (c) 2016, DiffPlug */ package matlabcontrol; /** * Creates local instances of {@link MatlabProxy}. * * @since 4.0.0 * * @author <a href="mailto:nonother@gmail.com">Joshua Kaplan</a> */ class LocalMatlabProxyFactory implements ProxyFactory { public LocalMatlabProxyFactory(MatlabProxyFactoryOptions options) {} @Override public LocalMatlabProxy getProxy() throws MatlabConnectionException { JMIValidator.validateJMIMethods(); return new LocalMatlabProxy(new LocalIdentifier()); } @Override
public Request requestProxy(RequestCallback requestCallback) throws MatlabConnectionException {
diffplug/matconsolectl
src/matlabcontrol/LocalMatlabProxyFactory.java
// Path: src/matlabcontrol/MatlabProxy.java // public static interface Identifier { // /** // * Returns {@code true} if {@code other} is equal to this identifier, {@code false} otherwise. // * // * @param other // * @return // */ // @Override // public boolean equals(Object other); // // /** // * Returns a hash code which conforms to the {@code hashCode} contract defined in {@link Object#hashCode()}. // * // * @return // */ // @Override // public int hashCode(); // } // // Path: src/matlabcontrol/MatlabProxyFactory.java // public static interface Request { // /** // * The identifier of the proxy associated with this request. If the proxy is created, then its identifier // * accessible via {@link MatlabProxy#getIdentifier()} will return {@code true} when tested for equivalence with // * the identifier returned by this method using {@link Identifier#equals(java.lang.Object)}. // * // * @return proxy's identifier // */ // public Identifier getProxyIdentifer(); // // /** // * Attempts to cancel the request. If the request has already been completed or cannot successfully be canceled // * then {@code false} will be returned, otherwise {@code true} will be returned. If the request has already been // * successfully canceled then this method will have no effect and {@code true} will be returned. // * // * @return if successfully cancelled // */ // public boolean cancel(); // // /** // * If the request has been successfully cancelled. // * // * @return if successfully cancelled // */ // public boolean isCancelled(); // // /** // * Returns {@code true} if the proxy has been created. // * // * @return if the proxy has been created // */ // public boolean isCompleted(); // } // // Path: src/matlabcontrol/MatlabProxyFactory.java // public static interface RequestCallback { // /** // * Called when the proxy has been created. Because requests have no timeout, there is no guarantee that this // * method will ever be called. // * // * @param proxy // */ // public void proxyCreated(MatlabProxy proxy); // }
import matlabcontrol.MatlabProxy.Identifier; import matlabcontrol.MatlabProxyFactory.Request; import matlabcontrol.MatlabProxyFactory.RequestCallback; import java.util.concurrent.atomic.AtomicInteger;
/* * Code licensed under new-style BSD (see LICENSE). * All code up to tags/original: Copyright (c) 2013, Joshua Kaplan * All code after tags/original: Copyright (c) 2016, DiffPlug */ package matlabcontrol; /** * Creates local instances of {@link MatlabProxy}. * * @since 4.0.0 * * @author <a href="mailto:nonother@gmail.com">Joshua Kaplan</a> */ class LocalMatlabProxyFactory implements ProxyFactory { public LocalMatlabProxyFactory(MatlabProxyFactoryOptions options) {} @Override public LocalMatlabProxy getProxy() throws MatlabConnectionException { JMIValidator.validateJMIMethods(); return new LocalMatlabProxy(new LocalIdentifier()); } @Override
// Path: src/matlabcontrol/MatlabProxy.java // public static interface Identifier { // /** // * Returns {@code true} if {@code other} is equal to this identifier, {@code false} otherwise. // * // * @param other // * @return // */ // @Override // public boolean equals(Object other); // // /** // * Returns a hash code which conforms to the {@code hashCode} contract defined in {@link Object#hashCode()}. // * // * @return // */ // @Override // public int hashCode(); // } // // Path: src/matlabcontrol/MatlabProxyFactory.java // public static interface Request { // /** // * The identifier of the proxy associated with this request. If the proxy is created, then its identifier // * accessible via {@link MatlabProxy#getIdentifier()} will return {@code true} when tested for equivalence with // * the identifier returned by this method using {@link Identifier#equals(java.lang.Object)}. // * // * @return proxy's identifier // */ // public Identifier getProxyIdentifer(); // // /** // * Attempts to cancel the request. If the request has already been completed or cannot successfully be canceled // * then {@code false} will be returned, otherwise {@code true} will be returned. If the request has already been // * successfully canceled then this method will have no effect and {@code true} will be returned. // * // * @return if successfully cancelled // */ // public boolean cancel(); // // /** // * If the request has been successfully cancelled. // * // * @return if successfully cancelled // */ // public boolean isCancelled(); // // /** // * Returns {@code true} if the proxy has been created. // * // * @return if the proxy has been created // */ // public boolean isCompleted(); // } // // Path: src/matlabcontrol/MatlabProxyFactory.java // public static interface RequestCallback { // /** // * Called when the proxy has been created. Because requests have no timeout, there is no guarantee that this // * method will ever be called. // * // * @param proxy // */ // public void proxyCreated(MatlabProxy proxy); // } // Path: src/matlabcontrol/LocalMatlabProxyFactory.java import matlabcontrol.MatlabProxy.Identifier; import matlabcontrol.MatlabProxyFactory.Request; import matlabcontrol.MatlabProxyFactory.RequestCallback; import java.util.concurrent.atomic.AtomicInteger; /* * Code licensed under new-style BSD (see LICENSE). * All code up to tags/original: Copyright (c) 2013, Joshua Kaplan * All code after tags/original: Copyright (c) 2016, DiffPlug */ package matlabcontrol; /** * Creates local instances of {@link MatlabProxy}. * * @since 4.0.0 * * @author <a href="mailto:nonother@gmail.com">Joshua Kaplan</a> */ class LocalMatlabProxyFactory implements ProxyFactory { public LocalMatlabProxyFactory(MatlabProxyFactoryOptions options) {} @Override public LocalMatlabProxy getProxy() throws MatlabConnectionException { JMIValidator.validateJMIMethods(); return new LocalMatlabProxy(new LocalIdentifier()); } @Override
public Request requestProxy(RequestCallback requestCallback) throws MatlabConnectionException {
diffplug/matconsolectl
src/matlabcontrol/LocalMatlabProxyFactory.java
// Path: src/matlabcontrol/MatlabProxy.java // public static interface Identifier { // /** // * Returns {@code true} if {@code other} is equal to this identifier, {@code false} otherwise. // * // * @param other // * @return // */ // @Override // public boolean equals(Object other); // // /** // * Returns a hash code which conforms to the {@code hashCode} contract defined in {@link Object#hashCode()}. // * // * @return // */ // @Override // public int hashCode(); // } // // Path: src/matlabcontrol/MatlabProxyFactory.java // public static interface Request { // /** // * The identifier of the proxy associated with this request. If the proxy is created, then its identifier // * accessible via {@link MatlabProxy#getIdentifier()} will return {@code true} when tested for equivalence with // * the identifier returned by this method using {@link Identifier#equals(java.lang.Object)}. // * // * @return proxy's identifier // */ // public Identifier getProxyIdentifer(); // // /** // * Attempts to cancel the request. If the request has already been completed or cannot successfully be canceled // * then {@code false} will be returned, otherwise {@code true} will be returned. If the request has already been // * successfully canceled then this method will have no effect and {@code true} will be returned. // * // * @return if successfully cancelled // */ // public boolean cancel(); // // /** // * If the request has been successfully cancelled. // * // * @return if successfully cancelled // */ // public boolean isCancelled(); // // /** // * Returns {@code true} if the proxy has been created. // * // * @return if the proxy has been created // */ // public boolean isCompleted(); // } // // Path: src/matlabcontrol/MatlabProxyFactory.java // public static interface RequestCallback { // /** // * Called when the proxy has been created. Because requests have no timeout, there is no guarantee that this // * method will ever be called. // * // * @param proxy // */ // public void proxyCreated(MatlabProxy proxy); // }
import matlabcontrol.MatlabProxy.Identifier; import matlabcontrol.MatlabProxyFactory.Request; import matlabcontrol.MatlabProxyFactory.RequestCallback; import java.util.concurrent.atomic.AtomicInteger;
/* * Code licensed under new-style BSD (see LICENSE). * All code up to tags/original: Copyright (c) 2013, Joshua Kaplan * All code after tags/original: Copyright (c) 2016, DiffPlug */ package matlabcontrol; /** * Creates local instances of {@link MatlabProxy}. * * @since 4.0.0 * * @author <a href="mailto:nonother@gmail.com">Joshua Kaplan</a> */ class LocalMatlabProxyFactory implements ProxyFactory { public LocalMatlabProxyFactory(MatlabProxyFactoryOptions options) {} @Override public LocalMatlabProxy getProxy() throws MatlabConnectionException { JMIValidator.validateJMIMethods(); return new LocalMatlabProxy(new LocalIdentifier()); } @Override public Request requestProxy(RequestCallback requestCallback) throws MatlabConnectionException { LocalMatlabProxy proxy = getProxy(); requestCallback.proxyCreated(proxy); return new LocalRequest(proxy.getIdentifier()); }
// Path: src/matlabcontrol/MatlabProxy.java // public static interface Identifier { // /** // * Returns {@code true} if {@code other} is equal to this identifier, {@code false} otherwise. // * // * @param other // * @return // */ // @Override // public boolean equals(Object other); // // /** // * Returns a hash code which conforms to the {@code hashCode} contract defined in {@link Object#hashCode()}. // * // * @return // */ // @Override // public int hashCode(); // } // // Path: src/matlabcontrol/MatlabProxyFactory.java // public static interface Request { // /** // * The identifier of the proxy associated with this request. If the proxy is created, then its identifier // * accessible via {@link MatlabProxy#getIdentifier()} will return {@code true} when tested for equivalence with // * the identifier returned by this method using {@link Identifier#equals(java.lang.Object)}. // * // * @return proxy's identifier // */ // public Identifier getProxyIdentifer(); // // /** // * Attempts to cancel the request. If the request has already been completed or cannot successfully be canceled // * then {@code false} will be returned, otherwise {@code true} will be returned. If the request has already been // * successfully canceled then this method will have no effect and {@code true} will be returned. // * // * @return if successfully cancelled // */ // public boolean cancel(); // // /** // * If the request has been successfully cancelled. // * // * @return if successfully cancelled // */ // public boolean isCancelled(); // // /** // * Returns {@code true} if the proxy has been created. // * // * @return if the proxy has been created // */ // public boolean isCompleted(); // } // // Path: src/matlabcontrol/MatlabProxyFactory.java // public static interface RequestCallback { // /** // * Called when the proxy has been created. Because requests have no timeout, there is no guarantee that this // * method will ever be called. // * // * @param proxy // */ // public void proxyCreated(MatlabProxy proxy); // } // Path: src/matlabcontrol/LocalMatlabProxyFactory.java import matlabcontrol.MatlabProxy.Identifier; import matlabcontrol.MatlabProxyFactory.Request; import matlabcontrol.MatlabProxyFactory.RequestCallback; import java.util.concurrent.atomic.AtomicInteger; /* * Code licensed under new-style BSD (see LICENSE). * All code up to tags/original: Copyright (c) 2013, Joshua Kaplan * All code after tags/original: Copyright (c) 2016, DiffPlug */ package matlabcontrol; /** * Creates local instances of {@link MatlabProxy}. * * @since 4.0.0 * * @author <a href="mailto:nonother@gmail.com">Joshua Kaplan</a> */ class LocalMatlabProxyFactory implements ProxyFactory { public LocalMatlabProxyFactory(MatlabProxyFactoryOptions options) {} @Override public LocalMatlabProxy getProxy() throws MatlabConnectionException { JMIValidator.validateJMIMethods(); return new LocalMatlabProxy(new LocalIdentifier()); } @Override public Request requestProxy(RequestCallback requestCallback) throws MatlabConnectionException { LocalMatlabProxy proxy = getProxy(); requestCallback.proxyCreated(proxy); return new LocalRequest(proxy.getIdentifier()); }
private static final class LocalIdentifier implements Identifier {
diffplug/matconsolectl
test/matlabcontrol/CopyPasteTest.java
// Path: src/matlabcontrol/MatlabProxyFactory.java // public interface CopyPasteCallback { // /** // * The given code should be copy-pasted into MATLAB. // */ // void copyPaste(String matlabCmdsToConnect); // }
import org.junit.Assert; import org.junit.Test; import org.junit.experimental.categories.Category; import matlabcontrol.MatlabProxyFactory.CopyPasteCallback;
/* * Code licensed under new-style BSD (see LICENSE). * All code up to tags/original: Copyright (c) 2013, Joshua Kaplan * All code after tags/original: Copyright (c) 2016, DiffPlug */ package matlabcontrol; @Category(MatlabRequired.Interactive.class) public class CopyPasteTest { private Runnable runnable; @Test public void testCopyPaste() throws MatlabConnectionException, MatlabInvocationException { MatlabProxyFactoryOptions.Builder builder = new MatlabProxyFactoryOptions.Builder();
// Path: src/matlabcontrol/MatlabProxyFactory.java // public interface CopyPasteCallback { // /** // * The given code should be copy-pasted into MATLAB. // */ // void copyPaste(String matlabCmdsToConnect); // } // Path: test/matlabcontrol/CopyPasteTest.java import org.junit.Assert; import org.junit.Test; import org.junit.experimental.categories.Category; import matlabcontrol.MatlabProxyFactory.CopyPasteCallback; /* * Code licensed under new-style BSD (see LICENSE). * All code up to tags/original: Copyright (c) 2013, Joshua Kaplan * All code after tags/original: Copyright (c) 2016, DiffPlug */ package matlabcontrol; @Category(MatlabRequired.Interactive.class) public class CopyPasteTest { private Runnable runnable; @Test public void testCopyPaste() throws MatlabConnectionException, MatlabInvocationException { MatlabProxyFactoryOptions.Builder builder = new MatlabProxyFactoryOptions.Builder();
builder.setCopyPasteCallback(new CopyPasteCallback() {
diffplug/matconsolectl
src/matlabcontrol/JMIWrapper.java
// Path: src/matlabcontrol/MatlabProxy.java // public static interface MatlabThreadCallable<T> { // /** // * Performs the computation in MATLAB. The {@code proxy} provided will invoke its methods directly on MATLAB's // * main thread without delay. This {@code proxy} should be used to interact with MATLAB, not a // * {@code MatlabProxy} (or any class delegating to it). // * // * @param proxy // * @return result of the computation // * @throws MatlabInvocationException // */ // public T call(MatlabThreadProxy proxy) throws MatlabInvocationException; // } // // Path: src/matlabcontrol/MatlabProxy.java // public static interface MatlabThreadProxy extends MatlabOperations { // // } // // Path: src/com/mathworks/jmi/Matlab.java // public class Matlab { // public static Object mtFevalConsoleOutput(String function, Object[] args, int nargout) throws Exception { // throw new UnsupportedOperationException("stub"); // } // // public static void whenMatlabIdle(Runnable runnable) { // throw new UnsupportedOperationException("stub"); // } // } // // Path: src/com/mathworks/jmi/NativeMatlab.java // public class NativeMatlab { // public static boolean nativeIsMatlabThread() { // throw new UnsupportedOperationException("stub"); // } // }
import java.awt.AWTEvent; import java.awt.EventQueue; import java.awt.Toolkit; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.atomic.AtomicReference; import matlabcontrol.MatlabProxy.MatlabThreadCallable; import matlabcontrol.MatlabProxy.MatlabThreadProxy; import com.mathworks.jmi.Matlab; import com.mathworks.jmi.NativeMatlab; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
/* * Code licensed under new-style BSD (see LICENSE). * All code up to tags/original: Copyright (c) 2013, Joshua Kaplan * All code after tags/original: Copyright (c) 2016, DiffPlug */ package matlabcontrol; /** * Interacts with MATLAB via the undocumented Java MATLAB Interface (JMI). * <br><br> * This code is inspired by <a href="mailto:whitehouse@virginia.edu">Kamin Whitehouse</a>'s * <a href="http://www.cs.virginia.edu/~whitehouse/matlab/JavaMatlab.html">MatlabControl</a>. Fixes to concurrency * bugs in this class have been aided by the feedback of several matlabcontrol users, thank you for your feedback! * <br><br> * This class runs inside of MATLAB's Java Virtual Machine and relies upon the Java MATLAB Interface which is * distributed by MathWorks as {@code jmi.jar}. It allows for Java to send {@code eval} and {@code feval} statements to * MATLAB and receive results. {@code jmi.jar} is <b>not</b> distributed with matlabcontrol as it is the property of * MathWorks. If you wish to compile the source code you will need to reference the version of {@code jmi.jar} that is * distributed with your copy of MATLAB. It is located at {@code matlabroot/java/jar/jmi.jar} where {@code matlabroot} * is the location of your MATLAB installation. The location of {@code matlabroot} can be determined by executing the * {@code matlabroot} command in the MATLAB Command Window. * <br><br> * This is the only class in matlabcontrol which directly links against code in {@code jmi.jar}. (And therefore also the * only class that needs {@code jmi.jar} to be on the classpath in order to compile.) {@link Configuration} also uses * code in {@code jmi.jar} but uses reflection to interact with it. * * @since 3.0.0 * * @author <a href="mailto:nonother@gmail.com">Joshua Kaplan</a> */ class JMIWrapper { private static final MatlabThreadOperations THREAD_OPERATIONS = new MatlabThreadOperations(); private static final EventQueue EVENT_QUEUE = Toolkit.getDefaultToolkit().getSystemEventQueue(); private static final Method EVENT_QUEUE_DISPATCH_METHOD; static { try { EVENT_QUEUE_DISPATCH_METHOD = EventQueue.class.getDeclaredMethod("dispatchEvent", AWTEvent.class); } catch (NoSuchMethodException e) { throw new IllegalStateException("java.awt.EventQueue's protected void dispatchEvent(java.awt.AWTEvent) " + "method could not be found", e); } EVENT_QUEUE_DISPATCH_METHOD.setAccessible(true); } private JMIWrapper() {} /** * Exits MATLAB without waiting for MATLAB to return, because MATLAB will not return when exiting. * * @throws MatlabInvocationException */ @SuppressFBWarnings(value = "DLS_DEAD_LOCAL_STORE", justification = "False positive.") static void exit() { Runnable runnable = new Runnable() { @Override public void run() { try {
// Path: src/matlabcontrol/MatlabProxy.java // public static interface MatlabThreadCallable<T> { // /** // * Performs the computation in MATLAB. The {@code proxy} provided will invoke its methods directly on MATLAB's // * main thread without delay. This {@code proxy} should be used to interact with MATLAB, not a // * {@code MatlabProxy} (or any class delegating to it). // * // * @param proxy // * @return result of the computation // * @throws MatlabInvocationException // */ // public T call(MatlabThreadProxy proxy) throws MatlabInvocationException; // } // // Path: src/matlabcontrol/MatlabProxy.java // public static interface MatlabThreadProxy extends MatlabOperations { // // } // // Path: src/com/mathworks/jmi/Matlab.java // public class Matlab { // public static Object mtFevalConsoleOutput(String function, Object[] args, int nargout) throws Exception { // throw new UnsupportedOperationException("stub"); // } // // public static void whenMatlabIdle(Runnable runnable) { // throw new UnsupportedOperationException("stub"); // } // } // // Path: src/com/mathworks/jmi/NativeMatlab.java // public class NativeMatlab { // public static boolean nativeIsMatlabThread() { // throw new UnsupportedOperationException("stub"); // } // } // Path: src/matlabcontrol/JMIWrapper.java import java.awt.AWTEvent; import java.awt.EventQueue; import java.awt.Toolkit; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.atomic.AtomicReference; import matlabcontrol.MatlabProxy.MatlabThreadCallable; import matlabcontrol.MatlabProxy.MatlabThreadProxy; import com.mathworks.jmi.Matlab; import com.mathworks.jmi.NativeMatlab; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; /* * Code licensed under new-style BSD (see LICENSE). * All code up to tags/original: Copyright (c) 2013, Joshua Kaplan * All code after tags/original: Copyright (c) 2016, DiffPlug */ package matlabcontrol; /** * Interacts with MATLAB via the undocumented Java MATLAB Interface (JMI). * <br><br> * This code is inspired by <a href="mailto:whitehouse@virginia.edu">Kamin Whitehouse</a>'s * <a href="http://www.cs.virginia.edu/~whitehouse/matlab/JavaMatlab.html">MatlabControl</a>. Fixes to concurrency * bugs in this class have been aided by the feedback of several matlabcontrol users, thank you for your feedback! * <br><br> * This class runs inside of MATLAB's Java Virtual Machine and relies upon the Java MATLAB Interface which is * distributed by MathWorks as {@code jmi.jar}. It allows for Java to send {@code eval} and {@code feval} statements to * MATLAB and receive results. {@code jmi.jar} is <b>not</b> distributed with matlabcontrol as it is the property of * MathWorks. If you wish to compile the source code you will need to reference the version of {@code jmi.jar} that is * distributed with your copy of MATLAB. It is located at {@code matlabroot/java/jar/jmi.jar} where {@code matlabroot} * is the location of your MATLAB installation. The location of {@code matlabroot} can be determined by executing the * {@code matlabroot} command in the MATLAB Command Window. * <br><br> * This is the only class in matlabcontrol which directly links against code in {@code jmi.jar}. (And therefore also the * only class that needs {@code jmi.jar} to be on the classpath in order to compile.) {@link Configuration} also uses * code in {@code jmi.jar} but uses reflection to interact with it. * * @since 3.0.0 * * @author <a href="mailto:nonother@gmail.com">Joshua Kaplan</a> */ class JMIWrapper { private static final MatlabThreadOperations THREAD_OPERATIONS = new MatlabThreadOperations(); private static final EventQueue EVENT_QUEUE = Toolkit.getDefaultToolkit().getSystemEventQueue(); private static final Method EVENT_QUEUE_DISPATCH_METHOD; static { try { EVENT_QUEUE_DISPATCH_METHOD = EventQueue.class.getDeclaredMethod("dispatchEvent", AWTEvent.class); } catch (NoSuchMethodException e) { throw new IllegalStateException("java.awt.EventQueue's protected void dispatchEvent(java.awt.AWTEvent) " + "method could not be found", e); } EVENT_QUEUE_DISPATCH_METHOD.setAccessible(true); } private JMIWrapper() {} /** * Exits MATLAB without waiting for MATLAB to return, because MATLAB will not return when exiting. * * @throws MatlabInvocationException */ @SuppressFBWarnings(value = "DLS_DEAD_LOCAL_STORE", justification = "False positive.") static void exit() { Runnable runnable = new Runnable() { @Override public void run() { try {
Matlab.mtFevalConsoleOutput("exit", null, 0);
diffplug/matconsolectl
src/matlabcontrol/JMIWrapper.java
// Path: src/matlabcontrol/MatlabProxy.java // public static interface MatlabThreadCallable<T> { // /** // * Performs the computation in MATLAB. The {@code proxy} provided will invoke its methods directly on MATLAB's // * main thread without delay. This {@code proxy} should be used to interact with MATLAB, not a // * {@code MatlabProxy} (or any class delegating to it). // * // * @param proxy // * @return result of the computation // * @throws MatlabInvocationException // */ // public T call(MatlabThreadProxy proxy) throws MatlabInvocationException; // } // // Path: src/matlabcontrol/MatlabProxy.java // public static interface MatlabThreadProxy extends MatlabOperations { // // } // // Path: src/com/mathworks/jmi/Matlab.java // public class Matlab { // public static Object mtFevalConsoleOutput(String function, Object[] args, int nargout) throws Exception { // throw new UnsupportedOperationException("stub"); // } // // public static void whenMatlabIdle(Runnable runnable) { // throw new UnsupportedOperationException("stub"); // } // } // // Path: src/com/mathworks/jmi/NativeMatlab.java // public class NativeMatlab { // public static boolean nativeIsMatlabThread() { // throw new UnsupportedOperationException("stub"); // } // }
import java.awt.AWTEvent; import java.awt.EventQueue; import java.awt.Toolkit; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.atomic.AtomicReference; import matlabcontrol.MatlabProxy.MatlabThreadCallable; import matlabcontrol.MatlabProxy.MatlabThreadProxy; import com.mathworks.jmi.Matlab; import com.mathworks.jmi.NativeMatlab; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
/* * Code licensed under new-style BSD (see LICENSE). * All code up to tags/original: Copyright (c) 2013, Joshua Kaplan * All code after tags/original: Copyright (c) 2016, DiffPlug */ package matlabcontrol; /** * Interacts with MATLAB via the undocumented Java MATLAB Interface (JMI). * <br><br> * This code is inspired by <a href="mailto:whitehouse@virginia.edu">Kamin Whitehouse</a>'s * <a href="http://www.cs.virginia.edu/~whitehouse/matlab/JavaMatlab.html">MatlabControl</a>. Fixes to concurrency * bugs in this class have been aided by the feedback of several matlabcontrol users, thank you for your feedback! * <br><br> * This class runs inside of MATLAB's Java Virtual Machine and relies upon the Java MATLAB Interface which is * distributed by MathWorks as {@code jmi.jar}. It allows for Java to send {@code eval} and {@code feval} statements to * MATLAB and receive results. {@code jmi.jar} is <b>not</b> distributed with matlabcontrol as it is the property of * MathWorks. If you wish to compile the source code you will need to reference the version of {@code jmi.jar} that is * distributed with your copy of MATLAB. It is located at {@code matlabroot/java/jar/jmi.jar} where {@code matlabroot} * is the location of your MATLAB installation. The location of {@code matlabroot} can be determined by executing the * {@code matlabroot} command in the MATLAB Command Window. * <br><br> * This is the only class in matlabcontrol which directly links against code in {@code jmi.jar}. (And therefore also the * only class that needs {@code jmi.jar} to be on the classpath in order to compile.) {@link Configuration} also uses * code in {@code jmi.jar} but uses reflection to interact with it. * * @since 3.0.0 * * @author <a href="mailto:nonother@gmail.com">Joshua Kaplan</a> */ class JMIWrapper { private static final MatlabThreadOperations THREAD_OPERATIONS = new MatlabThreadOperations(); private static final EventQueue EVENT_QUEUE = Toolkit.getDefaultToolkit().getSystemEventQueue(); private static final Method EVENT_QUEUE_DISPATCH_METHOD; static { try { EVENT_QUEUE_DISPATCH_METHOD = EventQueue.class.getDeclaredMethod("dispatchEvent", AWTEvent.class); } catch (NoSuchMethodException e) { throw new IllegalStateException("java.awt.EventQueue's protected void dispatchEvent(java.awt.AWTEvent) " + "method could not be found", e); } EVENT_QUEUE_DISPATCH_METHOD.setAccessible(true); } private JMIWrapper() {} /** * Exits MATLAB without waiting for MATLAB to return, because MATLAB will not return when exiting. * * @throws MatlabInvocationException */ @SuppressFBWarnings(value = "DLS_DEAD_LOCAL_STORE", justification = "False positive.") static void exit() { Runnable runnable = new Runnable() { @Override public void run() { try { Matlab.mtFevalConsoleOutput("exit", null, 0); } //This should never fail, and if it does there is no way to consistently report it back to the caller //because this method does not block catch (Exception e) { // make as much noise as we can e.printStackTrace(); throw new RuntimeException(e); } } };
// Path: src/matlabcontrol/MatlabProxy.java // public static interface MatlabThreadCallable<T> { // /** // * Performs the computation in MATLAB. The {@code proxy} provided will invoke its methods directly on MATLAB's // * main thread without delay. This {@code proxy} should be used to interact with MATLAB, not a // * {@code MatlabProxy} (or any class delegating to it). // * // * @param proxy // * @return result of the computation // * @throws MatlabInvocationException // */ // public T call(MatlabThreadProxy proxy) throws MatlabInvocationException; // } // // Path: src/matlabcontrol/MatlabProxy.java // public static interface MatlabThreadProxy extends MatlabOperations { // // } // // Path: src/com/mathworks/jmi/Matlab.java // public class Matlab { // public static Object mtFevalConsoleOutput(String function, Object[] args, int nargout) throws Exception { // throw new UnsupportedOperationException("stub"); // } // // public static void whenMatlabIdle(Runnable runnable) { // throw new UnsupportedOperationException("stub"); // } // } // // Path: src/com/mathworks/jmi/NativeMatlab.java // public class NativeMatlab { // public static boolean nativeIsMatlabThread() { // throw new UnsupportedOperationException("stub"); // } // } // Path: src/matlabcontrol/JMIWrapper.java import java.awt.AWTEvent; import java.awt.EventQueue; import java.awt.Toolkit; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.atomic.AtomicReference; import matlabcontrol.MatlabProxy.MatlabThreadCallable; import matlabcontrol.MatlabProxy.MatlabThreadProxy; import com.mathworks.jmi.Matlab; import com.mathworks.jmi.NativeMatlab; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; /* * Code licensed under new-style BSD (see LICENSE). * All code up to tags/original: Copyright (c) 2013, Joshua Kaplan * All code after tags/original: Copyright (c) 2016, DiffPlug */ package matlabcontrol; /** * Interacts with MATLAB via the undocumented Java MATLAB Interface (JMI). * <br><br> * This code is inspired by <a href="mailto:whitehouse@virginia.edu">Kamin Whitehouse</a>'s * <a href="http://www.cs.virginia.edu/~whitehouse/matlab/JavaMatlab.html">MatlabControl</a>. Fixes to concurrency * bugs in this class have been aided by the feedback of several matlabcontrol users, thank you for your feedback! * <br><br> * This class runs inside of MATLAB's Java Virtual Machine and relies upon the Java MATLAB Interface which is * distributed by MathWorks as {@code jmi.jar}. It allows for Java to send {@code eval} and {@code feval} statements to * MATLAB and receive results. {@code jmi.jar} is <b>not</b> distributed with matlabcontrol as it is the property of * MathWorks. If you wish to compile the source code you will need to reference the version of {@code jmi.jar} that is * distributed with your copy of MATLAB. It is located at {@code matlabroot/java/jar/jmi.jar} where {@code matlabroot} * is the location of your MATLAB installation. The location of {@code matlabroot} can be determined by executing the * {@code matlabroot} command in the MATLAB Command Window. * <br><br> * This is the only class in matlabcontrol which directly links against code in {@code jmi.jar}. (And therefore also the * only class that needs {@code jmi.jar} to be on the classpath in order to compile.) {@link Configuration} also uses * code in {@code jmi.jar} but uses reflection to interact with it. * * @since 3.0.0 * * @author <a href="mailto:nonother@gmail.com">Joshua Kaplan</a> */ class JMIWrapper { private static final MatlabThreadOperations THREAD_OPERATIONS = new MatlabThreadOperations(); private static final EventQueue EVENT_QUEUE = Toolkit.getDefaultToolkit().getSystemEventQueue(); private static final Method EVENT_QUEUE_DISPATCH_METHOD; static { try { EVENT_QUEUE_DISPATCH_METHOD = EventQueue.class.getDeclaredMethod("dispatchEvent", AWTEvent.class); } catch (NoSuchMethodException e) { throw new IllegalStateException("java.awt.EventQueue's protected void dispatchEvent(java.awt.AWTEvent) " + "method could not be found", e); } EVENT_QUEUE_DISPATCH_METHOD.setAccessible(true); } private JMIWrapper() {} /** * Exits MATLAB without waiting for MATLAB to return, because MATLAB will not return when exiting. * * @throws MatlabInvocationException */ @SuppressFBWarnings(value = "DLS_DEAD_LOCAL_STORE", justification = "False positive.") static void exit() { Runnable runnable = new Runnable() { @Override public void run() { try { Matlab.mtFevalConsoleOutput("exit", null, 0); } //This should never fail, and if it does there is no way to consistently report it back to the caller //because this method does not block catch (Exception e) { // make as much noise as we can e.printStackTrace(); throw new RuntimeException(e); } } };
if (NativeMatlab.nativeIsMatlabThread()) {
diffplug/matconsolectl
src/matlabcontrol/JMIWrapper.java
// Path: src/matlabcontrol/MatlabProxy.java // public static interface MatlabThreadCallable<T> { // /** // * Performs the computation in MATLAB. The {@code proxy} provided will invoke its methods directly on MATLAB's // * main thread without delay. This {@code proxy} should be used to interact with MATLAB, not a // * {@code MatlabProxy} (or any class delegating to it). // * // * @param proxy // * @return result of the computation // * @throws MatlabInvocationException // */ // public T call(MatlabThreadProxy proxy) throws MatlabInvocationException; // } // // Path: src/matlabcontrol/MatlabProxy.java // public static interface MatlabThreadProxy extends MatlabOperations { // // } // // Path: src/com/mathworks/jmi/Matlab.java // public class Matlab { // public static Object mtFevalConsoleOutput(String function, Object[] args, int nargout) throws Exception { // throw new UnsupportedOperationException("stub"); // } // // public static void whenMatlabIdle(Runnable runnable) { // throw new UnsupportedOperationException("stub"); // } // } // // Path: src/com/mathworks/jmi/NativeMatlab.java // public class NativeMatlab { // public static boolean nativeIsMatlabThread() { // throw new UnsupportedOperationException("stub"); // } // }
import java.awt.AWTEvent; import java.awt.EventQueue; import java.awt.Toolkit; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.atomic.AtomicReference; import matlabcontrol.MatlabProxy.MatlabThreadCallable; import matlabcontrol.MatlabProxy.MatlabThreadProxy; import com.mathworks.jmi.Matlab; import com.mathworks.jmi.NativeMatlab; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
@SuppressFBWarnings(value = "DLS_DEAD_LOCAL_STORE", justification = "False positive.") static void exit() { Runnable runnable = new Runnable() { @Override public void run() { try { Matlab.mtFevalConsoleOutput("exit", null, 0); } //This should never fail, and if it does there is no way to consistently report it back to the caller //because this method does not block catch (Exception e) { // make as much noise as we can e.printStackTrace(); throw new RuntimeException(e); } } }; if (NativeMatlab.nativeIsMatlabThread()) { runnable.run(); } else { Matlab.whenMatlabIdle(runnable); } } //The following functions wait for MATLAB to complete the computation before returning //See MatlabProxy for the method documentation, acts as if running inside MATLAB //(A LocalMatlabProxy is just a thin wrapper around these methods) static void setVariable(final String variableName, final Object value) throws MatlabInvocationException {
// Path: src/matlabcontrol/MatlabProxy.java // public static interface MatlabThreadCallable<T> { // /** // * Performs the computation in MATLAB. The {@code proxy} provided will invoke its methods directly on MATLAB's // * main thread without delay. This {@code proxy} should be used to interact with MATLAB, not a // * {@code MatlabProxy} (or any class delegating to it). // * // * @param proxy // * @return result of the computation // * @throws MatlabInvocationException // */ // public T call(MatlabThreadProxy proxy) throws MatlabInvocationException; // } // // Path: src/matlabcontrol/MatlabProxy.java // public static interface MatlabThreadProxy extends MatlabOperations { // // } // // Path: src/com/mathworks/jmi/Matlab.java // public class Matlab { // public static Object mtFevalConsoleOutput(String function, Object[] args, int nargout) throws Exception { // throw new UnsupportedOperationException("stub"); // } // // public static void whenMatlabIdle(Runnable runnable) { // throw new UnsupportedOperationException("stub"); // } // } // // Path: src/com/mathworks/jmi/NativeMatlab.java // public class NativeMatlab { // public static boolean nativeIsMatlabThread() { // throw new UnsupportedOperationException("stub"); // } // } // Path: src/matlabcontrol/JMIWrapper.java import java.awt.AWTEvent; import java.awt.EventQueue; import java.awt.Toolkit; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.atomic.AtomicReference; import matlabcontrol.MatlabProxy.MatlabThreadCallable; import matlabcontrol.MatlabProxy.MatlabThreadProxy; import com.mathworks.jmi.Matlab; import com.mathworks.jmi.NativeMatlab; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; @SuppressFBWarnings(value = "DLS_DEAD_LOCAL_STORE", justification = "False positive.") static void exit() { Runnable runnable = new Runnable() { @Override public void run() { try { Matlab.mtFevalConsoleOutput("exit", null, 0); } //This should never fail, and if it does there is no way to consistently report it back to the caller //because this method does not block catch (Exception e) { // make as much noise as we can e.printStackTrace(); throw new RuntimeException(e); } } }; if (NativeMatlab.nativeIsMatlabThread()) { runnable.run(); } else { Matlab.whenMatlabIdle(runnable); } } //The following functions wait for MATLAB to complete the computation before returning //See MatlabProxy for the method documentation, acts as if running inside MATLAB //(A LocalMatlabProxy is just a thin wrapper around these methods) static void setVariable(final String variableName, final Object value) throws MatlabInvocationException {
invokeAndWait(new MatlabThreadCallable<Void>() {
diffplug/matconsolectl
src/matlabcontrol/JMIWrapper.java
// Path: src/matlabcontrol/MatlabProxy.java // public static interface MatlabThreadCallable<T> { // /** // * Performs the computation in MATLAB. The {@code proxy} provided will invoke its methods directly on MATLAB's // * main thread without delay. This {@code proxy} should be used to interact with MATLAB, not a // * {@code MatlabProxy} (or any class delegating to it). // * // * @param proxy // * @return result of the computation // * @throws MatlabInvocationException // */ // public T call(MatlabThreadProxy proxy) throws MatlabInvocationException; // } // // Path: src/matlabcontrol/MatlabProxy.java // public static interface MatlabThreadProxy extends MatlabOperations { // // } // // Path: src/com/mathworks/jmi/Matlab.java // public class Matlab { // public static Object mtFevalConsoleOutput(String function, Object[] args, int nargout) throws Exception { // throw new UnsupportedOperationException("stub"); // } // // public static void whenMatlabIdle(Runnable runnable) { // throw new UnsupportedOperationException("stub"); // } // } // // Path: src/com/mathworks/jmi/NativeMatlab.java // public class NativeMatlab { // public static boolean nativeIsMatlabThread() { // throw new UnsupportedOperationException("stub"); // } // }
import java.awt.AWTEvent; import java.awt.EventQueue; import java.awt.Toolkit; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.atomic.AtomicReference; import matlabcontrol.MatlabProxy.MatlabThreadCallable; import matlabcontrol.MatlabProxy.MatlabThreadProxy; import com.mathworks.jmi.Matlab; import com.mathworks.jmi.NativeMatlab; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
Runnable runnable = new Runnable() { @Override public void run() { try { Matlab.mtFevalConsoleOutput("exit", null, 0); } //This should never fail, and if it does there is no way to consistently report it back to the caller //because this method does not block catch (Exception e) { // make as much noise as we can e.printStackTrace(); throw new RuntimeException(e); } } }; if (NativeMatlab.nativeIsMatlabThread()) { runnable.run(); } else { Matlab.whenMatlabIdle(runnable); } } //The following functions wait for MATLAB to complete the computation before returning //See MatlabProxy for the method documentation, acts as if running inside MATLAB //(A LocalMatlabProxy is just a thin wrapper around these methods) static void setVariable(final String variableName, final Object value) throws MatlabInvocationException { invokeAndWait(new MatlabThreadCallable<Void>() { @Override
// Path: src/matlabcontrol/MatlabProxy.java // public static interface MatlabThreadCallable<T> { // /** // * Performs the computation in MATLAB. The {@code proxy} provided will invoke its methods directly on MATLAB's // * main thread without delay. This {@code proxy} should be used to interact with MATLAB, not a // * {@code MatlabProxy} (or any class delegating to it). // * // * @param proxy // * @return result of the computation // * @throws MatlabInvocationException // */ // public T call(MatlabThreadProxy proxy) throws MatlabInvocationException; // } // // Path: src/matlabcontrol/MatlabProxy.java // public static interface MatlabThreadProxy extends MatlabOperations { // // } // // Path: src/com/mathworks/jmi/Matlab.java // public class Matlab { // public static Object mtFevalConsoleOutput(String function, Object[] args, int nargout) throws Exception { // throw new UnsupportedOperationException("stub"); // } // // public static void whenMatlabIdle(Runnable runnable) { // throw new UnsupportedOperationException("stub"); // } // } // // Path: src/com/mathworks/jmi/NativeMatlab.java // public class NativeMatlab { // public static boolean nativeIsMatlabThread() { // throw new UnsupportedOperationException("stub"); // } // } // Path: src/matlabcontrol/JMIWrapper.java import java.awt.AWTEvent; import java.awt.EventQueue; import java.awt.Toolkit; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.atomic.AtomicReference; import matlabcontrol.MatlabProxy.MatlabThreadCallable; import matlabcontrol.MatlabProxy.MatlabThreadProxy; import com.mathworks.jmi.Matlab; import com.mathworks.jmi.NativeMatlab; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; Runnable runnable = new Runnable() { @Override public void run() { try { Matlab.mtFevalConsoleOutput("exit", null, 0); } //This should never fail, and if it does there is no way to consistently report it back to the caller //because this method does not block catch (Exception e) { // make as much noise as we can e.printStackTrace(); throw new RuntimeException(e); } } }; if (NativeMatlab.nativeIsMatlabThread()) { runnable.run(); } else { Matlab.whenMatlabIdle(runnable); } } //The following functions wait for MATLAB to complete the computation before returning //See MatlabProxy for the method documentation, acts as if running inside MATLAB //(A LocalMatlabProxy is just a thin wrapper around these methods) static void setVariable(final String variableName, final Object value) throws MatlabInvocationException { invokeAndWait(new MatlabThreadCallable<Void>() { @Override
public Void call(MatlabThreadProxy proxy) throws MatlabInvocationException {
diffplug/matconsolectl
test/matlabcontrol/GetAndSetTest.java
// Path: test/matlabcontrol/link/ArrayUtilsTest.java // public class ArrayUtilsTest { // @Test // public void testDeepCopyOnPrimitives() { // byte[] bytes = new byte[]{1, 2, 3, 4, 5}; // byte[] bytesCopied = ArrayUtils.deepCopy(bytes); // Assert.assertTrue(bytes != bytesCopied); // Assert.assertArrayEquals(bytes, bytesCopied); // // short[] shorts = new short[]{1, 2, 3, 4, 5}; // short[] shortsCopied = ArrayUtils.deepCopy(shorts); // Assert.assertTrue(shorts != shortsCopied); // Assert.assertArrayEquals(shorts, shortsCopied); // // int[] ints = new int[]{1, 2, 3, 4, 5}; // int[] intsCopied = ArrayUtils.deepCopy(ints); // Assert.assertTrue(ints != intsCopied); // Assert.assertArrayEquals(ints, intsCopied); // // long[] longs = new long[]{1, 2, 3, 4, 5}; // long[] longsCopied = ArrayUtils.deepCopy(longs); // Assert.assertTrue(longs != longsCopied); // Assert.assertArrayEquals(longs, longsCopied); // // float[] floats = new float[]{1, 2, 3, 4, 5}; // float[] floatsCopied = ArrayUtils.deepCopy(floats); // Assert.assertTrue(floats != floatsCopied); // Assert.assertArrayEquals(floats, floatsCopied, 0.01f); // // double[] doubles = new double[]{1, 2, 3, 4, 5}; // double[] doublesCopied = ArrayUtils.deepCopy(doubles); // Assert.assertTrue(doubles != doublesCopied); // Assert.assertArrayEquals(doubles, doublesCopied, 0.01); // // boolean[] bools = new boolean[]{true, true, false, true}; // boolean[] boolsCopied = ArrayUtils.deepCopy(bools); // Assert.assertTrue(bools != boolsCopied); // Assert.assertArrayEquals(bools, boolsCopied); // // char[] chars = new char[]{1, 2, 3, 4, 5}; // char[] charsCopied = ArrayUtils.deepCopy(chars); // Assert.assertTrue(chars != charsCopied); // Assert.assertArrayEquals(chars, charsCopied); // } // // public static void assertArraysEqual(Object expected, Object actual) { // if (expected.getClass().isArray()) { // if (!ArrayUtils.equals(expected, actual)) { // throw new ComparisonFailure("test failed", toString(expected), toString(actual)); // } // } else { // if (!expected.equals(actual)) { // throw new ComparisonFailure("test failed", toString(expected), toString(actual)); // } // } // } // // private static String toString(Object any) { // return "class: " + any.getClass() + "\ntoString: " + any.toString(); // } // }
import matlabcontrol.link.ArrayUtilsTest; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.experimental.categories.Category;
builder.setUsePreviouslyControlledSession(true); MatlabProxyFactory factory = new MatlabProxyFactory(builder.build()); proxy = factory.getProxy(); } @AfterClass public static void exitMatlab() throws MatlabInvocationException { if (proxy != null) { proxy.disconnect(); } } @Before public void clear() throws MatlabInvocationException { proxy.eval("clear"); } @Test public void testSetGet() throws MatlabInvocationException { testCaseSetGet(new boolean[]{true}); testCaseSetGet(new boolean[]{false}); testCaseSetGet(new double[]{1.5}); testCaseSetGet("string"); } private void testCaseSetGet(Object set) throws MatlabInvocationException { proxy.setVariable("a", set); Object get = proxy.getVariable("a");
// Path: test/matlabcontrol/link/ArrayUtilsTest.java // public class ArrayUtilsTest { // @Test // public void testDeepCopyOnPrimitives() { // byte[] bytes = new byte[]{1, 2, 3, 4, 5}; // byte[] bytesCopied = ArrayUtils.deepCopy(bytes); // Assert.assertTrue(bytes != bytesCopied); // Assert.assertArrayEquals(bytes, bytesCopied); // // short[] shorts = new short[]{1, 2, 3, 4, 5}; // short[] shortsCopied = ArrayUtils.deepCopy(shorts); // Assert.assertTrue(shorts != shortsCopied); // Assert.assertArrayEquals(shorts, shortsCopied); // // int[] ints = new int[]{1, 2, 3, 4, 5}; // int[] intsCopied = ArrayUtils.deepCopy(ints); // Assert.assertTrue(ints != intsCopied); // Assert.assertArrayEquals(ints, intsCopied); // // long[] longs = new long[]{1, 2, 3, 4, 5}; // long[] longsCopied = ArrayUtils.deepCopy(longs); // Assert.assertTrue(longs != longsCopied); // Assert.assertArrayEquals(longs, longsCopied); // // float[] floats = new float[]{1, 2, 3, 4, 5}; // float[] floatsCopied = ArrayUtils.deepCopy(floats); // Assert.assertTrue(floats != floatsCopied); // Assert.assertArrayEquals(floats, floatsCopied, 0.01f); // // double[] doubles = new double[]{1, 2, 3, 4, 5}; // double[] doublesCopied = ArrayUtils.deepCopy(doubles); // Assert.assertTrue(doubles != doublesCopied); // Assert.assertArrayEquals(doubles, doublesCopied, 0.01); // // boolean[] bools = new boolean[]{true, true, false, true}; // boolean[] boolsCopied = ArrayUtils.deepCopy(bools); // Assert.assertTrue(bools != boolsCopied); // Assert.assertArrayEquals(bools, boolsCopied); // // char[] chars = new char[]{1, 2, 3, 4, 5}; // char[] charsCopied = ArrayUtils.deepCopy(chars); // Assert.assertTrue(chars != charsCopied); // Assert.assertArrayEquals(chars, charsCopied); // } // // public static void assertArraysEqual(Object expected, Object actual) { // if (expected.getClass().isArray()) { // if (!ArrayUtils.equals(expected, actual)) { // throw new ComparisonFailure("test failed", toString(expected), toString(actual)); // } // } else { // if (!expected.equals(actual)) { // throw new ComparisonFailure("test failed", toString(expected), toString(actual)); // } // } // } // // private static String toString(Object any) { // return "class: " + any.getClass() + "\ntoString: " + any.toString(); // } // } // Path: test/matlabcontrol/GetAndSetTest.java import matlabcontrol.link.ArrayUtilsTest; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.experimental.categories.Category; builder.setUsePreviouslyControlledSession(true); MatlabProxyFactory factory = new MatlabProxyFactory(builder.build()); proxy = factory.getProxy(); } @AfterClass public static void exitMatlab() throws MatlabInvocationException { if (proxy != null) { proxy.disconnect(); } } @Before public void clear() throws MatlabInvocationException { proxy.eval("clear"); } @Test public void testSetGet() throws MatlabInvocationException { testCaseSetGet(new boolean[]{true}); testCaseSetGet(new boolean[]{false}); testCaseSetGet(new double[]{1.5}); testCaseSetGet("string"); } private void testCaseSetGet(Object set) throws MatlabInvocationException { proxy.setVariable("a", set); Object get = proxy.getVariable("a");
ArrayUtilsTest.assertArraysEqual(set, get);
diffplug/matconsolectl
src/matlabcontrol/ProxyFactory.java
// Path: src/matlabcontrol/MatlabProxyFactory.java // public static interface Request { // /** // * The identifier of the proxy associated with this request. If the proxy is created, then its identifier // * accessible via {@link MatlabProxy#getIdentifier()} will return {@code true} when tested for equivalence with // * the identifier returned by this method using {@link Identifier#equals(java.lang.Object)}. // * // * @return proxy's identifier // */ // public Identifier getProxyIdentifer(); // // /** // * Attempts to cancel the request. If the request has already been completed or cannot successfully be canceled // * then {@code false} will be returned, otherwise {@code true} will be returned. If the request has already been // * successfully canceled then this method will have no effect and {@code true} will be returned. // * // * @return if successfully cancelled // */ // public boolean cancel(); // // /** // * If the request has been successfully cancelled. // * // * @return if successfully cancelled // */ // public boolean isCancelled(); // // /** // * Returns {@code true} if the proxy has been created. // * // * @return if the proxy has been created // */ // public boolean isCompleted(); // } // // Path: src/matlabcontrol/MatlabProxyFactory.java // public static interface RequestCallback { // /** // * Called when the proxy has been created. Because requests have no timeout, there is no guarantee that this // * method will ever be called. // * // * @param proxy // */ // public void proxyCreated(MatlabProxy proxy); // }
import matlabcontrol.MatlabProxyFactory.RequestCallback; import matlabcontrol.MatlabProxyFactory.Request;
/* * Code licensed under new-style BSD (see LICENSE). * All code up to tags/original: Copyright (c) 2013, Joshua Kaplan * All code after tags/original: Copyright (c) 2016, DiffPlug */ package matlabcontrol; /** * A factory which creates instances of {@link MatlabProxy}. * * @since 4.0.0 * * @author <a href="mailto:nonother@gmail.com">Joshua Kaplan</a> */ interface ProxyFactory { /** * Returns a {@link MatlabProxy}. If a connection cannot be established before the timeout then this method will end * execution and an exception will be thrown. A timeout can be specified with the options provided to this factory. * If no timeout was specified, then a default of 180 seconds will be used. * <br><br> * While this method blocks the calling thread until a proxy is created (or the timeout is reached), any number of * threads may call {@code getProxy()} simultaneously. * * @throws MatlabConnectionException * @return proxy */ public MatlabProxy getProxy() throws MatlabConnectionException; /** * Requests a {@link MatlabProxy}. When the proxy has been created it will be provided to the {@code callback}. The * proxy may be provided to the callback before this method returns. There is no timeout. The returned * {@link Request} instance provides information about the request and can be used to cancel the request. * <br><br> * This method is non-blocking. Any number of requests may be made simultaneously from the same thread or different * threads. * * @throws MatlabConnectionException * @return request */
// Path: src/matlabcontrol/MatlabProxyFactory.java // public static interface Request { // /** // * The identifier of the proxy associated with this request. If the proxy is created, then its identifier // * accessible via {@link MatlabProxy#getIdentifier()} will return {@code true} when tested for equivalence with // * the identifier returned by this method using {@link Identifier#equals(java.lang.Object)}. // * // * @return proxy's identifier // */ // public Identifier getProxyIdentifer(); // // /** // * Attempts to cancel the request. If the request has already been completed or cannot successfully be canceled // * then {@code false} will be returned, otherwise {@code true} will be returned. If the request has already been // * successfully canceled then this method will have no effect and {@code true} will be returned. // * // * @return if successfully cancelled // */ // public boolean cancel(); // // /** // * If the request has been successfully cancelled. // * // * @return if successfully cancelled // */ // public boolean isCancelled(); // // /** // * Returns {@code true} if the proxy has been created. // * // * @return if the proxy has been created // */ // public boolean isCompleted(); // } // // Path: src/matlabcontrol/MatlabProxyFactory.java // public static interface RequestCallback { // /** // * Called when the proxy has been created. Because requests have no timeout, there is no guarantee that this // * method will ever be called. // * // * @param proxy // */ // public void proxyCreated(MatlabProxy proxy); // } // Path: src/matlabcontrol/ProxyFactory.java import matlabcontrol.MatlabProxyFactory.RequestCallback; import matlabcontrol.MatlabProxyFactory.Request; /* * Code licensed under new-style BSD (see LICENSE). * All code up to tags/original: Copyright (c) 2013, Joshua Kaplan * All code after tags/original: Copyright (c) 2016, DiffPlug */ package matlabcontrol; /** * A factory which creates instances of {@link MatlabProxy}. * * @since 4.0.0 * * @author <a href="mailto:nonother@gmail.com">Joshua Kaplan</a> */ interface ProxyFactory { /** * Returns a {@link MatlabProxy}. If a connection cannot be established before the timeout then this method will end * execution and an exception will be thrown. A timeout can be specified with the options provided to this factory. * If no timeout was specified, then a default of 180 seconds will be used. * <br><br> * While this method blocks the calling thread until a proxy is created (or the timeout is reached), any number of * threads may call {@code getProxy()} simultaneously. * * @throws MatlabConnectionException * @return proxy */ public MatlabProxy getProxy() throws MatlabConnectionException; /** * Requests a {@link MatlabProxy}. When the proxy has been created it will be provided to the {@code callback}. The * proxy may be provided to the callback before this method returns. There is no timeout. The returned * {@link Request} instance provides information about the request and can be used to cancel the request. * <br><br> * This method is non-blocking. Any number of requests may be made simultaneously from the same thread or different * threads. * * @throws MatlabConnectionException * @return request */
public Request requestProxy(RequestCallback callback) throws MatlabConnectionException;
diffplug/matconsolectl
src/matlabcontrol/ProxyFactory.java
// Path: src/matlabcontrol/MatlabProxyFactory.java // public static interface Request { // /** // * The identifier of the proxy associated with this request. If the proxy is created, then its identifier // * accessible via {@link MatlabProxy#getIdentifier()} will return {@code true} when tested for equivalence with // * the identifier returned by this method using {@link Identifier#equals(java.lang.Object)}. // * // * @return proxy's identifier // */ // public Identifier getProxyIdentifer(); // // /** // * Attempts to cancel the request. If the request has already been completed or cannot successfully be canceled // * then {@code false} will be returned, otherwise {@code true} will be returned. If the request has already been // * successfully canceled then this method will have no effect and {@code true} will be returned. // * // * @return if successfully cancelled // */ // public boolean cancel(); // // /** // * If the request has been successfully cancelled. // * // * @return if successfully cancelled // */ // public boolean isCancelled(); // // /** // * Returns {@code true} if the proxy has been created. // * // * @return if the proxy has been created // */ // public boolean isCompleted(); // } // // Path: src/matlabcontrol/MatlabProxyFactory.java // public static interface RequestCallback { // /** // * Called when the proxy has been created. Because requests have no timeout, there is no guarantee that this // * method will ever be called. // * // * @param proxy // */ // public void proxyCreated(MatlabProxy proxy); // }
import matlabcontrol.MatlabProxyFactory.RequestCallback; import matlabcontrol.MatlabProxyFactory.Request;
/* * Code licensed under new-style BSD (see LICENSE). * All code up to tags/original: Copyright (c) 2013, Joshua Kaplan * All code after tags/original: Copyright (c) 2016, DiffPlug */ package matlabcontrol; /** * A factory which creates instances of {@link MatlabProxy}. * * @since 4.0.0 * * @author <a href="mailto:nonother@gmail.com">Joshua Kaplan</a> */ interface ProxyFactory { /** * Returns a {@link MatlabProxy}. If a connection cannot be established before the timeout then this method will end * execution and an exception will be thrown. A timeout can be specified with the options provided to this factory. * If no timeout was specified, then a default of 180 seconds will be used. * <br><br> * While this method blocks the calling thread until a proxy is created (or the timeout is reached), any number of * threads may call {@code getProxy()} simultaneously. * * @throws MatlabConnectionException * @return proxy */ public MatlabProxy getProxy() throws MatlabConnectionException; /** * Requests a {@link MatlabProxy}. When the proxy has been created it will be provided to the {@code callback}. The * proxy may be provided to the callback before this method returns. There is no timeout. The returned * {@link Request} instance provides information about the request and can be used to cancel the request. * <br><br> * This method is non-blocking. Any number of requests may be made simultaneously from the same thread or different * threads. * * @throws MatlabConnectionException * @return request */
// Path: src/matlabcontrol/MatlabProxyFactory.java // public static interface Request { // /** // * The identifier of the proxy associated with this request. If the proxy is created, then its identifier // * accessible via {@link MatlabProxy#getIdentifier()} will return {@code true} when tested for equivalence with // * the identifier returned by this method using {@link Identifier#equals(java.lang.Object)}. // * // * @return proxy's identifier // */ // public Identifier getProxyIdentifer(); // // /** // * Attempts to cancel the request. If the request has already been completed or cannot successfully be canceled // * then {@code false} will be returned, otherwise {@code true} will be returned. If the request has already been // * successfully canceled then this method will have no effect and {@code true} will be returned. // * // * @return if successfully cancelled // */ // public boolean cancel(); // // /** // * If the request has been successfully cancelled. // * // * @return if successfully cancelled // */ // public boolean isCancelled(); // // /** // * Returns {@code true} if the proxy has been created. // * // * @return if the proxy has been created // */ // public boolean isCompleted(); // } // // Path: src/matlabcontrol/MatlabProxyFactory.java // public static interface RequestCallback { // /** // * Called when the proxy has been created. Because requests have no timeout, there is no guarantee that this // * method will ever be called. // * // * @param proxy // */ // public void proxyCreated(MatlabProxy proxy); // } // Path: src/matlabcontrol/ProxyFactory.java import matlabcontrol.MatlabProxyFactory.RequestCallback; import matlabcontrol.MatlabProxyFactory.Request; /* * Code licensed under new-style BSD (see LICENSE). * All code up to tags/original: Copyright (c) 2013, Joshua Kaplan * All code after tags/original: Copyright (c) 2016, DiffPlug */ package matlabcontrol; /** * A factory which creates instances of {@link MatlabProxy}. * * @since 4.0.0 * * @author <a href="mailto:nonother@gmail.com">Joshua Kaplan</a> */ interface ProxyFactory { /** * Returns a {@link MatlabProxy}. If a connection cannot be established before the timeout then this method will end * execution and an exception will be thrown. A timeout can be specified with the options provided to this factory. * If no timeout was specified, then a default of 180 seconds will be used. * <br><br> * While this method blocks the calling thread until a proxy is created (or the timeout is reached), any number of * threads may call {@code getProxy()} simultaneously. * * @throws MatlabConnectionException * @return proxy */ public MatlabProxy getProxy() throws MatlabConnectionException; /** * Requests a {@link MatlabProxy}. When the proxy has been created it will be provided to the {@code callback}. The * proxy may be provided to the callback before this method returns. There is no timeout. The returned * {@link Request} instance provides information about the request and can be used to cancel the request. * <br><br> * This method is non-blocking. Any number of requests may be made simultaneously from the same thread or different * threads. * * @throws MatlabConnectionException * @return request */
public Request requestProxy(RequestCallback callback) throws MatlabConnectionException;
diffplug/matconsolectl
src/matlabcontrol/MatlabConnector.java
// Path: src/matlabcontrol/MatlabProxy.java // public static interface MatlabThreadCallable<T> { // /** // * Performs the computation in MATLAB. The {@code proxy} provided will invoke its methods directly on MATLAB's // * main thread without delay. This {@code proxy} should be used to interact with MATLAB, not a // * {@code MatlabProxy} (or any class delegating to it). // * // * @param proxy // * @return result of the computation // * @throws MatlabInvocationException // */ // public T call(MatlabThreadProxy proxy) throws MatlabInvocationException; // } // // Path: src/matlabcontrol/MatlabProxy.java // public static interface MatlabThreadProxy extends MatlabOperations { // // } // // Path: src/matlabcontrol/internal/MatlabRMIClassLoaderSpi.java // public class MatlabRMIClassLoaderSpi extends RMIClassLoaderSpi { // /** // * Loading of classes is delegated to the default {@link RMIClassLoaderSpi}. // */ // private final RMIClassLoaderSpi _delegateLoaderSpi = RMIClassLoader.getDefaultProviderInstance(); // // /** // * The codebase of the external virtual machine which has a proxy that can interact with this session of MATLAB. // * This is done instead of setting the {@code java.rmi.server.codebase} property so that matlabcontrol does not // * interfere with any other uses of RMI in the application. // */ // private static volatile String _remoteCodebase = null; // // /** // * Sets the codebase of the currently connected external JVM. This should be called only once per connection to an // * external JVM and should occur before users of the API can send objects over RMI. // * // * @param remoteCodebase // */ // public static void setCodebase(String remoteCodebase) { // _remoteCodebase = remoteCodebase; // } // // @Override // public Class<?> loadClass(String codebase, String name, ClassLoader defaultLoader) throws MalformedURLException, ClassNotFoundException { // return _delegateLoaderSpi.loadClass(_remoteCodebase, name, defaultLoader); // } // // @Override // public Class<?> loadProxyClass(String codebase, String[] interfaces, ClassLoader defaultLoader) throws MalformedURLException, ClassNotFoundException { // return _delegateLoaderSpi.loadProxyClass(_remoteCodebase, interfaces, defaultLoader); // } // // @Override // public ClassLoader getClassLoader(String codebase) throws MalformedURLException { // return _delegateLoaderSpi.getClassLoader(_remoteCodebase); // } // // /** // * {@inheritDoc} // * <br><br> // * The returned annotation becomes the {@code codebase} argument in // * {@link #loadClass(java.lang.String, java.lang.String, java.lang.ClassLoader)} when the {@code RMIClassLoaderSpi} // * in the receiving JVM attempts to load {@code clazz}. This allows for classes defined in MATLAB but not in the // * receiving JVM to find and load the class definition. // * // * @param clazz // * @return // */ // @Override // public String getClassAnnotation(Class<?> clazz) { // if (clazz == null) { // throw new NullPointerException("class may not be null"); // } // // String annotation = null; // // //If the class has a code source, meaning it is not part of the Java Runtime Environment // if (clazz.getProtectionDomain().getCodeSource() != null) { // //This convoluted way of determining the code source location is necessary due to a bug in early versions of // //Java 6 on Windows (such as what is used by MATLAB R2007b) which puts a space in the code source's URL. // //A space in the URL will cause the receiver of this annotation to treat it as a path separator, which would // //be very problematic and likely cause invalid protocol exceptions. // try { // File file = new File(clazz.getProtectionDomain().getCodeSource().getLocation().getPath()); // annotation = file.toURI().toURL().toString(); // } catch (MalformedURLException e) {} // } // // return annotation; // } // }
import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.rmi.registry.Registry; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import matlabcontrol.MatlabProxy.MatlabThreadCallable; import matlabcontrol.MatlabProxy.MatlabThreadProxy; import matlabcontrol.internal.MatlabRMIClassLoaderSpi;
/** * The classpath (with each classpath entry as an individual canonical path) of the most recently connected * receiver's JVM. * <br><br> * This variable can safely be volatile because the needed behavior is volatile read/write of the array, not * its entries. It is also unlikely the volatile behavior is actually necessary, but it could be if the thread * used by {@link MatlabConnector#_connectionExecutor} died and created a new one - this ensures visibility. */ private static volatile String[] _previousRemoteClassPath = new String[0]; private EstablishConnectionRunnable(String receiverID, int port, boolean existingSession) { _receiverID = receiverID; _port = port; _existingSession = existingSession; } @Override public void run() { //Validate matlabcontrol can be used try { JMIValidator.validateJMIMethods(); } catch (MatlabConnectionException ex) { System.err.println("matlabcontrol is not compatible with this version of MATLAB"); ex.printStackTrace(); return; } //If MATLAB was just launched if (!_existingSession) { //Set the RMI class loader service provider
// Path: src/matlabcontrol/MatlabProxy.java // public static interface MatlabThreadCallable<T> { // /** // * Performs the computation in MATLAB. The {@code proxy} provided will invoke its methods directly on MATLAB's // * main thread without delay. This {@code proxy} should be used to interact with MATLAB, not a // * {@code MatlabProxy} (or any class delegating to it). // * // * @param proxy // * @return result of the computation // * @throws MatlabInvocationException // */ // public T call(MatlabThreadProxy proxy) throws MatlabInvocationException; // } // // Path: src/matlabcontrol/MatlabProxy.java // public static interface MatlabThreadProxy extends MatlabOperations { // // } // // Path: src/matlabcontrol/internal/MatlabRMIClassLoaderSpi.java // public class MatlabRMIClassLoaderSpi extends RMIClassLoaderSpi { // /** // * Loading of classes is delegated to the default {@link RMIClassLoaderSpi}. // */ // private final RMIClassLoaderSpi _delegateLoaderSpi = RMIClassLoader.getDefaultProviderInstance(); // // /** // * The codebase of the external virtual machine which has a proxy that can interact with this session of MATLAB. // * This is done instead of setting the {@code java.rmi.server.codebase} property so that matlabcontrol does not // * interfere with any other uses of RMI in the application. // */ // private static volatile String _remoteCodebase = null; // // /** // * Sets the codebase of the currently connected external JVM. This should be called only once per connection to an // * external JVM and should occur before users of the API can send objects over RMI. // * // * @param remoteCodebase // */ // public static void setCodebase(String remoteCodebase) { // _remoteCodebase = remoteCodebase; // } // // @Override // public Class<?> loadClass(String codebase, String name, ClassLoader defaultLoader) throws MalformedURLException, ClassNotFoundException { // return _delegateLoaderSpi.loadClass(_remoteCodebase, name, defaultLoader); // } // // @Override // public Class<?> loadProxyClass(String codebase, String[] interfaces, ClassLoader defaultLoader) throws MalformedURLException, ClassNotFoundException { // return _delegateLoaderSpi.loadProxyClass(_remoteCodebase, interfaces, defaultLoader); // } // // @Override // public ClassLoader getClassLoader(String codebase) throws MalformedURLException { // return _delegateLoaderSpi.getClassLoader(_remoteCodebase); // } // // /** // * {@inheritDoc} // * <br><br> // * The returned annotation becomes the {@code codebase} argument in // * {@link #loadClass(java.lang.String, java.lang.String, java.lang.ClassLoader)} when the {@code RMIClassLoaderSpi} // * in the receiving JVM attempts to load {@code clazz}. This allows for classes defined in MATLAB but not in the // * receiving JVM to find and load the class definition. // * // * @param clazz // * @return // */ // @Override // public String getClassAnnotation(Class<?> clazz) { // if (clazz == null) { // throw new NullPointerException("class may not be null"); // } // // String annotation = null; // // //If the class has a code source, meaning it is not part of the Java Runtime Environment // if (clazz.getProtectionDomain().getCodeSource() != null) { // //This convoluted way of determining the code source location is necessary due to a bug in early versions of // //Java 6 on Windows (such as what is used by MATLAB R2007b) which puts a space in the code source's URL. // //A space in the URL will cause the receiver of this annotation to treat it as a path separator, which would // //be very problematic and likely cause invalid protocol exceptions. // try { // File file = new File(clazz.getProtectionDomain().getCodeSource().getLocation().getPath()); // annotation = file.toURI().toURL().toString(); // } catch (MalformedURLException e) {} // } // // return annotation; // } // } // Path: src/matlabcontrol/MatlabConnector.java import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.rmi.registry.Registry; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import matlabcontrol.MatlabProxy.MatlabThreadCallable; import matlabcontrol.MatlabProxy.MatlabThreadProxy; import matlabcontrol.internal.MatlabRMIClassLoaderSpi; /** * The classpath (with each classpath entry as an individual canonical path) of the most recently connected * receiver's JVM. * <br><br> * This variable can safely be volatile because the needed behavior is volatile read/write of the array, not * its entries. It is also unlikely the volatile behavior is actually necessary, but it could be if the thread * used by {@link MatlabConnector#_connectionExecutor} died and created a new one - this ensures visibility. */ private static volatile String[] _previousRemoteClassPath = new String[0]; private EstablishConnectionRunnable(String receiverID, int port, boolean existingSession) { _receiverID = receiverID; _port = port; _existingSession = existingSession; } @Override public void run() { //Validate matlabcontrol can be used try { JMIValidator.validateJMIMethods(); } catch (MatlabConnectionException ex) { System.err.println("matlabcontrol is not compatible with this version of MATLAB"); ex.printStackTrace(); return; } //If MATLAB was just launched if (!_existingSession) { //Set the RMI class loader service provider
System.setProperty("java.rmi.server.RMIClassLoaderSpi", MatlabRMIClassLoaderSpi.class.getName());
diffplug/matconsolectl
src/matlabcontrol/MatlabConnector.java
// Path: src/matlabcontrol/MatlabProxy.java // public static interface MatlabThreadCallable<T> { // /** // * Performs the computation in MATLAB. The {@code proxy} provided will invoke its methods directly on MATLAB's // * main thread without delay. This {@code proxy} should be used to interact with MATLAB, not a // * {@code MatlabProxy} (or any class delegating to it). // * // * @param proxy // * @return result of the computation // * @throws MatlabInvocationException // */ // public T call(MatlabThreadProxy proxy) throws MatlabInvocationException; // } // // Path: src/matlabcontrol/MatlabProxy.java // public static interface MatlabThreadProxy extends MatlabOperations { // // } // // Path: src/matlabcontrol/internal/MatlabRMIClassLoaderSpi.java // public class MatlabRMIClassLoaderSpi extends RMIClassLoaderSpi { // /** // * Loading of classes is delegated to the default {@link RMIClassLoaderSpi}. // */ // private final RMIClassLoaderSpi _delegateLoaderSpi = RMIClassLoader.getDefaultProviderInstance(); // // /** // * The codebase of the external virtual machine which has a proxy that can interact with this session of MATLAB. // * This is done instead of setting the {@code java.rmi.server.codebase} property so that matlabcontrol does not // * interfere with any other uses of RMI in the application. // */ // private static volatile String _remoteCodebase = null; // // /** // * Sets the codebase of the currently connected external JVM. This should be called only once per connection to an // * external JVM and should occur before users of the API can send objects over RMI. // * // * @param remoteCodebase // */ // public static void setCodebase(String remoteCodebase) { // _remoteCodebase = remoteCodebase; // } // // @Override // public Class<?> loadClass(String codebase, String name, ClassLoader defaultLoader) throws MalformedURLException, ClassNotFoundException { // return _delegateLoaderSpi.loadClass(_remoteCodebase, name, defaultLoader); // } // // @Override // public Class<?> loadProxyClass(String codebase, String[] interfaces, ClassLoader defaultLoader) throws MalformedURLException, ClassNotFoundException { // return _delegateLoaderSpi.loadProxyClass(_remoteCodebase, interfaces, defaultLoader); // } // // @Override // public ClassLoader getClassLoader(String codebase) throws MalformedURLException { // return _delegateLoaderSpi.getClassLoader(_remoteCodebase); // } // // /** // * {@inheritDoc} // * <br><br> // * The returned annotation becomes the {@code codebase} argument in // * {@link #loadClass(java.lang.String, java.lang.String, java.lang.ClassLoader)} when the {@code RMIClassLoaderSpi} // * in the receiving JVM attempts to load {@code clazz}. This allows for classes defined in MATLAB but not in the // * receiving JVM to find and load the class definition. // * // * @param clazz // * @return // */ // @Override // public String getClassAnnotation(Class<?> clazz) { // if (clazz == null) { // throw new NullPointerException("class may not be null"); // } // // String annotation = null; // // //If the class has a code source, meaning it is not part of the Java Runtime Environment // if (clazz.getProtectionDomain().getCodeSource() != null) { // //This convoluted way of determining the code source location is necessary due to a bug in early versions of // //Java 6 on Windows (such as what is used by MATLAB R2007b) which puts a space in the code source's URL. // //A space in the URL will cause the receiver of this annotation to treat it as a path separator, which would // //be very problematic and likely cause invalid protocol exceptions. // try { // File file = new File(clazz.getProtectionDomain().getCodeSource().getLocation().getPath()); // annotation = file.toURI().toURL().toString(); // } catch (MalformedURLException e) {} // } // // return annotation; // } // }
import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.rmi.registry.Registry; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import matlabcontrol.MatlabProxy.MatlabThreadCallable; import matlabcontrol.MatlabProxy.MatlabThreadProxy; import matlabcontrol.internal.MatlabRMIClassLoaderSpi;
//Tell MATLAB's class loader about the codebase where the receiver is from, if not then MATLAB's //environment will freak out when interacting with classes it cannot find the definition of and throw //exceptions with rather confusing messages String[] newClassPath = receiver.getClassPathAsCanonicalPaths(); try { JMIWrapper.invokeAndWait(new ModifyCodebaseCallable(_previousRemoteClassPath, newClassPath)); _previousRemoteClassPath = newClassPath; } catch (MatlabInvocationException e) { System.err.println("Unable to update MATLAB's class loader; issues may arise interacting with " + "classes not defined in MATLAB's Java Virtual Machine"); e.printStackTrace(); } //Create the remote JMI wrapper and then pass it over RMI to the Java application in its own JVM receiver.receiveJMIWrapper(new JMIWrapperRemoteImpl(), _existingSession); } catch (RemoteException ex) { System.err.println("Connection to Java application could not be established"); ex.printStackTrace(); } _connectionInProgress.set(false); } } /** * Modifies MATLAB's dynamic class path. Retrieves the current dynamic class path, removes all of the entries * from the previously connected JVM, adds the new ones, and if the classpath is now different, sets a new dynamic * classpath. */
// Path: src/matlabcontrol/MatlabProxy.java // public static interface MatlabThreadCallable<T> { // /** // * Performs the computation in MATLAB. The {@code proxy} provided will invoke its methods directly on MATLAB's // * main thread without delay. This {@code proxy} should be used to interact with MATLAB, not a // * {@code MatlabProxy} (or any class delegating to it). // * // * @param proxy // * @return result of the computation // * @throws MatlabInvocationException // */ // public T call(MatlabThreadProxy proxy) throws MatlabInvocationException; // } // // Path: src/matlabcontrol/MatlabProxy.java // public static interface MatlabThreadProxy extends MatlabOperations { // // } // // Path: src/matlabcontrol/internal/MatlabRMIClassLoaderSpi.java // public class MatlabRMIClassLoaderSpi extends RMIClassLoaderSpi { // /** // * Loading of classes is delegated to the default {@link RMIClassLoaderSpi}. // */ // private final RMIClassLoaderSpi _delegateLoaderSpi = RMIClassLoader.getDefaultProviderInstance(); // // /** // * The codebase of the external virtual machine which has a proxy that can interact with this session of MATLAB. // * This is done instead of setting the {@code java.rmi.server.codebase} property so that matlabcontrol does not // * interfere with any other uses of RMI in the application. // */ // private static volatile String _remoteCodebase = null; // // /** // * Sets the codebase of the currently connected external JVM. This should be called only once per connection to an // * external JVM and should occur before users of the API can send objects over RMI. // * // * @param remoteCodebase // */ // public static void setCodebase(String remoteCodebase) { // _remoteCodebase = remoteCodebase; // } // // @Override // public Class<?> loadClass(String codebase, String name, ClassLoader defaultLoader) throws MalformedURLException, ClassNotFoundException { // return _delegateLoaderSpi.loadClass(_remoteCodebase, name, defaultLoader); // } // // @Override // public Class<?> loadProxyClass(String codebase, String[] interfaces, ClassLoader defaultLoader) throws MalformedURLException, ClassNotFoundException { // return _delegateLoaderSpi.loadProxyClass(_remoteCodebase, interfaces, defaultLoader); // } // // @Override // public ClassLoader getClassLoader(String codebase) throws MalformedURLException { // return _delegateLoaderSpi.getClassLoader(_remoteCodebase); // } // // /** // * {@inheritDoc} // * <br><br> // * The returned annotation becomes the {@code codebase} argument in // * {@link #loadClass(java.lang.String, java.lang.String, java.lang.ClassLoader)} when the {@code RMIClassLoaderSpi} // * in the receiving JVM attempts to load {@code clazz}. This allows for classes defined in MATLAB but not in the // * receiving JVM to find and load the class definition. // * // * @param clazz // * @return // */ // @Override // public String getClassAnnotation(Class<?> clazz) { // if (clazz == null) { // throw new NullPointerException("class may not be null"); // } // // String annotation = null; // // //If the class has a code source, meaning it is not part of the Java Runtime Environment // if (clazz.getProtectionDomain().getCodeSource() != null) { // //This convoluted way of determining the code source location is necessary due to a bug in early versions of // //Java 6 on Windows (such as what is used by MATLAB R2007b) which puts a space in the code source's URL. // //A space in the URL will cause the receiver of this annotation to treat it as a path separator, which would // //be very problematic and likely cause invalid protocol exceptions. // try { // File file = new File(clazz.getProtectionDomain().getCodeSource().getLocation().getPath()); // annotation = file.toURI().toURL().toString(); // } catch (MalformedURLException e) {} // } // // return annotation; // } // } // Path: src/matlabcontrol/MatlabConnector.java import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.rmi.registry.Registry; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import matlabcontrol.MatlabProxy.MatlabThreadCallable; import matlabcontrol.MatlabProxy.MatlabThreadProxy; import matlabcontrol.internal.MatlabRMIClassLoaderSpi; //Tell MATLAB's class loader about the codebase where the receiver is from, if not then MATLAB's //environment will freak out when interacting with classes it cannot find the definition of and throw //exceptions with rather confusing messages String[] newClassPath = receiver.getClassPathAsCanonicalPaths(); try { JMIWrapper.invokeAndWait(new ModifyCodebaseCallable(_previousRemoteClassPath, newClassPath)); _previousRemoteClassPath = newClassPath; } catch (MatlabInvocationException e) { System.err.println("Unable to update MATLAB's class loader; issues may arise interacting with " + "classes not defined in MATLAB's Java Virtual Machine"); e.printStackTrace(); } //Create the remote JMI wrapper and then pass it over RMI to the Java application in its own JVM receiver.receiveJMIWrapper(new JMIWrapperRemoteImpl(), _existingSession); } catch (RemoteException ex) { System.err.println("Connection to Java application could not be established"); ex.printStackTrace(); } _connectionInProgress.set(false); } } /** * Modifies MATLAB's dynamic class path. Retrieves the current dynamic class path, removes all of the entries * from the previously connected JVM, adds the new ones, and if the classpath is now different, sets a new dynamic * classpath. */
private static class ModifyCodebaseCallable implements MatlabThreadCallable<Void> {
diffplug/matconsolectl
src/matlabcontrol/MatlabConnector.java
// Path: src/matlabcontrol/MatlabProxy.java // public static interface MatlabThreadCallable<T> { // /** // * Performs the computation in MATLAB. The {@code proxy} provided will invoke its methods directly on MATLAB's // * main thread without delay. This {@code proxy} should be used to interact with MATLAB, not a // * {@code MatlabProxy} (or any class delegating to it). // * // * @param proxy // * @return result of the computation // * @throws MatlabInvocationException // */ // public T call(MatlabThreadProxy proxy) throws MatlabInvocationException; // } // // Path: src/matlabcontrol/MatlabProxy.java // public static interface MatlabThreadProxy extends MatlabOperations { // // } // // Path: src/matlabcontrol/internal/MatlabRMIClassLoaderSpi.java // public class MatlabRMIClassLoaderSpi extends RMIClassLoaderSpi { // /** // * Loading of classes is delegated to the default {@link RMIClassLoaderSpi}. // */ // private final RMIClassLoaderSpi _delegateLoaderSpi = RMIClassLoader.getDefaultProviderInstance(); // // /** // * The codebase of the external virtual machine which has a proxy that can interact with this session of MATLAB. // * This is done instead of setting the {@code java.rmi.server.codebase} property so that matlabcontrol does not // * interfere with any other uses of RMI in the application. // */ // private static volatile String _remoteCodebase = null; // // /** // * Sets the codebase of the currently connected external JVM. This should be called only once per connection to an // * external JVM and should occur before users of the API can send objects over RMI. // * // * @param remoteCodebase // */ // public static void setCodebase(String remoteCodebase) { // _remoteCodebase = remoteCodebase; // } // // @Override // public Class<?> loadClass(String codebase, String name, ClassLoader defaultLoader) throws MalformedURLException, ClassNotFoundException { // return _delegateLoaderSpi.loadClass(_remoteCodebase, name, defaultLoader); // } // // @Override // public Class<?> loadProxyClass(String codebase, String[] interfaces, ClassLoader defaultLoader) throws MalformedURLException, ClassNotFoundException { // return _delegateLoaderSpi.loadProxyClass(_remoteCodebase, interfaces, defaultLoader); // } // // @Override // public ClassLoader getClassLoader(String codebase) throws MalformedURLException { // return _delegateLoaderSpi.getClassLoader(_remoteCodebase); // } // // /** // * {@inheritDoc} // * <br><br> // * The returned annotation becomes the {@code codebase} argument in // * {@link #loadClass(java.lang.String, java.lang.String, java.lang.ClassLoader)} when the {@code RMIClassLoaderSpi} // * in the receiving JVM attempts to load {@code clazz}. This allows for classes defined in MATLAB but not in the // * receiving JVM to find and load the class definition. // * // * @param clazz // * @return // */ // @Override // public String getClassAnnotation(Class<?> clazz) { // if (clazz == null) { // throw new NullPointerException("class may not be null"); // } // // String annotation = null; // // //If the class has a code source, meaning it is not part of the Java Runtime Environment // if (clazz.getProtectionDomain().getCodeSource() != null) { // //This convoluted way of determining the code source location is necessary due to a bug in early versions of // //Java 6 on Windows (such as what is used by MATLAB R2007b) which puts a space in the code source's URL. // //A space in the URL will cause the receiver of this annotation to treat it as a path separator, which would // //be very problematic and likely cause invalid protocol exceptions. // try { // File file = new File(clazz.getProtectionDomain().getCodeSource().getLocation().getPath()); // annotation = file.toURI().toURL().toString(); // } catch (MalformedURLException e) {} // } // // return annotation; // } // }
import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.rmi.registry.Registry; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import matlabcontrol.MatlabProxy.MatlabThreadCallable; import matlabcontrol.MatlabProxy.MatlabThreadProxy; import matlabcontrol.internal.MatlabRMIClassLoaderSpi;
"classes not defined in MATLAB's Java Virtual Machine"); e.printStackTrace(); } //Create the remote JMI wrapper and then pass it over RMI to the Java application in its own JVM receiver.receiveJMIWrapper(new JMIWrapperRemoteImpl(), _existingSession); } catch (RemoteException ex) { System.err.println("Connection to Java application could not be established"); ex.printStackTrace(); } _connectionInProgress.set(false); } } /** * Modifies MATLAB's dynamic class path. Retrieves the current dynamic class path, removes all of the entries * from the previously connected JVM, adds the new ones, and if the classpath is now different, sets a new dynamic * classpath. */ private static class ModifyCodebaseCallable implements MatlabThreadCallable<Void> { private final String[] _toRemove; private final String[] _toAdd; public ModifyCodebaseCallable(String[] oldRemoteClassPath, String[] newRemoteClassPath) { _toRemove = oldRemoteClassPath; _toAdd = newRemoteClassPath; } @Override
// Path: src/matlabcontrol/MatlabProxy.java // public static interface MatlabThreadCallable<T> { // /** // * Performs the computation in MATLAB. The {@code proxy} provided will invoke its methods directly on MATLAB's // * main thread without delay. This {@code proxy} should be used to interact with MATLAB, not a // * {@code MatlabProxy} (or any class delegating to it). // * // * @param proxy // * @return result of the computation // * @throws MatlabInvocationException // */ // public T call(MatlabThreadProxy proxy) throws MatlabInvocationException; // } // // Path: src/matlabcontrol/MatlabProxy.java // public static interface MatlabThreadProxy extends MatlabOperations { // // } // // Path: src/matlabcontrol/internal/MatlabRMIClassLoaderSpi.java // public class MatlabRMIClassLoaderSpi extends RMIClassLoaderSpi { // /** // * Loading of classes is delegated to the default {@link RMIClassLoaderSpi}. // */ // private final RMIClassLoaderSpi _delegateLoaderSpi = RMIClassLoader.getDefaultProviderInstance(); // // /** // * The codebase of the external virtual machine which has a proxy that can interact with this session of MATLAB. // * This is done instead of setting the {@code java.rmi.server.codebase} property so that matlabcontrol does not // * interfere with any other uses of RMI in the application. // */ // private static volatile String _remoteCodebase = null; // // /** // * Sets the codebase of the currently connected external JVM. This should be called only once per connection to an // * external JVM and should occur before users of the API can send objects over RMI. // * // * @param remoteCodebase // */ // public static void setCodebase(String remoteCodebase) { // _remoteCodebase = remoteCodebase; // } // // @Override // public Class<?> loadClass(String codebase, String name, ClassLoader defaultLoader) throws MalformedURLException, ClassNotFoundException { // return _delegateLoaderSpi.loadClass(_remoteCodebase, name, defaultLoader); // } // // @Override // public Class<?> loadProxyClass(String codebase, String[] interfaces, ClassLoader defaultLoader) throws MalformedURLException, ClassNotFoundException { // return _delegateLoaderSpi.loadProxyClass(_remoteCodebase, interfaces, defaultLoader); // } // // @Override // public ClassLoader getClassLoader(String codebase) throws MalformedURLException { // return _delegateLoaderSpi.getClassLoader(_remoteCodebase); // } // // /** // * {@inheritDoc} // * <br><br> // * The returned annotation becomes the {@code codebase} argument in // * {@link #loadClass(java.lang.String, java.lang.String, java.lang.ClassLoader)} when the {@code RMIClassLoaderSpi} // * in the receiving JVM attempts to load {@code clazz}. This allows for classes defined in MATLAB but not in the // * receiving JVM to find and load the class definition. // * // * @param clazz // * @return // */ // @Override // public String getClassAnnotation(Class<?> clazz) { // if (clazz == null) { // throw new NullPointerException("class may not be null"); // } // // String annotation = null; // // //If the class has a code source, meaning it is not part of the Java Runtime Environment // if (clazz.getProtectionDomain().getCodeSource() != null) { // //This convoluted way of determining the code source location is necessary due to a bug in early versions of // //Java 6 on Windows (such as what is used by MATLAB R2007b) which puts a space in the code source's URL. // //A space in the URL will cause the receiver of this annotation to treat it as a path separator, which would // //be very problematic and likely cause invalid protocol exceptions. // try { // File file = new File(clazz.getProtectionDomain().getCodeSource().getLocation().getPath()); // annotation = file.toURI().toURL().toString(); // } catch (MalformedURLException e) {} // } // // return annotation; // } // } // Path: src/matlabcontrol/MatlabConnector.java import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.rmi.registry.Registry; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import matlabcontrol.MatlabProxy.MatlabThreadCallable; import matlabcontrol.MatlabProxy.MatlabThreadProxy; import matlabcontrol.internal.MatlabRMIClassLoaderSpi; "classes not defined in MATLAB's Java Virtual Machine"); e.printStackTrace(); } //Create the remote JMI wrapper and then pass it over RMI to the Java application in its own JVM receiver.receiveJMIWrapper(new JMIWrapperRemoteImpl(), _existingSession); } catch (RemoteException ex) { System.err.println("Connection to Java application could not be established"); ex.printStackTrace(); } _connectionInProgress.set(false); } } /** * Modifies MATLAB's dynamic class path. Retrieves the current dynamic class path, removes all of the entries * from the previously connected JVM, adds the new ones, and if the classpath is now different, sets a new dynamic * classpath. */ private static class ModifyCodebaseCallable implements MatlabThreadCallable<Void> { private final String[] _toRemove; private final String[] _toAdd; public ModifyCodebaseCallable(String[] oldRemoteClassPath, String[] newRemoteClassPath) { _toRemove = oldRemoteClassPath; _toAdd = newRemoteClassPath; } @Override
public Void call(MatlabThreadProxy proxy) throws MatlabInvocationException {
diffplug/matconsolectl
src/matlabcontrol/MatlabProxyFactory.java
// Path: src/matlabcontrol/MatlabProxy.java // public static interface Identifier { // /** // * Returns {@code true} if {@code other} is equal to this identifier, {@code false} otherwise. // * // * @param other // * @return // */ // @Override // public boolean equals(Object other); // // /** // * Returns a hash code which conforms to the {@code hashCode} contract defined in {@link Object#hashCode()}. // * // * @return // */ // @Override // public int hashCode(); // }
import matlabcontrol.MatlabProxy.Identifier;
/* * Code licensed under new-style BSD (see LICENSE). * All code up to tags/original: Copyright (c) 2013, Joshua Kaplan * All code after tags/original: Copyright (c) 2016, DiffPlug */ package matlabcontrol; /** * Creates instances of {@link MatlabProxy}. Any number of proxies may be created with a factory. * <br><br> * How the proxies will connect to a session of MATLAB depends on whether the factory is running inside or outside * MATLAB: * <br><br> * <i>Running inside MATLAB</i><br> * The proxy will connect to the session of MATLAB this factory is running in. * <br><br> * <i>Running outside MATLAB</i><br> * By default a new session of MATLAB will be started and connected to, but the factory may be configured via the * options provided to this factory to connect to a previously controlled session. * <br><br> * This class is unconditionally thread-safe. Any number of proxies may be created simultaneously. * * @since 4.0.0 * * @author <a href="mailto:nonother@gmail.com">Joshua Kaplan</a> */ public class MatlabProxyFactory implements ProxyFactory { private final ProxyFactory _delegateFactory; /** * Constructs the factory using default options. * * @throws MatlabConnectionException */ public MatlabProxyFactory() { this(new MatlabProxyFactoryOptions.Builder().build()); } /** * Constructs the factory with the specified {@code options}. Depending on the whether the factory is running inside * MATLAB or outside MATLAB will determine if a given option is used. * * @param options */ public MatlabProxyFactory(MatlabProxyFactoryOptions options) { if (Configuration.isRunningInsideMatlab()) { _delegateFactory = new LocalMatlabProxyFactory(options); } else { _delegateFactory = new RemoteMatlabProxyFactory(options); } } @Override public MatlabProxy getProxy() throws MatlabConnectionException { return _delegateFactory.getProxy(); } @Override public Request requestProxy(RequestCallback callback) throws MatlabConnectionException { if (callback == null) { throw new NullPointerException("The request callback may not be null"); } return _delegateFactory.requestProxy(callback); } /** * Provides the requested proxy. * * @since 4.0.0 * @author <a href="mailto:nonother@gmail.com">Joshua Kaplan</a> */ public static interface RequestCallback { /** * Called when the proxy has been created. Because requests have no timeout, there is no guarantee that this * method will ever be called. * * @param proxy */ public void proxyCreated(MatlabProxy proxy); } /** * A request for a proxy. Because requests have no timeout, a {@code Request} has no concept of * failure. * <br><br> * Implementations of this class are unconditionally thread-safe. * <br><br> * <b>WARNING:</b> This interface is not intended to be implemented by users of matlabcontrol. Methods may be added * to this interface, and these additions will not be considered breaking binary compatibility. * * @since 4.0.0 * @author <a href="mailto:nonother@gmail.com">Joshua Kaplan</a> */ public static interface Request { /** * The identifier of the proxy associated with this request. If the proxy is created, then its identifier * accessible via {@link MatlabProxy#getIdentifier()} will return {@code true} when tested for equivalence with * the identifier returned by this method using {@link Identifier#equals(java.lang.Object)}. * * @return proxy's identifier */
// Path: src/matlabcontrol/MatlabProxy.java // public static interface Identifier { // /** // * Returns {@code true} if {@code other} is equal to this identifier, {@code false} otherwise. // * // * @param other // * @return // */ // @Override // public boolean equals(Object other); // // /** // * Returns a hash code which conforms to the {@code hashCode} contract defined in {@link Object#hashCode()}. // * // * @return // */ // @Override // public int hashCode(); // } // Path: src/matlabcontrol/MatlabProxyFactory.java import matlabcontrol.MatlabProxy.Identifier; /* * Code licensed under new-style BSD (see LICENSE). * All code up to tags/original: Copyright (c) 2013, Joshua Kaplan * All code after tags/original: Copyright (c) 2016, DiffPlug */ package matlabcontrol; /** * Creates instances of {@link MatlabProxy}. Any number of proxies may be created with a factory. * <br><br> * How the proxies will connect to a session of MATLAB depends on whether the factory is running inside or outside * MATLAB: * <br><br> * <i>Running inside MATLAB</i><br> * The proxy will connect to the session of MATLAB this factory is running in. * <br><br> * <i>Running outside MATLAB</i><br> * By default a new session of MATLAB will be started and connected to, but the factory may be configured via the * options provided to this factory to connect to a previously controlled session. * <br><br> * This class is unconditionally thread-safe. Any number of proxies may be created simultaneously. * * @since 4.0.0 * * @author <a href="mailto:nonother@gmail.com">Joshua Kaplan</a> */ public class MatlabProxyFactory implements ProxyFactory { private final ProxyFactory _delegateFactory; /** * Constructs the factory using default options. * * @throws MatlabConnectionException */ public MatlabProxyFactory() { this(new MatlabProxyFactoryOptions.Builder().build()); } /** * Constructs the factory with the specified {@code options}. Depending on the whether the factory is running inside * MATLAB or outside MATLAB will determine if a given option is used. * * @param options */ public MatlabProxyFactory(MatlabProxyFactoryOptions options) { if (Configuration.isRunningInsideMatlab()) { _delegateFactory = new LocalMatlabProxyFactory(options); } else { _delegateFactory = new RemoteMatlabProxyFactory(options); } } @Override public MatlabProxy getProxy() throws MatlabConnectionException { return _delegateFactory.getProxy(); } @Override public Request requestProxy(RequestCallback callback) throws MatlabConnectionException { if (callback == null) { throw new NullPointerException("The request callback may not be null"); } return _delegateFactory.requestProxy(callback); } /** * Provides the requested proxy. * * @since 4.0.0 * @author <a href="mailto:nonother@gmail.com">Joshua Kaplan</a> */ public static interface RequestCallback { /** * Called when the proxy has been created. Because requests have no timeout, there is no guarantee that this * method will ever be called. * * @param proxy */ public void proxyCreated(MatlabProxy proxy); } /** * A request for a proxy. Because requests have no timeout, a {@code Request} has no concept of * failure. * <br><br> * Implementations of this class are unconditionally thread-safe. * <br><br> * <b>WARNING:</b> This interface is not intended to be implemented by users of matlabcontrol. Methods may be added * to this interface, and these additions will not be considered breaking binary compatibility. * * @since 4.0.0 * @author <a href="mailto:nonother@gmail.com">Joshua Kaplan</a> */ public static interface Request { /** * The identifier of the proxy associated with this request. If the proxy is created, then its identifier * accessible via {@link MatlabProxy#getIdentifier()} will return {@code true} when tested for equivalence with * the identifier returned by this method using {@link Identifier#equals(java.lang.Object)}. * * @return proxy's identifier */
public Identifier getProxyIdentifer();
diffplug/matconsolectl
src/matlabcontrol/RemoteMatlabProxyFactory.java
// Path: src/matlabcontrol/MatlabProxy.java // public static interface Identifier { // /** // * Returns {@code true} if {@code other} is equal to this identifier, {@code false} otherwise. // * // * @param other // * @return // */ // @Override // public boolean equals(Object other); // // /** // * Returns a hash code which conforms to the {@code hashCode} contract defined in {@link Object#hashCode()}. // * // * @return // */ // @Override // public int hashCode(); // } // // Path: src/matlabcontrol/MatlabProxyFactory.java // public static interface Request { // /** // * The identifier of the proxy associated with this request. If the proxy is created, then its identifier // * accessible via {@link MatlabProxy#getIdentifier()} will return {@code true} when tested for equivalence with // * the identifier returned by this method using {@link Identifier#equals(java.lang.Object)}. // * // * @return proxy's identifier // */ // public Identifier getProxyIdentifer(); // // /** // * Attempts to cancel the request. If the request has already been completed or cannot successfully be canceled // * then {@code false} will be returned, otherwise {@code true} will be returned. If the request has already been // * successfully canceled then this method will have no effect and {@code true} will be returned. // * // * @return if successfully cancelled // */ // public boolean cancel(); // // /** // * If the request has been successfully cancelled. // * // * @return if successfully cancelled // */ // public boolean isCancelled(); // // /** // * Returns {@code true} if the proxy has been created. // * // * @return if the proxy has been created // */ // public boolean isCompleted(); // } // // Path: src/matlabcontrol/MatlabProxyFactory.java // public static interface RequestCallback { // /** // * Called when the proxy has been created. Because requests have no timeout, there is no guarantee that this // * method will ever be called. // * // * @param proxy // */ // public void proxyCreated(MatlabProxy proxy); // }
import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.Writer; import java.nio.charset.Charset; import java.rmi.AlreadyBoundException; import java.rmi.NoSuchObjectException; import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.CopyOnWriteArrayList; import matlabcontrol.MatlabProxy.Identifier; import matlabcontrol.MatlabProxyFactory.Request; import matlabcontrol.MatlabProxyFactory.RequestCallback;
/* * Code licensed under new-style BSD (see LICENSE). * All code up to tags/original: Copyright (c) 2013, Joshua Kaplan * All code after tags/original: Copyright (c) 2016, DiffPlug */ package matlabcontrol; /** * Creates remote instances of {@link MatlabProxy}. Creating a proxy will either connect to an existing session of * MATLAB or launch a new session of MATLAB. This factory can be used to create any number of proxies. * * @since 3.0.0 * * @author <a href="mailto:nonother@gmail.com">Joshua Kaplan</a> */ class RemoteMatlabProxyFactory implements ProxyFactory { /** * The options that configure this instance of the factory. */ private final MatlabProxyFactoryOptions _options; /** * {@link RemoteRequestReceiver} instances. They need to be stored because the RMI registry only holds weak * references to exported objects. */ private final CopyOnWriteArrayList<RemoteRequestReceiver> _receivers = new CopyOnWriteArrayList<RemoteRequestReceiver>(); /** * The frequency (in milliseconds) with which to check if a receiver is still bound to the registry. */ static final long RECEIVER_CHECK_PERIOD = 1000L; /** * The RMI registry used to communicate between JVMs. */ private volatile Registry _registry = null; public RemoteMatlabProxyFactory(MatlabProxyFactoryOptions options) { _options = options; } @Override
// Path: src/matlabcontrol/MatlabProxy.java // public static interface Identifier { // /** // * Returns {@code true} if {@code other} is equal to this identifier, {@code false} otherwise. // * // * @param other // * @return // */ // @Override // public boolean equals(Object other); // // /** // * Returns a hash code which conforms to the {@code hashCode} contract defined in {@link Object#hashCode()}. // * // * @return // */ // @Override // public int hashCode(); // } // // Path: src/matlabcontrol/MatlabProxyFactory.java // public static interface Request { // /** // * The identifier of the proxy associated with this request. If the proxy is created, then its identifier // * accessible via {@link MatlabProxy#getIdentifier()} will return {@code true} when tested for equivalence with // * the identifier returned by this method using {@link Identifier#equals(java.lang.Object)}. // * // * @return proxy's identifier // */ // public Identifier getProxyIdentifer(); // // /** // * Attempts to cancel the request. If the request has already been completed or cannot successfully be canceled // * then {@code false} will be returned, otherwise {@code true} will be returned. If the request has already been // * successfully canceled then this method will have no effect and {@code true} will be returned. // * // * @return if successfully cancelled // */ // public boolean cancel(); // // /** // * If the request has been successfully cancelled. // * // * @return if successfully cancelled // */ // public boolean isCancelled(); // // /** // * Returns {@code true} if the proxy has been created. // * // * @return if the proxy has been created // */ // public boolean isCompleted(); // } // // Path: src/matlabcontrol/MatlabProxyFactory.java // public static interface RequestCallback { // /** // * Called when the proxy has been created. Because requests have no timeout, there is no guarantee that this // * method will ever be called. // * // * @param proxy // */ // public void proxyCreated(MatlabProxy proxy); // } // Path: src/matlabcontrol/RemoteMatlabProxyFactory.java import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.Writer; import java.nio.charset.Charset; import java.rmi.AlreadyBoundException; import java.rmi.NoSuchObjectException; import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.CopyOnWriteArrayList; import matlabcontrol.MatlabProxy.Identifier; import matlabcontrol.MatlabProxyFactory.Request; import matlabcontrol.MatlabProxyFactory.RequestCallback; /* * Code licensed under new-style BSD (see LICENSE). * All code up to tags/original: Copyright (c) 2013, Joshua Kaplan * All code after tags/original: Copyright (c) 2016, DiffPlug */ package matlabcontrol; /** * Creates remote instances of {@link MatlabProxy}. Creating a proxy will either connect to an existing session of * MATLAB or launch a new session of MATLAB. This factory can be used to create any number of proxies. * * @since 3.0.0 * * @author <a href="mailto:nonother@gmail.com">Joshua Kaplan</a> */ class RemoteMatlabProxyFactory implements ProxyFactory { /** * The options that configure this instance of the factory. */ private final MatlabProxyFactoryOptions _options; /** * {@link RemoteRequestReceiver} instances. They need to be stored because the RMI registry only holds weak * references to exported objects. */ private final CopyOnWriteArrayList<RemoteRequestReceiver> _receivers = new CopyOnWriteArrayList<RemoteRequestReceiver>(); /** * The frequency (in milliseconds) with which to check if a receiver is still bound to the registry. */ static final long RECEIVER_CHECK_PERIOD = 1000L; /** * The RMI registry used to communicate between JVMs. */ private volatile Registry _registry = null; public RemoteMatlabProxyFactory(MatlabProxyFactoryOptions options) { _options = options; } @Override
public Request requestProxy(final RequestCallback requestCallback) throws MatlabConnectionException {
diffplug/matconsolectl
src/matlabcontrol/RemoteMatlabProxyFactory.java
// Path: src/matlabcontrol/MatlabProxy.java // public static interface Identifier { // /** // * Returns {@code true} if {@code other} is equal to this identifier, {@code false} otherwise. // * // * @param other // * @return // */ // @Override // public boolean equals(Object other); // // /** // * Returns a hash code which conforms to the {@code hashCode} contract defined in {@link Object#hashCode()}. // * // * @return // */ // @Override // public int hashCode(); // } // // Path: src/matlabcontrol/MatlabProxyFactory.java // public static interface Request { // /** // * The identifier of the proxy associated with this request. If the proxy is created, then its identifier // * accessible via {@link MatlabProxy#getIdentifier()} will return {@code true} when tested for equivalence with // * the identifier returned by this method using {@link Identifier#equals(java.lang.Object)}. // * // * @return proxy's identifier // */ // public Identifier getProxyIdentifer(); // // /** // * Attempts to cancel the request. If the request has already been completed or cannot successfully be canceled // * then {@code false} will be returned, otherwise {@code true} will be returned. If the request has already been // * successfully canceled then this method will have no effect and {@code true} will be returned. // * // * @return if successfully cancelled // */ // public boolean cancel(); // // /** // * If the request has been successfully cancelled. // * // * @return if successfully cancelled // */ // public boolean isCancelled(); // // /** // * Returns {@code true} if the proxy has been created. // * // * @return if the proxy has been created // */ // public boolean isCompleted(); // } // // Path: src/matlabcontrol/MatlabProxyFactory.java // public static interface RequestCallback { // /** // * Called when the proxy has been created. Because requests have no timeout, there is no guarantee that this // * method will ever be called. // * // * @param proxy // */ // public void proxyCreated(MatlabProxy proxy); // }
import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.Writer; import java.nio.charset.Charset; import java.rmi.AlreadyBoundException; import java.rmi.NoSuchObjectException; import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.CopyOnWriteArrayList; import matlabcontrol.MatlabProxy.Identifier; import matlabcontrol.MatlabProxyFactory.Request; import matlabcontrol.MatlabProxyFactory.RequestCallback;
/* * Code licensed under new-style BSD (see LICENSE). * All code up to tags/original: Copyright (c) 2013, Joshua Kaplan * All code after tags/original: Copyright (c) 2016, DiffPlug */ package matlabcontrol; /** * Creates remote instances of {@link MatlabProxy}. Creating a proxy will either connect to an existing session of * MATLAB or launch a new session of MATLAB. This factory can be used to create any number of proxies. * * @since 3.0.0 * * @author <a href="mailto:nonother@gmail.com">Joshua Kaplan</a> */ class RemoteMatlabProxyFactory implements ProxyFactory { /** * The options that configure this instance of the factory. */ private final MatlabProxyFactoryOptions _options; /** * {@link RemoteRequestReceiver} instances. They need to be stored because the RMI registry only holds weak * references to exported objects. */ private final CopyOnWriteArrayList<RemoteRequestReceiver> _receivers = new CopyOnWriteArrayList<RemoteRequestReceiver>(); /** * The frequency (in milliseconds) with which to check if a receiver is still bound to the registry. */ static final long RECEIVER_CHECK_PERIOD = 1000L; /** * The RMI registry used to communicate between JVMs. */ private volatile Registry _registry = null; public RemoteMatlabProxyFactory(MatlabProxyFactoryOptions options) { _options = options; } @Override
// Path: src/matlabcontrol/MatlabProxy.java // public static interface Identifier { // /** // * Returns {@code true} if {@code other} is equal to this identifier, {@code false} otherwise. // * // * @param other // * @return // */ // @Override // public boolean equals(Object other); // // /** // * Returns a hash code which conforms to the {@code hashCode} contract defined in {@link Object#hashCode()}. // * // * @return // */ // @Override // public int hashCode(); // } // // Path: src/matlabcontrol/MatlabProxyFactory.java // public static interface Request { // /** // * The identifier of the proxy associated with this request. If the proxy is created, then its identifier // * accessible via {@link MatlabProxy#getIdentifier()} will return {@code true} when tested for equivalence with // * the identifier returned by this method using {@link Identifier#equals(java.lang.Object)}. // * // * @return proxy's identifier // */ // public Identifier getProxyIdentifer(); // // /** // * Attempts to cancel the request. If the request has already been completed or cannot successfully be canceled // * then {@code false} will be returned, otherwise {@code true} will be returned. If the request has already been // * successfully canceled then this method will have no effect and {@code true} will be returned. // * // * @return if successfully cancelled // */ // public boolean cancel(); // // /** // * If the request has been successfully cancelled. // * // * @return if successfully cancelled // */ // public boolean isCancelled(); // // /** // * Returns {@code true} if the proxy has been created. // * // * @return if the proxy has been created // */ // public boolean isCompleted(); // } // // Path: src/matlabcontrol/MatlabProxyFactory.java // public static interface RequestCallback { // /** // * Called when the proxy has been created. Because requests have no timeout, there is no guarantee that this // * method will ever be called. // * // * @param proxy // */ // public void proxyCreated(MatlabProxy proxy); // } // Path: src/matlabcontrol/RemoteMatlabProxyFactory.java import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.Writer; import java.nio.charset.Charset; import java.rmi.AlreadyBoundException; import java.rmi.NoSuchObjectException; import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.CopyOnWriteArrayList; import matlabcontrol.MatlabProxy.Identifier; import matlabcontrol.MatlabProxyFactory.Request; import matlabcontrol.MatlabProxyFactory.RequestCallback; /* * Code licensed under new-style BSD (see LICENSE). * All code up to tags/original: Copyright (c) 2013, Joshua Kaplan * All code after tags/original: Copyright (c) 2016, DiffPlug */ package matlabcontrol; /** * Creates remote instances of {@link MatlabProxy}. Creating a proxy will either connect to an existing session of * MATLAB or launch a new session of MATLAB. This factory can be used to create any number of proxies. * * @since 3.0.0 * * @author <a href="mailto:nonother@gmail.com">Joshua Kaplan</a> */ class RemoteMatlabProxyFactory implements ProxyFactory { /** * The options that configure this instance of the factory. */ private final MatlabProxyFactoryOptions _options; /** * {@link RemoteRequestReceiver} instances. They need to be stored because the RMI registry only holds weak * references to exported objects. */ private final CopyOnWriteArrayList<RemoteRequestReceiver> _receivers = new CopyOnWriteArrayList<RemoteRequestReceiver>(); /** * The frequency (in milliseconds) with which to check if a receiver is still bound to the registry. */ static final long RECEIVER_CHECK_PERIOD = 1000L; /** * The RMI registry used to communicate between JVMs. */ private volatile Registry _registry = null; public RemoteMatlabProxyFactory(MatlabProxyFactoryOptions options) { _options = options; } @Override
public Request requestProxy(final RequestCallback requestCallback) throws MatlabConnectionException {
diffplug/matconsolectl
src/matlabcontrol/RemoteMatlabProxyFactory.java
// Path: src/matlabcontrol/MatlabProxy.java // public static interface Identifier { // /** // * Returns {@code true} if {@code other} is equal to this identifier, {@code false} otherwise. // * // * @param other // * @return // */ // @Override // public boolean equals(Object other); // // /** // * Returns a hash code which conforms to the {@code hashCode} contract defined in {@link Object#hashCode()}. // * // * @return // */ // @Override // public int hashCode(); // } // // Path: src/matlabcontrol/MatlabProxyFactory.java // public static interface Request { // /** // * The identifier of the proxy associated with this request. If the proxy is created, then its identifier // * accessible via {@link MatlabProxy#getIdentifier()} will return {@code true} when tested for equivalence with // * the identifier returned by this method using {@link Identifier#equals(java.lang.Object)}. // * // * @return proxy's identifier // */ // public Identifier getProxyIdentifer(); // // /** // * Attempts to cancel the request. If the request has already been completed or cannot successfully be canceled // * then {@code false} will be returned, otherwise {@code true} will be returned. If the request has already been // * successfully canceled then this method will have no effect and {@code true} will be returned. // * // * @return if successfully cancelled // */ // public boolean cancel(); // // /** // * If the request has been successfully cancelled. // * // * @return if successfully cancelled // */ // public boolean isCancelled(); // // /** // * Returns {@code true} if the proxy has been created. // * // * @return if the proxy has been created // */ // public boolean isCompleted(); // } // // Path: src/matlabcontrol/MatlabProxyFactory.java // public static interface RequestCallback { // /** // * Called when the proxy has been created. Because requests have no timeout, there is no guarantee that this // * method will ever be called. // * // * @param proxy // */ // public void proxyCreated(MatlabProxy proxy); // }
import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.Writer; import java.nio.charset.Charset; import java.rmi.AlreadyBoundException; import java.rmi.NoSuchObjectException; import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.CopyOnWriteArrayList; import matlabcontrol.MatlabProxy.Identifier; import matlabcontrol.MatlabProxyFactory.Request; import matlabcontrol.MatlabProxyFactory.RequestCallback;
} } }, RECEIVER_CHECK_PERIOD, RECEIVER_CHECK_PERIOD); } void shutdown() { _timer.cancel(); } } private static class GetProxyRequestCallback implements RequestCallback { private final Thread _requestingThread; private volatile MatlabProxy _proxy; public GetProxyRequestCallback() { _requestingThread = Thread.currentThread(); } @Override public void proxyCreated(MatlabProxy proxy) { _proxy = proxy; _requestingThread.interrupt(); } public MatlabProxy getProxy() { return _proxy; } }
// Path: src/matlabcontrol/MatlabProxy.java // public static interface Identifier { // /** // * Returns {@code true} if {@code other} is equal to this identifier, {@code false} otherwise. // * // * @param other // * @return // */ // @Override // public boolean equals(Object other); // // /** // * Returns a hash code which conforms to the {@code hashCode} contract defined in {@link Object#hashCode()}. // * // * @return // */ // @Override // public int hashCode(); // } // // Path: src/matlabcontrol/MatlabProxyFactory.java // public static interface Request { // /** // * The identifier of the proxy associated with this request. If the proxy is created, then its identifier // * accessible via {@link MatlabProxy#getIdentifier()} will return {@code true} when tested for equivalence with // * the identifier returned by this method using {@link Identifier#equals(java.lang.Object)}. // * // * @return proxy's identifier // */ // public Identifier getProxyIdentifer(); // // /** // * Attempts to cancel the request. If the request has already been completed or cannot successfully be canceled // * then {@code false} will be returned, otherwise {@code true} will be returned. If the request has already been // * successfully canceled then this method will have no effect and {@code true} will be returned. // * // * @return if successfully cancelled // */ // public boolean cancel(); // // /** // * If the request has been successfully cancelled. // * // * @return if successfully cancelled // */ // public boolean isCancelled(); // // /** // * Returns {@code true} if the proxy has been created. // * // * @return if the proxy has been created // */ // public boolean isCompleted(); // } // // Path: src/matlabcontrol/MatlabProxyFactory.java // public static interface RequestCallback { // /** // * Called when the proxy has been created. Because requests have no timeout, there is no guarantee that this // * method will ever be called. // * // * @param proxy // */ // public void proxyCreated(MatlabProxy proxy); // } // Path: src/matlabcontrol/RemoteMatlabProxyFactory.java import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.Writer; import java.nio.charset.Charset; import java.rmi.AlreadyBoundException; import java.rmi.NoSuchObjectException; import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.CopyOnWriteArrayList; import matlabcontrol.MatlabProxy.Identifier; import matlabcontrol.MatlabProxyFactory.Request; import matlabcontrol.MatlabProxyFactory.RequestCallback; } } }, RECEIVER_CHECK_PERIOD, RECEIVER_CHECK_PERIOD); } void shutdown() { _timer.cancel(); } } private static class GetProxyRequestCallback implements RequestCallback { private final Thread _requestingThread; private volatile MatlabProxy _proxy; public GetProxyRequestCallback() { _requestingThread = Thread.currentThread(); } @Override public void proxyCreated(MatlabProxy proxy) { _proxy = proxy; _requestingThread.interrupt(); } public MatlabProxy getProxy() { return _proxy; } }
private static final class RemoteIdentifier implements Identifier {
crate/elasticsearch-inout-plugin
src/main/java/crate/elasticsearch/searchinto/BulkWriterCollector.java
// Path: src/main/java/crate/elasticsearch/action/searchinto/SearchIntoContext.java // public class SearchIntoContext extends SearchContext { // // // currently we only support index targets // private String targetType = "index"; // // private List<InetSocketTransportAddress> targetNodes; // // // public Map<String, String> outputNames() { // return outputNames; // } // // private final Map<String, String> outputNames = new HashMap<String, // String>(); // // public SearchIntoContext(long id, ShardSearchRequest request, // SearchShardTarget shardTarget, Engine.Searcher engineSearcher, // IndexService indexService, IndexShard indexShard, // ScriptService scriptService, CacheRecycler cacheRecycler) { // super(id, request, shardTarget, engineSearcher, indexService, // indexShard, scriptService, cacheRecycler); // } // // public String targetType() { // // this is currently the only type supported // return targetType; // } // // public List<InetSocketTransportAddress> targetNodes() { // if (targetNodes == null) { // targetNodes = Lists.newArrayList(); // } // return targetNodes; // } // // public void emptyTargetNodes() { // this.targetNodes = ImmutableList.of(); // } // // }
import crate.elasticsearch.action.searchinto.SearchIntoContext; import org.elasticsearch.ElasticSearchException; import org.elasticsearch.action.bulk.BulkItemResponse; import org.elasticsearch.action.bulk.BulkProcessor; import org.elasticsearch.action.bulk.BulkRequest; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.client.Client; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.inject.assistedinject.Assisted; import org.elasticsearch.common.logging.ESLogger; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.transport.InetSocketTransportAddress; import org.elasticsearch.common.transport.TransportAddress; import org.elasticsearch.common.unit.ByteSizeUnit; import org.elasticsearch.common.unit.ByteSizeValue; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.util.concurrent.BaseFuture; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.fetch.FetchSubPhase; import org.elasticsearch.search.fetch.script.ScriptFieldsFetchSubPhase; import org.elasticsearch.search.fetch.version.VersionFetchSubPhase; import java.io.IOException; import java.util.Iterator; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicLong;
package crate.elasticsearch.searchinto; public class BulkWriterCollector extends WriterCollector { private static final ESLogger logger = Loggers.getLogger( BulkWriterCollector.class); private Client client; private Client transportClient; private BulkProcessor bulkProcessor; private final AtomicLong startedDocs = new AtomicLong(0); private final AtomicLong succeededDocs = new AtomicLong(0); public static final String NAME = "index"; private BulkListener bulkListener; public BulkWriterCollector() { super(); } @Inject
// Path: src/main/java/crate/elasticsearch/action/searchinto/SearchIntoContext.java // public class SearchIntoContext extends SearchContext { // // // currently we only support index targets // private String targetType = "index"; // // private List<InetSocketTransportAddress> targetNodes; // // // public Map<String, String> outputNames() { // return outputNames; // } // // private final Map<String, String> outputNames = new HashMap<String, // String>(); // // public SearchIntoContext(long id, ShardSearchRequest request, // SearchShardTarget shardTarget, Engine.Searcher engineSearcher, // IndexService indexService, IndexShard indexShard, // ScriptService scriptService, CacheRecycler cacheRecycler) { // super(id, request, shardTarget, engineSearcher, indexService, // indexShard, scriptService, cacheRecycler); // } // // public String targetType() { // // this is currently the only type supported // return targetType; // } // // public List<InetSocketTransportAddress> targetNodes() { // if (targetNodes == null) { // targetNodes = Lists.newArrayList(); // } // return targetNodes; // } // // public void emptyTargetNodes() { // this.targetNodes = ImmutableList.of(); // } // // } // Path: src/main/java/crate/elasticsearch/searchinto/BulkWriterCollector.java import crate.elasticsearch.action.searchinto.SearchIntoContext; import org.elasticsearch.ElasticSearchException; import org.elasticsearch.action.bulk.BulkItemResponse; import org.elasticsearch.action.bulk.BulkProcessor; import org.elasticsearch.action.bulk.BulkRequest; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.client.Client; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.inject.assistedinject.Assisted; import org.elasticsearch.common.logging.ESLogger; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.transport.InetSocketTransportAddress; import org.elasticsearch.common.transport.TransportAddress; import org.elasticsearch.common.unit.ByteSizeUnit; import org.elasticsearch.common.unit.ByteSizeValue; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.util.concurrent.BaseFuture; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.fetch.FetchSubPhase; import org.elasticsearch.search.fetch.script.ScriptFieldsFetchSubPhase; import org.elasticsearch.search.fetch.version.VersionFetchSubPhase; import java.io.IOException; import java.util.Iterator; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicLong; package crate.elasticsearch.searchinto; public class BulkWriterCollector extends WriterCollector { private static final ESLogger logger = Loggers.getLogger( BulkWriterCollector.class); private Client client; private Client transportClient; private BulkProcessor bulkProcessor; private final AtomicLong startedDocs = new AtomicLong(0); private final AtomicLong succeededDocs = new AtomicLong(0); public static final String NAME = "index"; private BulkListener bulkListener; public BulkWriterCollector() { super(); } @Inject
public BulkWriterCollector(@Assisted SearchIntoContext context,
crate/elasticsearch-inout-plugin
src/main/java/crate/elasticsearch/export/Exporter.java
// Path: src/main/java/crate/elasticsearch/action/export/ExportContext.java // public class ExportContext extends SearchContext { // // private static final String VAR_SHARD = "${shard}"; // private static final String VAR_INDEX = "${index}"; // private static final String VAR_CLUSTER = "${cluster}"; // // private List<String> outputCmdArray; // private String outputCmd; // private String outputFile; // private boolean forceOverride = false; // private boolean compression; // private String nodePath; // private boolean mappings = false; // private boolean settings = false; // // public ExportContext(long id, ShardSearchRequest request, SearchShardTarget shardTarget, // Engine.Searcher engineSearcher, IndexService indexService, IndexShard indexShard, // ScriptService scriptService, CacheRecycler cacheRecycler, String nodePath) { // super(id, request, shardTarget, engineSearcher, indexService, indexShard, scriptService, cacheRecycler); // this.nodePath = nodePath; // } // // public List<String> outputCmdArray() { // return outputCmdArray; // } // // public void outputCmdArray(List<String> outputCmdArray) { // this.outputCmdArray = applyVars(outputCmdArray); // } // // public String outputCmd() { // return outputCmd; // } // // public void outputCmd(String outputCmd) { // this.outputCmd = applyVars(outputCmd); // } // // public String outputFile() { // return outputFile; // } // // public void outputFile(String outputFile) { // outputFile = applyVars(outputFile); // File outFile = new File(outputFile); // if (!outFile.isAbsolute() && nodePath != null) { // outputFile = new File(nodePath, outputFile).getAbsolutePath(); // } // this.outputFile = outputFile; // } // // public boolean mappings() { // return mappings; // } // // public void mappings(boolean mappings) { // this.mappings = mappings; // } // // public boolean settings() { // return settings; // } // // public void settings(boolean settings) { // this.settings = settings; // } // // public String nodePath() { // return nodePath; // } // // public boolean forceOverride() { // return forceOverride; // } // // public void forceOverride(boolean forceOverride) { // this.forceOverride = forceOverride; // } // // public void compression(boolean compression) { // this.compression = compression; // } // // public boolean compression() { // return this.compression; // } // // /** // * Replaces variable placeholder with actual value in all elements of templateArray // * // * @param templateArray // * @return // */ // private List<String> applyVars(List<String> templateArray) { // List<String> ret = new ArrayList<String>(); // for (String part : templateArray) { // ret.add(applyVars(part)); // } // return ret; // } // // /** // * Replaces variable placeholder with actual value // * // * @param template // * @return // */ // private String applyVars(String template) { // template = template.replace(VAR_SHARD, String.valueOf(indexShard().shardId().getId())); // template = template.replace(VAR_INDEX, indexShard().shardId().getIndex()); // template = template.replace(VAR_CLUSTER, clusterName()); // return template; // } // // /** // * Method to retrieve name of cluster // * // * @return name of cluster // */ // private String clusterName() { // return ClusterName.clusterNameFromSettings(this.indexShard().indexSettings()).value(); // } // // public Output createOutput() { // if (outputFile()!=null){ // return new OutputFile(outputFile(), forceOverride(), compression); // } else { // if (outputCmd()!=null){ // return new OutputCommand(outputCmd(), compression); // } else { // return new OutputCommand(outputCmdArray(), compression); // } // } // } // }
import crate.elasticsearch.action.export.ExportContext; import org.apache.lucene.search.Query; import org.elasticsearch.action.admin.cluster.state.ClusterStateRequest; import org.elasticsearch.action.admin.cluster.state.ClusterStateResponse; import org.elasticsearch.client.ClusterAdminClient; import org.elasticsearch.client.Requests; import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.cluster.metadata.MappingMetaData; import org.elasticsearch.cluster.metadata.MetaData; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.inject.Injector; import org.elasticsearch.common.logging.ESLogger; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.SettingsFilter; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.search.fetch.FetchSubPhase; import org.elasticsearch.search.fetch.version.VersionFetchSubPhase; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Arrays; import java.util.HashSet; import java.util.Map; import java.util.Set;
package crate.elasticsearch.export; /** * Class to export data of given context */ public class Exporter { private static final ESLogger logger = Loggers.getLogger(Exporter.class); public static class Result { public Output.Result outputResult; public long numExported; } private final FetchSubPhase[] fetchSubPhases; private final Injector injector; private final SettingsFilter settingsFilter; private ClusterAdminClient client; @Inject public Exporter(VersionFetchSubPhase versionPhase, Injector injector, SettingsFilter settingsFilter) { this.fetchSubPhases = new FetchSubPhase[]{versionPhase}; this.injector = injector; this.settingsFilter = settingsFilter; } /** * Check for permission problems * * @param context * @throws ExportException */
// Path: src/main/java/crate/elasticsearch/action/export/ExportContext.java // public class ExportContext extends SearchContext { // // private static final String VAR_SHARD = "${shard}"; // private static final String VAR_INDEX = "${index}"; // private static final String VAR_CLUSTER = "${cluster}"; // // private List<String> outputCmdArray; // private String outputCmd; // private String outputFile; // private boolean forceOverride = false; // private boolean compression; // private String nodePath; // private boolean mappings = false; // private boolean settings = false; // // public ExportContext(long id, ShardSearchRequest request, SearchShardTarget shardTarget, // Engine.Searcher engineSearcher, IndexService indexService, IndexShard indexShard, // ScriptService scriptService, CacheRecycler cacheRecycler, String nodePath) { // super(id, request, shardTarget, engineSearcher, indexService, indexShard, scriptService, cacheRecycler); // this.nodePath = nodePath; // } // // public List<String> outputCmdArray() { // return outputCmdArray; // } // // public void outputCmdArray(List<String> outputCmdArray) { // this.outputCmdArray = applyVars(outputCmdArray); // } // // public String outputCmd() { // return outputCmd; // } // // public void outputCmd(String outputCmd) { // this.outputCmd = applyVars(outputCmd); // } // // public String outputFile() { // return outputFile; // } // // public void outputFile(String outputFile) { // outputFile = applyVars(outputFile); // File outFile = new File(outputFile); // if (!outFile.isAbsolute() && nodePath != null) { // outputFile = new File(nodePath, outputFile).getAbsolutePath(); // } // this.outputFile = outputFile; // } // // public boolean mappings() { // return mappings; // } // // public void mappings(boolean mappings) { // this.mappings = mappings; // } // // public boolean settings() { // return settings; // } // // public void settings(boolean settings) { // this.settings = settings; // } // // public String nodePath() { // return nodePath; // } // // public boolean forceOverride() { // return forceOverride; // } // // public void forceOverride(boolean forceOverride) { // this.forceOverride = forceOverride; // } // // public void compression(boolean compression) { // this.compression = compression; // } // // public boolean compression() { // return this.compression; // } // // /** // * Replaces variable placeholder with actual value in all elements of templateArray // * // * @param templateArray // * @return // */ // private List<String> applyVars(List<String> templateArray) { // List<String> ret = new ArrayList<String>(); // for (String part : templateArray) { // ret.add(applyVars(part)); // } // return ret; // } // // /** // * Replaces variable placeholder with actual value // * // * @param template // * @return // */ // private String applyVars(String template) { // template = template.replace(VAR_SHARD, String.valueOf(indexShard().shardId().getId())); // template = template.replace(VAR_INDEX, indexShard().shardId().getIndex()); // template = template.replace(VAR_CLUSTER, clusterName()); // return template; // } // // /** // * Method to retrieve name of cluster // * // * @return name of cluster // */ // private String clusterName() { // return ClusterName.clusterNameFromSettings(this.indexShard().indexSettings()).value(); // } // // public Output createOutput() { // if (outputFile()!=null){ // return new OutputFile(outputFile(), forceOverride(), compression); // } else { // if (outputCmd()!=null){ // return new OutputCommand(outputCmd(), compression); // } else { // return new OutputCommand(outputCmdArray(), compression); // } // } // } // } // Path: src/main/java/crate/elasticsearch/export/Exporter.java import crate.elasticsearch.action.export.ExportContext; import org.apache.lucene.search.Query; import org.elasticsearch.action.admin.cluster.state.ClusterStateRequest; import org.elasticsearch.action.admin.cluster.state.ClusterStateResponse; import org.elasticsearch.client.ClusterAdminClient; import org.elasticsearch.client.Requests; import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.cluster.metadata.MappingMetaData; import org.elasticsearch.cluster.metadata.MetaData; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.inject.Injector; import org.elasticsearch.common.logging.ESLogger; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.SettingsFilter; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.search.fetch.FetchSubPhase; import org.elasticsearch.search.fetch.version.VersionFetchSubPhase; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Arrays; import java.util.HashSet; import java.util.Map; import java.util.Set; package crate.elasticsearch.export; /** * Class to export data of given context */ public class Exporter { private static final ESLogger logger = Loggers.getLogger(Exporter.class); public static class Result { public Output.Result outputResult; public long numExported; } private final FetchSubPhase[] fetchSubPhases; private final Injector injector; private final SettingsFilter settingsFilter; private ClusterAdminClient client; @Inject public Exporter(VersionFetchSubPhase versionPhase, Injector injector, SettingsFilter settingsFilter) { this.fetchSubPhases = new FetchSubPhase[]{versionPhase}; this.injector = injector; this.settingsFilter = settingsFilter; } /** * Check for permission problems * * @param context * @throws ExportException */
public void check(ExportContext context) throws ExportException {
crate/elasticsearch-inout-plugin
src/main/java/crate/elasticsearch/module/dump/DumpModule.java
// Path: src/main/java/crate/elasticsearch/action/dump/TransportDumpAction.java // public class TransportDumpAction extends AbstractTransportExportAction { // // @Inject // public TransportDumpAction(Settings settings, ThreadPool threadPool, ClusterService clusterService, // TransportService transportService, IndicesService indicesService, // ScriptService scriptService, CacheRecycler cacheRecycler, // DumpParser dumpParser, Exporter exporter, NodeEnvironment nodeEnv) { // super(settings, threadPool, clusterService, transportService, indicesService, scriptService, // cacheRecycler, dumpParser, exporter, nodeEnv); // } // // @Override // protected String transportAction() { // return DumpAction.NAME; // } // }
import crate.elasticsearch.action.dump.DumpAction; import crate.elasticsearch.action.dump.TransportDumpAction; import crate.elasticsearch.action.dump.parser.DumpParser; import org.elasticsearch.action.GenericAction; import org.elasticsearch.action.support.TransportAction; import org.elasticsearch.common.inject.AbstractModule; import org.elasticsearch.common.inject.multibindings.MapBinder;
package crate.elasticsearch.module.dump; public class DumpModule extends AbstractModule { @Override protected void configure() {
// Path: src/main/java/crate/elasticsearch/action/dump/TransportDumpAction.java // public class TransportDumpAction extends AbstractTransportExportAction { // // @Inject // public TransportDumpAction(Settings settings, ThreadPool threadPool, ClusterService clusterService, // TransportService transportService, IndicesService indicesService, // ScriptService scriptService, CacheRecycler cacheRecycler, // DumpParser dumpParser, Exporter exporter, NodeEnvironment nodeEnv) { // super(settings, threadPool, clusterService, transportService, indicesService, scriptService, // cacheRecycler, dumpParser, exporter, nodeEnv); // } // // @Override // protected String transportAction() { // return DumpAction.NAME; // } // } // Path: src/main/java/crate/elasticsearch/module/dump/DumpModule.java import crate.elasticsearch.action.dump.DumpAction; import crate.elasticsearch.action.dump.TransportDumpAction; import crate.elasticsearch.action.dump.parser.DumpParser; import org.elasticsearch.action.GenericAction; import org.elasticsearch.action.support.TransportAction; import org.elasticsearch.common.inject.AbstractModule; import org.elasticsearch.common.inject.multibindings.MapBinder; package crate.elasticsearch.module.dump; public class DumpModule extends AbstractModule { @Override protected void configure() {
bind(TransportDumpAction.class).asEagerSingleton();
crate/elasticsearch-inout-plugin
src/main/java/crate/elasticsearch/action/searchinto/parser/SearchIntoParser.java
// Path: src/main/java/crate/elasticsearch/action/searchinto/SearchIntoContext.java // public class SearchIntoContext extends SearchContext { // // // currently we only support index targets // private String targetType = "index"; // // private List<InetSocketTransportAddress> targetNodes; // // // public Map<String, String> outputNames() { // return outputNames; // } // // private final Map<String, String> outputNames = new HashMap<String, // String>(); // // public SearchIntoContext(long id, ShardSearchRequest request, // SearchShardTarget shardTarget, Engine.Searcher engineSearcher, // IndexService indexService, IndexShard indexShard, // ScriptService scriptService, CacheRecycler cacheRecycler) { // super(id, request, shardTarget, engineSearcher, indexService, // indexShard, scriptService, cacheRecycler); // } // // public String targetType() { // // this is currently the only type supported // return targetType; // } // // public List<InetSocketTransportAddress> targetNodes() { // if (targetNodes == null) { // targetNodes = Lists.newArrayList(); // } // return targetNodes; // } // // public void emptyTargetNodes() { // this.targetNodes = ImmutableList.of(); // } // // }
import java.util.HashMap; import java.util.Map; import org.elasticsearch.common.collect.ImmutableMap; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.index.mapper.FieldMapper; import org.elasticsearch.search.SearchParseElement; import org.elasticsearch.search.SearchParseException; import org.elasticsearch.search.fetch.FetchPhase; import org.elasticsearch.search.fetch.explain.ExplainParseElement; import org.elasticsearch.search.query.QueryPhase; import crate.elasticsearch.action.searchinto.SearchIntoContext;
package crate.elasticsearch.action.searchinto.parser; /** * Parser for payload given to _search_into action. */ public class SearchIntoParser extends AbstractSearchIntoParser implements ISearchIntoParser { private final ImmutableMap<String, SearchParseElement> elementParsers; @Inject public SearchIntoParser(QueryPhase queryPhase, FetchPhase fetchPhase) { Map<String, SearchParseElement> elementParsers = new HashMap<String, SearchParseElement>(); elementParsers.putAll(queryPhase.parseElements()); elementParsers.put("fields", new FieldsParseElement()); elementParsers.put("targetNodes", new TargetNodesParseElement()); elementParsers.put("explain", new ExplainParseElement()); this.elementParsers = ImmutableMap.copyOf(elementParsers); } @Override
// Path: src/main/java/crate/elasticsearch/action/searchinto/SearchIntoContext.java // public class SearchIntoContext extends SearchContext { // // // currently we only support index targets // private String targetType = "index"; // // private List<InetSocketTransportAddress> targetNodes; // // // public Map<String, String> outputNames() { // return outputNames; // } // // private final Map<String, String> outputNames = new HashMap<String, // String>(); // // public SearchIntoContext(long id, ShardSearchRequest request, // SearchShardTarget shardTarget, Engine.Searcher engineSearcher, // IndexService indexService, IndexShard indexShard, // ScriptService scriptService, CacheRecycler cacheRecycler) { // super(id, request, shardTarget, engineSearcher, indexService, // indexShard, scriptService, cacheRecycler); // } // // public String targetType() { // // this is currently the only type supported // return targetType; // } // // public List<InetSocketTransportAddress> targetNodes() { // if (targetNodes == null) { // targetNodes = Lists.newArrayList(); // } // return targetNodes; // } // // public void emptyTargetNodes() { // this.targetNodes = ImmutableList.of(); // } // // } // Path: src/main/java/crate/elasticsearch/action/searchinto/parser/SearchIntoParser.java import java.util.HashMap; import java.util.Map; import org.elasticsearch.common.collect.ImmutableMap; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.index.mapper.FieldMapper; import org.elasticsearch.search.SearchParseElement; import org.elasticsearch.search.SearchParseException; import org.elasticsearch.search.fetch.FetchPhase; import org.elasticsearch.search.fetch.explain.ExplainParseElement; import org.elasticsearch.search.query.QueryPhase; import crate.elasticsearch.action.searchinto.SearchIntoContext; package crate.elasticsearch.action.searchinto.parser; /** * Parser for payload given to _search_into action. */ public class SearchIntoParser extends AbstractSearchIntoParser implements ISearchIntoParser { private final ImmutableMap<String, SearchParseElement> elementParsers; @Inject public SearchIntoParser(QueryPhase queryPhase, FetchPhase fetchPhase) { Map<String, SearchParseElement> elementParsers = new HashMap<String, SearchParseElement>(); elementParsers.putAll(queryPhase.parseElements()); elementParsers.put("fields", new FieldsParseElement()); elementParsers.put("targetNodes", new TargetNodesParseElement()); elementParsers.put("explain", new ExplainParseElement()); this.elementParsers = ImmutableMap.copyOf(elementParsers); } @Override
protected void validate(SearchIntoContext context) {
crate/elasticsearch-inout-plugin
src/main/java/crate/elasticsearch/action/searchinto/TransportSearchIntoAction.java
// Path: src/main/java/crate/elasticsearch/action/searchinto/parser/SearchIntoParser.java // public class SearchIntoParser extends AbstractSearchIntoParser implements ISearchIntoParser { // // private final ImmutableMap<String, SearchParseElement> elementParsers; // // @Inject // public SearchIntoParser(QueryPhase queryPhase, FetchPhase fetchPhase) { // Map<String, SearchParseElement> elementParsers = new HashMap<String, // SearchParseElement>(); // elementParsers.putAll(queryPhase.parseElements()); // elementParsers.put("fields", new FieldsParseElement()); // elementParsers.put("targetNodes", new TargetNodesParseElement()); // elementParsers.put("explain", new ExplainParseElement()); // this.elementParsers = ImmutableMap.copyOf(elementParsers); // } // // @Override // protected void validate(SearchIntoContext context) { // if (!context.hasFieldNames()) { // throw new SearchParseException(context, "No fields defined"); // } // // for (String field : context.fieldNames()) { // FieldMapper<?> mapper = context.mapperService().smartNameFieldMapper( // field); // if (mapper == null && !field.equals( // "_version") && !field.startsWith( // FieldsParseElement.SCRIPT_FIELD_PREFIX)) { // throw new SearchParseException(context, // "SearchInto field [" + field + "] does not exist in " + // "the mapping"); // } // } // super.validate(context); // } // // @Override // protected ImmutableMap<String, SearchParseElement> getElementParsers() { // return elementParsers; // } // // // }
import org.elasticsearch.cache.recycler.CacheRecycler; import org.elasticsearch.cluster.ClusterService; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.indices.IndicesService; import org.elasticsearch.script.ScriptService; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.TransportService; import crate.elasticsearch.action.searchinto.parser.SearchIntoParser; import crate.elasticsearch.searchinto.Writer;
package crate.elasticsearch.action.searchinto; /** * */ public class TransportSearchIntoAction extends AbstractTransportSearchIntoAction { @Inject public TransportSearchIntoAction(Settings settings, ThreadPool threadPool, ClusterService clusterService, TransportService transportService, CacheRecycler cacheRecycler, IndicesService indicesService, ScriptService scriptService,
// Path: src/main/java/crate/elasticsearch/action/searchinto/parser/SearchIntoParser.java // public class SearchIntoParser extends AbstractSearchIntoParser implements ISearchIntoParser { // // private final ImmutableMap<String, SearchParseElement> elementParsers; // // @Inject // public SearchIntoParser(QueryPhase queryPhase, FetchPhase fetchPhase) { // Map<String, SearchParseElement> elementParsers = new HashMap<String, // SearchParseElement>(); // elementParsers.putAll(queryPhase.parseElements()); // elementParsers.put("fields", new FieldsParseElement()); // elementParsers.put("targetNodes", new TargetNodesParseElement()); // elementParsers.put("explain", new ExplainParseElement()); // this.elementParsers = ImmutableMap.copyOf(elementParsers); // } // // @Override // protected void validate(SearchIntoContext context) { // if (!context.hasFieldNames()) { // throw new SearchParseException(context, "No fields defined"); // } // // for (String field : context.fieldNames()) { // FieldMapper<?> mapper = context.mapperService().smartNameFieldMapper( // field); // if (mapper == null && !field.equals( // "_version") && !field.startsWith( // FieldsParseElement.SCRIPT_FIELD_PREFIX)) { // throw new SearchParseException(context, // "SearchInto field [" + field + "] does not exist in " + // "the mapping"); // } // } // super.validate(context); // } // // @Override // protected ImmutableMap<String, SearchParseElement> getElementParsers() { // return elementParsers; // } // // // } // Path: src/main/java/crate/elasticsearch/action/searchinto/TransportSearchIntoAction.java import org.elasticsearch.cache.recycler.CacheRecycler; import org.elasticsearch.cluster.ClusterService; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.indices.IndicesService; import org.elasticsearch.script.ScriptService; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.TransportService; import crate.elasticsearch.action.searchinto.parser.SearchIntoParser; import crate.elasticsearch.searchinto.Writer; package crate.elasticsearch.action.searchinto; /** * */ public class TransportSearchIntoAction extends AbstractTransportSearchIntoAction { @Inject public TransportSearchIntoAction(Settings settings, ThreadPool threadPool, ClusterService clusterService, TransportService transportService, CacheRecycler cacheRecycler, IndicesService indicesService, ScriptService scriptService,
SearchIntoParser parser, Writer writer) {
crate/elasticsearch-inout-plugin
src/main/java/crate/elasticsearch/action/export/ExportContext.java
// Path: src/main/java/crate/elasticsearch/export/OutputFile.java // public class OutputFile extends Output { // // private Result result; // private final String path; // private OutputStream os; // private final boolean overwrite; // private final boolean compression; // // public OutputFile(String path, boolean overwrite, boolean compression) { // this.path = path; // this.overwrite = overwrite; // this.compression = compression; // } // // @Override // public void open() throws IOException { // File outFile = new File(path); // if (!overwrite && outFile.exists()){ // throw new IOException("File exists: " + path); // } // os = new FileOutputStream(outFile); // if (compression) { // os = new GZIPOutputStream(os); // } // } // // @Override // public void close() throws IOException { // result = new Result(); // if (os != null) { // os.close(); // result.exit = 0; // } else { // result.exit = 1; // } // os = null; // } // // @Override // public OutputStream getOutputStream() { // return os; // } // // @Override // public Result result() { // return result; // } // }
import crate.elasticsearch.export.Output; import crate.elasticsearch.export.OutputCommand; import crate.elasticsearch.export.OutputFile; import org.elasticsearch.cache.recycler.CacheRecycler; import org.elasticsearch.cluster.ClusterName; import org.elasticsearch.index.engine.Engine; import org.elasticsearch.index.service.IndexService; import org.elasticsearch.index.shard.service.IndexShard; import org.elasticsearch.script.ScriptService; import org.elasticsearch.search.SearchShardTarget; import org.elasticsearch.search.internal.SearchContext; import org.elasticsearch.search.internal.ShardSearchRequest; import java.io.File; import java.util.ArrayList; import java.util.List;
for (String part : templateArray) { ret.add(applyVars(part)); } return ret; } /** * Replaces variable placeholder with actual value * * @param template * @return */ private String applyVars(String template) { template = template.replace(VAR_SHARD, String.valueOf(indexShard().shardId().getId())); template = template.replace(VAR_INDEX, indexShard().shardId().getIndex()); template = template.replace(VAR_CLUSTER, clusterName()); return template; } /** * Method to retrieve name of cluster * * @return name of cluster */ private String clusterName() { return ClusterName.clusterNameFromSettings(this.indexShard().indexSettings()).value(); } public Output createOutput() { if (outputFile()!=null){
// Path: src/main/java/crate/elasticsearch/export/OutputFile.java // public class OutputFile extends Output { // // private Result result; // private final String path; // private OutputStream os; // private final boolean overwrite; // private final boolean compression; // // public OutputFile(String path, boolean overwrite, boolean compression) { // this.path = path; // this.overwrite = overwrite; // this.compression = compression; // } // // @Override // public void open() throws IOException { // File outFile = new File(path); // if (!overwrite && outFile.exists()){ // throw new IOException("File exists: " + path); // } // os = new FileOutputStream(outFile); // if (compression) { // os = new GZIPOutputStream(os); // } // } // // @Override // public void close() throws IOException { // result = new Result(); // if (os != null) { // os.close(); // result.exit = 0; // } else { // result.exit = 1; // } // os = null; // } // // @Override // public OutputStream getOutputStream() { // return os; // } // // @Override // public Result result() { // return result; // } // } // Path: src/main/java/crate/elasticsearch/action/export/ExportContext.java import crate.elasticsearch.export.Output; import crate.elasticsearch.export.OutputCommand; import crate.elasticsearch.export.OutputFile; import org.elasticsearch.cache.recycler.CacheRecycler; import org.elasticsearch.cluster.ClusterName; import org.elasticsearch.index.engine.Engine; import org.elasticsearch.index.service.IndexService; import org.elasticsearch.index.shard.service.IndexShard; import org.elasticsearch.script.ScriptService; import org.elasticsearch.search.SearchShardTarget; import org.elasticsearch.search.internal.SearchContext; import org.elasticsearch.search.internal.ShardSearchRequest; import java.io.File; import java.util.ArrayList; import java.util.List; for (String part : templateArray) { ret.add(applyVars(part)); } return ret; } /** * Replaces variable placeholder with actual value * * @param template * @return */ private String applyVars(String template) { template = template.replace(VAR_SHARD, String.valueOf(indexShard().shardId().getId())); template = template.replace(VAR_INDEX, indexShard().shardId().getIndex()); template = template.replace(VAR_CLUSTER, clusterName()); return template; } /** * Method to retrieve name of cluster * * @return name of cluster */ private String clusterName() { return ClusterName.clusterNameFromSettings(this.indexShard().indexSettings()).value(); } public Output createOutput() { if (outputFile()!=null){
return new OutputFile(outputFile(), forceOverride(), compression);
crate/elasticsearch-inout-plugin
src/main/java/crate/elasticsearch/action/export/parser/ExportOutputCmdParseElement.java
// Path: src/main/java/crate/elasticsearch/action/export/ExportContext.java // public class ExportContext extends SearchContext { // // private static final String VAR_SHARD = "${shard}"; // private static final String VAR_INDEX = "${index}"; // private static final String VAR_CLUSTER = "${cluster}"; // // private List<String> outputCmdArray; // private String outputCmd; // private String outputFile; // private boolean forceOverride = false; // private boolean compression; // private String nodePath; // private boolean mappings = false; // private boolean settings = false; // // public ExportContext(long id, ShardSearchRequest request, SearchShardTarget shardTarget, // Engine.Searcher engineSearcher, IndexService indexService, IndexShard indexShard, // ScriptService scriptService, CacheRecycler cacheRecycler, String nodePath) { // super(id, request, shardTarget, engineSearcher, indexService, indexShard, scriptService, cacheRecycler); // this.nodePath = nodePath; // } // // public List<String> outputCmdArray() { // return outputCmdArray; // } // // public void outputCmdArray(List<String> outputCmdArray) { // this.outputCmdArray = applyVars(outputCmdArray); // } // // public String outputCmd() { // return outputCmd; // } // // public void outputCmd(String outputCmd) { // this.outputCmd = applyVars(outputCmd); // } // // public String outputFile() { // return outputFile; // } // // public void outputFile(String outputFile) { // outputFile = applyVars(outputFile); // File outFile = new File(outputFile); // if (!outFile.isAbsolute() && nodePath != null) { // outputFile = new File(nodePath, outputFile).getAbsolutePath(); // } // this.outputFile = outputFile; // } // // public boolean mappings() { // return mappings; // } // // public void mappings(boolean mappings) { // this.mappings = mappings; // } // // public boolean settings() { // return settings; // } // // public void settings(boolean settings) { // this.settings = settings; // } // // public String nodePath() { // return nodePath; // } // // public boolean forceOverride() { // return forceOverride; // } // // public void forceOverride(boolean forceOverride) { // this.forceOverride = forceOverride; // } // // public void compression(boolean compression) { // this.compression = compression; // } // // public boolean compression() { // return this.compression; // } // // /** // * Replaces variable placeholder with actual value in all elements of templateArray // * // * @param templateArray // * @return // */ // private List<String> applyVars(List<String> templateArray) { // List<String> ret = new ArrayList<String>(); // for (String part : templateArray) { // ret.add(applyVars(part)); // } // return ret; // } // // /** // * Replaces variable placeholder with actual value // * // * @param template // * @return // */ // private String applyVars(String template) { // template = template.replace(VAR_SHARD, String.valueOf(indexShard().shardId().getId())); // template = template.replace(VAR_INDEX, indexShard().shardId().getIndex()); // template = template.replace(VAR_CLUSTER, clusterName()); // return template; // } // // /** // * Method to retrieve name of cluster // * // * @return name of cluster // */ // private String clusterName() { // return ClusterName.clusterNameFromSettings(this.indexShard().indexSettings()).value(); // } // // public Output createOutput() { // if (outputFile()!=null){ // return new OutputFile(outputFile(), forceOverride(), compression); // } else { // if (outputCmd()!=null){ // return new OutputCommand(outputCmd(), compression); // } else { // return new OutputCommand(outputCmdArray(), compression); // } // } // } // }
import crate.elasticsearch.action.export.ExportContext; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.search.SearchParseElement; import org.elasticsearch.search.internal.SearchContext; import java.util.ArrayList; import java.util.List;
package crate.elasticsearch.action.export.parser; /** * Parser for token ``output_cmd``. The value of the token might be a String * containing the command or an array containing the command and all * arguments as seperated parts. * <p/> * <pre> * "output_cmd": "gzip > /tmp/out" * * or * * "output_cmd": ["gzip", ">" "/tmp/out"] * </pre> */ public class ExportOutputCmdParseElement implements SearchParseElement { @Override public void parse(XContentParser parser, SearchContext context) throws Exception { XContentParser.Token token = parser.currentToken(); if (token.isValue()) {
// Path: src/main/java/crate/elasticsearch/action/export/ExportContext.java // public class ExportContext extends SearchContext { // // private static final String VAR_SHARD = "${shard}"; // private static final String VAR_INDEX = "${index}"; // private static final String VAR_CLUSTER = "${cluster}"; // // private List<String> outputCmdArray; // private String outputCmd; // private String outputFile; // private boolean forceOverride = false; // private boolean compression; // private String nodePath; // private boolean mappings = false; // private boolean settings = false; // // public ExportContext(long id, ShardSearchRequest request, SearchShardTarget shardTarget, // Engine.Searcher engineSearcher, IndexService indexService, IndexShard indexShard, // ScriptService scriptService, CacheRecycler cacheRecycler, String nodePath) { // super(id, request, shardTarget, engineSearcher, indexService, indexShard, scriptService, cacheRecycler); // this.nodePath = nodePath; // } // // public List<String> outputCmdArray() { // return outputCmdArray; // } // // public void outputCmdArray(List<String> outputCmdArray) { // this.outputCmdArray = applyVars(outputCmdArray); // } // // public String outputCmd() { // return outputCmd; // } // // public void outputCmd(String outputCmd) { // this.outputCmd = applyVars(outputCmd); // } // // public String outputFile() { // return outputFile; // } // // public void outputFile(String outputFile) { // outputFile = applyVars(outputFile); // File outFile = new File(outputFile); // if (!outFile.isAbsolute() && nodePath != null) { // outputFile = new File(nodePath, outputFile).getAbsolutePath(); // } // this.outputFile = outputFile; // } // // public boolean mappings() { // return mappings; // } // // public void mappings(boolean mappings) { // this.mappings = mappings; // } // // public boolean settings() { // return settings; // } // // public void settings(boolean settings) { // this.settings = settings; // } // // public String nodePath() { // return nodePath; // } // // public boolean forceOverride() { // return forceOverride; // } // // public void forceOverride(boolean forceOverride) { // this.forceOverride = forceOverride; // } // // public void compression(boolean compression) { // this.compression = compression; // } // // public boolean compression() { // return this.compression; // } // // /** // * Replaces variable placeholder with actual value in all elements of templateArray // * // * @param templateArray // * @return // */ // private List<String> applyVars(List<String> templateArray) { // List<String> ret = new ArrayList<String>(); // for (String part : templateArray) { // ret.add(applyVars(part)); // } // return ret; // } // // /** // * Replaces variable placeholder with actual value // * // * @param template // * @return // */ // private String applyVars(String template) { // template = template.replace(VAR_SHARD, String.valueOf(indexShard().shardId().getId())); // template = template.replace(VAR_INDEX, indexShard().shardId().getIndex()); // template = template.replace(VAR_CLUSTER, clusterName()); // return template; // } // // /** // * Method to retrieve name of cluster // * // * @return name of cluster // */ // private String clusterName() { // return ClusterName.clusterNameFromSettings(this.indexShard().indexSettings()).value(); // } // // public Output createOutput() { // if (outputFile()!=null){ // return new OutputFile(outputFile(), forceOverride(), compression); // } else { // if (outputCmd()!=null){ // return new OutputCommand(outputCmd(), compression); // } else { // return new OutputCommand(outputCmdArray(), compression); // } // } // } // } // Path: src/main/java/crate/elasticsearch/action/export/parser/ExportOutputCmdParseElement.java import crate.elasticsearch.action.export.ExportContext; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.search.SearchParseElement; import org.elasticsearch.search.internal.SearchContext; import java.util.ArrayList; import java.util.List; package crate.elasticsearch.action.export.parser; /** * Parser for token ``output_cmd``. The value of the token might be a String * containing the command or an array containing the command and all * arguments as seperated parts. * <p/> * <pre> * "output_cmd": "gzip > /tmp/out" * * or * * "output_cmd": ["gzip", ">" "/tmp/out"] * </pre> */ public class ExportOutputCmdParseElement implements SearchParseElement { @Override public void parse(XContentParser parser, SearchContext context) throws Exception { XContentParser.Token token = parser.currentToken(); if (token.isValue()) {
((ExportContext) context).outputCmd(parser.text());
crate/elasticsearch-inout-plugin
src/main/java/crate/elasticsearch/import_/Importer.java
// Path: src/main/java/crate/elasticsearch/action/import_/ImportContext.java // public class ImportContext { // // private String nodePath; // private boolean compression; // private String directory; // private Pattern file_pattern; // private boolean mappings = false; // private boolean settings = false; // // public ImportContext(String nodePath) { // this.nodePath = nodePath; // } // // public boolean compression() { // return compression; // } // // public void compression(boolean compression) { // this.compression = compression; // } // // public String directory() { // return directory; // } // // public void directory(String directory) { // File file = new File(directory); // if (!file.isAbsolute() && nodePath != null) { // file = new File(nodePath, directory); // directory = file.getAbsolutePath(); // } // this.directory = directory; // } // // public Pattern file_pattern() { // return file_pattern; // } // // public void file_pattern(Pattern file_pattern) { // this.file_pattern = file_pattern; // } // // public boolean mappings() { // return mappings; // } // // public void mappings(boolean mappings) { // this.mappings = mappings; // } // // public boolean settings() { // return settings; // } // // public void settings(boolean settings) { // this.settings = settings; // } // } // // Path: src/main/java/crate/elasticsearch/action/import_/NodeImportRequest.java // public class NodeImportRequest extends NodeOperationRequest { // // public static final int DEFAULT_BULK_SIZE = 10000; // // private BytesReference source; // private String index; // private String type; // // NodeImportRequest() { // } // // public NodeImportRequest(String nodeId, ImportRequest request) { // super(request, nodeId); // this.source = request.source(); // this.index = request.index(); // this.type = request.type(); // } // // @Override // public void readFrom(StreamInput in) throws IOException { // super.readFrom(in); // source = in.readBytesReference(); // index = in.readOptionalString(); // type = in.readOptionalString(); // } // // @Override // public void writeTo(StreamOutput out) throws IOException { // super.writeTo(out); // out.writeBytesReference(source); // out.writeOptionalString(index); // out.writeOptionalString(type); // } // // public BytesReference source() { // return source; // } // // public String index() { // return index; // } // // public String type() { // return type; // } // // public int bulkSize() { // return DEFAULT_BULK_SIZE; // } // }
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.GZIPInputStream; import org.elasticsearch.ElasticSearchException; import org.elasticsearch.ElasticSearchParseException; import org.elasticsearch.action.admin.cluster.state.ClusterStateRequest; import org.elasticsearch.action.admin.cluster.state.ClusterStateResponse; import org.elasticsearch.action.admin.indices.create.CreateIndexRequest; import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest; import org.elasticsearch.action.bulk.BulkProcessor; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.index.IndexRequest.OpType; import org.elasticsearch.client.Client; import org.elasticsearch.client.Requests; import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.common.collect.ImmutableMap; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.inject.Injector; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.settings.ImmutableSettings.Builder; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.ByteSizeUnit; import org.elasticsearch.common.unit.ByteSizeValue; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentParser.Token; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.index.VersionType; import org.elasticsearch.index.mapper.internal.IdFieldMapper; import org.elasticsearch.index.mapper.internal.IndexFieldMapper; import org.elasticsearch.index.mapper.internal.RoutingFieldMapper; import org.elasticsearch.index.mapper.internal.SourceFieldMapper; import org.elasticsearch.index.mapper.internal.TTLFieldMapper; import org.elasticsearch.index.mapper.internal.TimestampFieldMapper; import org.elasticsearch.index.mapper.internal.TypeFieldMapper; import org.elasticsearch.indices.IndexAlreadyExistsException; import org.elasticsearch.indices.IndexMissingException; import crate.elasticsearch.action.import_.ImportContext; import crate.elasticsearch.action.import_.NodeImportRequest;
package crate.elasticsearch.import_; public class Importer { private Client client; private final Injector injector; private final ByteSizeValue bulkByteSize = new ByteSizeValue(5, ByteSizeUnit.MB); private final TimeValue flushInterval = TimeValue.timeValueSeconds(5); private final int concurrentRequests = 4; @Inject public Importer(Injector injector) { this.injector = injector; }
// Path: src/main/java/crate/elasticsearch/action/import_/ImportContext.java // public class ImportContext { // // private String nodePath; // private boolean compression; // private String directory; // private Pattern file_pattern; // private boolean mappings = false; // private boolean settings = false; // // public ImportContext(String nodePath) { // this.nodePath = nodePath; // } // // public boolean compression() { // return compression; // } // // public void compression(boolean compression) { // this.compression = compression; // } // // public String directory() { // return directory; // } // // public void directory(String directory) { // File file = new File(directory); // if (!file.isAbsolute() && nodePath != null) { // file = new File(nodePath, directory); // directory = file.getAbsolutePath(); // } // this.directory = directory; // } // // public Pattern file_pattern() { // return file_pattern; // } // // public void file_pattern(Pattern file_pattern) { // this.file_pattern = file_pattern; // } // // public boolean mappings() { // return mappings; // } // // public void mappings(boolean mappings) { // this.mappings = mappings; // } // // public boolean settings() { // return settings; // } // // public void settings(boolean settings) { // this.settings = settings; // } // } // // Path: src/main/java/crate/elasticsearch/action/import_/NodeImportRequest.java // public class NodeImportRequest extends NodeOperationRequest { // // public static final int DEFAULT_BULK_SIZE = 10000; // // private BytesReference source; // private String index; // private String type; // // NodeImportRequest() { // } // // public NodeImportRequest(String nodeId, ImportRequest request) { // super(request, nodeId); // this.source = request.source(); // this.index = request.index(); // this.type = request.type(); // } // // @Override // public void readFrom(StreamInput in) throws IOException { // super.readFrom(in); // source = in.readBytesReference(); // index = in.readOptionalString(); // type = in.readOptionalString(); // } // // @Override // public void writeTo(StreamOutput out) throws IOException { // super.writeTo(out); // out.writeBytesReference(source); // out.writeOptionalString(index); // out.writeOptionalString(type); // } // // public BytesReference source() { // return source; // } // // public String index() { // return index; // } // // public String type() { // return type; // } // // public int bulkSize() { // return DEFAULT_BULK_SIZE; // } // } // Path: src/main/java/crate/elasticsearch/import_/Importer.java import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.GZIPInputStream; import org.elasticsearch.ElasticSearchException; import org.elasticsearch.ElasticSearchParseException; import org.elasticsearch.action.admin.cluster.state.ClusterStateRequest; import org.elasticsearch.action.admin.cluster.state.ClusterStateResponse; import org.elasticsearch.action.admin.indices.create.CreateIndexRequest; import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest; import org.elasticsearch.action.bulk.BulkProcessor; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.index.IndexRequest.OpType; import org.elasticsearch.client.Client; import org.elasticsearch.client.Requests; import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.common.collect.ImmutableMap; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.inject.Injector; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.settings.ImmutableSettings.Builder; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.ByteSizeUnit; import org.elasticsearch.common.unit.ByteSizeValue; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentParser.Token; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.index.VersionType; import org.elasticsearch.index.mapper.internal.IdFieldMapper; import org.elasticsearch.index.mapper.internal.IndexFieldMapper; import org.elasticsearch.index.mapper.internal.RoutingFieldMapper; import org.elasticsearch.index.mapper.internal.SourceFieldMapper; import org.elasticsearch.index.mapper.internal.TTLFieldMapper; import org.elasticsearch.index.mapper.internal.TimestampFieldMapper; import org.elasticsearch.index.mapper.internal.TypeFieldMapper; import org.elasticsearch.indices.IndexAlreadyExistsException; import org.elasticsearch.indices.IndexMissingException; import crate.elasticsearch.action.import_.ImportContext; import crate.elasticsearch.action.import_.NodeImportRequest; package crate.elasticsearch.import_; public class Importer { private Client client; private final Injector injector; private final ByteSizeValue bulkByteSize = new ByteSizeValue(5, ByteSizeUnit.MB); private final TimeValue flushInterval = TimeValue.timeValueSeconds(5); private final int concurrentRequests = 4; @Inject public Importer(Injector injector) { this.injector = injector; }
public Result execute(ImportContext context, NodeImportRequest request) {
crate/elasticsearch-inout-plugin
src/main/java/crate/elasticsearch/import_/Importer.java
// Path: src/main/java/crate/elasticsearch/action/import_/ImportContext.java // public class ImportContext { // // private String nodePath; // private boolean compression; // private String directory; // private Pattern file_pattern; // private boolean mappings = false; // private boolean settings = false; // // public ImportContext(String nodePath) { // this.nodePath = nodePath; // } // // public boolean compression() { // return compression; // } // // public void compression(boolean compression) { // this.compression = compression; // } // // public String directory() { // return directory; // } // // public void directory(String directory) { // File file = new File(directory); // if (!file.isAbsolute() && nodePath != null) { // file = new File(nodePath, directory); // directory = file.getAbsolutePath(); // } // this.directory = directory; // } // // public Pattern file_pattern() { // return file_pattern; // } // // public void file_pattern(Pattern file_pattern) { // this.file_pattern = file_pattern; // } // // public boolean mappings() { // return mappings; // } // // public void mappings(boolean mappings) { // this.mappings = mappings; // } // // public boolean settings() { // return settings; // } // // public void settings(boolean settings) { // this.settings = settings; // } // } // // Path: src/main/java/crate/elasticsearch/action/import_/NodeImportRequest.java // public class NodeImportRequest extends NodeOperationRequest { // // public static final int DEFAULT_BULK_SIZE = 10000; // // private BytesReference source; // private String index; // private String type; // // NodeImportRequest() { // } // // public NodeImportRequest(String nodeId, ImportRequest request) { // super(request, nodeId); // this.source = request.source(); // this.index = request.index(); // this.type = request.type(); // } // // @Override // public void readFrom(StreamInput in) throws IOException { // super.readFrom(in); // source = in.readBytesReference(); // index = in.readOptionalString(); // type = in.readOptionalString(); // } // // @Override // public void writeTo(StreamOutput out) throws IOException { // super.writeTo(out); // out.writeBytesReference(source); // out.writeOptionalString(index); // out.writeOptionalString(type); // } // // public BytesReference source() { // return source; // } // // public String index() { // return index; // } // // public String type() { // return type; // } // // public int bulkSize() { // return DEFAULT_BULK_SIZE; // } // }
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.GZIPInputStream; import org.elasticsearch.ElasticSearchException; import org.elasticsearch.ElasticSearchParseException; import org.elasticsearch.action.admin.cluster.state.ClusterStateRequest; import org.elasticsearch.action.admin.cluster.state.ClusterStateResponse; import org.elasticsearch.action.admin.indices.create.CreateIndexRequest; import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest; import org.elasticsearch.action.bulk.BulkProcessor; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.index.IndexRequest.OpType; import org.elasticsearch.client.Client; import org.elasticsearch.client.Requests; import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.common.collect.ImmutableMap; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.inject.Injector; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.settings.ImmutableSettings.Builder; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.ByteSizeUnit; import org.elasticsearch.common.unit.ByteSizeValue; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentParser.Token; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.index.VersionType; import org.elasticsearch.index.mapper.internal.IdFieldMapper; import org.elasticsearch.index.mapper.internal.IndexFieldMapper; import org.elasticsearch.index.mapper.internal.RoutingFieldMapper; import org.elasticsearch.index.mapper.internal.SourceFieldMapper; import org.elasticsearch.index.mapper.internal.TTLFieldMapper; import org.elasticsearch.index.mapper.internal.TimestampFieldMapper; import org.elasticsearch.index.mapper.internal.TypeFieldMapper; import org.elasticsearch.indices.IndexAlreadyExistsException; import org.elasticsearch.indices.IndexMissingException; import crate.elasticsearch.action.import_.ImportContext; import crate.elasticsearch.action.import_.NodeImportRequest;
package crate.elasticsearch.import_; public class Importer { private Client client; private final Injector injector; private final ByteSizeValue bulkByteSize = new ByteSizeValue(5, ByteSizeUnit.MB); private final TimeValue flushInterval = TimeValue.timeValueSeconds(5); private final int concurrentRequests = 4; @Inject public Importer(Injector injector) { this.injector = injector; }
// Path: src/main/java/crate/elasticsearch/action/import_/ImportContext.java // public class ImportContext { // // private String nodePath; // private boolean compression; // private String directory; // private Pattern file_pattern; // private boolean mappings = false; // private boolean settings = false; // // public ImportContext(String nodePath) { // this.nodePath = nodePath; // } // // public boolean compression() { // return compression; // } // // public void compression(boolean compression) { // this.compression = compression; // } // // public String directory() { // return directory; // } // // public void directory(String directory) { // File file = new File(directory); // if (!file.isAbsolute() && nodePath != null) { // file = new File(nodePath, directory); // directory = file.getAbsolutePath(); // } // this.directory = directory; // } // // public Pattern file_pattern() { // return file_pattern; // } // // public void file_pattern(Pattern file_pattern) { // this.file_pattern = file_pattern; // } // // public boolean mappings() { // return mappings; // } // // public void mappings(boolean mappings) { // this.mappings = mappings; // } // // public boolean settings() { // return settings; // } // // public void settings(boolean settings) { // this.settings = settings; // } // } // // Path: src/main/java/crate/elasticsearch/action/import_/NodeImportRequest.java // public class NodeImportRequest extends NodeOperationRequest { // // public static final int DEFAULT_BULK_SIZE = 10000; // // private BytesReference source; // private String index; // private String type; // // NodeImportRequest() { // } // // public NodeImportRequest(String nodeId, ImportRequest request) { // super(request, nodeId); // this.source = request.source(); // this.index = request.index(); // this.type = request.type(); // } // // @Override // public void readFrom(StreamInput in) throws IOException { // super.readFrom(in); // source = in.readBytesReference(); // index = in.readOptionalString(); // type = in.readOptionalString(); // } // // @Override // public void writeTo(StreamOutput out) throws IOException { // super.writeTo(out); // out.writeBytesReference(source); // out.writeOptionalString(index); // out.writeOptionalString(type); // } // // public BytesReference source() { // return source; // } // // public String index() { // return index; // } // // public String type() { // return type; // } // // public int bulkSize() { // return DEFAULT_BULK_SIZE; // } // } // Path: src/main/java/crate/elasticsearch/import_/Importer.java import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.GZIPInputStream; import org.elasticsearch.ElasticSearchException; import org.elasticsearch.ElasticSearchParseException; import org.elasticsearch.action.admin.cluster.state.ClusterStateRequest; import org.elasticsearch.action.admin.cluster.state.ClusterStateResponse; import org.elasticsearch.action.admin.indices.create.CreateIndexRequest; import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest; import org.elasticsearch.action.bulk.BulkProcessor; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.index.IndexRequest.OpType; import org.elasticsearch.client.Client; import org.elasticsearch.client.Requests; import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.common.collect.ImmutableMap; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.inject.Injector; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.settings.ImmutableSettings.Builder; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.ByteSizeUnit; import org.elasticsearch.common.unit.ByteSizeValue; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentParser.Token; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.index.VersionType; import org.elasticsearch.index.mapper.internal.IdFieldMapper; import org.elasticsearch.index.mapper.internal.IndexFieldMapper; import org.elasticsearch.index.mapper.internal.RoutingFieldMapper; import org.elasticsearch.index.mapper.internal.SourceFieldMapper; import org.elasticsearch.index.mapper.internal.TTLFieldMapper; import org.elasticsearch.index.mapper.internal.TimestampFieldMapper; import org.elasticsearch.index.mapper.internal.TypeFieldMapper; import org.elasticsearch.indices.IndexAlreadyExistsException; import org.elasticsearch.indices.IndexMissingException; import crate.elasticsearch.action.import_.ImportContext; import crate.elasticsearch.action.import_.NodeImportRequest; package crate.elasticsearch.import_; public class Importer { private Client client; private final Injector injector; private final ByteSizeValue bulkByteSize = new ByteSizeValue(5, ByteSizeUnit.MB); private final TimeValue flushInterval = TimeValue.timeValueSeconds(5); private final int concurrentRequests = 4; @Inject public Importer(Injector injector) { this.injector = injector; }
public Result execute(ImportContext context, NodeImportRequest request) {
crate/elasticsearch-inout-plugin
src/main/java/crate/elasticsearch/action/import_/parser/ImportParseException.java
// Path: src/main/java/crate/elasticsearch/action/import_/ImportContext.java // public class ImportContext { // // private String nodePath; // private boolean compression; // private String directory; // private Pattern file_pattern; // private boolean mappings = false; // private boolean settings = false; // // public ImportContext(String nodePath) { // this.nodePath = nodePath; // } // // public boolean compression() { // return compression; // } // // public void compression(boolean compression) { // this.compression = compression; // } // // public String directory() { // return directory; // } // // public void directory(String directory) { // File file = new File(directory); // if (!file.isAbsolute() && nodePath != null) { // file = new File(nodePath, directory); // directory = file.getAbsolutePath(); // } // this.directory = directory; // } // // public Pattern file_pattern() { // return file_pattern; // } // // public void file_pattern(Pattern file_pattern) { // this.file_pattern = file_pattern; // } // // public boolean mappings() { // return mappings; // } // // public void mappings(boolean mappings) { // this.mappings = mappings; // } // // public boolean settings() { // return settings; // } // // public void settings(boolean settings) { // this.settings = settings; // } // }
import org.elasticsearch.ElasticSearchException; import crate.elasticsearch.action.import_.ImportContext;
package crate.elasticsearch.action.import_.parser; public class ImportParseException extends ElasticSearchException { private static final long serialVersionUID = 910205724931139923L;
// Path: src/main/java/crate/elasticsearch/action/import_/ImportContext.java // public class ImportContext { // // private String nodePath; // private boolean compression; // private String directory; // private Pattern file_pattern; // private boolean mappings = false; // private boolean settings = false; // // public ImportContext(String nodePath) { // this.nodePath = nodePath; // } // // public boolean compression() { // return compression; // } // // public void compression(boolean compression) { // this.compression = compression; // } // // public String directory() { // return directory; // } // // public void directory(String directory) { // File file = new File(directory); // if (!file.isAbsolute() && nodePath != null) { // file = new File(nodePath, directory); // directory = file.getAbsolutePath(); // } // this.directory = directory; // } // // public Pattern file_pattern() { // return file_pattern; // } // // public void file_pattern(Pattern file_pattern) { // this.file_pattern = file_pattern; // } // // public boolean mappings() { // return mappings; // } // // public void mappings(boolean mappings) { // this.mappings = mappings; // } // // public boolean settings() { // return settings; // } // // public void settings(boolean settings) { // this.settings = settings; // } // } // Path: src/main/java/crate/elasticsearch/action/import_/parser/ImportParseException.java import org.elasticsearch.ElasticSearchException; import crate.elasticsearch.action.import_.ImportContext; package crate.elasticsearch.action.import_.parser; public class ImportParseException extends ElasticSearchException { private static final long serialVersionUID = 910205724931139923L;
public ImportParseException(ImportContext context, String msg) {
crate/elasticsearch-inout-plugin
src/main/java/crate/elasticsearch/action/restore/parser/RestoreParser.java
// Path: src/main/java/crate/elasticsearch/action/import_/ImportContext.java // public class ImportContext { // // private String nodePath; // private boolean compression; // private String directory; // private Pattern file_pattern; // private boolean mappings = false; // private boolean settings = false; // // public ImportContext(String nodePath) { // this.nodePath = nodePath; // } // // public boolean compression() { // return compression; // } // // public void compression(boolean compression) { // this.compression = compression; // } // // public String directory() { // return directory; // } // // public void directory(String directory) { // File file = new File(directory); // if (!file.isAbsolute() && nodePath != null) { // file = new File(nodePath, directory); // directory = file.getAbsolutePath(); // } // this.directory = directory; // } // // public Pattern file_pattern() { // return file_pattern; // } // // public void file_pattern(Pattern file_pattern) { // this.file_pattern = file_pattern; // } // // public boolean mappings() { // return mappings; // } // // public void mappings(boolean mappings) { // this.mappings = mappings; // } // // public boolean settings() { // return settings; // } // // public void settings(boolean settings) { // this.settings = settings; // } // } // // Path: src/main/java/crate/elasticsearch/action/import_/parser/ImportParseException.java // public class ImportParseException extends ElasticSearchException { // // private static final long serialVersionUID = 910205724931139923L; // // public ImportParseException(ImportContext context, String msg) { // super("Parse Failure [" + msg + "]"); // } // // public ImportParseException(ImportContext context, String msg, Throwable cause) { // super("Parse Failure [" + msg + "]", cause); // } // }
import crate.elasticsearch.action.dump.parser.DumpParser; import crate.elasticsearch.action.import_.ImportContext; import crate.elasticsearch.action.import_.parser.DirectoryParseElement; import crate.elasticsearch.action.import_.parser.IImportParser; import crate.elasticsearch.action.import_.parser.ImportParseElement; import crate.elasticsearch.action.import_.parser.ImportParseException; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.collect.ImmutableMap; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentHelper; import org.elasticsearch.common.xcontent.XContentParser; import java.util.HashMap; import java.util.Map; import java.util.regex.Pattern;
package crate.elasticsearch.action.restore.parser; public class RestoreParser implements IImportParser { private final ImmutableMap<String, ImportParseElement> elementParsers; public static final String FILE_PATTERN = ".*_.*_.*\\.json\\.gz"; public RestoreParser() { Map<String, ImportParseElement> elementParsers = new HashMap<String, ImportParseElement>(); elementParsers.put("directory", new DirectoryParseElement()); this.elementParsers = ImmutableMap.copyOf(elementParsers); } /** * Main method of this class to parse given payload of _restore action * * @param context * @param source * @throws org.elasticsearch.search.SearchParseException */
// Path: src/main/java/crate/elasticsearch/action/import_/ImportContext.java // public class ImportContext { // // private String nodePath; // private boolean compression; // private String directory; // private Pattern file_pattern; // private boolean mappings = false; // private boolean settings = false; // // public ImportContext(String nodePath) { // this.nodePath = nodePath; // } // // public boolean compression() { // return compression; // } // // public void compression(boolean compression) { // this.compression = compression; // } // // public String directory() { // return directory; // } // // public void directory(String directory) { // File file = new File(directory); // if (!file.isAbsolute() && nodePath != null) { // file = new File(nodePath, directory); // directory = file.getAbsolutePath(); // } // this.directory = directory; // } // // public Pattern file_pattern() { // return file_pattern; // } // // public void file_pattern(Pattern file_pattern) { // this.file_pattern = file_pattern; // } // // public boolean mappings() { // return mappings; // } // // public void mappings(boolean mappings) { // this.mappings = mappings; // } // // public boolean settings() { // return settings; // } // // public void settings(boolean settings) { // this.settings = settings; // } // } // // Path: src/main/java/crate/elasticsearch/action/import_/parser/ImportParseException.java // public class ImportParseException extends ElasticSearchException { // // private static final long serialVersionUID = 910205724931139923L; // // public ImportParseException(ImportContext context, String msg) { // super("Parse Failure [" + msg + "]"); // } // // public ImportParseException(ImportContext context, String msg, Throwable cause) { // super("Parse Failure [" + msg + "]", cause); // } // } // Path: src/main/java/crate/elasticsearch/action/restore/parser/RestoreParser.java import crate.elasticsearch.action.dump.parser.DumpParser; import crate.elasticsearch.action.import_.ImportContext; import crate.elasticsearch.action.import_.parser.DirectoryParseElement; import crate.elasticsearch.action.import_.parser.IImportParser; import crate.elasticsearch.action.import_.parser.ImportParseElement; import crate.elasticsearch.action.import_.parser.ImportParseException; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.collect.ImmutableMap; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentHelper; import org.elasticsearch.common.xcontent.XContentParser; import java.util.HashMap; import java.util.Map; import java.util.regex.Pattern; package crate.elasticsearch.action.restore.parser; public class RestoreParser implements IImportParser { private final ImmutableMap<String, ImportParseElement> elementParsers; public static final String FILE_PATTERN = ".*_.*_.*\\.json\\.gz"; public RestoreParser() { Map<String, ImportParseElement> elementParsers = new HashMap<String, ImportParseElement>(); elementParsers.put("directory", new DirectoryParseElement()); this.elementParsers = ImmutableMap.copyOf(elementParsers); } /** * Main method of this class to parse given payload of _restore action * * @param context * @param source * @throws org.elasticsearch.search.SearchParseException */
public void parseSource(ImportContext context, BytesReference source) throws ImportParseException {
crate/elasticsearch-inout-plugin
src/main/java/crate/elasticsearch/action/restore/parser/RestoreParser.java
// Path: src/main/java/crate/elasticsearch/action/import_/ImportContext.java // public class ImportContext { // // private String nodePath; // private boolean compression; // private String directory; // private Pattern file_pattern; // private boolean mappings = false; // private boolean settings = false; // // public ImportContext(String nodePath) { // this.nodePath = nodePath; // } // // public boolean compression() { // return compression; // } // // public void compression(boolean compression) { // this.compression = compression; // } // // public String directory() { // return directory; // } // // public void directory(String directory) { // File file = new File(directory); // if (!file.isAbsolute() && nodePath != null) { // file = new File(nodePath, directory); // directory = file.getAbsolutePath(); // } // this.directory = directory; // } // // public Pattern file_pattern() { // return file_pattern; // } // // public void file_pattern(Pattern file_pattern) { // this.file_pattern = file_pattern; // } // // public boolean mappings() { // return mappings; // } // // public void mappings(boolean mappings) { // this.mappings = mappings; // } // // public boolean settings() { // return settings; // } // // public void settings(boolean settings) { // this.settings = settings; // } // } // // Path: src/main/java/crate/elasticsearch/action/import_/parser/ImportParseException.java // public class ImportParseException extends ElasticSearchException { // // private static final long serialVersionUID = 910205724931139923L; // // public ImportParseException(ImportContext context, String msg) { // super("Parse Failure [" + msg + "]"); // } // // public ImportParseException(ImportContext context, String msg, Throwable cause) { // super("Parse Failure [" + msg + "]", cause); // } // }
import crate.elasticsearch.action.dump.parser.DumpParser; import crate.elasticsearch.action.import_.ImportContext; import crate.elasticsearch.action.import_.parser.DirectoryParseElement; import crate.elasticsearch.action.import_.parser.IImportParser; import crate.elasticsearch.action.import_.parser.ImportParseElement; import crate.elasticsearch.action.import_.parser.ImportParseException; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.collect.ImmutableMap; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentHelper; import org.elasticsearch.common.xcontent.XContentParser; import java.util.HashMap; import java.util.Map; import java.util.regex.Pattern;
package crate.elasticsearch.action.restore.parser; public class RestoreParser implements IImportParser { private final ImmutableMap<String, ImportParseElement> elementParsers; public static final String FILE_PATTERN = ".*_.*_.*\\.json\\.gz"; public RestoreParser() { Map<String, ImportParseElement> elementParsers = new HashMap<String, ImportParseElement>(); elementParsers.put("directory", new DirectoryParseElement()); this.elementParsers = ImmutableMap.copyOf(elementParsers); } /** * Main method of this class to parse given payload of _restore action * * @param context * @param source * @throws org.elasticsearch.search.SearchParseException */
// Path: src/main/java/crate/elasticsearch/action/import_/ImportContext.java // public class ImportContext { // // private String nodePath; // private boolean compression; // private String directory; // private Pattern file_pattern; // private boolean mappings = false; // private boolean settings = false; // // public ImportContext(String nodePath) { // this.nodePath = nodePath; // } // // public boolean compression() { // return compression; // } // // public void compression(boolean compression) { // this.compression = compression; // } // // public String directory() { // return directory; // } // // public void directory(String directory) { // File file = new File(directory); // if (!file.isAbsolute() && nodePath != null) { // file = new File(nodePath, directory); // directory = file.getAbsolutePath(); // } // this.directory = directory; // } // // public Pattern file_pattern() { // return file_pattern; // } // // public void file_pattern(Pattern file_pattern) { // this.file_pattern = file_pattern; // } // // public boolean mappings() { // return mappings; // } // // public void mappings(boolean mappings) { // this.mappings = mappings; // } // // public boolean settings() { // return settings; // } // // public void settings(boolean settings) { // this.settings = settings; // } // } // // Path: src/main/java/crate/elasticsearch/action/import_/parser/ImportParseException.java // public class ImportParseException extends ElasticSearchException { // // private static final long serialVersionUID = 910205724931139923L; // // public ImportParseException(ImportContext context, String msg) { // super("Parse Failure [" + msg + "]"); // } // // public ImportParseException(ImportContext context, String msg, Throwable cause) { // super("Parse Failure [" + msg + "]", cause); // } // } // Path: src/main/java/crate/elasticsearch/action/restore/parser/RestoreParser.java import crate.elasticsearch.action.dump.parser.DumpParser; import crate.elasticsearch.action.import_.ImportContext; import crate.elasticsearch.action.import_.parser.DirectoryParseElement; import crate.elasticsearch.action.import_.parser.IImportParser; import crate.elasticsearch.action.import_.parser.ImportParseElement; import crate.elasticsearch.action.import_.parser.ImportParseException; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.collect.ImmutableMap; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentHelper; import org.elasticsearch.common.xcontent.XContentParser; import java.util.HashMap; import java.util.Map; import java.util.regex.Pattern; package crate.elasticsearch.action.restore.parser; public class RestoreParser implements IImportParser { private final ImmutableMap<String, ImportParseElement> elementParsers; public static final String FILE_PATTERN = ".*_.*_.*\\.json\\.gz"; public RestoreParser() { Map<String, ImportParseElement> elementParsers = new HashMap<String, ImportParseElement>(); elementParsers.put("directory", new DirectoryParseElement()); this.elementParsers = ImmutableMap.copyOf(elementParsers); } /** * Main method of this class to parse given payload of _restore action * * @param context * @param source * @throws org.elasticsearch.search.SearchParseException */
public void parseSource(ImportContext context, BytesReference source) throws ImportParseException {
crate/elasticsearch-inout-plugin
src/main/java/crate/elasticsearch/action/searchinto/parser/TargetNodesParseElement.java
// Path: src/main/java/crate/elasticsearch/action/searchinto/SearchIntoContext.java // public class SearchIntoContext extends SearchContext { // // // currently we only support index targets // private String targetType = "index"; // // private List<InetSocketTransportAddress> targetNodes; // // // public Map<String, String> outputNames() { // return outputNames; // } // // private final Map<String, String> outputNames = new HashMap<String, // String>(); // // public SearchIntoContext(long id, ShardSearchRequest request, // SearchShardTarget shardTarget, Engine.Searcher engineSearcher, // IndexService indexService, IndexShard indexShard, // ScriptService scriptService, CacheRecycler cacheRecycler) { // super(id, request, shardTarget, engineSearcher, indexService, // indexShard, scriptService, cacheRecycler); // } // // public String targetType() { // // this is currently the only type supported // return targetType; // } // // public List<InetSocketTransportAddress> targetNodes() { // if (targetNodes == null) { // targetNodes = Lists.newArrayList(); // } // return targetNodes; // } // // public void emptyTargetNodes() { // this.targetNodes = ImmutableList.of(); // } // // }
import crate.elasticsearch.action.searchinto.SearchIntoContext; import org.elasticsearch.common.transport.InetSocketTransportAddress; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.search.SearchParseElement; import org.elasticsearch.search.internal.SearchContext; import java.util.regex.Matcher; import java.util.regex.Pattern;
package crate.elasticsearch.action.searchinto.parser; /** * parses the targetNode field which looks like * <p/> * "targetNode": ["host:9300", "host:9301"] * <p/> * or * <p/> * "targetNode": "host:9300" * */ public class TargetNodesParseElement implements SearchParseElement { private Pattern PATTERN = Pattern.compile("^\\s*(.*?):(\\d+)\\s*$"); @Override public void parse(XContentParser parser, SearchContext context) throws Exception { XContentParser.Token token = parser.currentToken(); if (token == XContentParser.Token.START_ARRAY) { boolean added = false;
// Path: src/main/java/crate/elasticsearch/action/searchinto/SearchIntoContext.java // public class SearchIntoContext extends SearchContext { // // // currently we only support index targets // private String targetType = "index"; // // private List<InetSocketTransportAddress> targetNodes; // // // public Map<String, String> outputNames() { // return outputNames; // } // // private final Map<String, String> outputNames = new HashMap<String, // String>(); // // public SearchIntoContext(long id, ShardSearchRequest request, // SearchShardTarget shardTarget, Engine.Searcher engineSearcher, // IndexService indexService, IndexShard indexShard, // ScriptService scriptService, CacheRecycler cacheRecycler) { // super(id, request, shardTarget, engineSearcher, indexService, // indexShard, scriptService, cacheRecycler); // } // // public String targetType() { // // this is currently the only type supported // return targetType; // } // // public List<InetSocketTransportAddress> targetNodes() { // if (targetNodes == null) { // targetNodes = Lists.newArrayList(); // } // return targetNodes; // } // // public void emptyTargetNodes() { // this.targetNodes = ImmutableList.of(); // } // // } // Path: src/main/java/crate/elasticsearch/action/searchinto/parser/TargetNodesParseElement.java import crate.elasticsearch.action.searchinto.SearchIntoContext; import org.elasticsearch.common.transport.InetSocketTransportAddress; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.search.SearchParseElement; import org.elasticsearch.search.internal.SearchContext; import java.util.regex.Matcher; import java.util.regex.Pattern; package crate.elasticsearch.action.searchinto.parser; /** * parses the targetNode field which looks like * <p/> * "targetNode": ["host:9300", "host:9301"] * <p/> * or * <p/> * "targetNode": "host:9300" * */ public class TargetNodesParseElement implements SearchParseElement { private Pattern PATTERN = Pattern.compile("^\\s*(.*?):(\\d+)\\s*$"); @Override public void parse(XContentParser parser, SearchContext context) throws Exception { XContentParser.Token token = parser.currentToken(); if (token == XContentParser.Token.START_ARRAY) { boolean added = false;
SearchIntoContext ctx = (SearchIntoContext)context;
crate/elasticsearch-inout-plugin
src/main/java/crate/elasticsearch/action/import_/parser/ImportParser.java
// Path: src/main/java/crate/elasticsearch/action/import_/ImportContext.java // public class ImportContext { // // private String nodePath; // private boolean compression; // private String directory; // private Pattern file_pattern; // private boolean mappings = false; // private boolean settings = false; // // public ImportContext(String nodePath) { // this.nodePath = nodePath; // } // // public boolean compression() { // return compression; // } // // public void compression(boolean compression) { // this.compression = compression; // } // // public String directory() { // return directory; // } // // public void directory(String directory) { // File file = new File(directory); // if (!file.isAbsolute() && nodePath != null) { // file = new File(nodePath, directory); // directory = file.getAbsolutePath(); // } // this.directory = directory; // } // // public Pattern file_pattern() { // return file_pattern; // } // // public void file_pattern(Pattern file_pattern) { // this.file_pattern = file_pattern; // } // // public boolean mappings() { // return mappings; // } // // public void mappings(boolean mappings) { // this.mappings = mappings; // } // // public boolean settings() { // return settings; // } // // public void settings(boolean settings) { // this.settings = settings; // } // }
import java.util.HashMap; import java.util.Map; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.collect.ImmutableMap; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentHelper; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.search.SearchParseException; import crate.elasticsearch.action.import_.ImportContext;
package crate.elasticsearch.action.import_.parser; public class ImportParser implements IImportParser { private final ImmutableMap<String, ImportParseElement> elementParsers; public ImportParser() { Map<String, ImportParseElement> elementParsers = new HashMap<String, ImportParseElement>(); elementParsers.put("directory", new DirectoryParseElement()); elementParsers.put("compression", new ImportCompressionParseElement()); elementParsers.put("file_pattern", new FilePatternParseElement()); elementParsers.put("mappings", new ImportMappingsParseElement()); elementParsers.put("settings", new ImportSettingsParseElement()); this.elementParsers = ImmutableMap.copyOf(elementParsers); } /** * Main method of this class to parse given payload of _export action * * @param context * @param source * @throws SearchParseException */
// Path: src/main/java/crate/elasticsearch/action/import_/ImportContext.java // public class ImportContext { // // private String nodePath; // private boolean compression; // private String directory; // private Pattern file_pattern; // private boolean mappings = false; // private boolean settings = false; // // public ImportContext(String nodePath) { // this.nodePath = nodePath; // } // // public boolean compression() { // return compression; // } // // public void compression(boolean compression) { // this.compression = compression; // } // // public String directory() { // return directory; // } // // public void directory(String directory) { // File file = new File(directory); // if (!file.isAbsolute() && nodePath != null) { // file = new File(nodePath, directory); // directory = file.getAbsolutePath(); // } // this.directory = directory; // } // // public Pattern file_pattern() { // return file_pattern; // } // // public void file_pattern(Pattern file_pattern) { // this.file_pattern = file_pattern; // } // // public boolean mappings() { // return mappings; // } // // public void mappings(boolean mappings) { // this.mappings = mappings; // } // // public boolean settings() { // return settings; // } // // public void settings(boolean settings) { // this.settings = settings; // } // } // Path: src/main/java/crate/elasticsearch/action/import_/parser/ImportParser.java import java.util.HashMap; import java.util.Map; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.collect.ImmutableMap; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentHelper; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.search.SearchParseException; import crate.elasticsearch.action.import_.ImportContext; package crate.elasticsearch.action.import_.parser; public class ImportParser implements IImportParser { private final ImmutableMap<String, ImportParseElement> elementParsers; public ImportParser() { Map<String, ImportParseElement> elementParsers = new HashMap<String, ImportParseElement>(); elementParsers.put("directory", new DirectoryParseElement()); elementParsers.put("compression", new ImportCompressionParseElement()); elementParsers.put("file_pattern", new FilePatternParseElement()); elementParsers.put("mappings", new ImportMappingsParseElement()); elementParsers.put("settings", new ImportSettingsParseElement()); this.elementParsers = ImmutableMap.copyOf(elementParsers); } /** * Main method of this class to parse given payload of _export action * * @param context * @param source * @throws SearchParseException */
public void parseSource(ImportContext context, BytesReference source) throws ImportParseException {
crate/elasticsearch-inout-plugin
src/main/java/crate/elasticsearch/export/ExportCollector.java
// Path: src/main/java/crate/elasticsearch/action/export/ExportContext.java // public class ExportContext extends SearchContext { // // private static final String VAR_SHARD = "${shard}"; // private static final String VAR_INDEX = "${index}"; // private static final String VAR_CLUSTER = "${cluster}"; // // private List<String> outputCmdArray; // private String outputCmd; // private String outputFile; // private boolean forceOverride = false; // private boolean compression; // private String nodePath; // private boolean mappings = false; // private boolean settings = false; // // public ExportContext(long id, ShardSearchRequest request, SearchShardTarget shardTarget, // Engine.Searcher engineSearcher, IndexService indexService, IndexShard indexShard, // ScriptService scriptService, CacheRecycler cacheRecycler, String nodePath) { // super(id, request, shardTarget, engineSearcher, indexService, indexShard, scriptService, cacheRecycler); // this.nodePath = nodePath; // } // // public List<String> outputCmdArray() { // return outputCmdArray; // } // // public void outputCmdArray(List<String> outputCmdArray) { // this.outputCmdArray = applyVars(outputCmdArray); // } // // public String outputCmd() { // return outputCmd; // } // // public void outputCmd(String outputCmd) { // this.outputCmd = applyVars(outputCmd); // } // // public String outputFile() { // return outputFile; // } // // public void outputFile(String outputFile) { // outputFile = applyVars(outputFile); // File outFile = new File(outputFile); // if (!outFile.isAbsolute() && nodePath != null) { // outputFile = new File(nodePath, outputFile).getAbsolutePath(); // } // this.outputFile = outputFile; // } // // public boolean mappings() { // return mappings; // } // // public void mappings(boolean mappings) { // this.mappings = mappings; // } // // public boolean settings() { // return settings; // } // // public void settings(boolean settings) { // this.settings = settings; // } // // public String nodePath() { // return nodePath; // } // // public boolean forceOverride() { // return forceOverride; // } // // public void forceOverride(boolean forceOverride) { // this.forceOverride = forceOverride; // } // // public void compression(boolean compression) { // this.compression = compression; // } // // public boolean compression() { // return this.compression; // } // // /** // * Replaces variable placeholder with actual value in all elements of templateArray // * // * @param templateArray // * @return // */ // private List<String> applyVars(List<String> templateArray) { // List<String> ret = new ArrayList<String>(); // for (String part : templateArray) { // ret.add(applyVars(part)); // } // return ret; // } // // /** // * Replaces variable placeholder with actual value // * // * @param template // * @return // */ // private String applyVars(String template) { // template = template.replace(VAR_SHARD, String.valueOf(indexShard().shardId().getId())); // template = template.replace(VAR_INDEX, indexShard().shardId().getIndex()); // template = template.replace(VAR_CLUSTER, clusterName()); // return template; // } // // /** // * Method to retrieve name of cluster // * // * @return name of cluster // */ // private String clusterName() { // return ClusterName.clusterNameFromSettings(this.indexShard().indexSettings()).value(); // } // // public Output createOutput() { // if (outputFile()!=null){ // return new OutputFile(outputFile(), forceOverride(), compression); // } else { // if (outputCmd()!=null){ // return new OutputCommand(outputCmd(), compression); // } else { // return new OutputCommand(outputCmdArray(), compression); // } // } // } // }
import static org.elasticsearch.common.collect.Lists.newArrayList; import java.io.IOException; import java.io.OutputStream; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.lucene.index.AtomicReaderContext; import org.apache.lucene.index.IndexReader; import org.apache.lucene.search.Collector; import org.apache.lucene.search.Scorer; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.io.stream.BytesStreamOutput; import org.elasticsearch.common.text.StringAndBytesText; import org.elasticsearch.common.text.Text; import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.index.fieldvisitor.CustomFieldsVisitor; import org.elasticsearch.index.fieldvisitor.FieldsVisitor; import org.elasticsearch.index.fieldvisitor.JustUidFieldsVisitor; import org.elasticsearch.index.fieldvisitor.UidAndSourceFieldsVisitor; import org.elasticsearch.index.mapper.DocumentMapper; import org.elasticsearch.index.mapper.FieldMappers; import org.elasticsearch.index.mapper.internal.SourceFieldMapper; import org.elasticsearch.search.SearchHitField; import org.elasticsearch.search.fetch.FetchSubPhase; import org.elasticsearch.search.internal.InternalSearchHit; import org.elasticsearch.search.internal.InternalSearchHitField; import crate.elasticsearch.action.export.ExportContext;
package crate.elasticsearch.export; public class ExportCollector extends Collector { private IndexReader currentReader; private long numExported = 0; private final FieldsVisitor fieldsVisitor;
// Path: src/main/java/crate/elasticsearch/action/export/ExportContext.java // public class ExportContext extends SearchContext { // // private static final String VAR_SHARD = "${shard}"; // private static final String VAR_INDEX = "${index}"; // private static final String VAR_CLUSTER = "${cluster}"; // // private List<String> outputCmdArray; // private String outputCmd; // private String outputFile; // private boolean forceOverride = false; // private boolean compression; // private String nodePath; // private boolean mappings = false; // private boolean settings = false; // // public ExportContext(long id, ShardSearchRequest request, SearchShardTarget shardTarget, // Engine.Searcher engineSearcher, IndexService indexService, IndexShard indexShard, // ScriptService scriptService, CacheRecycler cacheRecycler, String nodePath) { // super(id, request, shardTarget, engineSearcher, indexService, indexShard, scriptService, cacheRecycler); // this.nodePath = nodePath; // } // // public List<String> outputCmdArray() { // return outputCmdArray; // } // // public void outputCmdArray(List<String> outputCmdArray) { // this.outputCmdArray = applyVars(outputCmdArray); // } // // public String outputCmd() { // return outputCmd; // } // // public void outputCmd(String outputCmd) { // this.outputCmd = applyVars(outputCmd); // } // // public String outputFile() { // return outputFile; // } // // public void outputFile(String outputFile) { // outputFile = applyVars(outputFile); // File outFile = new File(outputFile); // if (!outFile.isAbsolute() && nodePath != null) { // outputFile = new File(nodePath, outputFile).getAbsolutePath(); // } // this.outputFile = outputFile; // } // // public boolean mappings() { // return mappings; // } // // public void mappings(boolean mappings) { // this.mappings = mappings; // } // // public boolean settings() { // return settings; // } // // public void settings(boolean settings) { // this.settings = settings; // } // // public String nodePath() { // return nodePath; // } // // public boolean forceOverride() { // return forceOverride; // } // // public void forceOverride(boolean forceOverride) { // this.forceOverride = forceOverride; // } // // public void compression(boolean compression) { // this.compression = compression; // } // // public boolean compression() { // return this.compression; // } // // /** // * Replaces variable placeholder with actual value in all elements of templateArray // * // * @param templateArray // * @return // */ // private List<String> applyVars(List<String> templateArray) { // List<String> ret = new ArrayList<String>(); // for (String part : templateArray) { // ret.add(applyVars(part)); // } // return ret; // } // // /** // * Replaces variable placeholder with actual value // * // * @param template // * @return // */ // private String applyVars(String template) { // template = template.replace(VAR_SHARD, String.valueOf(indexShard().shardId().getId())); // template = template.replace(VAR_INDEX, indexShard().shardId().getIndex()); // template = template.replace(VAR_CLUSTER, clusterName()); // return template; // } // // /** // * Method to retrieve name of cluster // * // * @return name of cluster // */ // private String clusterName() { // return ClusterName.clusterNameFromSettings(this.indexShard().indexSettings()).value(); // } // // public Output createOutput() { // if (outputFile()!=null){ // return new OutputFile(outputFile(), forceOverride(), compression); // } else { // if (outputCmd()!=null){ // return new OutputCommand(outputCmd(), compression); // } else { // return new OutputCommand(outputCmdArray(), compression); // } // } // } // } // Path: src/main/java/crate/elasticsearch/export/ExportCollector.java import static org.elasticsearch.common.collect.Lists.newArrayList; import java.io.IOException; import java.io.OutputStream; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.lucene.index.AtomicReaderContext; import org.apache.lucene.index.IndexReader; import org.apache.lucene.search.Collector; import org.apache.lucene.search.Scorer; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.io.stream.BytesStreamOutput; import org.elasticsearch.common.text.StringAndBytesText; import org.elasticsearch.common.text.Text; import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.index.fieldvisitor.CustomFieldsVisitor; import org.elasticsearch.index.fieldvisitor.FieldsVisitor; import org.elasticsearch.index.fieldvisitor.JustUidFieldsVisitor; import org.elasticsearch.index.fieldvisitor.UidAndSourceFieldsVisitor; import org.elasticsearch.index.mapper.DocumentMapper; import org.elasticsearch.index.mapper.FieldMappers; import org.elasticsearch.index.mapper.internal.SourceFieldMapper; import org.elasticsearch.search.SearchHitField; import org.elasticsearch.search.fetch.FetchSubPhase; import org.elasticsearch.search.internal.InternalSearchHit; import org.elasticsearch.search.internal.InternalSearchHitField; import crate.elasticsearch.action.export.ExportContext; package crate.elasticsearch.export; public class ExportCollector extends Collector { private IndexReader currentReader; private long numExported = 0; private final FieldsVisitor fieldsVisitor;
private final ExportContext context;
crate/elasticsearch-inout-plugin
src/main/java/crate/elasticsearch/searchinto/WriterCollector.java
// Path: src/main/java/crate/elasticsearch/action/searchinto/SearchIntoContext.java // public class SearchIntoContext extends SearchContext { // // // currently we only support index targets // private String targetType = "index"; // // private List<InetSocketTransportAddress> targetNodes; // // // public Map<String, String> outputNames() { // return outputNames; // } // // private final Map<String, String> outputNames = new HashMap<String, // String>(); // // public SearchIntoContext(long id, ShardSearchRequest request, // SearchShardTarget shardTarget, Engine.Searcher engineSearcher, // IndexService indexService, IndexShard indexShard, // ScriptService scriptService, CacheRecycler cacheRecycler) { // super(id, request, shardTarget, engineSearcher, indexService, // indexShard, scriptService, cacheRecycler); // } // // public String targetType() { // // this is currently the only type supported // return targetType; // } // // public List<InetSocketTransportAddress> targetNodes() { // if (targetNodes == null) { // targetNodes = Lists.newArrayList(); // } // return targetNodes; // } // // public void emptyTargetNodes() { // this.targetNodes = ImmutableList.of(); // } // // } // // Path: src/main/java/crate/elasticsearch/searchinto/mapping/MappedFields.java // public class MappedFields { // // private final SearchIntoContext context; // private SearchHit hit; // private final List<OutputMapping> outputMappings; // // public MappedFields(SearchIntoContext context) { // this.context = context; // this.outputMappings = getOutputMappings(); // } // // public void hit(SearchHit hit) { // this.hit = hit; // } // // private List<OutputMapping> getOutputMappings() { // List<OutputMapping> oms = new ArrayList<OutputMapping>( // context.outputNames().size()); // boolean indexDefined = false; // boolean typeDefined = false; // for (Map.Entry<String, String> e : context.outputNames().entrySet()) { // String srcName = e.getKey(); // String trgName = e.getValue(); // assert (trgName != null); // if (trgName.equals("_index")) { // indexDefined = true; // } else if (trgName.equals("_type")) { // typeDefined = true; // } // OutputMapping om = new OutputMapping(srcName, trgName); // oms.add(om); // } // if (!indexDefined) { // oms.add(new OutputMapping("_index", "_index")); // } // if (!typeDefined) { // oms.add(new OutputMapping("_type", "_type")); // } // // return oms; // } // // public IndexRequest newIndexRequest() { // IndexRequestBuilder builder = new IndexRequestBuilder(); // for (OutputMapping om : outputMappings) { // om.setHit(hit); // builder = om.toRequestBuilder(builder); // } // return builder.build(); // // } // }
import crate.elasticsearch.action.searchinto.SearchIntoContext; import crate.elasticsearch.searchinto.mapping.MappedFields; import org.apache.lucene.index.AtomicReaderContext; import org.apache.lucene.index.IndexReader; import org.apache.lucene.search.Collector; import org.apache.lucene.search.Scorer; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.text.StringAndBytesText; import org.elasticsearch.common.text.Text; import org.elasticsearch.index.fieldvisitor.CustomFieldsVisitor; import org.elasticsearch.index.fieldvisitor.FieldsVisitor; import org.elasticsearch.index.fieldvisitor.JustUidFieldsVisitor; import org.elasticsearch.index.fieldvisitor.UidAndSourceFieldsVisitor; import org.elasticsearch.index.mapper.DocumentMapper; import org.elasticsearch.index.mapper.FieldMappers; import org.elasticsearch.index.mapper.internal.SourceFieldMapper; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.SearchHitField; import org.elasticsearch.search.fetch.FetchSubPhase; import org.elasticsearch.search.internal.InternalSearchHit; import org.elasticsearch.search.internal.InternalSearchHitField; import java.io.IOException; import java.util.*; import static org.elasticsearch.common.collect.Lists.newArrayList;
package crate.elasticsearch.searchinto; public abstract class WriterCollector extends Collector { private List<String> extractFieldNames; protected FieldsVisitor fieldsVisitor;
// Path: src/main/java/crate/elasticsearch/action/searchinto/SearchIntoContext.java // public class SearchIntoContext extends SearchContext { // // // currently we only support index targets // private String targetType = "index"; // // private List<InetSocketTransportAddress> targetNodes; // // // public Map<String, String> outputNames() { // return outputNames; // } // // private final Map<String, String> outputNames = new HashMap<String, // String>(); // // public SearchIntoContext(long id, ShardSearchRequest request, // SearchShardTarget shardTarget, Engine.Searcher engineSearcher, // IndexService indexService, IndexShard indexShard, // ScriptService scriptService, CacheRecycler cacheRecycler) { // super(id, request, shardTarget, engineSearcher, indexService, // indexShard, scriptService, cacheRecycler); // } // // public String targetType() { // // this is currently the only type supported // return targetType; // } // // public List<InetSocketTransportAddress> targetNodes() { // if (targetNodes == null) { // targetNodes = Lists.newArrayList(); // } // return targetNodes; // } // // public void emptyTargetNodes() { // this.targetNodes = ImmutableList.of(); // } // // } // // Path: src/main/java/crate/elasticsearch/searchinto/mapping/MappedFields.java // public class MappedFields { // // private final SearchIntoContext context; // private SearchHit hit; // private final List<OutputMapping> outputMappings; // // public MappedFields(SearchIntoContext context) { // this.context = context; // this.outputMappings = getOutputMappings(); // } // // public void hit(SearchHit hit) { // this.hit = hit; // } // // private List<OutputMapping> getOutputMappings() { // List<OutputMapping> oms = new ArrayList<OutputMapping>( // context.outputNames().size()); // boolean indexDefined = false; // boolean typeDefined = false; // for (Map.Entry<String, String> e : context.outputNames().entrySet()) { // String srcName = e.getKey(); // String trgName = e.getValue(); // assert (trgName != null); // if (trgName.equals("_index")) { // indexDefined = true; // } else if (trgName.equals("_type")) { // typeDefined = true; // } // OutputMapping om = new OutputMapping(srcName, trgName); // oms.add(om); // } // if (!indexDefined) { // oms.add(new OutputMapping("_index", "_index")); // } // if (!typeDefined) { // oms.add(new OutputMapping("_type", "_type")); // } // // return oms; // } // // public IndexRequest newIndexRequest() { // IndexRequestBuilder builder = new IndexRequestBuilder(); // for (OutputMapping om : outputMappings) { // om.setHit(hit); // builder = om.toRequestBuilder(builder); // } // return builder.build(); // // } // } // Path: src/main/java/crate/elasticsearch/searchinto/WriterCollector.java import crate.elasticsearch.action.searchinto.SearchIntoContext; import crate.elasticsearch.searchinto.mapping.MappedFields; import org.apache.lucene.index.AtomicReaderContext; import org.apache.lucene.index.IndexReader; import org.apache.lucene.search.Collector; import org.apache.lucene.search.Scorer; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.text.StringAndBytesText; import org.elasticsearch.common.text.Text; import org.elasticsearch.index.fieldvisitor.CustomFieldsVisitor; import org.elasticsearch.index.fieldvisitor.FieldsVisitor; import org.elasticsearch.index.fieldvisitor.JustUidFieldsVisitor; import org.elasticsearch.index.fieldvisitor.UidAndSourceFieldsVisitor; import org.elasticsearch.index.mapper.DocumentMapper; import org.elasticsearch.index.mapper.FieldMappers; import org.elasticsearch.index.mapper.internal.SourceFieldMapper; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.SearchHitField; import org.elasticsearch.search.fetch.FetchSubPhase; import org.elasticsearch.search.internal.InternalSearchHit; import org.elasticsearch.search.internal.InternalSearchHitField; import java.io.IOException; import java.util.*; import static org.elasticsearch.common.collect.Lists.newArrayList; package crate.elasticsearch.searchinto; public abstract class WriterCollector extends Collector { private List<String> extractFieldNames; protected FieldsVisitor fieldsVisitor;
protected SearchIntoContext context;
crate/elasticsearch-inout-plugin
src/main/java/crate/elasticsearch/searchinto/WriterCollector.java
// Path: src/main/java/crate/elasticsearch/action/searchinto/SearchIntoContext.java // public class SearchIntoContext extends SearchContext { // // // currently we only support index targets // private String targetType = "index"; // // private List<InetSocketTransportAddress> targetNodes; // // // public Map<String, String> outputNames() { // return outputNames; // } // // private final Map<String, String> outputNames = new HashMap<String, // String>(); // // public SearchIntoContext(long id, ShardSearchRequest request, // SearchShardTarget shardTarget, Engine.Searcher engineSearcher, // IndexService indexService, IndexShard indexShard, // ScriptService scriptService, CacheRecycler cacheRecycler) { // super(id, request, shardTarget, engineSearcher, indexService, // indexShard, scriptService, cacheRecycler); // } // // public String targetType() { // // this is currently the only type supported // return targetType; // } // // public List<InetSocketTransportAddress> targetNodes() { // if (targetNodes == null) { // targetNodes = Lists.newArrayList(); // } // return targetNodes; // } // // public void emptyTargetNodes() { // this.targetNodes = ImmutableList.of(); // } // // } // // Path: src/main/java/crate/elasticsearch/searchinto/mapping/MappedFields.java // public class MappedFields { // // private final SearchIntoContext context; // private SearchHit hit; // private final List<OutputMapping> outputMappings; // // public MappedFields(SearchIntoContext context) { // this.context = context; // this.outputMappings = getOutputMappings(); // } // // public void hit(SearchHit hit) { // this.hit = hit; // } // // private List<OutputMapping> getOutputMappings() { // List<OutputMapping> oms = new ArrayList<OutputMapping>( // context.outputNames().size()); // boolean indexDefined = false; // boolean typeDefined = false; // for (Map.Entry<String, String> e : context.outputNames().entrySet()) { // String srcName = e.getKey(); // String trgName = e.getValue(); // assert (trgName != null); // if (trgName.equals("_index")) { // indexDefined = true; // } else if (trgName.equals("_type")) { // typeDefined = true; // } // OutputMapping om = new OutputMapping(srcName, trgName); // oms.add(om); // } // if (!indexDefined) { // oms.add(new OutputMapping("_index", "_index")); // } // if (!typeDefined) { // oms.add(new OutputMapping("_type", "_type")); // } // // return oms; // } // // public IndexRequest newIndexRequest() { // IndexRequestBuilder builder = new IndexRequestBuilder(); // for (OutputMapping om : outputMappings) { // om.setHit(hit); // builder = om.toRequestBuilder(builder); // } // return builder.build(); // // } // }
import crate.elasticsearch.action.searchinto.SearchIntoContext; import crate.elasticsearch.searchinto.mapping.MappedFields; import org.apache.lucene.index.AtomicReaderContext; import org.apache.lucene.index.IndexReader; import org.apache.lucene.search.Collector; import org.apache.lucene.search.Scorer; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.text.StringAndBytesText; import org.elasticsearch.common.text.Text; import org.elasticsearch.index.fieldvisitor.CustomFieldsVisitor; import org.elasticsearch.index.fieldvisitor.FieldsVisitor; import org.elasticsearch.index.fieldvisitor.JustUidFieldsVisitor; import org.elasticsearch.index.fieldvisitor.UidAndSourceFieldsVisitor; import org.elasticsearch.index.mapper.DocumentMapper; import org.elasticsearch.index.mapper.FieldMappers; import org.elasticsearch.index.mapper.internal.SourceFieldMapper; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.SearchHitField; import org.elasticsearch.search.fetch.FetchSubPhase; import org.elasticsearch.search.internal.InternalSearchHit; import org.elasticsearch.search.internal.InternalSearchHitField; import java.io.IOException; import java.util.*; import static org.elasticsearch.common.collect.Lists.newArrayList;
package crate.elasticsearch.searchinto; public abstract class WriterCollector extends Collector { private List<String> extractFieldNames; protected FieldsVisitor fieldsVisitor; protected SearchIntoContext context;
// Path: src/main/java/crate/elasticsearch/action/searchinto/SearchIntoContext.java // public class SearchIntoContext extends SearchContext { // // // currently we only support index targets // private String targetType = "index"; // // private List<InetSocketTransportAddress> targetNodes; // // // public Map<String, String> outputNames() { // return outputNames; // } // // private final Map<String, String> outputNames = new HashMap<String, // String>(); // // public SearchIntoContext(long id, ShardSearchRequest request, // SearchShardTarget shardTarget, Engine.Searcher engineSearcher, // IndexService indexService, IndexShard indexShard, // ScriptService scriptService, CacheRecycler cacheRecycler) { // super(id, request, shardTarget, engineSearcher, indexService, // indexShard, scriptService, cacheRecycler); // } // // public String targetType() { // // this is currently the only type supported // return targetType; // } // // public List<InetSocketTransportAddress> targetNodes() { // if (targetNodes == null) { // targetNodes = Lists.newArrayList(); // } // return targetNodes; // } // // public void emptyTargetNodes() { // this.targetNodes = ImmutableList.of(); // } // // } // // Path: src/main/java/crate/elasticsearch/searchinto/mapping/MappedFields.java // public class MappedFields { // // private final SearchIntoContext context; // private SearchHit hit; // private final List<OutputMapping> outputMappings; // // public MappedFields(SearchIntoContext context) { // this.context = context; // this.outputMappings = getOutputMappings(); // } // // public void hit(SearchHit hit) { // this.hit = hit; // } // // private List<OutputMapping> getOutputMappings() { // List<OutputMapping> oms = new ArrayList<OutputMapping>( // context.outputNames().size()); // boolean indexDefined = false; // boolean typeDefined = false; // for (Map.Entry<String, String> e : context.outputNames().entrySet()) { // String srcName = e.getKey(); // String trgName = e.getValue(); // assert (trgName != null); // if (trgName.equals("_index")) { // indexDefined = true; // } else if (trgName.equals("_type")) { // typeDefined = true; // } // OutputMapping om = new OutputMapping(srcName, trgName); // oms.add(om); // } // if (!indexDefined) { // oms.add(new OutputMapping("_index", "_index")); // } // if (!typeDefined) { // oms.add(new OutputMapping("_type", "_type")); // } // // return oms; // } // // public IndexRequest newIndexRequest() { // IndexRequestBuilder builder = new IndexRequestBuilder(); // for (OutputMapping om : outputMappings) { // om.setHit(hit); // builder = om.toRequestBuilder(builder); // } // return builder.build(); // // } // } // Path: src/main/java/crate/elasticsearch/searchinto/WriterCollector.java import crate.elasticsearch.action.searchinto.SearchIntoContext; import crate.elasticsearch.searchinto.mapping.MappedFields; import org.apache.lucene.index.AtomicReaderContext; import org.apache.lucene.index.IndexReader; import org.apache.lucene.search.Collector; import org.apache.lucene.search.Scorer; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.text.StringAndBytesText; import org.elasticsearch.common.text.Text; import org.elasticsearch.index.fieldvisitor.CustomFieldsVisitor; import org.elasticsearch.index.fieldvisitor.FieldsVisitor; import org.elasticsearch.index.fieldvisitor.JustUidFieldsVisitor; import org.elasticsearch.index.fieldvisitor.UidAndSourceFieldsVisitor; import org.elasticsearch.index.mapper.DocumentMapper; import org.elasticsearch.index.mapper.FieldMappers; import org.elasticsearch.index.mapper.internal.SourceFieldMapper; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.SearchHitField; import org.elasticsearch.search.fetch.FetchSubPhase; import org.elasticsearch.search.internal.InternalSearchHit; import org.elasticsearch.search.internal.InternalSearchHitField; import java.io.IOException; import java.util.*; import static org.elasticsearch.common.collect.Lists.newArrayList; package crate.elasticsearch.searchinto; public abstract class WriterCollector extends Collector { private List<String> extractFieldNames; protected FieldsVisitor fieldsVisitor; protected SearchIntoContext context;
protected MappedFields mappedFields;
crate/elasticsearch-inout-plugin
src/main/java/crate/elasticsearch/action/import_/parser/FilePatternParseElement.java
// Path: src/main/java/crate/elasticsearch/action/import_/ImportContext.java // public class ImportContext { // // private String nodePath; // private boolean compression; // private String directory; // private Pattern file_pattern; // private boolean mappings = false; // private boolean settings = false; // // public ImportContext(String nodePath) { // this.nodePath = nodePath; // } // // public boolean compression() { // return compression; // } // // public void compression(boolean compression) { // this.compression = compression; // } // // public String directory() { // return directory; // } // // public void directory(String directory) { // File file = new File(directory); // if (!file.isAbsolute() && nodePath != null) { // file = new File(nodePath, directory); // directory = file.getAbsolutePath(); // } // this.directory = directory; // } // // public Pattern file_pattern() { // return file_pattern; // } // // public void file_pattern(Pattern file_pattern) { // this.file_pattern = file_pattern; // } // // public boolean mappings() { // return mappings; // } // // public void mappings(boolean mappings) { // this.mappings = mappings; // } // // public boolean settings() { // return settings; // } // // public void settings(boolean settings) { // this.settings = settings; // } // }
import java.util.regex.Pattern; import org.elasticsearch.common.xcontent.XContentParser; import crate.elasticsearch.action.import_.ImportContext;
package crate.elasticsearch.action.import_.parser; public class FilePatternParseElement implements ImportParseElement { @Override
// Path: src/main/java/crate/elasticsearch/action/import_/ImportContext.java // public class ImportContext { // // private String nodePath; // private boolean compression; // private String directory; // private Pattern file_pattern; // private boolean mappings = false; // private boolean settings = false; // // public ImportContext(String nodePath) { // this.nodePath = nodePath; // } // // public boolean compression() { // return compression; // } // // public void compression(boolean compression) { // this.compression = compression; // } // // public String directory() { // return directory; // } // // public void directory(String directory) { // File file = new File(directory); // if (!file.isAbsolute() && nodePath != null) { // file = new File(nodePath, directory); // directory = file.getAbsolutePath(); // } // this.directory = directory; // } // // public Pattern file_pattern() { // return file_pattern; // } // // public void file_pattern(Pattern file_pattern) { // this.file_pattern = file_pattern; // } // // public boolean mappings() { // return mappings; // } // // public void mappings(boolean mappings) { // this.mappings = mappings; // } // // public boolean settings() { // return settings; // } // // public void settings(boolean settings) { // this.settings = settings; // } // } // Path: src/main/java/crate/elasticsearch/action/import_/parser/FilePatternParseElement.java import java.util.regex.Pattern; import org.elasticsearch.common.xcontent.XContentParser; import crate.elasticsearch.action.import_.ImportContext; package crate.elasticsearch.action.import_.parser; public class FilePatternParseElement implements ImportParseElement { @Override
public void parse(XContentParser parser, ImportContext context)
crate/elasticsearch-inout-plugin
src/main/java/crate/elasticsearch/rest/action/admin/import_/RestImportAction.java
// Path: src/main/java/crate/elasticsearch/action/import_/ImportRequest.java // public class ImportRequest extends NodesOperationRequest<ImportRequest> { // // private BytesReference source; // // private String type; // private String index; // // /** // * Constructs a new import request against the provided nodes. No nodes provided // * means it will run against all nodes. // */ // public ImportRequest(String... nodes) { // super(nodes); // } // // /** // * The query source to execute. // * @return // */ // public BytesReference source() { // return source; // } // // @Required // public ImportRequest source(String source) { // return this.source(new BytesArray(source), false); // } // // @Required // public ImportRequest source(BytesReference source, boolean unsafe) { // this.source = source; // return this; // } // // public String type() { // return this.type; // } // // public void type(String type) { // this.type = type; // } // // public String index() { // return this.index ; // } // // public void index(String index) { // this.index = index; // } // // @Override // public void readFrom(StreamInput in) throws IOException { // super.readFrom(in); // index = in.readOptionalString(); // type = in.readOptionalString(); // source = in.readBytesReference(); // } // // @Override // public void writeTo(StreamOutput out) throws IOException { // super.writeTo(out); // out.writeOptionalString(index); // out.writeOptionalString(type); // out.writeBytesReference(source); // } // // } // // Path: src/main/java/crate/elasticsearch/action/import_/ImportResponse.java // public class ImportResponse extends NodesOperationResponse<NodeImportResponse> implements ToXContent { // // private List<NodeImportResponse> responses; // private List<FailedNodeException> nodeFailures; // // public ImportResponse() { // } // // public ImportResponse(List<NodeImportResponse> responses, int total, // int successfulNodes, int failedNodes, List<FailedNodeException> nodeFailures) { // this.responses = responses; // this.nodeFailures = nodeFailures; // } // // public List<NodeImportResponse> getResponses() { // return responses; // } // // @Override // public XContentBuilder toXContent(XContentBuilder builder, Params params) // throws IOException { // builder.startObject(); // builder.startArray("imports"); // for (NodeImportResponse r : this.responses) { // r.toXContent(builder, params); // } // builder.endArray(); // if (nodeFailures != null && nodeFailures.size() > 0) { // builder.startArray("failures"); // for (FailedNodeException failure : nodeFailures) { // builder.startObject(); // builder.field("node_id", failure.nodeId()); // builder.field("reason", failure.getDetailedMessage()); // builder.endObject(); // } // builder.endArray(); // } // builder.endObject(); // return builder; // } // // @Override // public void readFrom(StreamInput in) throws IOException { // super.readFrom(in); // int responsesCount = in.readInt(); // this.responses = new ArrayList<NodeImportResponse>(responsesCount); // for (int i = 0; i < responsesCount; i++) { // responses.add(NodeImportResponse.readNew(in)); // } // int failuresCount = in.readInt(); // this.nodeFailures = new ArrayList<FailedNodeException>(failuresCount); // for (int i = 0; i < failuresCount; i++) { // String nodeId = in.readString(); // String msg = in.readOptionalString(); // FailedNodeException e = new FailedNodeException(nodeId, msg, null); // nodeFailures.add(e); // } // } // // @Override // public void writeTo(StreamOutput out) throws IOException { // super.writeTo(out); // out.writeInt(responses.size()); // for (NodeImportResponse response : responses) { // response.writeTo(out); // } // out.writeInt(nodeFailures.size()); // for (FailedNodeException e : nodeFailures) { // out.writeString(e.nodeId()); // out.writeOptionalString(e.getMessage()); // } // } // }
import crate.elasticsearch.action.import_.ImportAction; import crate.elasticsearch.action.import_.ImportRequest; import crate.elasticsearch.action.import_.ImportResponse; import org.elasticsearch.action.Action; import org.elasticsearch.action.ActionListener; import org.elasticsearch.client.Client; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.rest.*; import org.elasticsearch.rest.action.support.RestActions; import org.elasticsearch.rest.action.support.RestXContentBuilder; import java.io.IOException; import static org.elasticsearch.rest.RestRequest.Method.POST; import static org.elasticsearch.rest.RestStatus.BAD_REQUEST; import static org.elasticsearch.rest.RestStatus.OK;
package crate.elasticsearch.rest.action.admin.import_; public class RestImportAction extends BaseRestHandler { @Inject public RestImportAction(Settings settings, Client client, RestController controller) { super(settings, client); registerHandlers(controller); } protected void registerHandlers(RestController controller) { controller.registerHandler(POST, "/_import", this); controller.registerHandler(POST, "/{index}/_import", this); controller.registerHandler(POST, "/{index}/{type}/_import", this); } protected Action action() { return ImportAction.INSTANCE; } public void handleRequest(final RestRequest request, final RestChannel channel) {
// Path: src/main/java/crate/elasticsearch/action/import_/ImportRequest.java // public class ImportRequest extends NodesOperationRequest<ImportRequest> { // // private BytesReference source; // // private String type; // private String index; // // /** // * Constructs a new import request against the provided nodes. No nodes provided // * means it will run against all nodes. // */ // public ImportRequest(String... nodes) { // super(nodes); // } // // /** // * The query source to execute. // * @return // */ // public BytesReference source() { // return source; // } // // @Required // public ImportRequest source(String source) { // return this.source(new BytesArray(source), false); // } // // @Required // public ImportRequest source(BytesReference source, boolean unsafe) { // this.source = source; // return this; // } // // public String type() { // return this.type; // } // // public void type(String type) { // this.type = type; // } // // public String index() { // return this.index ; // } // // public void index(String index) { // this.index = index; // } // // @Override // public void readFrom(StreamInput in) throws IOException { // super.readFrom(in); // index = in.readOptionalString(); // type = in.readOptionalString(); // source = in.readBytesReference(); // } // // @Override // public void writeTo(StreamOutput out) throws IOException { // super.writeTo(out); // out.writeOptionalString(index); // out.writeOptionalString(type); // out.writeBytesReference(source); // } // // } // // Path: src/main/java/crate/elasticsearch/action/import_/ImportResponse.java // public class ImportResponse extends NodesOperationResponse<NodeImportResponse> implements ToXContent { // // private List<NodeImportResponse> responses; // private List<FailedNodeException> nodeFailures; // // public ImportResponse() { // } // // public ImportResponse(List<NodeImportResponse> responses, int total, // int successfulNodes, int failedNodes, List<FailedNodeException> nodeFailures) { // this.responses = responses; // this.nodeFailures = nodeFailures; // } // // public List<NodeImportResponse> getResponses() { // return responses; // } // // @Override // public XContentBuilder toXContent(XContentBuilder builder, Params params) // throws IOException { // builder.startObject(); // builder.startArray("imports"); // for (NodeImportResponse r : this.responses) { // r.toXContent(builder, params); // } // builder.endArray(); // if (nodeFailures != null && nodeFailures.size() > 0) { // builder.startArray("failures"); // for (FailedNodeException failure : nodeFailures) { // builder.startObject(); // builder.field("node_id", failure.nodeId()); // builder.field("reason", failure.getDetailedMessage()); // builder.endObject(); // } // builder.endArray(); // } // builder.endObject(); // return builder; // } // // @Override // public void readFrom(StreamInput in) throws IOException { // super.readFrom(in); // int responsesCount = in.readInt(); // this.responses = new ArrayList<NodeImportResponse>(responsesCount); // for (int i = 0; i < responsesCount; i++) { // responses.add(NodeImportResponse.readNew(in)); // } // int failuresCount = in.readInt(); // this.nodeFailures = new ArrayList<FailedNodeException>(failuresCount); // for (int i = 0; i < failuresCount; i++) { // String nodeId = in.readString(); // String msg = in.readOptionalString(); // FailedNodeException e = new FailedNodeException(nodeId, msg, null); // nodeFailures.add(e); // } // } // // @Override // public void writeTo(StreamOutput out) throws IOException { // super.writeTo(out); // out.writeInt(responses.size()); // for (NodeImportResponse response : responses) { // response.writeTo(out); // } // out.writeInt(nodeFailures.size()); // for (FailedNodeException e : nodeFailures) { // out.writeString(e.nodeId()); // out.writeOptionalString(e.getMessage()); // } // } // } // Path: src/main/java/crate/elasticsearch/rest/action/admin/import_/RestImportAction.java import crate.elasticsearch.action.import_.ImportAction; import crate.elasticsearch.action.import_.ImportRequest; import crate.elasticsearch.action.import_.ImportResponse; import org.elasticsearch.action.Action; import org.elasticsearch.action.ActionListener; import org.elasticsearch.client.Client; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.rest.*; import org.elasticsearch.rest.action.support.RestActions; import org.elasticsearch.rest.action.support.RestXContentBuilder; import java.io.IOException; import static org.elasticsearch.rest.RestRequest.Method.POST; import static org.elasticsearch.rest.RestStatus.BAD_REQUEST; import static org.elasticsearch.rest.RestStatus.OK; package crate.elasticsearch.rest.action.admin.import_; public class RestImportAction extends BaseRestHandler { @Inject public RestImportAction(Settings settings, Client client, RestController controller) { super(settings, client); registerHandlers(controller); } protected void registerHandlers(RestController controller) { controller.registerHandler(POST, "/_import", this); controller.registerHandler(POST, "/{index}/_import", this); controller.registerHandler(POST, "/{index}/{type}/_import", this); } protected Action action() { return ImportAction.INSTANCE; } public void handleRequest(final RestRequest request, final RestChannel channel) {
ImportRequest importRequest = new ImportRequest();
crate/elasticsearch-inout-plugin
src/main/java/crate/elasticsearch/rest/action/admin/import_/RestImportAction.java
// Path: src/main/java/crate/elasticsearch/action/import_/ImportRequest.java // public class ImportRequest extends NodesOperationRequest<ImportRequest> { // // private BytesReference source; // // private String type; // private String index; // // /** // * Constructs a new import request against the provided nodes. No nodes provided // * means it will run against all nodes. // */ // public ImportRequest(String... nodes) { // super(nodes); // } // // /** // * The query source to execute. // * @return // */ // public BytesReference source() { // return source; // } // // @Required // public ImportRequest source(String source) { // return this.source(new BytesArray(source), false); // } // // @Required // public ImportRequest source(BytesReference source, boolean unsafe) { // this.source = source; // return this; // } // // public String type() { // return this.type; // } // // public void type(String type) { // this.type = type; // } // // public String index() { // return this.index ; // } // // public void index(String index) { // this.index = index; // } // // @Override // public void readFrom(StreamInput in) throws IOException { // super.readFrom(in); // index = in.readOptionalString(); // type = in.readOptionalString(); // source = in.readBytesReference(); // } // // @Override // public void writeTo(StreamOutput out) throws IOException { // super.writeTo(out); // out.writeOptionalString(index); // out.writeOptionalString(type); // out.writeBytesReference(source); // } // // } // // Path: src/main/java/crate/elasticsearch/action/import_/ImportResponse.java // public class ImportResponse extends NodesOperationResponse<NodeImportResponse> implements ToXContent { // // private List<NodeImportResponse> responses; // private List<FailedNodeException> nodeFailures; // // public ImportResponse() { // } // // public ImportResponse(List<NodeImportResponse> responses, int total, // int successfulNodes, int failedNodes, List<FailedNodeException> nodeFailures) { // this.responses = responses; // this.nodeFailures = nodeFailures; // } // // public List<NodeImportResponse> getResponses() { // return responses; // } // // @Override // public XContentBuilder toXContent(XContentBuilder builder, Params params) // throws IOException { // builder.startObject(); // builder.startArray("imports"); // for (NodeImportResponse r : this.responses) { // r.toXContent(builder, params); // } // builder.endArray(); // if (nodeFailures != null && nodeFailures.size() > 0) { // builder.startArray("failures"); // for (FailedNodeException failure : nodeFailures) { // builder.startObject(); // builder.field("node_id", failure.nodeId()); // builder.field("reason", failure.getDetailedMessage()); // builder.endObject(); // } // builder.endArray(); // } // builder.endObject(); // return builder; // } // // @Override // public void readFrom(StreamInput in) throws IOException { // super.readFrom(in); // int responsesCount = in.readInt(); // this.responses = new ArrayList<NodeImportResponse>(responsesCount); // for (int i = 0; i < responsesCount; i++) { // responses.add(NodeImportResponse.readNew(in)); // } // int failuresCount = in.readInt(); // this.nodeFailures = new ArrayList<FailedNodeException>(failuresCount); // for (int i = 0; i < failuresCount; i++) { // String nodeId = in.readString(); // String msg = in.readOptionalString(); // FailedNodeException e = new FailedNodeException(nodeId, msg, null); // nodeFailures.add(e); // } // } // // @Override // public void writeTo(StreamOutput out) throws IOException { // super.writeTo(out); // out.writeInt(responses.size()); // for (NodeImportResponse response : responses) { // response.writeTo(out); // } // out.writeInt(nodeFailures.size()); // for (FailedNodeException e : nodeFailures) { // out.writeString(e.nodeId()); // out.writeOptionalString(e.getMessage()); // } // } // }
import crate.elasticsearch.action.import_.ImportAction; import crate.elasticsearch.action.import_.ImportRequest; import crate.elasticsearch.action.import_.ImportResponse; import org.elasticsearch.action.Action; import org.elasticsearch.action.ActionListener; import org.elasticsearch.client.Client; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.rest.*; import org.elasticsearch.rest.action.support.RestActions; import org.elasticsearch.rest.action.support.RestXContentBuilder; import java.io.IOException; import static org.elasticsearch.rest.RestRequest.Method.POST; import static org.elasticsearch.rest.RestStatus.BAD_REQUEST; import static org.elasticsearch.rest.RestStatus.OK;
public void handleRequest(final RestRequest request, final RestChannel channel) { ImportRequest importRequest = new ImportRequest(); importRequest.listenerThreaded(false); try { if (request.hasContent()) { importRequest.source(request.content(), request.contentUnsafe()); } else { String source = request.param("source"); if (source != null) { importRequest.source(source); } else { BytesReference querySource = RestActions.parseQuerySource(request); if (querySource != null) { importRequest.source(querySource, false); } } } importRequest.index(request.param("index")); importRequest.type(request.param("type")); } catch (Exception e) { try { XContentBuilder builder = RestXContentBuilder.restContentBuilder(request); channel.sendResponse(new XContentRestResponse(request, BAD_REQUEST, builder.startObject().field("error", e.getMessage()).endObject())); } catch (IOException e1) { logger.error("Failed to send failure response", e1); } return; }
// Path: src/main/java/crate/elasticsearch/action/import_/ImportRequest.java // public class ImportRequest extends NodesOperationRequest<ImportRequest> { // // private BytesReference source; // // private String type; // private String index; // // /** // * Constructs a new import request against the provided nodes. No nodes provided // * means it will run against all nodes. // */ // public ImportRequest(String... nodes) { // super(nodes); // } // // /** // * The query source to execute. // * @return // */ // public BytesReference source() { // return source; // } // // @Required // public ImportRequest source(String source) { // return this.source(new BytesArray(source), false); // } // // @Required // public ImportRequest source(BytesReference source, boolean unsafe) { // this.source = source; // return this; // } // // public String type() { // return this.type; // } // // public void type(String type) { // this.type = type; // } // // public String index() { // return this.index ; // } // // public void index(String index) { // this.index = index; // } // // @Override // public void readFrom(StreamInput in) throws IOException { // super.readFrom(in); // index = in.readOptionalString(); // type = in.readOptionalString(); // source = in.readBytesReference(); // } // // @Override // public void writeTo(StreamOutput out) throws IOException { // super.writeTo(out); // out.writeOptionalString(index); // out.writeOptionalString(type); // out.writeBytesReference(source); // } // // } // // Path: src/main/java/crate/elasticsearch/action/import_/ImportResponse.java // public class ImportResponse extends NodesOperationResponse<NodeImportResponse> implements ToXContent { // // private List<NodeImportResponse> responses; // private List<FailedNodeException> nodeFailures; // // public ImportResponse() { // } // // public ImportResponse(List<NodeImportResponse> responses, int total, // int successfulNodes, int failedNodes, List<FailedNodeException> nodeFailures) { // this.responses = responses; // this.nodeFailures = nodeFailures; // } // // public List<NodeImportResponse> getResponses() { // return responses; // } // // @Override // public XContentBuilder toXContent(XContentBuilder builder, Params params) // throws IOException { // builder.startObject(); // builder.startArray("imports"); // for (NodeImportResponse r : this.responses) { // r.toXContent(builder, params); // } // builder.endArray(); // if (nodeFailures != null && nodeFailures.size() > 0) { // builder.startArray("failures"); // for (FailedNodeException failure : nodeFailures) { // builder.startObject(); // builder.field("node_id", failure.nodeId()); // builder.field("reason", failure.getDetailedMessage()); // builder.endObject(); // } // builder.endArray(); // } // builder.endObject(); // return builder; // } // // @Override // public void readFrom(StreamInput in) throws IOException { // super.readFrom(in); // int responsesCount = in.readInt(); // this.responses = new ArrayList<NodeImportResponse>(responsesCount); // for (int i = 0; i < responsesCount; i++) { // responses.add(NodeImportResponse.readNew(in)); // } // int failuresCount = in.readInt(); // this.nodeFailures = new ArrayList<FailedNodeException>(failuresCount); // for (int i = 0; i < failuresCount; i++) { // String nodeId = in.readString(); // String msg = in.readOptionalString(); // FailedNodeException e = new FailedNodeException(nodeId, msg, null); // nodeFailures.add(e); // } // } // // @Override // public void writeTo(StreamOutput out) throws IOException { // super.writeTo(out); // out.writeInt(responses.size()); // for (NodeImportResponse response : responses) { // response.writeTo(out); // } // out.writeInt(nodeFailures.size()); // for (FailedNodeException e : nodeFailures) { // out.writeString(e.nodeId()); // out.writeOptionalString(e.getMessage()); // } // } // } // Path: src/main/java/crate/elasticsearch/rest/action/admin/import_/RestImportAction.java import crate.elasticsearch.action.import_.ImportAction; import crate.elasticsearch.action.import_.ImportRequest; import crate.elasticsearch.action.import_.ImportResponse; import org.elasticsearch.action.Action; import org.elasticsearch.action.ActionListener; import org.elasticsearch.client.Client; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.rest.*; import org.elasticsearch.rest.action.support.RestActions; import org.elasticsearch.rest.action.support.RestXContentBuilder; import java.io.IOException; import static org.elasticsearch.rest.RestRequest.Method.POST; import static org.elasticsearch.rest.RestStatus.BAD_REQUEST; import static org.elasticsearch.rest.RestStatus.OK; public void handleRequest(final RestRequest request, final RestChannel channel) { ImportRequest importRequest = new ImportRequest(); importRequest.listenerThreaded(false); try { if (request.hasContent()) { importRequest.source(request.content(), request.contentUnsafe()); } else { String source = request.param("source"); if (source != null) { importRequest.source(source); } else { BytesReference querySource = RestActions.parseQuerySource(request); if (querySource != null) { importRequest.source(querySource, false); } } } importRequest.index(request.param("index")); importRequest.type(request.param("type")); } catch (Exception e) { try { XContentBuilder builder = RestXContentBuilder.restContentBuilder(request); channel.sendResponse(new XContentRestResponse(request, BAD_REQUEST, builder.startObject().field("error", e.getMessage()).endObject())); } catch (IOException e1) { logger.error("Failed to send failure response", e1); } return; }
client.execute(action(), importRequest, new ActionListener<ImportResponse>() {
crate/elasticsearch-inout-plugin
src/main/java/crate/elasticsearch/import_/ImportBulkListener.java
// Path: src/main/java/crate/elasticsearch/import_/Importer.java // public static class ImportCounts { // public String fileName; // public int successes = 0; // public int failures = 0; // public int invalid = 0; // }
import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicLong; import org.elasticsearch.action.bulk.BulkItemResponse; import org.elasticsearch.action.bulk.BulkProcessor; import org.elasticsearch.action.bulk.BulkRequest; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.common.util.concurrent.BaseFuture; import crate.elasticsearch.import_.Importer.ImportCounts;
package crate.elasticsearch.import_; public class ImportBulkListener extends BaseFuture<ImportBulkListener> implements BulkProcessor.Listener { private AtomicLong bulksInProgress = new AtomicLong();
// Path: src/main/java/crate/elasticsearch/import_/Importer.java // public static class ImportCounts { // public String fileName; // public int successes = 0; // public int failures = 0; // public int invalid = 0; // } // Path: src/main/java/crate/elasticsearch/import_/ImportBulkListener.java import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicLong; import org.elasticsearch.action.bulk.BulkItemResponse; import org.elasticsearch.action.bulk.BulkProcessor; import org.elasticsearch.action.bulk.BulkRequest; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.common.util.concurrent.BaseFuture; import crate.elasticsearch.import_.Importer.ImportCounts; package crate.elasticsearch.import_; public class ImportBulkListener extends BaseFuture<ImportBulkListener> implements BulkProcessor.Listener { private AtomicLong bulksInProgress = new AtomicLong();
private ImportCounts counts = new ImportCounts();
crate/elasticsearch-inout-plugin
src/main/java/crate/elasticsearch/action/reindex/ReindexParser.java
// Path: src/main/java/crate/elasticsearch/action/searchinto/SearchIntoContext.java // public class SearchIntoContext extends SearchContext { // // // currently we only support index targets // private String targetType = "index"; // // private List<InetSocketTransportAddress> targetNodes; // // // public Map<String, String> outputNames() { // return outputNames; // } // // private final Map<String, String> outputNames = new HashMap<String, // String>(); // // public SearchIntoContext(long id, ShardSearchRequest request, // SearchShardTarget shardTarget, Engine.Searcher engineSearcher, // IndexService indexService, IndexShard indexShard, // ScriptService scriptService, CacheRecycler cacheRecycler) { // super(id, request, shardTarget, engineSearcher, indexService, // indexShard, scriptService, cacheRecycler); // } // // public String targetType() { // // this is currently the only type supported // return targetType; // } // // public List<InetSocketTransportAddress> targetNodes() { // if (targetNodes == null) { // targetNodes = Lists.newArrayList(); // } // return targetNodes; // } // // public void emptyTargetNodes() { // this.targetNodes = ImmutableList.of(); // } // // } // // Path: src/main/java/crate/elasticsearch/action/searchinto/parser/AbstractSearchIntoParser.java // public abstract class AbstractSearchIntoParser implements ISearchIntoParser { // // /** // * Main method of this class to parse given payload of _search_into action // * // * @param context // * @param source // * @throws org.elasticsearch.search.SearchParseException // * // */ // public void parseSource(SearchIntoContext context, // BytesReference source) throws SearchParseException { // XContentParser parser = null; // try { // if (source != null) { // parser = XContentFactory.xContent(source).createParser(source); // XContentParser.Token token; // while ((token = parser.nextToken()) != XContentParser.Token // .END_OBJECT) { // if (token == XContentParser.Token.FIELD_NAME) { // String fieldName = parser.currentName(); // parser.nextToken(); // SearchParseElement element = getElementParsers().get( // fieldName); // if (element == null) { // throw new SearchParseException(context, // "No parser for element [" + fieldName + // "]"); // } // element.parse(parser, context); // } else if (token == null) { // break; // } // } // } // validate(context); // } catch (Exception e) { // String sSource = "_na_"; // try { // sSource = XContentHelper.convertToJson(source, false); // } catch (Throwable e1) { // // ignore // } // throw new SearchParseException(context, // "Failed to parse source [" + sSource + "]", e); // } finally { // if (parser != null) { // parser.close(); // } // } // } // // /** // * Get the element parser map // * @return // */ // protected abstract ImmutableMap<String, SearchParseElement> getElementParsers(); // // /** // * Validate the pay load of the search-into context. // * @param context // */ // protected void validate(SearchIntoContext context) { // if (context.hasFieldNames() && context.fieldNames().contains("_source")) { // String index = context.mapperService().index().getName(); // for (String type : context.mapperService().types()) { // if (!context.mapperService().documentMapper(type).sourceMapper().enabled()) { // throw new SearchParseException(context, // "The _source field of index " + index + " and type " + type + " is not stored."); // } // } // } // } // }
import java.util.HashMap; import java.util.Map; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.collect.ImmutableMap; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.search.SearchParseElement; import org.elasticsearch.search.SearchParseException; import org.elasticsearch.search.fetch.FetchPhase; import org.elasticsearch.search.fetch.explain.ExplainParseElement; import org.elasticsearch.search.query.QueryPhase; import crate.elasticsearch.action.searchinto.SearchIntoContext; import crate.elasticsearch.action.searchinto.parser.AbstractSearchIntoParser; import crate.elasticsearch.action.searchinto.parser.ISearchIntoParser;
package crate.elasticsearch.action.reindex; /** * Parser for pay load given to _reindex action. */ public class ReindexParser extends AbstractSearchIntoParser implements ISearchIntoParser { private final ImmutableMap<String, SearchParseElement> elementParsers; @Inject public ReindexParser(QueryPhase queryPhase, FetchPhase fetchPhase) { Map<String, SearchParseElement> elementParsers = new HashMap<String, SearchParseElement>(); elementParsers.putAll(queryPhase.parseElements()); elementParsers.put("explain", new ExplainParseElement()); this.elementParsers = ImmutableMap.copyOf(elementParsers); } @Override protected ImmutableMap<String, SearchParseElement> getElementParsers() { return elementParsers; } @Override
// Path: src/main/java/crate/elasticsearch/action/searchinto/SearchIntoContext.java // public class SearchIntoContext extends SearchContext { // // // currently we only support index targets // private String targetType = "index"; // // private List<InetSocketTransportAddress> targetNodes; // // // public Map<String, String> outputNames() { // return outputNames; // } // // private final Map<String, String> outputNames = new HashMap<String, // String>(); // // public SearchIntoContext(long id, ShardSearchRequest request, // SearchShardTarget shardTarget, Engine.Searcher engineSearcher, // IndexService indexService, IndexShard indexShard, // ScriptService scriptService, CacheRecycler cacheRecycler) { // super(id, request, shardTarget, engineSearcher, indexService, // indexShard, scriptService, cacheRecycler); // } // // public String targetType() { // // this is currently the only type supported // return targetType; // } // // public List<InetSocketTransportAddress> targetNodes() { // if (targetNodes == null) { // targetNodes = Lists.newArrayList(); // } // return targetNodes; // } // // public void emptyTargetNodes() { // this.targetNodes = ImmutableList.of(); // } // // } // // Path: src/main/java/crate/elasticsearch/action/searchinto/parser/AbstractSearchIntoParser.java // public abstract class AbstractSearchIntoParser implements ISearchIntoParser { // // /** // * Main method of this class to parse given payload of _search_into action // * // * @param context // * @param source // * @throws org.elasticsearch.search.SearchParseException // * // */ // public void parseSource(SearchIntoContext context, // BytesReference source) throws SearchParseException { // XContentParser parser = null; // try { // if (source != null) { // parser = XContentFactory.xContent(source).createParser(source); // XContentParser.Token token; // while ((token = parser.nextToken()) != XContentParser.Token // .END_OBJECT) { // if (token == XContentParser.Token.FIELD_NAME) { // String fieldName = parser.currentName(); // parser.nextToken(); // SearchParseElement element = getElementParsers().get( // fieldName); // if (element == null) { // throw new SearchParseException(context, // "No parser for element [" + fieldName + // "]"); // } // element.parse(parser, context); // } else if (token == null) { // break; // } // } // } // validate(context); // } catch (Exception e) { // String sSource = "_na_"; // try { // sSource = XContentHelper.convertToJson(source, false); // } catch (Throwable e1) { // // ignore // } // throw new SearchParseException(context, // "Failed to parse source [" + sSource + "]", e); // } finally { // if (parser != null) { // parser.close(); // } // } // } // // /** // * Get the element parser map // * @return // */ // protected abstract ImmutableMap<String, SearchParseElement> getElementParsers(); // // /** // * Validate the pay load of the search-into context. // * @param context // */ // protected void validate(SearchIntoContext context) { // if (context.hasFieldNames() && context.fieldNames().contains("_source")) { // String index = context.mapperService().index().getName(); // for (String type : context.mapperService().types()) { // if (!context.mapperService().documentMapper(type).sourceMapper().enabled()) { // throw new SearchParseException(context, // "The _source field of index " + index + " and type " + type + " is not stored."); // } // } // } // } // } // Path: src/main/java/crate/elasticsearch/action/reindex/ReindexParser.java import java.util.HashMap; import java.util.Map; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.collect.ImmutableMap; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.search.SearchParseElement; import org.elasticsearch.search.SearchParseException; import org.elasticsearch.search.fetch.FetchPhase; import org.elasticsearch.search.fetch.explain.ExplainParseElement; import org.elasticsearch.search.query.QueryPhase; import crate.elasticsearch.action.searchinto.SearchIntoContext; import crate.elasticsearch.action.searchinto.parser.AbstractSearchIntoParser; import crate.elasticsearch.action.searchinto.parser.ISearchIntoParser; package crate.elasticsearch.action.reindex; /** * Parser for pay load given to _reindex action. */ public class ReindexParser extends AbstractSearchIntoParser implements ISearchIntoParser { private final ImmutableMap<String, SearchParseElement> elementParsers; @Inject public ReindexParser(QueryPhase queryPhase, FetchPhase fetchPhase) { Map<String, SearchParseElement> elementParsers = new HashMap<String, SearchParseElement>(); elementParsers.putAll(queryPhase.parseElements()); elementParsers.put("explain", new ExplainParseElement()); this.elementParsers = ImmutableMap.copyOf(elementParsers); } @Override protected ImmutableMap<String, SearchParseElement> getElementParsers() { return elementParsers; } @Override
public void parseSource(SearchIntoContext context, BytesReference source)
crate/elasticsearch-inout-plugin
src/main/java/crate/elasticsearch/action/dump/parser/DumpDirectoryParseElement.java
// Path: src/main/java/crate/elasticsearch/action/export/ExportContext.java // public class ExportContext extends SearchContext { // // private static final String VAR_SHARD = "${shard}"; // private static final String VAR_INDEX = "${index}"; // private static final String VAR_CLUSTER = "${cluster}"; // // private List<String> outputCmdArray; // private String outputCmd; // private String outputFile; // private boolean forceOverride = false; // private boolean compression; // private String nodePath; // private boolean mappings = false; // private boolean settings = false; // // public ExportContext(long id, ShardSearchRequest request, SearchShardTarget shardTarget, // Engine.Searcher engineSearcher, IndexService indexService, IndexShard indexShard, // ScriptService scriptService, CacheRecycler cacheRecycler, String nodePath) { // super(id, request, shardTarget, engineSearcher, indexService, indexShard, scriptService, cacheRecycler); // this.nodePath = nodePath; // } // // public List<String> outputCmdArray() { // return outputCmdArray; // } // // public void outputCmdArray(List<String> outputCmdArray) { // this.outputCmdArray = applyVars(outputCmdArray); // } // // public String outputCmd() { // return outputCmd; // } // // public void outputCmd(String outputCmd) { // this.outputCmd = applyVars(outputCmd); // } // // public String outputFile() { // return outputFile; // } // // public void outputFile(String outputFile) { // outputFile = applyVars(outputFile); // File outFile = new File(outputFile); // if (!outFile.isAbsolute() && nodePath != null) { // outputFile = new File(nodePath, outputFile).getAbsolutePath(); // } // this.outputFile = outputFile; // } // // public boolean mappings() { // return mappings; // } // // public void mappings(boolean mappings) { // this.mappings = mappings; // } // // public boolean settings() { // return settings; // } // // public void settings(boolean settings) { // this.settings = settings; // } // // public String nodePath() { // return nodePath; // } // // public boolean forceOverride() { // return forceOverride; // } // // public void forceOverride(boolean forceOverride) { // this.forceOverride = forceOverride; // } // // public void compression(boolean compression) { // this.compression = compression; // } // // public boolean compression() { // return this.compression; // } // // /** // * Replaces variable placeholder with actual value in all elements of templateArray // * // * @param templateArray // * @return // */ // private List<String> applyVars(List<String> templateArray) { // List<String> ret = new ArrayList<String>(); // for (String part : templateArray) { // ret.add(applyVars(part)); // } // return ret; // } // // /** // * Replaces variable placeholder with actual value // * // * @param template // * @return // */ // private String applyVars(String template) { // template = template.replace(VAR_SHARD, String.valueOf(indexShard().shardId().getId())); // template = template.replace(VAR_INDEX, indexShard().shardId().getIndex()); // template = template.replace(VAR_CLUSTER, clusterName()); // return template; // } // // /** // * Method to retrieve name of cluster // * // * @return name of cluster // */ // private String clusterName() { // return ClusterName.clusterNameFromSettings(this.indexShard().indexSettings()).value(); // } // // public Output createOutput() { // if (outputFile()!=null){ // return new OutputFile(outputFile(), forceOverride(), compression); // } else { // if (outputCmd()!=null){ // return new OutputCommand(outputCmd(), compression); // } else { // return new OutputCommand(outputCmdArray(), compression); // } // } // } // } // // Path: src/main/java/crate/elasticsearch/action/import_/ImportContext.java // public class ImportContext { // // private String nodePath; // private boolean compression; // private String directory; // private Pattern file_pattern; // private boolean mappings = false; // private boolean settings = false; // // public ImportContext(String nodePath) { // this.nodePath = nodePath; // } // // public boolean compression() { // return compression; // } // // public void compression(boolean compression) { // this.compression = compression; // } // // public String directory() { // return directory; // } // // public void directory(String directory) { // File file = new File(directory); // if (!file.isAbsolute() && nodePath != null) { // file = new File(nodePath, directory); // directory = file.getAbsolutePath(); // } // this.directory = directory; // } // // public Pattern file_pattern() { // return file_pattern; // } // // public void file_pattern(Pattern file_pattern) { // this.file_pattern = file_pattern; // } // // public boolean mappings() { // return mappings; // } // // public void mappings(boolean mappings) { // this.mappings = mappings; // } // // public boolean settings() { // return settings; // } // // public void settings(boolean settings) { // this.settings = settings; // } // }
import crate.elasticsearch.action.export.ExportContext; import crate.elasticsearch.action.import_.ImportContext; import crate.elasticsearch.action.import_.parser.ImportParseElement; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.search.SearchParseElement; import org.elasticsearch.search.internal.SearchContext; import java.io.File;
package crate.elasticsearch.action.dump.parser; /** * Parser element class to parse a given 'directory' option to the _dump endpoint */ public class DumpDirectoryParseElement implements SearchParseElement { @Override public void parse(XContentParser parser, SearchContext context) throws Exception { XContentParser.Token token = parser.currentToken(); if (token.isValue()) {
// Path: src/main/java/crate/elasticsearch/action/export/ExportContext.java // public class ExportContext extends SearchContext { // // private static final String VAR_SHARD = "${shard}"; // private static final String VAR_INDEX = "${index}"; // private static final String VAR_CLUSTER = "${cluster}"; // // private List<String> outputCmdArray; // private String outputCmd; // private String outputFile; // private boolean forceOverride = false; // private boolean compression; // private String nodePath; // private boolean mappings = false; // private boolean settings = false; // // public ExportContext(long id, ShardSearchRequest request, SearchShardTarget shardTarget, // Engine.Searcher engineSearcher, IndexService indexService, IndexShard indexShard, // ScriptService scriptService, CacheRecycler cacheRecycler, String nodePath) { // super(id, request, shardTarget, engineSearcher, indexService, indexShard, scriptService, cacheRecycler); // this.nodePath = nodePath; // } // // public List<String> outputCmdArray() { // return outputCmdArray; // } // // public void outputCmdArray(List<String> outputCmdArray) { // this.outputCmdArray = applyVars(outputCmdArray); // } // // public String outputCmd() { // return outputCmd; // } // // public void outputCmd(String outputCmd) { // this.outputCmd = applyVars(outputCmd); // } // // public String outputFile() { // return outputFile; // } // // public void outputFile(String outputFile) { // outputFile = applyVars(outputFile); // File outFile = new File(outputFile); // if (!outFile.isAbsolute() && nodePath != null) { // outputFile = new File(nodePath, outputFile).getAbsolutePath(); // } // this.outputFile = outputFile; // } // // public boolean mappings() { // return mappings; // } // // public void mappings(boolean mappings) { // this.mappings = mappings; // } // // public boolean settings() { // return settings; // } // // public void settings(boolean settings) { // this.settings = settings; // } // // public String nodePath() { // return nodePath; // } // // public boolean forceOverride() { // return forceOverride; // } // // public void forceOverride(boolean forceOverride) { // this.forceOverride = forceOverride; // } // // public void compression(boolean compression) { // this.compression = compression; // } // // public boolean compression() { // return this.compression; // } // // /** // * Replaces variable placeholder with actual value in all elements of templateArray // * // * @param templateArray // * @return // */ // private List<String> applyVars(List<String> templateArray) { // List<String> ret = new ArrayList<String>(); // for (String part : templateArray) { // ret.add(applyVars(part)); // } // return ret; // } // // /** // * Replaces variable placeholder with actual value // * // * @param template // * @return // */ // private String applyVars(String template) { // template = template.replace(VAR_SHARD, String.valueOf(indexShard().shardId().getId())); // template = template.replace(VAR_INDEX, indexShard().shardId().getIndex()); // template = template.replace(VAR_CLUSTER, clusterName()); // return template; // } // // /** // * Method to retrieve name of cluster // * // * @return name of cluster // */ // private String clusterName() { // return ClusterName.clusterNameFromSettings(this.indexShard().indexSettings()).value(); // } // // public Output createOutput() { // if (outputFile()!=null){ // return new OutputFile(outputFile(), forceOverride(), compression); // } else { // if (outputCmd()!=null){ // return new OutputCommand(outputCmd(), compression); // } else { // return new OutputCommand(outputCmdArray(), compression); // } // } // } // } // // Path: src/main/java/crate/elasticsearch/action/import_/ImportContext.java // public class ImportContext { // // private String nodePath; // private boolean compression; // private String directory; // private Pattern file_pattern; // private boolean mappings = false; // private boolean settings = false; // // public ImportContext(String nodePath) { // this.nodePath = nodePath; // } // // public boolean compression() { // return compression; // } // // public void compression(boolean compression) { // this.compression = compression; // } // // public String directory() { // return directory; // } // // public void directory(String directory) { // File file = new File(directory); // if (!file.isAbsolute() && nodePath != null) { // file = new File(nodePath, directory); // directory = file.getAbsolutePath(); // } // this.directory = directory; // } // // public Pattern file_pattern() { // return file_pattern; // } // // public void file_pattern(Pattern file_pattern) { // this.file_pattern = file_pattern; // } // // public boolean mappings() { // return mappings; // } // // public void mappings(boolean mappings) { // this.mappings = mappings; // } // // public boolean settings() { // return settings; // } // // public void settings(boolean settings) { // this.settings = settings; // } // } // Path: src/main/java/crate/elasticsearch/action/dump/parser/DumpDirectoryParseElement.java import crate.elasticsearch.action.export.ExportContext; import crate.elasticsearch.action.import_.ImportContext; import crate.elasticsearch.action.import_.parser.ImportParseElement; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.search.SearchParseElement; import org.elasticsearch.search.internal.SearchContext; import java.io.File; package crate.elasticsearch.action.dump.parser; /** * Parser element class to parse a given 'directory' option to the _dump endpoint */ public class DumpDirectoryParseElement implements SearchParseElement { @Override public void parse(XContentParser parser, SearchContext context) throws Exception { XContentParser.Token token = parser.currentToken(); if (token.isValue()) {
setOutPutFile((ExportContext) context, parser.text());
crate/elasticsearch-inout-plugin
src/main/java/crate/elasticsearch/action/export/parser/ExportOutputFileParseElement.java
// Path: src/main/java/crate/elasticsearch/action/export/ExportContext.java // public class ExportContext extends SearchContext { // // private static final String VAR_SHARD = "${shard}"; // private static final String VAR_INDEX = "${index}"; // private static final String VAR_CLUSTER = "${cluster}"; // // private List<String> outputCmdArray; // private String outputCmd; // private String outputFile; // private boolean forceOverride = false; // private boolean compression; // private String nodePath; // private boolean mappings = false; // private boolean settings = false; // // public ExportContext(long id, ShardSearchRequest request, SearchShardTarget shardTarget, // Engine.Searcher engineSearcher, IndexService indexService, IndexShard indexShard, // ScriptService scriptService, CacheRecycler cacheRecycler, String nodePath) { // super(id, request, shardTarget, engineSearcher, indexService, indexShard, scriptService, cacheRecycler); // this.nodePath = nodePath; // } // // public List<String> outputCmdArray() { // return outputCmdArray; // } // // public void outputCmdArray(List<String> outputCmdArray) { // this.outputCmdArray = applyVars(outputCmdArray); // } // // public String outputCmd() { // return outputCmd; // } // // public void outputCmd(String outputCmd) { // this.outputCmd = applyVars(outputCmd); // } // // public String outputFile() { // return outputFile; // } // // public void outputFile(String outputFile) { // outputFile = applyVars(outputFile); // File outFile = new File(outputFile); // if (!outFile.isAbsolute() && nodePath != null) { // outputFile = new File(nodePath, outputFile).getAbsolutePath(); // } // this.outputFile = outputFile; // } // // public boolean mappings() { // return mappings; // } // // public void mappings(boolean mappings) { // this.mappings = mappings; // } // // public boolean settings() { // return settings; // } // // public void settings(boolean settings) { // this.settings = settings; // } // // public String nodePath() { // return nodePath; // } // // public boolean forceOverride() { // return forceOverride; // } // // public void forceOverride(boolean forceOverride) { // this.forceOverride = forceOverride; // } // // public void compression(boolean compression) { // this.compression = compression; // } // // public boolean compression() { // return this.compression; // } // // /** // * Replaces variable placeholder with actual value in all elements of templateArray // * // * @param templateArray // * @return // */ // private List<String> applyVars(List<String> templateArray) { // List<String> ret = new ArrayList<String>(); // for (String part : templateArray) { // ret.add(applyVars(part)); // } // return ret; // } // // /** // * Replaces variable placeholder with actual value // * // * @param template // * @return // */ // private String applyVars(String template) { // template = template.replace(VAR_SHARD, String.valueOf(indexShard().shardId().getId())); // template = template.replace(VAR_INDEX, indexShard().shardId().getIndex()); // template = template.replace(VAR_CLUSTER, clusterName()); // return template; // } // // /** // * Method to retrieve name of cluster // * // * @return name of cluster // */ // private String clusterName() { // return ClusterName.clusterNameFromSettings(this.indexShard().indexSettings()).value(); // } // // public Output createOutput() { // if (outputFile()!=null){ // return new OutputFile(outputFile(), forceOverride(), compression); // } else { // if (outputCmd()!=null){ // return new OutputCommand(outputCmd(), compression); // } else { // return new OutputCommand(outputCmdArray(), compression); // } // } // } // }
import crate.elasticsearch.action.export.ExportContext; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.search.SearchParseElement; import org.elasticsearch.search.internal.SearchContext;
package crate.elasticsearch.action.export.parser; /** * Parser for token ``output_file``. The value of the token must be a String. * <p/> * <pre> * "output_file": "/tmp/out" * </pre> */ public class ExportOutputFileParseElement implements SearchParseElement { @Override public void parse(XContentParser parser, SearchContext context) throws Exception { XContentParser.Token token = parser.currentToken(); if (token.isValue()) {
// Path: src/main/java/crate/elasticsearch/action/export/ExportContext.java // public class ExportContext extends SearchContext { // // private static final String VAR_SHARD = "${shard}"; // private static final String VAR_INDEX = "${index}"; // private static final String VAR_CLUSTER = "${cluster}"; // // private List<String> outputCmdArray; // private String outputCmd; // private String outputFile; // private boolean forceOverride = false; // private boolean compression; // private String nodePath; // private boolean mappings = false; // private boolean settings = false; // // public ExportContext(long id, ShardSearchRequest request, SearchShardTarget shardTarget, // Engine.Searcher engineSearcher, IndexService indexService, IndexShard indexShard, // ScriptService scriptService, CacheRecycler cacheRecycler, String nodePath) { // super(id, request, shardTarget, engineSearcher, indexService, indexShard, scriptService, cacheRecycler); // this.nodePath = nodePath; // } // // public List<String> outputCmdArray() { // return outputCmdArray; // } // // public void outputCmdArray(List<String> outputCmdArray) { // this.outputCmdArray = applyVars(outputCmdArray); // } // // public String outputCmd() { // return outputCmd; // } // // public void outputCmd(String outputCmd) { // this.outputCmd = applyVars(outputCmd); // } // // public String outputFile() { // return outputFile; // } // // public void outputFile(String outputFile) { // outputFile = applyVars(outputFile); // File outFile = new File(outputFile); // if (!outFile.isAbsolute() && nodePath != null) { // outputFile = new File(nodePath, outputFile).getAbsolutePath(); // } // this.outputFile = outputFile; // } // // public boolean mappings() { // return mappings; // } // // public void mappings(boolean mappings) { // this.mappings = mappings; // } // // public boolean settings() { // return settings; // } // // public void settings(boolean settings) { // this.settings = settings; // } // // public String nodePath() { // return nodePath; // } // // public boolean forceOverride() { // return forceOverride; // } // // public void forceOverride(boolean forceOverride) { // this.forceOverride = forceOverride; // } // // public void compression(boolean compression) { // this.compression = compression; // } // // public boolean compression() { // return this.compression; // } // // /** // * Replaces variable placeholder with actual value in all elements of templateArray // * // * @param templateArray // * @return // */ // private List<String> applyVars(List<String> templateArray) { // List<String> ret = new ArrayList<String>(); // for (String part : templateArray) { // ret.add(applyVars(part)); // } // return ret; // } // // /** // * Replaces variable placeholder with actual value // * // * @param template // * @return // */ // private String applyVars(String template) { // template = template.replace(VAR_SHARD, String.valueOf(indexShard().shardId().getId())); // template = template.replace(VAR_INDEX, indexShard().shardId().getIndex()); // template = template.replace(VAR_CLUSTER, clusterName()); // return template; // } // // /** // * Method to retrieve name of cluster // * // * @return name of cluster // */ // private String clusterName() { // return ClusterName.clusterNameFromSettings(this.indexShard().indexSettings()).value(); // } // // public Output createOutput() { // if (outputFile()!=null){ // return new OutputFile(outputFile(), forceOverride(), compression); // } else { // if (outputCmd()!=null){ // return new OutputCommand(outputCmd(), compression); // } else { // return new OutputCommand(outputCmdArray(), compression); // } // } // } // } // Path: src/main/java/crate/elasticsearch/action/export/parser/ExportOutputFileParseElement.java import crate.elasticsearch.action.export.ExportContext; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.search.SearchParseElement; import org.elasticsearch.search.internal.SearchContext; package crate.elasticsearch.action.export.parser; /** * Parser for token ``output_file``. The value of the token must be a String. * <p/> * <pre> * "output_file": "/tmp/out" * </pre> */ public class ExportOutputFileParseElement implements SearchParseElement { @Override public void parse(XContentParser parser, SearchContext context) throws Exception { XContentParser.Token token = parser.currentToken(); if (token.isValue()) {
((ExportContext) context).outputFile(parser.text());
titokone/titokone
src/main/java/fi/helsinki/cs/titokone/Display.java
// Path: src/main/java/fi/helsinki/cs/ttk91/TTK91Memory.java // public interface TTK91Memory { // /** // * @return the size of the memory. // */ // public int getSize(); // // /** // * First usable index is 0, last is getSize()-1 // * // * @param memoryslot memory address where required data is // * @return data from requested address // */ // public int getValue(int memoryslot); // // /** // * @return HashMap with symbol name as a key, and Integer as value. // * Integer describes the memory slot where the value is stored. // */ // public HashMap<String, Integer> getSymbolTable(); // // /** // * @return whole memory as a dump // */ // public int[] getMemory(); // // /** // * @return a code area dump. assumed to be located from // * offset 0 to "codeAreaSize" // */ // public int[] getCodeArea(); // // /** // * @return a data area dump. Assumed to be located beginning // * from the end of codeAreaSize to codeAreaSize+dataAreaSize // */ // public int[] getDataArea(); // }
import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; import fi.helsinki.cs.ttk91.TTK91Memory;
// Copyright © 2004-2006 University of Helsinki, Department of Computer Science // Copyright © 2012 various contributors // This software is released under GNU Lesser General Public License 2.1. // The license text is at http://www.gnu.org/licenses/lgpl-2.1.html package fi.helsinki.cs.titokone; // Display class was added by Toni Ruottu 8.4.2012 public class Display extends JPanel implements Runnable { static final int fontWidth = 5, fontHeight = 6; static final int X = 160, Y = 120; static final int MARGIN = 50; //30 minimum real pixel margin on every side static final int DEFAULT_START = 0x2000;
// Path: src/main/java/fi/helsinki/cs/ttk91/TTK91Memory.java // public interface TTK91Memory { // /** // * @return the size of the memory. // */ // public int getSize(); // // /** // * First usable index is 0, last is getSize()-1 // * // * @param memoryslot memory address where required data is // * @return data from requested address // */ // public int getValue(int memoryslot); // // /** // * @return HashMap with symbol name as a key, and Integer as value. // * Integer describes the memory slot where the value is stored. // */ // public HashMap<String, Integer> getSymbolTable(); // // /** // * @return whole memory as a dump // */ // public int[] getMemory(); // // /** // * @return a code area dump. assumed to be located from // * offset 0 to "codeAreaSize" // */ // public int[] getCodeArea(); // // /** // * @return a data area dump. Assumed to be located beginning // * from the end of codeAreaSize to codeAreaSize+dataAreaSize // */ // public int[] getDataArea(); // } // Path: src/main/java/fi/helsinki/cs/titokone/Display.java import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; import fi.helsinki.cs.ttk91.TTK91Memory; // Copyright © 2004-2006 University of Helsinki, Department of Computer Science // Copyright © 2012 various contributors // This software is released under GNU Lesser General Public License 2.1. // The license text is at http://www.gnu.org/licenses/lgpl-2.1.html package fi.helsinki.cs.titokone; // Display class was added by Toni Ruottu 8.4.2012 public class Display extends JPanel implements Runnable { static final int fontWidth = 5, fontHeight = 6; static final int X = 160, Y = 120; static final int MARGIN = 50; //30 minimum real pixel margin on every side static final int DEFAULT_START = 0x2000;
static TTK91Memory mem;
titokone/titokone
src/main/java/fi/helsinki/cs/titokone/Compiler.java
// Path: src/main/java/fi/helsinki/cs/ttk91/TTK91CompileException.java // public class TTK91CompileException extends TTK91Exception { // public TTK91CompileException(String message) { // super(message); // } // }
import fi.helsinki.cs.ttk91.TTK91CompileException; import java.util.*; import fi.helsinki.cs.titokone.devices.DeviceNames;
code = new Vector<String>(); symbols = new HashMap<String, Integer>(); symbolTable = new Vector<String[]>(); invalidLabels = new HashMap<String, Integer>(); invalidLabels.putAll(DeviceNames.DEVICES); invalidLabels.putAll(SvcNames.SVCS); } /** * This function goes through one line of the code. On the first * round, it gathers the symbols and their definitions to a * symbol table and conducts syntax-checking, on the second round * it transforms each command to its binary format. For the * transformations, the CompileConstants class is used. It calls * the private methods firstRoundProcess() and * secondRoundProcess() to do the actual work, if there is any to * do. The transfer from first round of compilation to the * second is done automatically; during it, * initializeSecondRound() is called. * * @return A CompileInfo debug information object, describing * what happened during the compilation of this line and whether * this is the first or second round of compilation or null if * there are no more lines left to process. * @throws TTK91CompileException If a) there is a syntax error * during the first round of checking (error code 101) or b) a * symbol is still undefined after the first round of compilation * is finished. */
// Path: src/main/java/fi/helsinki/cs/ttk91/TTK91CompileException.java // public class TTK91CompileException extends TTK91Exception { // public TTK91CompileException(String message) { // super(message); // } // } // Path: src/main/java/fi/helsinki/cs/titokone/Compiler.java import fi.helsinki.cs.ttk91.TTK91CompileException; import java.util.*; import fi.helsinki.cs.titokone.devices.DeviceNames; code = new Vector<String>(); symbols = new HashMap<String, Integer>(); symbolTable = new Vector<String[]>(); invalidLabels = new HashMap<String, Integer>(); invalidLabels.putAll(DeviceNames.DEVICES); invalidLabels.putAll(SvcNames.SVCS); } /** * This function goes through one line of the code. On the first * round, it gathers the symbols and their definitions to a * symbol table and conducts syntax-checking, on the second round * it transforms each command to its binary format. For the * transformations, the CompileConstants class is used. It calls * the private methods firstRoundProcess() and * secondRoundProcess() to do the actual work, if there is any to * do. The transfer from first round of compilation to the * second is done automatically; during it, * initializeSecondRound() is called. * * @return A CompileInfo debug information object, describing * what happened during the compilation of this line and whether * this is the first or second round of compilation or null if * there are no more lines left to process. * @throws TTK91CompileException If a) there is a syntax error * during the first round of checking (error code 101) or b) a * symbol is still undefined after the first round of compilation * is finished. */
public CompileInfo compileLine() throws TTK91CompileException {
titokone/titokone
src/main/java/fi/helsinki/cs/titokone/devices/AddressMappingIODevice.java
// Path: src/main/java/fi/helsinki/cs/ttk91/TTK91RuntimeException.java // public class TTK91RuntimeException extends TTK91Exception { // public TTK91RuntimeException(String message) { // super(message); // } // // public TTK91RuntimeException(Throwable cause) { // super(cause); // } // // public TTK91RuntimeException(String message, Throwable cause) { // super(message, cause); // } // // }
import fi.helsinki.cs.ttk91.TTK91RuntimeException; import fi.helsinki.cs.titokone.IODevice;
// Copyright © 2004-2006 University of Helsinki, Department of Computer Science // Copyright © 2012 various contributors // This software is released under GNU Lesser General Public License 2.1. // The license text is at http://www.gnu.org/licenses/lgpl-2.1.html package fi.helsinki.cs.titokone.devices; /** * a dummy device which maps underlying device to a new address */ public class AddressMappingIODevice implements IODevice { protected IODevice delegate; protected int base; public AddressMappingIODevice(int base, IODevice delegate) { this.delegate = delegate; this.base = base; if (delegate == null || base < 0 || base > 65000) { throw new IllegalArgumentException("delegate must not be null"); } } public int getPortCount() { return delegate.getPortCount(); } public int getPort(int n)
// Path: src/main/java/fi/helsinki/cs/ttk91/TTK91RuntimeException.java // public class TTK91RuntimeException extends TTK91Exception { // public TTK91RuntimeException(String message) { // super(message); // } // // public TTK91RuntimeException(Throwable cause) { // super(cause); // } // // public TTK91RuntimeException(String message, Throwable cause) { // super(message, cause); // } // // } // Path: src/main/java/fi/helsinki/cs/titokone/devices/AddressMappingIODevice.java import fi.helsinki.cs.ttk91.TTK91RuntimeException; import fi.helsinki.cs.titokone.IODevice; // Copyright © 2004-2006 University of Helsinki, Department of Computer Science // Copyright © 2012 various contributors // This software is released under GNU Lesser General Public License 2.1. // The license text is at http://www.gnu.org/licenses/lgpl-2.1.html package fi.helsinki.cs.titokone.devices; /** * a dummy device which maps underlying device to a new address */ public class AddressMappingIODevice implements IODevice { protected IODevice delegate; protected int base; public AddressMappingIODevice(int base, IODevice delegate) { this.delegate = delegate; this.base = base; if (delegate == null || base < 0 || base > 65000) { throw new IllegalArgumentException("delegate must not be null"); } } public int getPortCount() { return delegate.getPortCount(); } public int getPort(int n)
throws TTK91RuntimeException {
titokone/titokone
src/main/java/fi/helsinki/cs/titokone/Loader.java
// Path: src/main/java/fi/helsinki/cs/ttk91/TTK91AddressOutOfBounds.java // public class TTK91AddressOutOfBounds extends TTK91RuntimeException { // public TTK91AddressOutOfBounds(String message) { // super(message); // } // }
import fi.helsinki.cs.ttk91.TTK91AddressOutOfBounds;
// Copyright © 2004-2006 University of Helsinki, Department of Computer Science // Copyright © 2012 various contributors // This software is released under GNU Lesser General Public License 2.1. // The license text is at http://www.gnu.org/licenses/lgpl-2.1.html package fi.helsinki.cs.titokone; /** * This class can load a TTK91Application. It changes the processor * state accordingly. Everything is loaded when loadApplication is * called. Function returns the state of memory after loading. If it * runs out of memory it throws a TTK91AddressOutOfBounds exception. */ public class Loader { /** * This variable holds the current application to be loaded. */ private Application application; private Processor processor; private BinaryInterpreter binInterpreter; public Loader(Processor processor) { String errorMessage; if (processor == null) { errorMessage = new Message("Null is an invalid parameter," + " instance of {0} required.", Processor.class.getName()).toString(); throw new IllegalArgumentException(errorMessage); } this.processor = processor; binInterpreter = new BinaryInterpreter(); } /** * You can set the file to load. Each time an application is set to load, the counter is set to * one. */ public void setApplicationToLoad(Application application) { String errorMessage; if (application == null) { errorMessage = new Message("Null is an invalid parameter," + " instance of {0} required.", Application.class.getName()).toString(); throw new IllegalArgumentException(errorMessage); } this.application = application; } /** * Loads an application to memory. LoadInfo contains all the needed information about the process. * * @return Info from the load procedure, null if no application has been set for loading. */
// Path: src/main/java/fi/helsinki/cs/ttk91/TTK91AddressOutOfBounds.java // public class TTK91AddressOutOfBounds extends TTK91RuntimeException { // public TTK91AddressOutOfBounds(String message) { // super(message); // } // } // Path: src/main/java/fi/helsinki/cs/titokone/Loader.java import fi.helsinki.cs.ttk91.TTK91AddressOutOfBounds; // Copyright © 2004-2006 University of Helsinki, Department of Computer Science // Copyright © 2012 various contributors // This software is released under GNU Lesser General Public License 2.1. // The license text is at http://www.gnu.org/licenses/lgpl-2.1.html package fi.helsinki.cs.titokone; /** * This class can load a TTK91Application. It changes the processor * state accordingly. Everything is loaded when loadApplication is * called. Function returns the state of memory after loading. If it * runs out of memory it throws a TTK91AddressOutOfBounds exception. */ public class Loader { /** * This variable holds the current application to be loaded. */ private Application application; private Processor processor; private BinaryInterpreter binInterpreter; public Loader(Processor processor) { String errorMessage; if (processor == null) { errorMessage = new Message("Null is an invalid parameter," + " instance of {0} required.", Processor.class.getName()).toString(); throw new IllegalArgumentException(errorMessage); } this.processor = processor; binInterpreter = new BinaryInterpreter(); } /** * You can set the file to load. Each time an application is set to load, the counter is set to * one. */ public void setApplicationToLoad(Application application) { String errorMessage; if (application == null) { errorMessage = new Message("Null is an invalid parameter," + " instance of {0} required.", Application.class.getName()).toString(); throw new IllegalArgumentException(errorMessage); } this.application = application; } /** * Loads an application to memory. LoadInfo contains all the needed information about the process. * * @return Info from the load procedure, null if no application has been set for loading. */
public LoadInfo loadApplication() throws TTK91AddressOutOfBounds {
titokone/titokone
src/main/java/fi/helsinki/cs/titokone/devices/MMU.java
// Path: src/main/java/fi/helsinki/cs/ttk91/TTK91AddressOutOfBounds.java // public class TTK91AddressOutOfBounds extends TTK91RuntimeException { // public TTK91AddressOutOfBounds(String message) { // super(message); // } // }
import fi.helsinki.cs.ttk91.TTK91AddressOutOfBounds; import java.util.HashMap; import fi.helsinki.cs.titokone.*;
return getMem().getSize(); } public int getCodeAreaSize() { return getMem().getCodeAreaSize(); } public int getDataAreaSize() { return getMem().getDataAreaSize(); } public MemoryLine getMemoryLine(int index) { return getMem().getMemoryLine(mapslot(index)); } public MemoryLine[] getMemoryLines() { MemoryLine[] ret = getMem().getMemoryLines(); if (from != 0 || to != 0 || length != 0) { for (int i = 0; i < length; i++) { ret[to + i] = getMem().getMemoryLine(from + i); } } return ret; } public void setSymbolTable(SymbolTable symbols) { getMem().setSymbolTable(symbols); } public void setMemoryLine(int index, MemoryLine memoryLine)
// Path: src/main/java/fi/helsinki/cs/ttk91/TTK91AddressOutOfBounds.java // public class TTK91AddressOutOfBounds extends TTK91RuntimeException { // public TTK91AddressOutOfBounds(String message) { // super(message); // } // } // Path: src/main/java/fi/helsinki/cs/titokone/devices/MMU.java import fi.helsinki.cs.ttk91.TTK91AddressOutOfBounds; import java.util.HashMap; import fi.helsinki.cs.titokone.*; return getMem().getSize(); } public int getCodeAreaSize() { return getMem().getCodeAreaSize(); } public int getDataAreaSize() { return getMem().getDataAreaSize(); } public MemoryLine getMemoryLine(int index) { return getMem().getMemoryLine(mapslot(index)); } public MemoryLine[] getMemoryLines() { MemoryLine[] ret = getMem().getMemoryLines(); if (from != 0 || to != 0 || length != 0) { for (int i = 0; i < length; i++) { ret[to + i] = getMem().getMemoryLine(from + i); } } return ret; } public void setSymbolTable(SymbolTable symbols) { getMem().setSymbolTable(symbols); } public void setMemoryLine(int index, MemoryLine memoryLine)
throws TTK91AddressOutOfBounds {
OPEN-ENT-NG/rbs
src/main/java/net/atos/entng/rbs/service/pdf/PdfExportService.java
// Path: src/main/java/net/atos/entng/rbs/model/ExportRequest.java // public class ExportRequest { // // private static final SimpleDateFormat DATE_FORMATTER = new SimpleDateFormat("yyyy-MM-dd"); // public static final String USER_TZ = "usertimezone"; // public static final String START_DATE = "startdate"; // public static final String END_DATE = "enddate"; // public static final String FORMAT = "format"; // public static final String VIEW = "view"; // public static final String RESOURCE_IDS = "resourceIds"; // // public enum Format {ICAL, PDF} // // public enum View {DAY, WEEK, LIST, NA} // // private UserInfos userInfos; // private View view = View.WEEK; // private Format format = Format.ICAL; // private List<Long> resourceIds = new ArrayList<>(); // private String userTz; // Needed for dates to be expressed in the user time zone. (UTC by default) // private String startDate; // private String endDate; // // public ExportRequest(JsonObject data) { // this(data, null); // } // // public ExportRequest(JsonObject userExportRequest, UserInfos userInfos) { // this.userInfos = userInfos; // this.format = Format.valueOf(userExportRequest.getString(FORMAT)); // this.view = View.valueOf(userExportRequest.getString(VIEW)); // // this.userTz = userExportRequest.getString(USER_TZ); // // this.startDate = userExportRequest.getString(START_DATE); // this.endDate = userExportRequest.getString(END_DATE); // checkPeriodValid(startDate, endDate); // // try { // JsonArray userExportResourceArray = userExportRequest.getJsonArray(RESOURCE_IDS, new fr.wseduc.webutils.collections.JsonArray()); // for (Object resourceId : userExportResourceArray) { // this.resourceIds.add(new Long((Integer) resourceId)); // } // } catch (NumberFormatException | NullPointerException | ClassCastException e) { // throw new IllegalArgumentException("params resources must be defined with an array of Integer"); // } // // } // // private void checkPeriodValid(String startInput, String endInput) { // Date start; // Date end; // try { // start = DATE_FORMATTER.parse(startInput); // end = DATE_FORMATTER.parse(endInput); // } catch (NullPointerException | ParseException e) { // throw new IllegalArgumentException("params start and end date must be defined with YYYY-MM-DD format !"); // } // if (start.after(end)) { // throw new IllegalArgumentException("Param startdate must be before enddate"); // } // } // // public UserInfos getUserInfos() { // return userInfos; // } // // public View getView() { // return view; // } // // public Format getFormat() { // return format; // } // // public List<Long> getResourceIds() { // return resourceIds; // } // // public String getStartDate() { // return startDate; // } // // public String getEndDate() { // return endDate; // } // // // public void setFormat(Format format) { // this.format = format; // } // // public void setView(View view) { // this.view = view; // } // // public void setResourceIds(List<Long> resourceIds) { // this.resourceIds = resourceIds; // } // // public void setStartDate(String startDate) { // this.startDate = startDate; // } // // public void setEndDate(String endDate) { // this.endDate = endDate; // } // // public String getUserTz() { // return userTz; // } // // public void setUserTz(String userTz) { // this.userTz = userTz; // } // } // // Path: src/main/java/net/atos/entng/rbs/model/ExportResponse.java // public static ExportRequest.View getView(JsonObject exportResponse) { // String viewAsString = exportResponse.getString(ExportRequest.VIEW, ExportRequest.View.WEEK.name()); // return ExportRequest.View.valueOf(viewAsString); // }
import com.samskivert.mustache.Mustache; import com.samskivert.mustache.Template; import fr.wseduc.webutils.data.FileResolver; import io.vertx.core.AbstractVerticle; import io.vertx.core.shareddata.LocalMap; import net.atos.entng.rbs.model.ExportRequest; import io.vertx.core.AsyncResult; import io.vertx.core.Handler; import io.vertx.core.buffer.Buffer; import io.vertx.core.eventbus.Message; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; import java.io.StringWriter; import java.util.Locale; import java.util.Map; import static fr.wseduc.webutils.Utils.handlerToAsyncHandler; import static net.atos.entng.rbs.model.ExportResponse.getView;
results.put("message", e.getMessage()); message.reply(results); return; } }); } private JsonObject prepareData(JsonObject jsonExportResponse, String host, Locale locale, String userTimeZone) { JsonFormatter formatter = JsonFormatter.buildFormater(jsonExportResponse, host, locale, userTimeZone); JsonObject convertedJson = formatter.format(); JsonArray jsonFileArray = new fr.wseduc.webutils.collections.JsonArray(); jsonFileArray.add(convertedJson); return new JsonObject().put("export", jsonFileArray); } private String fillTemplate(String templateAsString, JsonObject preparedData) { Mustache.Compiler compiler = Mustache.compiler().defaultValue(""); Template template = compiler.compile(templateAsString); Map<String, Object> ctx = new JsonObject(preparedData.toString()).getMap(); StringWriter writer = new StringWriter(); template.execute(ctx, writer); return writer.getBuffer().toString(); } private String getTemplate(JsonObject exportResponse) { String htmlTemplateFile;
// Path: src/main/java/net/atos/entng/rbs/model/ExportRequest.java // public class ExportRequest { // // private static final SimpleDateFormat DATE_FORMATTER = new SimpleDateFormat("yyyy-MM-dd"); // public static final String USER_TZ = "usertimezone"; // public static final String START_DATE = "startdate"; // public static final String END_DATE = "enddate"; // public static final String FORMAT = "format"; // public static final String VIEW = "view"; // public static final String RESOURCE_IDS = "resourceIds"; // // public enum Format {ICAL, PDF} // // public enum View {DAY, WEEK, LIST, NA} // // private UserInfos userInfos; // private View view = View.WEEK; // private Format format = Format.ICAL; // private List<Long> resourceIds = new ArrayList<>(); // private String userTz; // Needed for dates to be expressed in the user time zone. (UTC by default) // private String startDate; // private String endDate; // // public ExportRequest(JsonObject data) { // this(data, null); // } // // public ExportRequest(JsonObject userExportRequest, UserInfos userInfos) { // this.userInfos = userInfos; // this.format = Format.valueOf(userExportRequest.getString(FORMAT)); // this.view = View.valueOf(userExportRequest.getString(VIEW)); // // this.userTz = userExportRequest.getString(USER_TZ); // // this.startDate = userExportRequest.getString(START_DATE); // this.endDate = userExportRequest.getString(END_DATE); // checkPeriodValid(startDate, endDate); // // try { // JsonArray userExportResourceArray = userExportRequest.getJsonArray(RESOURCE_IDS, new fr.wseduc.webutils.collections.JsonArray()); // for (Object resourceId : userExportResourceArray) { // this.resourceIds.add(new Long((Integer) resourceId)); // } // } catch (NumberFormatException | NullPointerException | ClassCastException e) { // throw new IllegalArgumentException("params resources must be defined with an array of Integer"); // } // // } // // private void checkPeriodValid(String startInput, String endInput) { // Date start; // Date end; // try { // start = DATE_FORMATTER.parse(startInput); // end = DATE_FORMATTER.parse(endInput); // } catch (NullPointerException | ParseException e) { // throw new IllegalArgumentException("params start and end date must be defined with YYYY-MM-DD format !"); // } // if (start.after(end)) { // throw new IllegalArgumentException("Param startdate must be before enddate"); // } // } // // public UserInfos getUserInfos() { // return userInfos; // } // // public View getView() { // return view; // } // // public Format getFormat() { // return format; // } // // public List<Long> getResourceIds() { // return resourceIds; // } // // public String getStartDate() { // return startDate; // } // // public String getEndDate() { // return endDate; // } // // // public void setFormat(Format format) { // this.format = format; // } // // public void setView(View view) { // this.view = view; // } // // public void setResourceIds(List<Long> resourceIds) { // this.resourceIds = resourceIds; // } // // public void setStartDate(String startDate) { // this.startDate = startDate; // } // // public void setEndDate(String endDate) { // this.endDate = endDate; // } // // public String getUserTz() { // return userTz; // } // // public void setUserTz(String userTz) { // this.userTz = userTz; // } // } // // Path: src/main/java/net/atos/entng/rbs/model/ExportResponse.java // public static ExportRequest.View getView(JsonObject exportResponse) { // String viewAsString = exportResponse.getString(ExportRequest.VIEW, ExportRequest.View.WEEK.name()); // return ExportRequest.View.valueOf(viewAsString); // } // Path: src/main/java/net/atos/entng/rbs/service/pdf/PdfExportService.java import com.samskivert.mustache.Mustache; import com.samskivert.mustache.Template; import fr.wseduc.webutils.data.FileResolver; import io.vertx.core.AbstractVerticle; import io.vertx.core.shareddata.LocalMap; import net.atos.entng.rbs.model.ExportRequest; import io.vertx.core.AsyncResult; import io.vertx.core.Handler; import io.vertx.core.buffer.Buffer; import io.vertx.core.eventbus.Message; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; import java.io.StringWriter; import java.util.Locale; import java.util.Map; import static fr.wseduc.webutils.Utils.handlerToAsyncHandler; import static net.atos.entng.rbs.model.ExportResponse.getView; results.put("message", e.getMessage()); message.reply(results); return; } }); } private JsonObject prepareData(JsonObject jsonExportResponse, String host, Locale locale, String userTimeZone) { JsonFormatter formatter = JsonFormatter.buildFormater(jsonExportResponse, host, locale, userTimeZone); JsonObject convertedJson = formatter.format(); JsonArray jsonFileArray = new fr.wseduc.webutils.collections.JsonArray(); jsonFileArray.add(convertedJson); return new JsonObject().put("export", jsonFileArray); } private String fillTemplate(String templateAsString, JsonObject preparedData) { Mustache.Compiler compiler = Mustache.compiler().defaultValue(""); Template template = compiler.compile(templateAsString); Map<String, Object> ctx = new JsonObject(preparedData.toString()).getMap(); StringWriter writer = new StringWriter(); template.execute(ctx, writer); return writer.getBuffer().toString(); } private String getTemplate(JsonObject exportResponse) { String htmlTemplateFile;
ExportRequest.View view = getView(exportResponse);
OPEN-ENT-NG/rbs
src/main/java/net/atos/entng/rbs/service/pdf/PdfExportService.java
// Path: src/main/java/net/atos/entng/rbs/model/ExportRequest.java // public class ExportRequest { // // private static final SimpleDateFormat DATE_FORMATTER = new SimpleDateFormat("yyyy-MM-dd"); // public static final String USER_TZ = "usertimezone"; // public static final String START_DATE = "startdate"; // public static final String END_DATE = "enddate"; // public static final String FORMAT = "format"; // public static final String VIEW = "view"; // public static final String RESOURCE_IDS = "resourceIds"; // // public enum Format {ICAL, PDF} // // public enum View {DAY, WEEK, LIST, NA} // // private UserInfos userInfos; // private View view = View.WEEK; // private Format format = Format.ICAL; // private List<Long> resourceIds = new ArrayList<>(); // private String userTz; // Needed for dates to be expressed in the user time zone. (UTC by default) // private String startDate; // private String endDate; // // public ExportRequest(JsonObject data) { // this(data, null); // } // // public ExportRequest(JsonObject userExportRequest, UserInfos userInfos) { // this.userInfos = userInfos; // this.format = Format.valueOf(userExportRequest.getString(FORMAT)); // this.view = View.valueOf(userExportRequest.getString(VIEW)); // // this.userTz = userExportRequest.getString(USER_TZ); // // this.startDate = userExportRequest.getString(START_DATE); // this.endDate = userExportRequest.getString(END_DATE); // checkPeriodValid(startDate, endDate); // // try { // JsonArray userExportResourceArray = userExportRequest.getJsonArray(RESOURCE_IDS, new fr.wseduc.webutils.collections.JsonArray()); // for (Object resourceId : userExportResourceArray) { // this.resourceIds.add(new Long((Integer) resourceId)); // } // } catch (NumberFormatException | NullPointerException | ClassCastException e) { // throw new IllegalArgumentException("params resources must be defined with an array of Integer"); // } // // } // // private void checkPeriodValid(String startInput, String endInput) { // Date start; // Date end; // try { // start = DATE_FORMATTER.parse(startInput); // end = DATE_FORMATTER.parse(endInput); // } catch (NullPointerException | ParseException e) { // throw new IllegalArgumentException("params start and end date must be defined with YYYY-MM-DD format !"); // } // if (start.after(end)) { // throw new IllegalArgumentException("Param startdate must be before enddate"); // } // } // // public UserInfos getUserInfos() { // return userInfos; // } // // public View getView() { // return view; // } // // public Format getFormat() { // return format; // } // // public List<Long> getResourceIds() { // return resourceIds; // } // // public String getStartDate() { // return startDate; // } // // public String getEndDate() { // return endDate; // } // // // public void setFormat(Format format) { // this.format = format; // } // // public void setView(View view) { // this.view = view; // } // // public void setResourceIds(List<Long> resourceIds) { // this.resourceIds = resourceIds; // } // // public void setStartDate(String startDate) { // this.startDate = startDate; // } // // public void setEndDate(String endDate) { // this.endDate = endDate; // } // // public String getUserTz() { // return userTz; // } // // public void setUserTz(String userTz) { // this.userTz = userTz; // } // } // // Path: src/main/java/net/atos/entng/rbs/model/ExportResponse.java // public static ExportRequest.View getView(JsonObject exportResponse) { // String viewAsString = exportResponse.getString(ExportRequest.VIEW, ExportRequest.View.WEEK.name()); // return ExportRequest.View.valueOf(viewAsString); // }
import com.samskivert.mustache.Mustache; import com.samskivert.mustache.Template; import fr.wseduc.webutils.data.FileResolver; import io.vertx.core.AbstractVerticle; import io.vertx.core.shareddata.LocalMap; import net.atos.entng.rbs.model.ExportRequest; import io.vertx.core.AsyncResult; import io.vertx.core.Handler; import io.vertx.core.buffer.Buffer; import io.vertx.core.eventbus.Message; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; import java.io.StringWriter; import java.util.Locale; import java.util.Map; import static fr.wseduc.webutils.Utils.handlerToAsyncHandler; import static net.atos.entng.rbs.model.ExportResponse.getView;
results.put("message", e.getMessage()); message.reply(results); return; } }); } private JsonObject prepareData(JsonObject jsonExportResponse, String host, Locale locale, String userTimeZone) { JsonFormatter formatter = JsonFormatter.buildFormater(jsonExportResponse, host, locale, userTimeZone); JsonObject convertedJson = formatter.format(); JsonArray jsonFileArray = new fr.wseduc.webutils.collections.JsonArray(); jsonFileArray.add(convertedJson); return new JsonObject().put("export", jsonFileArray); } private String fillTemplate(String templateAsString, JsonObject preparedData) { Mustache.Compiler compiler = Mustache.compiler().defaultValue(""); Template template = compiler.compile(templateAsString); Map<String, Object> ctx = new JsonObject(preparedData.toString()).getMap(); StringWriter writer = new StringWriter(); template.execute(ctx, writer); return writer.getBuffer().toString(); } private String getTemplate(JsonObject exportResponse) { String htmlTemplateFile;
// Path: src/main/java/net/atos/entng/rbs/model/ExportRequest.java // public class ExportRequest { // // private static final SimpleDateFormat DATE_FORMATTER = new SimpleDateFormat("yyyy-MM-dd"); // public static final String USER_TZ = "usertimezone"; // public static final String START_DATE = "startdate"; // public static final String END_DATE = "enddate"; // public static final String FORMAT = "format"; // public static final String VIEW = "view"; // public static final String RESOURCE_IDS = "resourceIds"; // // public enum Format {ICAL, PDF} // // public enum View {DAY, WEEK, LIST, NA} // // private UserInfos userInfos; // private View view = View.WEEK; // private Format format = Format.ICAL; // private List<Long> resourceIds = new ArrayList<>(); // private String userTz; // Needed for dates to be expressed in the user time zone. (UTC by default) // private String startDate; // private String endDate; // // public ExportRequest(JsonObject data) { // this(data, null); // } // // public ExportRequest(JsonObject userExportRequest, UserInfos userInfos) { // this.userInfos = userInfos; // this.format = Format.valueOf(userExportRequest.getString(FORMAT)); // this.view = View.valueOf(userExportRequest.getString(VIEW)); // // this.userTz = userExportRequest.getString(USER_TZ); // // this.startDate = userExportRequest.getString(START_DATE); // this.endDate = userExportRequest.getString(END_DATE); // checkPeriodValid(startDate, endDate); // // try { // JsonArray userExportResourceArray = userExportRequest.getJsonArray(RESOURCE_IDS, new fr.wseduc.webutils.collections.JsonArray()); // for (Object resourceId : userExportResourceArray) { // this.resourceIds.add(new Long((Integer) resourceId)); // } // } catch (NumberFormatException | NullPointerException | ClassCastException e) { // throw new IllegalArgumentException("params resources must be defined with an array of Integer"); // } // // } // // private void checkPeriodValid(String startInput, String endInput) { // Date start; // Date end; // try { // start = DATE_FORMATTER.parse(startInput); // end = DATE_FORMATTER.parse(endInput); // } catch (NullPointerException | ParseException e) { // throw new IllegalArgumentException("params start and end date must be defined with YYYY-MM-DD format !"); // } // if (start.after(end)) { // throw new IllegalArgumentException("Param startdate must be before enddate"); // } // } // // public UserInfos getUserInfos() { // return userInfos; // } // // public View getView() { // return view; // } // // public Format getFormat() { // return format; // } // // public List<Long> getResourceIds() { // return resourceIds; // } // // public String getStartDate() { // return startDate; // } // // public String getEndDate() { // return endDate; // } // // // public void setFormat(Format format) { // this.format = format; // } // // public void setView(View view) { // this.view = view; // } // // public void setResourceIds(List<Long> resourceIds) { // this.resourceIds = resourceIds; // } // // public void setStartDate(String startDate) { // this.startDate = startDate; // } // // public void setEndDate(String endDate) { // this.endDate = endDate; // } // // public String getUserTz() { // return userTz; // } // // public void setUserTz(String userTz) { // this.userTz = userTz; // } // } // // Path: src/main/java/net/atos/entng/rbs/model/ExportResponse.java // public static ExportRequest.View getView(JsonObject exportResponse) { // String viewAsString = exportResponse.getString(ExportRequest.VIEW, ExportRequest.View.WEEK.name()); // return ExportRequest.View.valueOf(viewAsString); // } // Path: src/main/java/net/atos/entng/rbs/service/pdf/PdfExportService.java import com.samskivert.mustache.Mustache; import com.samskivert.mustache.Template; import fr.wseduc.webutils.data.FileResolver; import io.vertx.core.AbstractVerticle; import io.vertx.core.shareddata.LocalMap; import net.atos.entng.rbs.model.ExportRequest; import io.vertx.core.AsyncResult; import io.vertx.core.Handler; import io.vertx.core.buffer.Buffer; import io.vertx.core.eventbus.Message; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; import java.io.StringWriter; import java.util.Locale; import java.util.Map; import static fr.wseduc.webutils.Utils.handlerToAsyncHandler; import static net.atos.entng.rbs.model.ExportResponse.getView; results.put("message", e.getMessage()); message.reply(results); return; } }); } private JsonObject prepareData(JsonObject jsonExportResponse, String host, Locale locale, String userTimeZone) { JsonFormatter formatter = JsonFormatter.buildFormater(jsonExportResponse, host, locale, userTimeZone); JsonObject convertedJson = formatter.format(); JsonArray jsonFileArray = new fr.wseduc.webutils.collections.JsonArray(); jsonFileArray.add(convertedJson); return new JsonObject().put("export", jsonFileArray); } private String fillTemplate(String templateAsString, JsonObject preparedData) { Mustache.Compiler compiler = Mustache.compiler().defaultValue(""); Template template = compiler.compile(templateAsString); Map<String, Object> ctx = new JsonObject(preparedData.toString()).getMap(); StringWriter writer = new StringWriter(); template.execute(ctx, writer); return writer.getBuffer().toString(); } private String getTemplate(JsonObject exportResponse) { String htmlTemplateFile;
ExportRequest.View view = getView(exportResponse);
OPEN-ENT-NG/rbs
src/main/java/net/atos/entng/rbs/service/ResourceTypeServiceSqlImpl.java
// Path: src/main/java/net/atos/entng/rbs/BookingUtils.java // public static List<String> getLocalAdminScope(final UserInfos user) { // Map<String, UserInfos.Function> functions = user.getFunctions(); // if (functions != null && functions.containsKey(DefaultFunctions.ADMIN_LOCAL)) { // Function adminLocal = functions.get(DefaultFunctions.ADMIN_LOCAL); // if (adminLocal != null) { // return adminLocal.getScope(); // } // } // // return new ArrayList<String>(); // }
import io.vertx.core.eventbus.Message; import io.vertx.core.json.JsonArray; import fr.wseduc.webutils.Either; import io.vertx.core.json.JsonObject; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; import static net.atos.entng.rbs.BookingUtils.getLocalAdminScope; import static org.entcore.common.neo4j.Neo4jResult.validResultHandler; import static org.entcore.common.sql.Sql.parseId; import static org.entcore.common.sql.SqlResult.*; import java.util.List; import fr.wseduc.webutils.http.Renders; import org.entcore.common.sql.Sql; import org.entcore.common.user.UserInfos; import io.vertx.core.Handler;
/* * Copyright © Région Nord Pas de Calais-Picardie, Département 91, Région Aquitaine-Limousin-Poitou-Charentes, 2016. * * This file is part of OPEN ENT NG. OPEN ENT NG is a versatile ENT Project based on the JVM and ENT Core Project. * * 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 (version 3 of the License). * * For the sake of explanation, any module that communicate over native * Web protocols, such as HTTP, with OPEN ENT NG is outside the scope of this * license and could be license under its own terms. This is merely considered * normal use of OPEN ENT NG, and does not fall under the heading of "covered work". * * 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. */ package net.atos.entng.rbs.service; public class ResourceTypeServiceSqlImpl implements ResourceTypeService { protected static final Logger log = LoggerFactory.getLogger(Renders.class); @Override public void list(final List<String> groupsAndUserIds, final UserInfos user, final Handler<Either<String, JsonArray>> handler) { StringBuilder query = new StringBuilder(); JsonArray values = new fr.wseduc.webutils.collections.JsonArray(); query.append("SELECT t.*,") .append(" json_agg(row_to_json(row(ts.member_id,ts.action)::rbs.share_tuple)) as shared,") .append(" array_to_json(array_agg(m.group_id)) as groups ") .append(" FROM rbs.resource_type AS t") .append(" LEFT JOIN rbs.resource_type_shares AS ts ON t.id = ts.resource_id") .append(" LEFT JOIN rbs.members AS m ON (ts.member_id = m.id AND m.group_id IS NOT NULL)"); query.append(" WHERE ts.member_id IN ").append(Sql.listPrepared(groupsAndUserIds.toArray())); for (String groupOruser : groupsAndUserIds) { values.add(groupOruser); } query.append(" OR t.owner = ?"); values.add(user.getUserId()); // A local administrator of a given school can see its types, even if he is not owner or manager of these types
// Path: src/main/java/net/atos/entng/rbs/BookingUtils.java // public static List<String> getLocalAdminScope(final UserInfos user) { // Map<String, UserInfos.Function> functions = user.getFunctions(); // if (functions != null && functions.containsKey(DefaultFunctions.ADMIN_LOCAL)) { // Function adminLocal = functions.get(DefaultFunctions.ADMIN_LOCAL); // if (adminLocal != null) { // return adminLocal.getScope(); // } // } // // return new ArrayList<String>(); // } // Path: src/main/java/net/atos/entng/rbs/service/ResourceTypeServiceSqlImpl.java import io.vertx.core.eventbus.Message; import io.vertx.core.json.JsonArray; import fr.wseduc.webutils.Either; import io.vertx.core.json.JsonObject; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; import static net.atos.entng.rbs.BookingUtils.getLocalAdminScope; import static org.entcore.common.neo4j.Neo4jResult.validResultHandler; import static org.entcore.common.sql.Sql.parseId; import static org.entcore.common.sql.SqlResult.*; import java.util.List; import fr.wseduc.webutils.http.Renders; import org.entcore.common.sql.Sql; import org.entcore.common.user.UserInfos; import io.vertx.core.Handler; /* * Copyright © Région Nord Pas de Calais-Picardie, Département 91, Région Aquitaine-Limousin-Poitou-Charentes, 2016. * * This file is part of OPEN ENT NG. OPEN ENT NG is a versatile ENT Project based on the JVM and ENT Core Project. * * 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 (version 3 of the License). * * For the sake of explanation, any module that communicate over native * Web protocols, such as HTTP, with OPEN ENT NG is outside the scope of this * license and could be license under its own terms. This is merely considered * normal use of OPEN ENT NG, and does not fall under the heading of "covered work". * * 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. */ package net.atos.entng.rbs.service; public class ResourceTypeServiceSqlImpl implements ResourceTypeService { protected static final Logger log = LoggerFactory.getLogger(Renders.class); @Override public void list(final List<String> groupsAndUserIds, final UserInfos user, final Handler<Either<String, JsonArray>> handler) { StringBuilder query = new StringBuilder(); JsonArray values = new fr.wseduc.webutils.collections.JsonArray(); query.append("SELECT t.*,") .append(" json_agg(row_to_json(row(ts.member_id,ts.action)::rbs.share_tuple)) as shared,") .append(" array_to_json(array_agg(m.group_id)) as groups ") .append(" FROM rbs.resource_type AS t") .append(" LEFT JOIN rbs.resource_type_shares AS ts ON t.id = ts.resource_id") .append(" LEFT JOIN rbs.members AS m ON (ts.member_id = m.id AND m.group_id IS NOT NULL)"); query.append(" WHERE ts.member_id IN ").append(Sql.listPrepared(groupsAndUserIds.toArray())); for (String groupOruser : groupsAndUserIds) { values.add(groupOruser); } query.append(" OR t.owner = ?"); values.add(user.getUserId()); // A local administrator of a given school can see its types, even if he is not owner or manager of these types
List<String> scope = getLocalAdminScope(user);
OPEN-ENT-NG/rbs
src/main/java/net/atos/entng/rbs/controllers/DisplayController.java
// Path: src/main/java/net/atos/entng/rbs/Rbs.java // public class Rbs extends BaseServer { // // public final static String RBS_NAME = "RBS"; // public final static String BOOKING_TABLE_NAME = "booking"; // public final static String RESOURCE_TABLE_NAME = "resource"; // public final static String RESOURCE_SHARE_TABLE_NAME = "resource_shares"; // public final static String RESOURCE_TYPE_TABLE_NAME = "resource_type"; // public final static String RESOURCE_TYPE_SHARE_TABLE_NAME = "resource_type_shares"; // // public static String DB_SCHEMA; // public static String AVAILABILITY_TABLE; // public static String BOOKING_TABLE; // public static String GROUPS_TABLE; // public static String MEMBERS_TABLE; // public static String NOTIFICATIONS_TABLE; // public static String RESOURCE_TABLE; // public static String RESOURCE_SHARES_TABLE; // public static String RESOURCE_TYPE_TABLE; // public static String RESOURCE_TYPE_SHARES_TABLE; // public static String USERS_TABLE; // // @Override // public void start() throws Exception { // super.start(); // final EventBus eb = getEventBus(vertx); // // // Set RepositoryEvents implementation used to process events published for transition // setRepositoryEvents(new RbsRepositoryEvents()); // if (config.getBoolean("searching-event", true)) { // setSearchingEvents(new RbsSearchingEvents()); // } // // // Store tables' SQL name in constants // DB_SCHEMA = "rbs"; // AVAILABILITY_TABLE = DB_SCHEMA + ".availability"; // BOOKING_TABLE = DB_SCHEMA + ".booking"; // GROUPS_TABLE = DB_SCHEMA + ".groups"; // MEMBERS_TABLE = DB_SCHEMA + ".members"; // NOTIFICATIONS_TABLE = DB_SCHEMA + ".notifications"; // RESOURCE_TABLE = DB_SCHEMA + ".resource"; // RESOURCE_SHARES_TABLE = DB_SCHEMA + ".resource_shares"; // RESOURCE_TYPE_TABLE = DB_SCHEMA + ".resource_type"; // RESOURCE_TYPE_SHARES_TABLE = DB_SCHEMA + ".resource_type_shares"; // USERS_TABLE = DB_SCHEMA + ".users"; // // // // Controllers // addController(new DisplayController()); // // SqlConf confType = SqlConfs.createConf(ResourceTypeController.class.getName()); // confType.setTable(RESOURCE_TYPE_TABLE_NAME); // confType.setShareTable(RESOURCE_TYPE_SHARE_TABLE_NAME); // confType.setSchema(getSchema()); // ResourceTypeController typeController = new ResourceTypeController(eb); // SqlCrudService typeSqlCrudService = new SqlCrudService(getSchema(), RESOURCE_TYPE_TABLE_NAME, RESOURCE_TYPE_SHARE_TABLE_NAME, // new fr.wseduc.webutils.collections.JsonArray().add("*"), new JsonArray().add("*"), true); // typeController.setCrudService(typeSqlCrudService); // typeController.setShareService(new SqlShareService(getSchema(), RESOURCE_TYPE_SHARE_TABLE_NAME, // eb, securedActions, null)); // addController(typeController); // // SqlConf confResource = SqlConfs.createConf(ResourceController.class.getName()); // confResource.setTable(RESOURCE_TABLE_NAME); // confResource.setShareTable(RESOURCE_SHARE_TABLE_NAME); // confResource.setSchema(getSchema()); // ResourceController resourceController = new ResourceController(); // SqlCrudService resourceSqlCrudService = new SqlCrudService(getSchema(), RESOURCE_TABLE_NAME, RESOURCE_SHARE_TABLE_NAME, // new fr.wseduc.webutils.collections.JsonArray().add("*"), new JsonArray().add("*"), true); // resourceController.setCrudService(resourceSqlCrudService); // resourceController.setShareService(new SqlShareService(getSchema(), RESOURCE_SHARE_TABLE_NAME, // eb, securedActions, null)); // addController(resourceController); // // // DeploymentOptions options = new DeploymentOptions().setWorker(true); // vertx.deployVerticle(new PdfExportService(), options); // vertx.deployVerticle(new IcalExportService(), options); // // addController(new BookingController(eb)); // addController(new AvailabilityController()); // // setDefaultResourceFilter(new TypeOwnerSharedOrLocalAdmin()); // } // // }
import fr.wseduc.rs.Get; import fr.wseduc.security.SecuredAction; import fr.wseduc.webutils.http.BaseController; import java.util.Map; import io.vertx.core.json.JsonObject; import net.atos.entng.rbs.Rbs; import org.entcore.common.events.EventStore; import org.entcore.common.events.EventStoreFactory; import io.vertx.core.Vertx; import io.vertx.core.http.HttpServerRequest; import org.vertx.java.core.http.RouteMatcher;
/* * Copyright © Région Nord Pas de Calais-Picardie, Département 91, Région Aquitaine-Limousin-Poitou-Charentes, 2016. * * This file is part of OPEN ENT NG. OPEN ENT NG is a versatile ENT Project based on the JVM and ENT Core Project. * * 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 (version 3 of the License). * * For the sake of explanation, any module that communicate over native * Web protocols, such as HTTP, with OPEN ENT NG is outside the scope of this * license and could be license under its own terms. This is merely considered * normal use of OPEN ENT NG, and does not fall under the heading of "covered work". * * 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. */ package net.atos.entng.rbs.controllers; public class DisplayController extends BaseController { private EventStore eventStore; private enum RbsEvent { ACCESS } @Override public void init(Vertx vertx, JsonObject config, RouteMatcher rm, Map<String, fr.wseduc.webutils.security.SecuredAction> securedActions) { super.init(vertx, config, rm, securedActions);
// Path: src/main/java/net/atos/entng/rbs/Rbs.java // public class Rbs extends BaseServer { // // public final static String RBS_NAME = "RBS"; // public final static String BOOKING_TABLE_NAME = "booking"; // public final static String RESOURCE_TABLE_NAME = "resource"; // public final static String RESOURCE_SHARE_TABLE_NAME = "resource_shares"; // public final static String RESOURCE_TYPE_TABLE_NAME = "resource_type"; // public final static String RESOURCE_TYPE_SHARE_TABLE_NAME = "resource_type_shares"; // // public static String DB_SCHEMA; // public static String AVAILABILITY_TABLE; // public static String BOOKING_TABLE; // public static String GROUPS_TABLE; // public static String MEMBERS_TABLE; // public static String NOTIFICATIONS_TABLE; // public static String RESOURCE_TABLE; // public static String RESOURCE_SHARES_TABLE; // public static String RESOURCE_TYPE_TABLE; // public static String RESOURCE_TYPE_SHARES_TABLE; // public static String USERS_TABLE; // // @Override // public void start() throws Exception { // super.start(); // final EventBus eb = getEventBus(vertx); // // // Set RepositoryEvents implementation used to process events published for transition // setRepositoryEvents(new RbsRepositoryEvents()); // if (config.getBoolean("searching-event", true)) { // setSearchingEvents(new RbsSearchingEvents()); // } // // // Store tables' SQL name in constants // DB_SCHEMA = "rbs"; // AVAILABILITY_TABLE = DB_SCHEMA + ".availability"; // BOOKING_TABLE = DB_SCHEMA + ".booking"; // GROUPS_TABLE = DB_SCHEMA + ".groups"; // MEMBERS_TABLE = DB_SCHEMA + ".members"; // NOTIFICATIONS_TABLE = DB_SCHEMA + ".notifications"; // RESOURCE_TABLE = DB_SCHEMA + ".resource"; // RESOURCE_SHARES_TABLE = DB_SCHEMA + ".resource_shares"; // RESOURCE_TYPE_TABLE = DB_SCHEMA + ".resource_type"; // RESOURCE_TYPE_SHARES_TABLE = DB_SCHEMA + ".resource_type_shares"; // USERS_TABLE = DB_SCHEMA + ".users"; // // // // Controllers // addController(new DisplayController()); // // SqlConf confType = SqlConfs.createConf(ResourceTypeController.class.getName()); // confType.setTable(RESOURCE_TYPE_TABLE_NAME); // confType.setShareTable(RESOURCE_TYPE_SHARE_TABLE_NAME); // confType.setSchema(getSchema()); // ResourceTypeController typeController = new ResourceTypeController(eb); // SqlCrudService typeSqlCrudService = new SqlCrudService(getSchema(), RESOURCE_TYPE_TABLE_NAME, RESOURCE_TYPE_SHARE_TABLE_NAME, // new fr.wseduc.webutils.collections.JsonArray().add("*"), new JsonArray().add("*"), true); // typeController.setCrudService(typeSqlCrudService); // typeController.setShareService(new SqlShareService(getSchema(), RESOURCE_TYPE_SHARE_TABLE_NAME, // eb, securedActions, null)); // addController(typeController); // // SqlConf confResource = SqlConfs.createConf(ResourceController.class.getName()); // confResource.setTable(RESOURCE_TABLE_NAME); // confResource.setShareTable(RESOURCE_SHARE_TABLE_NAME); // confResource.setSchema(getSchema()); // ResourceController resourceController = new ResourceController(); // SqlCrudService resourceSqlCrudService = new SqlCrudService(getSchema(), RESOURCE_TABLE_NAME, RESOURCE_SHARE_TABLE_NAME, // new fr.wseduc.webutils.collections.JsonArray().add("*"), new JsonArray().add("*"), true); // resourceController.setCrudService(resourceSqlCrudService); // resourceController.setShareService(new SqlShareService(getSchema(), RESOURCE_SHARE_TABLE_NAME, // eb, securedActions, null)); // addController(resourceController); // // // DeploymentOptions options = new DeploymentOptions().setWorker(true); // vertx.deployVerticle(new PdfExportService(), options); // vertx.deployVerticle(new IcalExportService(), options); // // addController(new BookingController(eb)); // addController(new AvailabilityController()); // // setDefaultResourceFilter(new TypeOwnerSharedOrLocalAdmin()); // } // // } // Path: src/main/java/net/atos/entng/rbs/controllers/DisplayController.java import fr.wseduc.rs.Get; import fr.wseduc.security.SecuredAction; import fr.wseduc.webutils.http.BaseController; import java.util.Map; import io.vertx.core.json.JsonObject; import net.atos.entng.rbs.Rbs; import org.entcore.common.events.EventStore; import org.entcore.common.events.EventStoreFactory; import io.vertx.core.Vertx; import io.vertx.core.http.HttpServerRequest; import org.vertx.java.core.http.RouteMatcher; /* * Copyright © Région Nord Pas de Calais-Picardie, Département 91, Région Aquitaine-Limousin-Poitou-Charentes, 2016. * * This file is part of OPEN ENT NG. OPEN ENT NG is a versatile ENT Project based on the JVM and ENT Core Project. * * 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 (version 3 of the License). * * For the sake of explanation, any module that communicate over native * Web protocols, such as HTTP, with OPEN ENT NG is outside the scope of this * license and could be license under its own terms. This is merely considered * normal use of OPEN ENT NG, and does not fall under the heading of "covered work". * * 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. */ package net.atos.entng.rbs.controllers; public class DisplayController extends BaseController { private EventStore eventStore; private enum RbsEvent { ACCESS } @Override public void init(Vertx vertx, JsonObject config, RouteMatcher rm, Map<String, fr.wseduc.webutils.security.SecuredAction> securedActions) { super.init(vertx, config, rm, securedActions);
eventStore = EventStoreFactory.getFactory().getEventStore(Rbs.class.getSimpleName());
OPEN-ENT-NG/rbs
src/main/java/net/atos/entng/rbs/service/ResourceServiceSqlImpl.java
// Path: src/main/java/net/atos/entng/rbs/BookingUtils.java // public static List<String> getLocalAdminScope(final UserInfos user) { // Map<String, UserInfos.Function> functions = user.getFunctions(); // if (functions != null && functions.containsKey(DefaultFunctions.ADMIN_LOCAL)) { // Function adminLocal = functions.get(DefaultFunctions.ADMIN_LOCAL); // if (adminLocal != null) { // return adminLocal.getScope(); // } // } // // return new ArrayList<String>(); // } // // Path: src/main/java/net/atos/entng/rbs/BookingStatus.java // public enum BookingStatus { // CREATED(1), VALIDATED(2), REFUSED(3), SUSPENDED(4); // // private final int status; // // BookingStatus(int pStatus) { // this.status = pStatus; // } // public int status(){ // return status; // } // }
import org.entcore.common.service.impl.SqlCrudService; import org.entcore.common.sql.Sql; import org.entcore.common.sql.SqlStatementsBuilder; import org.entcore.common.user.UserInfos; import io.vertx.core.Handler; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import fr.wseduc.webutils.Either; import static net.atos.entng.rbs.BookingStatus.CREATED; import static net.atos.entng.rbs.BookingStatus.REFUSED; import static net.atos.entng.rbs.BookingStatus.SUSPENDED; import static net.atos.entng.rbs.BookingUtils.getLocalAdminScope; import static org.entcore.common.sql.Sql.parseId; import static org.entcore.common.sql.SqlResult.*; import static org.entcore.common.sql.SqlResult.validUniqueResultHandler; import java.util.List; import net.atos.entng.rbs.BookingStatus;
/* * Copyright © Région Nord Pas de Calais-Picardie, Département 91, Région Aquitaine-Limousin-Poitou-Charentes, 2016. * * This file is part of OPEN ENT NG. OPEN ENT NG is a versatile ENT Project based on the JVM and ENT Core Project. * * 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 (version 3 of the License). * * For the sake of explanation, any module that communicate over native * Web protocols, such as HTTP, with OPEN ENT NG is outside the scope of this * license and could be license under its own terms. This is merely considered * normal use of OPEN ENT NG, and does not fall under the heading of "covered work". * * 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. */ package net.atos.entng.rbs.service; public class ResourceServiceSqlImpl extends SqlCrudService implements ResourceService { public ResourceServiceSqlImpl() { super("rbs", "resource"); } @Override public void listResources(final List<String> groupsAndUserIds, final UserInfos user, final Handler<Either<String, JsonArray>> handler) { StringBuilder query = new StringBuilder(); JsonArray values = new fr.wseduc.webutils.collections.JsonArray(); query.append("SELECT r.*,") .append(" json_agg(row_to_json(row(rs.member_id,rs.action)::rbs.share_tuple)) as shared,") .append(" array_to_json(array_agg(m.group_id)) as groups ") .append(" FROM rbs.resource AS r") .append(" INNER JOIN rbs.resource_type AS t ON r.type_id = t.id") .append(" LEFT JOIN rbs.resource_shares AS rs ON r.id = rs.resource_id") .append(" LEFT JOIN rbs.resource_type_shares AS ts ON t.id = ts.resource_id") .append(" LEFT JOIN rbs.members AS m ON (rs.member_id = m.id AND m.group_id IS NOT NULL)"); query.append(" WHERE rs.member_id IN ").append(Sql.listPrepared(groupsAndUserIds.toArray())); for (String groupOruser : groupsAndUserIds) { values.add(groupOruser); } query.append(" OR r.owner = ? "); values.add(user.getUserId()); query.append(" OR ts.member_id IN ").append(Sql.listPrepared(groupsAndUserIds.toArray())); for (String groupOruser : groupsAndUserIds) { values.add(groupOruser); } query.append(" OR t.owner = ?"); values.add(user.getUserId()); // A local administrator of a given school can see all resources of the school's types, even if he is not owner or manager of these types or resources
// Path: src/main/java/net/atos/entng/rbs/BookingUtils.java // public static List<String> getLocalAdminScope(final UserInfos user) { // Map<String, UserInfos.Function> functions = user.getFunctions(); // if (functions != null && functions.containsKey(DefaultFunctions.ADMIN_LOCAL)) { // Function adminLocal = functions.get(DefaultFunctions.ADMIN_LOCAL); // if (adminLocal != null) { // return adminLocal.getScope(); // } // } // // return new ArrayList<String>(); // } // // Path: src/main/java/net/atos/entng/rbs/BookingStatus.java // public enum BookingStatus { // CREATED(1), VALIDATED(2), REFUSED(3), SUSPENDED(4); // // private final int status; // // BookingStatus(int pStatus) { // this.status = pStatus; // } // public int status(){ // return status; // } // } // Path: src/main/java/net/atos/entng/rbs/service/ResourceServiceSqlImpl.java import org.entcore.common.service.impl.SqlCrudService; import org.entcore.common.sql.Sql; import org.entcore.common.sql.SqlStatementsBuilder; import org.entcore.common.user.UserInfos; import io.vertx.core.Handler; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import fr.wseduc.webutils.Either; import static net.atos.entng.rbs.BookingStatus.CREATED; import static net.atos.entng.rbs.BookingStatus.REFUSED; import static net.atos.entng.rbs.BookingStatus.SUSPENDED; import static net.atos.entng.rbs.BookingUtils.getLocalAdminScope; import static org.entcore.common.sql.Sql.parseId; import static org.entcore.common.sql.SqlResult.*; import static org.entcore.common.sql.SqlResult.validUniqueResultHandler; import java.util.List; import net.atos.entng.rbs.BookingStatus; /* * Copyright © Région Nord Pas de Calais-Picardie, Département 91, Région Aquitaine-Limousin-Poitou-Charentes, 2016. * * This file is part of OPEN ENT NG. OPEN ENT NG is a versatile ENT Project based on the JVM and ENT Core Project. * * 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 (version 3 of the License). * * For the sake of explanation, any module that communicate over native * Web protocols, such as HTTP, with OPEN ENT NG is outside the scope of this * license and could be license under its own terms. This is merely considered * normal use of OPEN ENT NG, and does not fall under the heading of "covered work". * * 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. */ package net.atos.entng.rbs.service; public class ResourceServiceSqlImpl extends SqlCrudService implements ResourceService { public ResourceServiceSqlImpl() { super("rbs", "resource"); } @Override public void listResources(final List<String> groupsAndUserIds, final UserInfos user, final Handler<Either<String, JsonArray>> handler) { StringBuilder query = new StringBuilder(); JsonArray values = new fr.wseduc.webutils.collections.JsonArray(); query.append("SELECT r.*,") .append(" json_agg(row_to_json(row(rs.member_id,rs.action)::rbs.share_tuple)) as shared,") .append(" array_to_json(array_agg(m.group_id)) as groups ") .append(" FROM rbs.resource AS r") .append(" INNER JOIN rbs.resource_type AS t ON r.type_id = t.id") .append(" LEFT JOIN rbs.resource_shares AS rs ON r.id = rs.resource_id") .append(" LEFT JOIN rbs.resource_type_shares AS ts ON t.id = ts.resource_id") .append(" LEFT JOIN rbs.members AS m ON (rs.member_id = m.id AND m.group_id IS NOT NULL)"); query.append(" WHERE rs.member_id IN ").append(Sql.listPrepared(groupsAndUserIds.toArray())); for (String groupOruser : groupsAndUserIds) { values.add(groupOruser); } query.append(" OR r.owner = ? "); values.add(user.getUserId()); query.append(" OR ts.member_id IN ").append(Sql.listPrepared(groupsAndUserIds.toArray())); for (String groupOruser : groupsAndUserIds) { values.add(groupOruser); } query.append(" OR t.owner = ?"); values.add(user.getUserId()); // A local administrator of a given school can see all resources of the school's types, even if he is not owner or manager of these types or resources
List<String> scope = getLocalAdminScope(user);
OPEN-ENT-NG/rbs
src/main/java/net/atos/entng/rbs/service/ResourceServiceSqlImpl.java
// Path: src/main/java/net/atos/entng/rbs/BookingUtils.java // public static List<String> getLocalAdminScope(final UserInfos user) { // Map<String, UserInfos.Function> functions = user.getFunctions(); // if (functions != null && functions.containsKey(DefaultFunctions.ADMIN_LOCAL)) { // Function adminLocal = functions.get(DefaultFunctions.ADMIN_LOCAL); // if (adminLocal != null) { // return adminLocal.getScope(); // } // } // // return new ArrayList<String>(); // } // // Path: src/main/java/net/atos/entng/rbs/BookingStatus.java // public enum BookingStatus { // CREATED(1), VALIDATED(2), REFUSED(3), SUSPENDED(4); // // private final int status; // // BookingStatus(int pStatus) { // this.status = pStatus; // } // public int status(){ // return status; // } // }
import org.entcore.common.service.impl.SqlCrudService; import org.entcore.common.sql.Sql; import org.entcore.common.sql.SqlStatementsBuilder; import org.entcore.common.user.UserInfos; import io.vertx.core.Handler; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import fr.wseduc.webutils.Either; import static net.atos.entng.rbs.BookingStatus.CREATED; import static net.atos.entng.rbs.BookingStatus.REFUSED; import static net.atos.entng.rbs.BookingStatus.SUSPENDED; import static net.atos.entng.rbs.BookingUtils.getLocalAdminScope; import static org.entcore.common.sql.Sql.parseId; import static org.entcore.common.sql.SqlResult.*; import static org.entcore.common.sql.SqlResult.validUniqueResultHandler; import java.util.List; import net.atos.entng.rbs.BookingStatus;
for (String attr : resource.fieldNames()) { if ("was_available".equals(attr)) { continue; } sb.append(attr).append(" = ?, "); values.add(resource.getValue(attr)); } unsetFieldIfNull(resource, sb, values, "max_delay"); unsetFieldIfNull(resource, sb, values, "min_delay"); StringBuilder query = new StringBuilder(); query.append("UPDATE rbs.resource") .append(" SET ") .append(sb.toString()) .append("modified = NOW()") .append(" WHERE id = ?") .append(" RETURNING id, name"); values.add(parseId(resourceId)); final boolean isAvailable = resource.getBoolean("is_available"); final boolean wasAvailable = resource.getBoolean("was_available"); if(isAvailable == wasAvailable) { Sql.getInstance().prepared(query.toString(), values, validUniqueResultHandler(handler)); } else { SqlStatementsBuilder statementsBuilder = new SqlStatementsBuilder(); statementsBuilder.prepared(query.toString(), values); // Update bookings' status to "created" if resource is available again, and to "suspended" if resource is now unavailable
// Path: src/main/java/net/atos/entng/rbs/BookingUtils.java // public static List<String> getLocalAdminScope(final UserInfos user) { // Map<String, UserInfos.Function> functions = user.getFunctions(); // if (functions != null && functions.containsKey(DefaultFunctions.ADMIN_LOCAL)) { // Function adminLocal = functions.get(DefaultFunctions.ADMIN_LOCAL); // if (adminLocal != null) { // return adminLocal.getScope(); // } // } // // return new ArrayList<String>(); // } // // Path: src/main/java/net/atos/entng/rbs/BookingStatus.java // public enum BookingStatus { // CREATED(1), VALIDATED(2), REFUSED(3), SUSPENDED(4); // // private final int status; // // BookingStatus(int pStatus) { // this.status = pStatus; // } // public int status(){ // return status; // } // } // Path: src/main/java/net/atos/entng/rbs/service/ResourceServiceSqlImpl.java import org.entcore.common.service.impl.SqlCrudService; import org.entcore.common.sql.Sql; import org.entcore.common.sql.SqlStatementsBuilder; import org.entcore.common.user.UserInfos; import io.vertx.core.Handler; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import fr.wseduc.webutils.Either; import static net.atos.entng.rbs.BookingStatus.CREATED; import static net.atos.entng.rbs.BookingStatus.REFUSED; import static net.atos.entng.rbs.BookingStatus.SUSPENDED; import static net.atos.entng.rbs.BookingUtils.getLocalAdminScope; import static org.entcore.common.sql.Sql.parseId; import static org.entcore.common.sql.SqlResult.*; import static org.entcore.common.sql.SqlResult.validUniqueResultHandler; import java.util.List; import net.atos.entng.rbs.BookingStatus; for (String attr : resource.fieldNames()) { if ("was_available".equals(attr)) { continue; } sb.append(attr).append(" = ?, "); values.add(resource.getValue(attr)); } unsetFieldIfNull(resource, sb, values, "max_delay"); unsetFieldIfNull(resource, sb, values, "min_delay"); StringBuilder query = new StringBuilder(); query.append("UPDATE rbs.resource") .append(" SET ") .append(sb.toString()) .append("modified = NOW()") .append(" WHERE id = ?") .append(" RETURNING id, name"); values.add(parseId(resourceId)); final boolean isAvailable = resource.getBoolean("is_available"); final boolean wasAvailable = resource.getBoolean("was_available"); if(isAvailable == wasAvailable) { Sql.getInstance().prepared(query.toString(), values, validUniqueResultHandler(handler)); } else { SqlStatementsBuilder statementsBuilder = new SqlStatementsBuilder(); statementsBuilder.prepared(query.toString(), values); // Update bookings' status to "created" if resource is available again, and to "suspended" if resource is now unavailable
BookingStatus newStatus = isAvailable ? CREATED : SUSPENDED;
OPEN-ENT-NG/rbs
src/main/java/net/atos/entng/rbs/service/AvailabilityService.java
// Path: src/main/java/net/atos/entng/rbs/models/Availability.java // public class Availability { // private final Integer availability_id; // private final JsonObject json; // private String selectedDaysBitString; // private final ZonedDateTime start_date; // private final ZonedDateTime end_date; // private final ZonedDateTime start_time; // private final ZonedDateTime end_time; // DateTimeFormatter sqlDateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); // DateTimeFormatter sqlTimeFormatter = DateTimeFormatter.ofPattern("HH:mm"); // // public Availability(JsonObject json) { // this(json, json.getString("iana"), null); // } // // public Availability(JsonObject json, Integer id) { // this(json, json.getString("iana"), id); // } // // public Availability(JsonObject json, String iana, Integer id) { // super(); // this.json = json; // this.availability_id = id > 0 ? id : null; // this.start_date = BookingDateUtils.localDateTimeForTimestampSecondsAndIana(json.getLong("start_date", 0l), iana); // this.end_date = BookingDateUtils.localDateTimeForTimestampSecondsAndIana(json.getLong("end_date", 0l), iana); // this.start_time = BookingDateUtils.localDateTimeForTimestampSecondsAndIana(json.getLong("start_time", 0l), iana); // this.end_time = BookingDateUtils.localDateTimeForTimestampSecondsAndIana(json.getLong("end_time", 0l), iana); // } // // // // public Integer getId() { // return availability_id; // } // // public Integer getResourceId() { // return json.getInteger("resource_id"); // } // // public Integer getQuantity() { // return json.getInteger("quantity"); // } // // public Boolean isUnavailability() { // return json.getBoolean("is_unavailability"); // } // // public String getStartDate() { // return sqlDateFormatter.format(this.start_date); // } // // public String getEndDate() { // return sqlDateFormatter.format(this.end_date); // } // // public String getStartTime() { // return sqlTimeFormatter.format(this.start_time); // } // // public String getEndTime() { // return sqlTimeFormatter.format(this.end_time); // } // // public Optional<JsonArray> getDays() { // return Optional.ofNullable(json.getJsonArray("days", null)); // } // // public String getSelectedDaysBitString() { // if (selectedDaysBitString == null) { // computeSelectedDaysAsBitString(); // } // return selectedDaysBitString; // } // // public void computeSelectedDaysAsBitString() { // JsonArray selectedDaysArray = getDays().get(); // StringBuilder selectedDays = new StringBuilder(); // for (Object day : selectedDaysArray) { // int isSelectedDay = ((Boolean) day) ? 1 : 0; // selectedDays.append(isSelectedDay); // } // selectedDaysBitString = selectedDays.toString(); // } // }
import fr.wseduc.webutils.Either; import net.atos.entng.rbs.models.Availability; import org.entcore.common.service.CrudService; import org.entcore.common.user.UserInfos; import io.vertx.core.Handler; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject;
/* * Copyright © Région Nord Pas de Calais-Picardie, Département 91, Région Aquitaine-Limousin-Poitou-Charentes, 2016. * * This file is part of OPEN ENT NG. OPEN ENT NG is a versatile ENT Project based on the JVM and ENT Core Project. * * 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 (version 3 of the License). * * For the sake of explanation, any module that communicate over native * Web protocols, such as HTTP, with OPEN ENT NG is outside the scope of this * license and could be license under its own terms. This is merely considered * normal use of OPEN ENT NG, and does not fall under the heading of "covered work". * * 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. */ package net.atos.entng.rbs.service; public interface AvailabilityService extends CrudService { /** * List all the (un)availabilities of a user * * @param resourceIds : resources' id * @param user : information of current user logged * @param handler : handler which contains the response */ void listAvailabilities(JsonArray resourceIds, UserInfos user, Handler<Either<String, JsonArray>> handler); /** * List all the (un)availabilities of a resource * * @param resourceId : resource id * @param is_unavailability : type of (un)availability to list * @param user : information of current user logged * @param handler : handler which contains the response */ void listResourceAvailability(Integer resourceId, boolean is_unavailability, UserInfos user, Handler<Either<String, JsonArray>> handler); /** * Create an (un)availability * * @param availability : current (un)availability * @param user : information of current user logged * @param handler : handler which contains the response */
// Path: src/main/java/net/atos/entng/rbs/models/Availability.java // public class Availability { // private final Integer availability_id; // private final JsonObject json; // private String selectedDaysBitString; // private final ZonedDateTime start_date; // private final ZonedDateTime end_date; // private final ZonedDateTime start_time; // private final ZonedDateTime end_time; // DateTimeFormatter sqlDateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); // DateTimeFormatter sqlTimeFormatter = DateTimeFormatter.ofPattern("HH:mm"); // // public Availability(JsonObject json) { // this(json, json.getString("iana"), null); // } // // public Availability(JsonObject json, Integer id) { // this(json, json.getString("iana"), id); // } // // public Availability(JsonObject json, String iana, Integer id) { // super(); // this.json = json; // this.availability_id = id > 0 ? id : null; // this.start_date = BookingDateUtils.localDateTimeForTimestampSecondsAndIana(json.getLong("start_date", 0l), iana); // this.end_date = BookingDateUtils.localDateTimeForTimestampSecondsAndIana(json.getLong("end_date", 0l), iana); // this.start_time = BookingDateUtils.localDateTimeForTimestampSecondsAndIana(json.getLong("start_time", 0l), iana); // this.end_time = BookingDateUtils.localDateTimeForTimestampSecondsAndIana(json.getLong("end_time", 0l), iana); // } // // // // public Integer getId() { // return availability_id; // } // // public Integer getResourceId() { // return json.getInteger("resource_id"); // } // // public Integer getQuantity() { // return json.getInteger("quantity"); // } // // public Boolean isUnavailability() { // return json.getBoolean("is_unavailability"); // } // // public String getStartDate() { // return sqlDateFormatter.format(this.start_date); // } // // public String getEndDate() { // return sqlDateFormatter.format(this.end_date); // } // // public String getStartTime() { // return sqlTimeFormatter.format(this.start_time); // } // // public String getEndTime() { // return sqlTimeFormatter.format(this.end_time); // } // // public Optional<JsonArray> getDays() { // return Optional.ofNullable(json.getJsonArray("days", null)); // } // // public String getSelectedDaysBitString() { // if (selectedDaysBitString == null) { // computeSelectedDaysAsBitString(); // } // return selectedDaysBitString; // } // // public void computeSelectedDaysAsBitString() { // JsonArray selectedDaysArray = getDays().get(); // StringBuilder selectedDays = new StringBuilder(); // for (Object day : selectedDaysArray) { // int isSelectedDay = ((Boolean) day) ? 1 : 0; // selectedDays.append(isSelectedDay); // } // selectedDaysBitString = selectedDays.toString(); // } // } // Path: src/main/java/net/atos/entng/rbs/service/AvailabilityService.java import fr.wseduc.webutils.Either; import net.atos.entng.rbs.models.Availability; import org.entcore.common.service.CrudService; import org.entcore.common.user.UserInfos; import io.vertx.core.Handler; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; /* * Copyright © Région Nord Pas de Calais-Picardie, Département 91, Région Aquitaine-Limousin-Poitou-Charentes, 2016. * * This file is part of OPEN ENT NG. OPEN ENT NG is a versatile ENT Project based on the JVM and ENT Core Project. * * 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 (version 3 of the License). * * For the sake of explanation, any module that communicate over native * Web protocols, such as HTTP, with OPEN ENT NG is outside the scope of this * license and could be license under its own terms. This is merely considered * normal use of OPEN ENT NG, and does not fall under the heading of "covered work". * * 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. */ package net.atos.entng.rbs.service; public interface AvailabilityService extends CrudService { /** * List all the (un)availabilities of a user * * @param resourceIds : resources' id * @param user : information of current user logged * @param handler : handler which contains the response */ void listAvailabilities(JsonArray resourceIds, UserInfos user, Handler<Either<String, JsonArray>> handler); /** * List all the (un)availabilities of a resource * * @param resourceId : resource id * @param is_unavailability : type of (un)availability to list * @param user : information of current user logged * @param handler : handler which contains the response */ void listResourceAvailability(Integer resourceId, boolean is_unavailability, UserInfos user, Handler<Either<String, JsonArray>> handler); /** * Create an (un)availability * * @param availability : current (un)availability * @param user : information of current user logged * @param handler : handler which contains the response */
void createAvailability(Availability availability, UserInfos user, Handler<Either<String, JsonObject>> handler);
OPEN-ENT-NG/rbs
src/main/java/net/atos/entng/rbs/service/pdf/JsonListFormatter.java
// Path: src/main/java/net/atos/entng/rbs/model/ExportBooking.java // public class ExportBooking { // // public static final String BOOKING_ID = "id"; // public static final String BOOKING_OWNER_ID = "owner"; // "ff2238cd-5110-431b-a6fa-bbc4fa51411d", // public static final String BOOKING_START_DATE = "start_date"; //:"2017-06-26T09:00:00.000", // public static final String BOOKING_END_DATE = "end_date"; // "2017-06-26T10:00:00.000", // public static final String BOOKING_REASON = "booking_reason"; // free text // public static final String BOOKING_OWNER_NAME = "owner_name"; // "Catherine BAILLY", // public static final String BOOKING_MODERATOR_ID = "moderator_id"; // null, // public static final String BOOKING_MODERATOR_NAME = "moderator_name"; // null // public static final String SCHOOL_ID = "school_id"; // "a4d06ecc-e3cd-428b-b239-0a82a208f715", // public static final String RESOURCE_TYPE_ID = "type_id"; // 1, // public static final String RESOURCE_TYPE_COLOR = "type_color"; // "#02ed09", // public static final String RESOURCE_ID = "resource_id"; //2, // public static final String RESOURCE_NAME = "resource_name"; // "PC Windaube", // public static final String RESOURCE_COLOR = "resource_color"; // "#02ed19", // public static final String SCHOOL_NAME = "school_name"; // added by post treatment (stored in MongoDB, not PostgreSQL) // public static final String QUANTITY = "quantity"; // 5 // // private JsonObject data; // // public ExportBooking(JsonObject data) { // this.data = data; // } // // public JsonObject toJson() { // return data; // } // // public String getSchoolId() { // return data.getString(SCHOOL_ID); // } // // public void setSchoolName(String schoolName) { // data.put(SCHOOL_NAME, schoolName); // } // // public String getColor() { // String resourceColor = data.getString(RESOURCE_COLOR); // if (resourceColor == null || resourceColor.isEmpty()) { // return data.getString(RESOURCE_TYPE_COLOR); // } // return resourceColor; // } // // public String getStart() { // return data.getString(BOOKING_START_DATE); // } // // public String getEnd() { // return data.getString(BOOKING_END_DATE); // } // // public Number getQuantity() { // return data.getInteger(QUANTITY); // } // // // @Override // public String toString() { // final StringBuffer sb = new StringBuffer("ExportBooking{"); // sb.append("resource=").append(getResource()); // sb.append(", owner=").append(getOwner()); // sb.append(", start=").append(getStart()); // sb.append(", end=").append(getEnd()); // sb.append(", quantity=").append(getQuantity()); // sb.append('}'); // return sb.toString(); // } // // public String getOwner() { // return data.getString(BOOKING_OWNER_NAME); // } // // public String getResource() { // return data.getString(RESOURCE_NAME); // } // // public String getSchoolName() { // return data.getString(SCHOOL_NAME); // } // // public String getBookingReason() { // return data.getString(BOOKING_REASON); // } // // public Number getId() { // return data.getInteger(BOOKING_ID); // } // // public String getOwnerId() { // return data.getString(BOOKING_OWNER_ID); // } // }
import fr.wseduc.webutils.I18n; import net.atos.entng.rbs.model.ExportBooking; import org.joda.time.DateTime; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Locale;
return booking.getStartDate().compareTo(t1.getStartDate()); } } private final int CALENDAR_WIDTH = 680; private final int NUMBER_OF_BOOKINGS_BY_PAGE = 25; public JsonListFormatter(JsonObject jsonFileObject, String host, Locale locale, String userTimeZone) { super(jsonFileObject, host, locale, userTimeZone); } public JsonObject format(){ JsonObject convertedObject = new JsonObject(); convertedObject.put(EDITION_DATE_FIELD_NAME, DateTime.now().toString("dd/MM/YYYY")); // General calendar settings convertedObject.put(CALENDAR_WIDTH_FIELD_NAME, CALENDAR_WIDTH); convertedObject.put(CALENDAR_WIDTH_UNIT_FIELD_NAME, DEFAULT_SIZE_UNIT); convertedObject.put(I18N_TITLE, I18n.getInstance().translate(MAP_I18N.get(I18N_TITLE), this.host, this.locale)); JsonArray exportBookingList = exportObject.getJsonArray(BOOKING_LIST_FIELD_NAME); // Building resource list ArrayList<Long> performedResourceId = new ArrayList<Long>(); JsonArray resourceList = new fr.wseduc.webutils.collections.JsonArray(); final String i18nTo = I18n.getInstance().translate(MAP_I18N.get(I18N_TO), this.host, this.locale); for (int i = 0; i < exportBookingList.size(); i++) { JsonObject bookingIterator = exportBookingList.getJsonObject(i);
// Path: src/main/java/net/atos/entng/rbs/model/ExportBooking.java // public class ExportBooking { // // public static final String BOOKING_ID = "id"; // public static final String BOOKING_OWNER_ID = "owner"; // "ff2238cd-5110-431b-a6fa-bbc4fa51411d", // public static final String BOOKING_START_DATE = "start_date"; //:"2017-06-26T09:00:00.000", // public static final String BOOKING_END_DATE = "end_date"; // "2017-06-26T10:00:00.000", // public static final String BOOKING_REASON = "booking_reason"; // free text // public static final String BOOKING_OWNER_NAME = "owner_name"; // "Catherine BAILLY", // public static final String BOOKING_MODERATOR_ID = "moderator_id"; // null, // public static final String BOOKING_MODERATOR_NAME = "moderator_name"; // null // public static final String SCHOOL_ID = "school_id"; // "a4d06ecc-e3cd-428b-b239-0a82a208f715", // public static final String RESOURCE_TYPE_ID = "type_id"; // 1, // public static final String RESOURCE_TYPE_COLOR = "type_color"; // "#02ed09", // public static final String RESOURCE_ID = "resource_id"; //2, // public static final String RESOURCE_NAME = "resource_name"; // "PC Windaube", // public static final String RESOURCE_COLOR = "resource_color"; // "#02ed19", // public static final String SCHOOL_NAME = "school_name"; // added by post treatment (stored in MongoDB, not PostgreSQL) // public static final String QUANTITY = "quantity"; // 5 // // private JsonObject data; // // public ExportBooking(JsonObject data) { // this.data = data; // } // // public JsonObject toJson() { // return data; // } // // public String getSchoolId() { // return data.getString(SCHOOL_ID); // } // // public void setSchoolName(String schoolName) { // data.put(SCHOOL_NAME, schoolName); // } // // public String getColor() { // String resourceColor = data.getString(RESOURCE_COLOR); // if (resourceColor == null || resourceColor.isEmpty()) { // return data.getString(RESOURCE_TYPE_COLOR); // } // return resourceColor; // } // // public String getStart() { // return data.getString(BOOKING_START_DATE); // } // // public String getEnd() { // return data.getString(BOOKING_END_DATE); // } // // public Number getQuantity() { // return data.getInteger(QUANTITY); // } // // // @Override // public String toString() { // final StringBuffer sb = new StringBuffer("ExportBooking{"); // sb.append("resource=").append(getResource()); // sb.append(", owner=").append(getOwner()); // sb.append(", start=").append(getStart()); // sb.append(", end=").append(getEnd()); // sb.append(", quantity=").append(getQuantity()); // sb.append('}'); // return sb.toString(); // } // // public String getOwner() { // return data.getString(BOOKING_OWNER_NAME); // } // // public String getResource() { // return data.getString(RESOURCE_NAME); // } // // public String getSchoolName() { // return data.getString(SCHOOL_NAME); // } // // public String getBookingReason() { // return data.getString(BOOKING_REASON); // } // // public Number getId() { // return data.getInteger(BOOKING_ID); // } // // public String getOwnerId() { // return data.getString(BOOKING_OWNER_ID); // } // } // Path: src/main/java/net/atos/entng/rbs/service/pdf/JsonListFormatter.java import fr.wseduc.webutils.I18n; import net.atos.entng.rbs.model.ExportBooking; import org.joda.time.DateTime; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Locale; return booking.getStartDate().compareTo(t1.getStartDate()); } } private final int CALENDAR_WIDTH = 680; private final int NUMBER_OF_BOOKINGS_BY_PAGE = 25; public JsonListFormatter(JsonObject jsonFileObject, String host, Locale locale, String userTimeZone) { super(jsonFileObject, host, locale, userTimeZone); } public JsonObject format(){ JsonObject convertedObject = new JsonObject(); convertedObject.put(EDITION_DATE_FIELD_NAME, DateTime.now().toString("dd/MM/YYYY")); // General calendar settings convertedObject.put(CALENDAR_WIDTH_FIELD_NAME, CALENDAR_WIDTH); convertedObject.put(CALENDAR_WIDTH_UNIT_FIELD_NAME, DEFAULT_SIZE_UNIT); convertedObject.put(I18N_TITLE, I18n.getInstance().translate(MAP_I18N.get(I18N_TITLE), this.host, this.locale)); JsonArray exportBookingList = exportObject.getJsonArray(BOOKING_LIST_FIELD_NAME); // Building resource list ArrayList<Long> performedResourceId = new ArrayList<Long>(); JsonArray resourceList = new fr.wseduc.webutils.collections.JsonArray(); final String i18nTo = I18n.getInstance().translate(MAP_I18N.get(I18N_TO), this.host, this.locale); for (int i = 0; i < exportBookingList.size(); i++) { JsonObject bookingIterator = exportBookingList.getJsonObject(i);
Long currentResourceId = bookingIterator.getLong(ExportBooking.RESOURCE_ID);
OPEN-ENT-NG/rbs
src/main/java/net/atos/entng/rbs/models/Resource.java
// Path: src/main/java/net/atos/entng/rbs/BookingUtils.java // public static List<String> getLocalAdminScope(final UserInfos user) { // Map<String, UserInfos.Function> functions = user.getFunctions(); // if (functions != null && functions.containsKey(DefaultFunctions.ADMIN_LOCAL)) { // Function adminLocal = functions.get(DefaultFunctions.ADMIN_LOCAL); // if (adminLocal != null) { // return adminLocal.getScope(); // } // } // // return new ArrayList<String>(); // }
import static net.atos.entng.rbs.BookingUtils.getLocalAdminScope; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; import org.entcore.common.user.UserInfos; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject;
} public Optional<String> getManagers() { return Optional.ofNullable(json.getString("managers", null)); } public boolean hasNotOwnerOrSchoolId() { return !getOwner().isPresent() || !getSchoolId().isPresent(); } public Optional<JsonArray> getManagersAsJsonArray() { Optional<String> managersString = getManagers(); JsonArray managers = (managersString.isPresent()) ? new JsonArray(managersString.get()) : null; return Optional.ofNullable(managers); } /* * Owner or managers of a resourceType, as well as local administrators of a * resourceType's schoolId, do no need to respect constraints on resources' * delays */ public boolean canBypassDelaysConstraints(UserInfos user) { String owner = getOwner().orElse(null); String schoolId = getSchoolId().orElse(null); JsonArray managers = getManagersAsJsonArray().orElse(null); if (user.getUserId().equals(owner)) { return true; }
// Path: src/main/java/net/atos/entng/rbs/BookingUtils.java // public static List<String> getLocalAdminScope(final UserInfos user) { // Map<String, UserInfos.Function> functions = user.getFunctions(); // if (functions != null && functions.containsKey(DefaultFunctions.ADMIN_LOCAL)) { // Function adminLocal = functions.get(DefaultFunctions.ADMIN_LOCAL); // if (adminLocal != null) { // return adminLocal.getScope(); // } // } // // return new ArrayList<String>(); // } // Path: src/main/java/net/atos/entng/rbs/models/Resource.java import static net.atos.entng.rbs.BookingUtils.getLocalAdminScope; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; import org.entcore.common.user.UserInfos; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; } public Optional<String> getManagers() { return Optional.ofNullable(json.getString("managers", null)); } public boolean hasNotOwnerOrSchoolId() { return !getOwner().isPresent() || !getSchoolId().isPresent(); } public Optional<JsonArray> getManagersAsJsonArray() { Optional<String> managersString = getManagers(); JsonArray managers = (managersString.isPresent()) ? new JsonArray(managersString.get()) : null; return Optional.ofNullable(managers); } /* * Owner or managers of a resourceType, as well as local administrators of a * resourceType's schoolId, do no need to respect constraints on resources' * delays */ public boolean canBypassDelaysConstraints(UserInfos user) { String owner = getOwner().orElse(null); String schoolId = getSchoolId().orElse(null); JsonArray managers = getManagersAsJsonArray().orElse(null); if (user.getUserId().equals(owner)) { return true; }
List<String> scope = getLocalAdminScope(user);
OPEN-ENT-NG/rbs
src/test/java/net/atos/entng/rbs/test/units/BookingDateTest.java
// Path: src/main/java/net/atos/entng/rbs/models/BookingDateUtils.java // public class BookingDateUtils { // public static long secondToDays(long seconds) { // return TimeUnit.DAYS.convert(seconds, TimeUnit.SECONDS); // } // // public static ZonedDateTime addDaysIgnoreDST(ZonedDateTime base, int plusNbDays) { // ZonedDateTime result = base.plusDays(plusNbDays); // if (result.getHour() != base.getHour()) { // result.withHour(base.getHour()); // } // return result; // } // // public static long daysToSecond(long days) { // return TimeUnit.SECONDS.convert(days, TimeUnit.DAYS); // } // // public static long currentTimestampSecondsForIana(String iana) { // return ZonedDateTime.now(ZoneId.of(iana)).toEpochSecond(); // } // // public static int nextDayOfWeek(final int currentDayOfWeek, final int plusDays) { // return (currentDayOfWeek + plusDays) % 7; // } // // public static long tomorrowTimestampSecondsForIana(String iana) { // // Get tomorrow by adding one day to current time // ZonedDateTime today = ZonedDateTime.now(ZoneId.of(iana)); // today = today.truncatedTo(ChronoUnit.DAYS); // ZonedDateTime tomorrowMidnight = today.plusDays(1); // return tomorrowMidnight.toEpochSecond(); // } // // /** // * // * @param unixTimestamp in seconds // * @return 0 for sunday, 1 for monday, etc // */ // public static int dayOfWeekForTimestampSecondsAndIana(final long unixTimestamp, String iana) { // Instant i = Instant.ofEpochSecond(unixTimestamp);// UTC // ZonedDateTime z = ZonedDateTime.ofInstant(i, ZoneId.of(iana));// LOCAL // // %7 so that sunday is 0, monday is 1, etc // return z.getDayOfWeek().getValue() % 7; // } // // public static ZonedDateTime localDateTimeForTimestampSecondsAndIana(long timestampSeconds, String iana) { // Instant i = Instant.ofEpochSecond(timestampSeconds);// UTC // ZonedDateTime z = ZonedDateTime.ofInstant(i, ZoneId.of(iana));// LOCAL // return z; // } // // // }
import java.time.Instant; import java.time.ZoneId; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.time.zone.ZoneOffsetTransition; import java.time.zone.ZoneRules; import java.util.Date; import org.junit.Assert; import org.junit.Test; import net.atos.entng.rbs.models.BookingDateUtils;
ZonedDateTime after = nextTransition.getInstant().atZone(ZoneId.of(IANA_PARIS)).plusDays(1); System.out.println("Before transition : " + before); System.out.println("Before transition no zoned : " + Date.from(before.toOffsetDateTime().toInstant())); System.out.println("Before UTC: " + before.toEpochSecond()); // moment.utc(...).tz("Europe/paris").format("DD/MM/YYYY HH:mm") System.out.println("Before UTC 2:00: " + before.toLocalDateTime().withHour(2).withMinute(0)); System.out.println("Before UTC 2:00 at offset utc: " + before.toLocalDateTime().withHour(2).withMinute(0).toEpochSecond(ZoneOffset.UTC)); // => moment.utc(...).format("DD/MM/YYYY HH:mm") long beforeUTCTimestamp = before.toEpochSecond(); System.out.println("Before transition reverse UTC: " + ZonedDateTime.ofInstant(Instant.ofEpochSecond(beforeUTCTimestamp), ZoneId.of(IANA_PARIS))); System.out.println("Transition : " + transition); System.out.println("After transition : " + after); System.out.println("After UTC : " + after.toEpochSecond()); // moment.utc(...).tz("Europe/paris").format("DD/MM/YYYY HH:mm") System.out.println("After UTC 2:00: " + after.toLocalDateTime().withHour(2).withMinute(0)); System.out.println("After UTC 2:00 at offset utc: " + after.toLocalDateTime().withHour(2).withMinute(0).toEpochSecond(ZoneOffset.UTC)); // => moment.utc(...).format("DD/MM/YYYY HH:mm") } @Test public void shouldAddDayIgnoreDST() { ZoneId zoneId = ZoneId.of(IANA_PARIS); ZoneRules rules = zoneId.getRules(); ZoneOffsetTransition nextTransition = rules.nextTransition(Instant.now()); Instant transition = nextTransition.getInstant(); ZonedDateTime before = nextTransition.getInstant().atZone(ZoneId.of(IANA_PARIS)).plusDays(-1); before = before.withHour(10).withMinute(0);
// Path: src/main/java/net/atos/entng/rbs/models/BookingDateUtils.java // public class BookingDateUtils { // public static long secondToDays(long seconds) { // return TimeUnit.DAYS.convert(seconds, TimeUnit.SECONDS); // } // // public static ZonedDateTime addDaysIgnoreDST(ZonedDateTime base, int plusNbDays) { // ZonedDateTime result = base.plusDays(plusNbDays); // if (result.getHour() != base.getHour()) { // result.withHour(base.getHour()); // } // return result; // } // // public static long daysToSecond(long days) { // return TimeUnit.SECONDS.convert(days, TimeUnit.DAYS); // } // // public static long currentTimestampSecondsForIana(String iana) { // return ZonedDateTime.now(ZoneId.of(iana)).toEpochSecond(); // } // // public static int nextDayOfWeek(final int currentDayOfWeek, final int plusDays) { // return (currentDayOfWeek + plusDays) % 7; // } // // public static long tomorrowTimestampSecondsForIana(String iana) { // // Get tomorrow by adding one day to current time // ZonedDateTime today = ZonedDateTime.now(ZoneId.of(iana)); // today = today.truncatedTo(ChronoUnit.DAYS); // ZonedDateTime tomorrowMidnight = today.plusDays(1); // return tomorrowMidnight.toEpochSecond(); // } // // /** // * // * @param unixTimestamp in seconds // * @return 0 for sunday, 1 for monday, etc // */ // public static int dayOfWeekForTimestampSecondsAndIana(final long unixTimestamp, String iana) { // Instant i = Instant.ofEpochSecond(unixTimestamp);// UTC // ZonedDateTime z = ZonedDateTime.ofInstant(i, ZoneId.of(iana));// LOCAL // // %7 so that sunday is 0, monday is 1, etc // return z.getDayOfWeek().getValue() % 7; // } // // public static ZonedDateTime localDateTimeForTimestampSecondsAndIana(long timestampSeconds, String iana) { // Instant i = Instant.ofEpochSecond(timestampSeconds);// UTC // ZonedDateTime z = ZonedDateTime.ofInstant(i, ZoneId.of(iana));// LOCAL // return z; // } // // // } // Path: src/test/java/net/atos/entng/rbs/test/units/BookingDateTest.java import java.time.Instant; import java.time.ZoneId; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.time.zone.ZoneOffsetTransition; import java.time.zone.ZoneRules; import java.util.Date; import org.junit.Assert; import org.junit.Test; import net.atos.entng.rbs.models.BookingDateUtils; ZonedDateTime after = nextTransition.getInstant().atZone(ZoneId.of(IANA_PARIS)).plusDays(1); System.out.println("Before transition : " + before); System.out.println("Before transition no zoned : " + Date.from(before.toOffsetDateTime().toInstant())); System.out.println("Before UTC: " + before.toEpochSecond()); // moment.utc(...).tz("Europe/paris").format("DD/MM/YYYY HH:mm") System.out.println("Before UTC 2:00: " + before.toLocalDateTime().withHour(2).withMinute(0)); System.out.println("Before UTC 2:00 at offset utc: " + before.toLocalDateTime().withHour(2).withMinute(0).toEpochSecond(ZoneOffset.UTC)); // => moment.utc(...).format("DD/MM/YYYY HH:mm") long beforeUTCTimestamp = before.toEpochSecond(); System.out.println("Before transition reverse UTC: " + ZonedDateTime.ofInstant(Instant.ofEpochSecond(beforeUTCTimestamp), ZoneId.of(IANA_PARIS))); System.out.println("Transition : " + transition); System.out.println("After transition : " + after); System.out.println("After UTC : " + after.toEpochSecond()); // moment.utc(...).tz("Europe/paris").format("DD/MM/YYYY HH:mm") System.out.println("After UTC 2:00: " + after.toLocalDateTime().withHour(2).withMinute(0)); System.out.println("After UTC 2:00 at offset utc: " + after.toLocalDateTime().withHour(2).withMinute(0).toEpochSecond(ZoneOffset.UTC)); // => moment.utc(...).format("DD/MM/YYYY HH:mm") } @Test public void shouldAddDayIgnoreDST() { ZoneId zoneId = ZoneId.of(IANA_PARIS); ZoneRules rules = zoneId.getRules(); ZoneOffsetTransition nextTransition = rules.nextTransition(Instant.now()); Instant transition = nextTransition.getInstant(); ZonedDateTime before = nextTransition.getInstant().atZone(ZoneId.of(IANA_PARIS)).plusDays(-1); before = before.withHour(10).withMinute(0);
ZonedDateTime after = BookingDateUtils.addDaysIgnoreDST(before, 2);
sakserv/hadoop-mini-clusters
hadoop-mini-clusters-storm/src/main/java/com/github/sakserv/minicluster/impl/StormLocalCluster.java
// Path: hadoop-mini-clusters-common/src/main/java/com/github/sakserv/minicluster/util/FileUtils.java // public final class FileUtils { // // // Logger // private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(FileUtils.class); // // public static void deleteFolder(String directory, boolean quietly) { // try { // Path directoryPath = Paths.get(directory).toAbsolutePath(); // if (!quietly) { // LOG.info("FILEUTILS: Deleting contents of directory: {}", // directoryPath.toAbsolutePath().toString()); // } // Files.walkFileTree(directoryPath, new SimpleFileVisitor<Path>() { // @Override // public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) // throws IOException { // Files.delete(file); // if (!quietly) { // LOG.info("Removing file: {}", file.toAbsolutePath().toString()); // } // return FileVisitResult.CONTINUE; // } // // @Override // public FileVisitResult postVisitDirectory(Path dir, IOException exc) // throws IOException { // Files.delete(dir); // if (!quietly) { // LOG.info("Removing directory: {}", dir.toAbsolutePath().toString()); // } // return FileVisitResult.CONTINUE; // } // }); // } catch (IOException e) { // LOG.error("FILEUTILS: Unable to remove {}", directory); // } // } // // public static void deleteFolder(String directory) { // deleteFolder(directory, false); // } // // @Override // public String toString() { // return "FileUtils"; // } // }
import com.github.sakserv.minicluster.util.FileUtils; import org.apache.storm.ILocalCluster; import org.apache.storm.Testing; import org.apache.storm.generated.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.sakserv.minicluster.MiniCluster; import org.apache.storm.Config; import org.apache.storm.LocalCluster; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List;
@Override public void stop(boolean cleanUp) throws Exception { LOG.info("STORM: Stopping StormLocalCluster"); localCluster.shutdown(); if(cleanUp) { cleanUp(); } } @Override public void configure() throws Exception { stormConf.setDebug(enableDebug); stormConf.setNumWorkers(numWorkers); stormConf.put("nimbus-daemon", true); List<String> stormNimbusSeeds = new ArrayList<>(); stormNimbusSeeds.add("localhost"); stormConf.put(Config.NIMBUS_SEEDS, stormNimbusSeeds); stormConf.put(Config.NIMBUS_THRIFT_PORT, 6627); stormConf.put(Config.STORM_THRIFT_TRANSPORT_PLUGIN, "org.apache.storm.security.auth.SimpleTransportPlugin"); stormConf.put(Config.STORM_NIMBUS_RETRY_INTERVAL_CEILING, 60000); stormConf.put(Config.STORM_NIMBUS_RETRY_TIMES, 5); stormConf.put(Config.STORM_NIMBUS_RETRY_INTERVAL, 2000); stormConf.put(Config.NIMBUS_THRIFT_MAX_BUFFER_SIZE, 1048576); stormConf.put(Config.STORM_ZOOKEEPER_SERVERS, Arrays.asList(getZookeeperHost())); stormConf.put(Config.STORM_ZOOKEEPER_PORT, getZookeeperPort()); } @Override public void cleanUp() throws Exception {
// Path: hadoop-mini-clusters-common/src/main/java/com/github/sakserv/minicluster/util/FileUtils.java // public final class FileUtils { // // // Logger // private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(FileUtils.class); // // public static void deleteFolder(String directory, boolean quietly) { // try { // Path directoryPath = Paths.get(directory).toAbsolutePath(); // if (!quietly) { // LOG.info("FILEUTILS: Deleting contents of directory: {}", // directoryPath.toAbsolutePath().toString()); // } // Files.walkFileTree(directoryPath, new SimpleFileVisitor<Path>() { // @Override // public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) // throws IOException { // Files.delete(file); // if (!quietly) { // LOG.info("Removing file: {}", file.toAbsolutePath().toString()); // } // return FileVisitResult.CONTINUE; // } // // @Override // public FileVisitResult postVisitDirectory(Path dir, IOException exc) // throws IOException { // Files.delete(dir); // if (!quietly) { // LOG.info("Removing directory: {}", dir.toAbsolutePath().toString()); // } // return FileVisitResult.CONTINUE; // } // }); // } catch (IOException e) { // LOG.error("FILEUTILS: Unable to remove {}", directory); // } // } // // public static void deleteFolder(String directory) { // deleteFolder(directory, false); // } // // @Override // public String toString() { // return "FileUtils"; // } // } // Path: hadoop-mini-clusters-storm/src/main/java/com/github/sakserv/minicluster/impl/StormLocalCluster.java import com.github.sakserv.minicluster.util.FileUtils; import org.apache.storm.ILocalCluster; import org.apache.storm.Testing; import org.apache.storm.generated.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.sakserv.minicluster.MiniCluster; import org.apache.storm.Config; import org.apache.storm.LocalCluster; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; @Override public void stop(boolean cleanUp) throws Exception { LOG.info("STORM: Stopping StormLocalCluster"); localCluster.shutdown(); if(cleanUp) { cleanUp(); } } @Override public void configure() throws Exception { stormConf.setDebug(enableDebug); stormConf.setNumWorkers(numWorkers); stormConf.put("nimbus-daemon", true); List<String> stormNimbusSeeds = new ArrayList<>(); stormNimbusSeeds.add("localhost"); stormConf.put(Config.NIMBUS_SEEDS, stormNimbusSeeds); stormConf.put(Config.NIMBUS_THRIFT_PORT, 6627); stormConf.put(Config.STORM_THRIFT_TRANSPORT_PLUGIN, "org.apache.storm.security.auth.SimpleTransportPlugin"); stormConf.put(Config.STORM_NIMBUS_RETRY_INTERVAL_CEILING, 60000); stormConf.put(Config.STORM_NIMBUS_RETRY_TIMES, 5); stormConf.put(Config.STORM_NIMBUS_RETRY_INTERVAL, 2000); stormConf.put(Config.NIMBUS_THRIFT_MAX_BUFFER_SIZE, 1048576); stormConf.put(Config.STORM_ZOOKEEPER_SERVERS, Arrays.asList(getZookeeperHost())); stormConf.put(Config.STORM_ZOOKEEPER_PORT, getZookeeperPort()); } @Override public void cleanUp() throws Exception {
FileUtils.deleteFolder("logs");
sakserv/hadoop-mini-clusters
hadoop-mini-clusters-mapreduce/src/main/java/com/github/sakserv/minicluster/impl/MRLocalCluster.java
// Path: hadoop-mini-clusters-common/src/main/java/com/github/sakserv/minicluster/util/FileUtils.java // public final class FileUtils { // // // Logger // private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(FileUtils.class); // // public static void deleteFolder(String directory, boolean quietly) { // try { // Path directoryPath = Paths.get(directory).toAbsolutePath(); // if (!quietly) { // LOG.info("FILEUTILS: Deleting contents of directory: {}", // directoryPath.toAbsolutePath().toString()); // } // Files.walkFileTree(directoryPath, new SimpleFileVisitor<Path>() { // @Override // public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) // throws IOException { // Files.delete(file); // if (!quietly) { // LOG.info("Removing file: {}", file.toAbsolutePath().toString()); // } // return FileVisitResult.CONTINUE; // } // // @Override // public FileVisitResult postVisitDirectory(Path dir, IOException exc) // throws IOException { // Files.delete(dir); // if (!quietly) { // LOG.info("Removing directory: {}", dir.toAbsolutePath().toString()); // } // return FileVisitResult.CONTINUE; // } // }); // } catch (IOException e) { // LOG.error("FILEUTILS: Unable to remove {}", directory); // } // } // // public static void deleteFolder(String directory) { // deleteFolder(directory, false); // } // // @Override // public String toString() { // return "FileUtils"; // } // } // // Path: hadoop-mini-clusters-common/src/main/java/com/github/sakserv/minicluster/util/WindowsLibsUtils.java // public class WindowsLibsUtils { // // // Logger // private static final Logger LOG = LoggerFactory.getLogger(WindowsLibsUtils.class); // // public static void setHadoopHome() { // // // Set hadoop.home.dir to point to the windows lib dir // if (System.getProperty("os.name").startsWith("Windows")) { // // String windowsLibDir = getHadoopHome(); // // LOG.info("WINDOWS: Setting hadoop.home.dir: {}", windowsLibDir); // System.setProperty("hadoop.home.dir", windowsLibDir); // System.load(new File(windowsLibDir + Path.SEPARATOR + "lib" + Path.SEPARATOR + "hadoop.dll").getAbsolutePath()); // System.load(new File(windowsLibDir + Path.SEPARATOR + "lib" + Path.SEPARATOR + "hdfs.dll").getAbsolutePath()); // // } // } // // public static String getHadoopHome() { // // if(System.getProperty("HADOOP_HOME") != null) { // LOG.info("HADOOP_HOME: " + System.getProperty("HADOOP_HOME")); // return System.getProperty("HADOOP_HOME"); // } else if (System.getenv("HADOOP_HOME") != null) { //takes the hadoop home from system environment variable // LOG.info("HADOOP_HOME: " + System.getenv("HADOOP_HOME")); // return System.getenv("HADOOP_HOME"); // } else { // // File windowsLibDir = new File("." + Path.SEPARATOR + "windows_libs" + // Path.SEPARATOR + System.getProperty("hdp.release.version")); // // if (!windowsLibDir.exists()) { // windowsLibDir = new File(".." + Path.SEPARATOR + windowsLibDir); // if (!windowsLibDir.exists()) { // LOG.error("WINDOWS: ERROR: Could not find windows native libs"); // } // } // return windowsLibDir.getAbsolutePath(); // } // // } // // }
import java.io.File; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.mapreduce.v2.MiniMRYarnCluster; import org.apache.hadoop.mapreduce.v2.jobhistory.JHAdminConfig; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.sakserv.minicluster.MiniCluster; import com.github.sakserv.minicluster.util.FileUtils; import com.github.sakserv.minicluster.util.WindowsLibsUtils;
@Override public void start() throws Exception { LOG.info("MR: Starting MiniMRYarnCluster"); configure(); miniMRYarnCluster = new MiniMRYarnCluster(testName, numNodeManagers); miniMRYarnCluster.serviceInit(configuration); miniMRYarnCluster.init(configuration); miniMRYarnCluster.start(); } @Override public void stop() throws Exception {stop(true);} @Override public void stop(boolean cleanUp) throws Exception { LOG.info("MR: Stopping MiniMRYarnCluster"); miniMRYarnCluster.stop(); if(cleanUp) { cleanUp(); } } @Override public void configure() throws Exception { // Handle Windows
// Path: hadoop-mini-clusters-common/src/main/java/com/github/sakserv/minicluster/util/FileUtils.java // public final class FileUtils { // // // Logger // private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(FileUtils.class); // // public static void deleteFolder(String directory, boolean quietly) { // try { // Path directoryPath = Paths.get(directory).toAbsolutePath(); // if (!quietly) { // LOG.info("FILEUTILS: Deleting contents of directory: {}", // directoryPath.toAbsolutePath().toString()); // } // Files.walkFileTree(directoryPath, new SimpleFileVisitor<Path>() { // @Override // public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) // throws IOException { // Files.delete(file); // if (!quietly) { // LOG.info("Removing file: {}", file.toAbsolutePath().toString()); // } // return FileVisitResult.CONTINUE; // } // // @Override // public FileVisitResult postVisitDirectory(Path dir, IOException exc) // throws IOException { // Files.delete(dir); // if (!quietly) { // LOG.info("Removing directory: {}", dir.toAbsolutePath().toString()); // } // return FileVisitResult.CONTINUE; // } // }); // } catch (IOException e) { // LOG.error("FILEUTILS: Unable to remove {}", directory); // } // } // // public static void deleteFolder(String directory) { // deleteFolder(directory, false); // } // // @Override // public String toString() { // return "FileUtils"; // } // } // // Path: hadoop-mini-clusters-common/src/main/java/com/github/sakserv/minicluster/util/WindowsLibsUtils.java // public class WindowsLibsUtils { // // // Logger // private static final Logger LOG = LoggerFactory.getLogger(WindowsLibsUtils.class); // // public static void setHadoopHome() { // // // Set hadoop.home.dir to point to the windows lib dir // if (System.getProperty("os.name").startsWith("Windows")) { // // String windowsLibDir = getHadoopHome(); // // LOG.info("WINDOWS: Setting hadoop.home.dir: {}", windowsLibDir); // System.setProperty("hadoop.home.dir", windowsLibDir); // System.load(new File(windowsLibDir + Path.SEPARATOR + "lib" + Path.SEPARATOR + "hadoop.dll").getAbsolutePath()); // System.load(new File(windowsLibDir + Path.SEPARATOR + "lib" + Path.SEPARATOR + "hdfs.dll").getAbsolutePath()); // // } // } // // public static String getHadoopHome() { // // if(System.getProperty("HADOOP_HOME") != null) { // LOG.info("HADOOP_HOME: " + System.getProperty("HADOOP_HOME")); // return System.getProperty("HADOOP_HOME"); // } else if (System.getenv("HADOOP_HOME") != null) { //takes the hadoop home from system environment variable // LOG.info("HADOOP_HOME: " + System.getenv("HADOOP_HOME")); // return System.getenv("HADOOP_HOME"); // } else { // // File windowsLibDir = new File("." + Path.SEPARATOR + "windows_libs" + // Path.SEPARATOR + System.getProperty("hdp.release.version")); // // if (!windowsLibDir.exists()) { // windowsLibDir = new File(".." + Path.SEPARATOR + windowsLibDir); // if (!windowsLibDir.exists()) { // LOG.error("WINDOWS: ERROR: Could not find windows native libs"); // } // } // return windowsLibDir.getAbsolutePath(); // } // // } // // } // Path: hadoop-mini-clusters-mapreduce/src/main/java/com/github/sakserv/minicluster/impl/MRLocalCluster.java import java.io.File; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.mapreduce.v2.MiniMRYarnCluster; import org.apache.hadoop.mapreduce.v2.jobhistory.JHAdminConfig; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.sakserv.minicluster.MiniCluster; import com.github.sakserv.minicluster.util.FileUtils; import com.github.sakserv.minicluster.util.WindowsLibsUtils; @Override public void start() throws Exception { LOG.info("MR: Starting MiniMRYarnCluster"); configure(); miniMRYarnCluster = new MiniMRYarnCluster(testName, numNodeManagers); miniMRYarnCluster.serviceInit(configuration); miniMRYarnCluster.init(configuration); miniMRYarnCluster.start(); } @Override public void stop() throws Exception {stop(true);} @Override public void stop(boolean cleanUp) throws Exception { LOG.info("MR: Stopping MiniMRYarnCluster"); miniMRYarnCluster.stop(); if(cleanUp) { cleanUp(); } } @Override public void configure() throws Exception { // Handle Windows
WindowsLibsUtils.setHadoopHome();
sakserv/hadoop-mini-clusters
hadoop-mini-clusters-mapreduce/src/main/java/com/github/sakserv/minicluster/impl/MRLocalCluster.java
// Path: hadoop-mini-clusters-common/src/main/java/com/github/sakserv/minicluster/util/FileUtils.java // public final class FileUtils { // // // Logger // private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(FileUtils.class); // // public static void deleteFolder(String directory, boolean quietly) { // try { // Path directoryPath = Paths.get(directory).toAbsolutePath(); // if (!quietly) { // LOG.info("FILEUTILS: Deleting contents of directory: {}", // directoryPath.toAbsolutePath().toString()); // } // Files.walkFileTree(directoryPath, new SimpleFileVisitor<Path>() { // @Override // public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) // throws IOException { // Files.delete(file); // if (!quietly) { // LOG.info("Removing file: {}", file.toAbsolutePath().toString()); // } // return FileVisitResult.CONTINUE; // } // // @Override // public FileVisitResult postVisitDirectory(Path dir, IOException exc) // throws IOException { // Files.delete(dir); // if (!quietly) { // LOG.info("Removing directory: {}", dir.toAbsolutePath().toString()); // } // return FileVisitResult.CONTINUE; // } // }); // } catch (IOException e) { // LOG.error("FILEUTILS: Unable to remove {}", directory); // } // } // // public static void deleteFolder(String directory) { // deleteFolder(directory, false); // } // // @Override // public String toString() { // return "FileUtils"; // } // } // // Path: hadoop-mini-clusters-common/src/main/java/com/github/sakserv/minicluster/util/WindowsLibsUtils.java // public class WindowsLibsUtils { // // // Logger // private static final Logger LOG = LoggerFactory.getLogger(WindowsLibsUtils.class); // // public static void setHadoopHome() { // // // Set hadoop.home.dir to point to the windows lib dir // if (System.getProperty("os.name").startsWith("Windows")) { // // String windowsLibDir = getHadoopHome(); // // LOG.info("WINDOWS: Setting hadoop.home.dir: {}", windowsLibDir); // System.setProperty("hadoop.home.dir", windowsLibDir); // System.load(new File(windowsLibDir + Path.SEPARATOR + "lib" + Path.SEPARATOR + "hadoop.dll").getAbsolutePath()); // System.load(new File(windowsLibDir + Path.SEPARATOR + "lib" + Path.SEPARATOR + "hdfs.dll").getAbsolutePath()); // // } // } // // public static String getHadoopHome() { // // if(System.getProperty("HADOOP_HOME") != null) { // LOG.info("HADOOP_HOME: " + System.getProperty("HADOOP_HOME")); // return System.getProperty("HADOOP_HOME"); // } else if (System.getenv("HADOOP_HOME") != null) { //takes the hadoop home from system environment variable // LOG.info("HADOOP_HOME: " + System.getenv("HADOOP_HOME")); // return System.getenv("HADOOP_HOME"); // } else { // // File windowsLibDir = new File("." + Path.SEPARATOR + "windows_libs" + // Path.SEPARATOR + System.getProperty("hdp.release.version")); // // if (!windowsLibDir.exists()) { // windowsLibDir = new File(".." + Path.SEPARATOR + windowsLibDir); // if (!windowsLibDir.exists()) { // LOG.error("WINDOWS: ERROR: Could not find windows native libs"); // } // } // return windowsLibDir.getAbsolutePath(); // } // // } // // }
import java.io.File; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.mapreduce.v2.MiniMRYarnCluster; import org.apache.hadoop.mapreduce.v2.jobhistory.JHAdminConfig; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.sakserv.minicluster.MiniCluster; import com.github.sakserv.minicluster.util.FileUtils; import com.github.sakserv.minicluster.util.WindowsLibsUtils;
configuration.set(YarnConfiguration.RM_ADDRESS, resourceManagerAddress); configuration.set(YarnConfiguration.RM_HOSTNAME, resourceManagerHostname); configuration.set(YarnConfiguration.RM_SCHEDULER_ADDRESS, resourceManagerSchedulerAddress); configuration.set(YarnConfiguration.RM_RESOURCE_TRACKER_ADDRESS, resourceManagerResourceTrackerAddress); configuration.set(YarnConfiguration.RM_WEBAPP_ADDRESS, resourceManagerWebappAddress); configuration.set(JHAdminConfig.MR_HISTORY_ADDRESS, jobHistoryAddress); configuration.set(YarnConfiguration.YARN_MINICLUSTER_FIXED_PORTS, "true"); configuration.set(JHAdminConfig.MR_HISTORY_MINICLUSTER_FIXED_PORTS, "true"); if (getUseInJvmContainerExecutor()) { configuration.set(YarnConfiguration.NM_CONTAINER_EXECUTOR, inJvmContainerExecutorClass); configuration.set("fs.hdfs.impl", org.apache.hadoop.hdfs.DistributedFileSystem.class.getName()); configuration.set("fs.file.impl", org.apache.hadoop.fs.LocalFileSystem.class.getName()); } if (null != hdfsDefaultFs) { configuration.set("fs.defaultFS", hdfsDefaultFs); configuration.set("dfs.replication", "1"); } } @Override public void cleanUp() throws Exception { // Depending on if we are running in the module or the parent // project, the target folder will be in a different location. // We don't want to nuke the entire target directory, unless only // the mini cluster is using it. // A reasonable check to keep things clean is to check for the existence // of ./target/classes and only delete the mini cluster temporary dir if true. // Delete the entire ./target if false if (new File("./target/classes").exists()) {
// Path: hadoop-mini-clusters-common/src/main/java/com/github/sakserv/minicluster/util/FileUtils.java // public final class FileUtils { // // // Logger // private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(FileUtils.class); // // public static void deleteFolder(String directory, boolean quietly) { // try { // Path directoryPath = Paths.get(directory).toAbsolutePath(); // if (!quietly) { // LOG.info("FILEUTILS: Deleting contents of directory: {}", // directoryPath.toAbsolutePath().toString()); // } // Files.walkFileTree(directoryPath, new SimpleFileVisitor<Path>() { // @Override // public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) // throws IOException { // Files.delete(file); // if (!quietly) { // LOG.info("Removing file: {}", file.toAbsolutePath().toString()); // } // return FileVisitResult.CONTINUE; // } // // @Override // public FileVisitResult postVisitDirectory(Path dir, IOException exc) // throws IOException { // Files.delete(dir); // if (!quietly) { // LOG.info("Removing directory: {}", dir.toAbsolutePath().toString()); // } // return FileVisitResult.CONTINUE; // } // }); // } catch (IOException e) { // LOG.error("FILEUTILS: Unable to remove {}", directory); // } // } // // public static void deleteFolder(String directory) { // deleteFolder(directory, false); // } // // @Override // public String toString() { // return "FileUtils"; // } // } // // Path: hadoop-mini-clusters-common/src/main/java/com/github/sakserv/minicluster/util/WindowsLibsUtils.java // public class WindowsLibsUtils { // // // Logger // private static final Logger LOG = LoggerFactory.getLogger(WindowsLibsUtils.class); // // public static void setHadoopHome() { // // // Set hadoop.home.dir to point to the windows lib dir // if (System.getProperty("os.name").startsWith("Windows")) { // // String windowsLibDir = getHadoopHome(); // // LOG.info("WINDOWS: Setting hadoop.home.dir: {}", windowsLibDir); // System.setProperty("hadoop.home.dir", windowsLibDir); // System.load(new File(windowsLibDir + Path.SEPARATOR + "lib" + Path.SEPARATOR + "hadoop.dll").getAbsolutePath()); // System.load(new File(windowsLibDir + Path.SEPARATOR + "lib" + Path.SEPARATOR + "hdfs.dll").getAbsolutePath()); // // } // } // // public static String getHadoopHome() { // // if(System.getProperty("HADOOP_HOME") != null) { // LOG.info("HADOOP_HOME: " + System.getProperty("HADOOP_HOME")); // return System.getProperty("HADOOP_HOME"); // } else if (System.getenv("HADOOP_HOME") != null) { //takes the hadoop home from system environment variable // LOG.info("HADOOP_HOME: " + System.getenv("HADOOP_HOME")); // return System.getenv("HADOOP_HOME"); // } else { // // File windowsLibDir = new File("." + Path.SEPARATOR + "windows_libs" + // Path.SEPARATOR + System.getProperty("hdp.release.version")); // // if (!windowsLibDir.exists()) { // windowsLibDir = new File(".." + Path.SEPARATOR + windowsLibDir); // if (!windowsLibDir.exists()) { // LOG.error("WINDOWS: ERROR: Could not find windows native libs"); // } // } // return windowsLibDir.getAbsolutePath(); // } // // } // // } // Path: hadoop-mini-clusters-mapreduce/src/main/java/com/github/sakserv/minicluster/impl/MRLocalCluster.java import java.io.File; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.mapreduce.v2.MiniMRYarnCluster; import org.apache.hadoop.mapreduce.v2.jobhistory.JHAdminConfig; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.sakserv.minicluster.MiniCluster; import com.github.sakserv.minicluster.util.FileUtils; import com.github.sakserv.minicluster.util.WindowsLibsUtils; configuration.set(YarnConfiguration.RM_ADDRESS, resourceManagerAddress); configuration.set(YarnConfiguration.RM_HOSTNAME, resourceManagerHostname); configuration.set(YarnConfiguration.RM_SCHEDULER_ADDRESS, resourceManagerSchedulerAddress); configuration.set(YarnConfiguration.RM_RESOURCE_TRACKER_ADDRESS, resourceManagerResourceTrackerAddress); configuration.set(YarnConfiguration.RM_WEBAPP_ADDRESS, resourceManagerWebappAddress); configuration.set(JHAdminConfig.MR_HISTORY_ADDRESS, jobHistoryAddress); configuration.set(YarnConfiguration.YARN_MINICLUSTER_FIXED_PORTS, "true"); configuration.set(JHAdminConfig.MR_HISTORY_MINICLUSTER_FIXED_PORTS, "true"); if (getUseInJvmContainerExecutor()) { configuration.set(YarnConfiguration.NM_CONTAINER_EXECUTOR, inJvmContainerExecutorClass); configuration.set("fs.hdfs.impl", org.apache.hadoop.hdfs.DistributedFileSystem.class.getName()); configuration.set("fs.file.impl", org.apache.hadoop.fs.LocalFileSystem.class.getName()); } if (null != hdfsDefaultFs) { configuration.set("fs.defaultFS", hdfsDefaultFs); configuration.set("dfs.replication", "1"); } } @Override public void cleanUp() throws Exception { // Depending on if we are running in the module or the parent // project, the target folder will be in a different location. // We don't want to nuke the entire target directory, unless only // the mini cluster is using it. // A reasonable check to keep things clean is to check for the existence // of ./target/classes and only delete the mini cluster temporary dir if true. // Delete the entire ./target if false if (new File("./target/classes").exists()) {
FileUtils.deleteFolder("./target/" + testName);
sakserv/hadoop-mini-clusters
hadoop-mini-clusters-hyperscaledb/src/main/java/com/github/sakserv/minicluster/impl/HsqldbLocalServer.java
// Path: hadoop-mini-clusters-common/src/main/java/com/github/sakserv/minicluster/util/FileUtils.java // public final class FileUtils { // // // Logger // private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(FileUtils.class); // // public static void deleteFolder(String directory, boolean quietly) { // try { // Path directoryPath = Paths.get(directory).toAbsolutePath(); // if (!quietly) { // LOG.info("FILEUTILS: Deleting contents of directory: {}", // directoryPath.toAbsolutePath().toString()); // } // Files.walkFileTree(directoryPath, new SimpleFileVisitor<Path>() { // @Override // public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) // throws IOException { // Files.delete(file); // if (!quietly) { // LOG.info("Removing file: {}", file.toAbsolutePath().toString()); // } // return FileVisitResult.CONTINUE; // } // // @Override // public FileVisitResult postVisitDirectory(Path dir, IOException exc) // throws IOException { // Files.delete(dir); // if (!quietly) { // LOG.info("Removing directory: {}", dir.toAbsolutePath().toString()); // } // return FileVisitResult.CONTINUE; // } // }); // } catch (IOException e) { // LOG.error("FILEUTILS: Unable to remove {}", directory); // } // } // // public static void deleteFolder(String directory) { // deleteFolder(directory, false); // } // // @Override // public String toString() { // return "FileUtils"; // } // }
import java.io.File; import org.hsqldb.persist.HsqlProperties; import org.hsqldb.server.Server; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.sakserv.minicluster.MiniCluster; import com.github.sakserv.minicluster.util.FileUtils;
server.start(); } @Override public void stop() throws Exception { stop(true); } @Override public void stop(boolean cleanUp) throws Exception { LOG.info("HSQLDB: Stopping HSQLDB"); server.stop(); if (cleanUp) { cleanUp(); } } @Override public void configure() throws Exception { hsqlProperties.setProperty("server.address", getHsqldbHostName()); hsqlProperties.setProperty("server.port", getHsqldbPort()); hsqlProperties.setProperty("server.database.0", "file:" + new File(getHsqldbTempDir()).getAbsolutePath()); hsqlProperties.setProperty("server.dbname.0", getHsqldbDatabaseName()); hsqlProperties.setProperty("server.remote_open", "true"); hsqlProperties.setProperty("server.max_allowed_packet", "32M"); } @Override public void cleanUp() throws Exception {
// Path: hadoop-mini-clusters-common/src/main/java/com/github/sakserv/minicluster/util/FileUtils.java // public final class FileUtils { // // // Logger // private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(FileUtils.class); // // public static void deleteFolder(String directory, boolean quietly) { // try { // Path directoryPath = Paths.get(directory).toAbsolutePath(); // if (!quietly) { // LOG.info("FILEUTILS: Deleting contents of directory: {}", // directoryPath.toAbsolutePath().toString()); // } // Files.walkFileTree(directoryPath, new SimpleFileVisitor<Path>() { // @Override // public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) // throws IOException { // Files.delete(file); // if (!quietly) { // LOG.info("Removing file: {}", file.toAbsolutePath().toString()); // } // return FileVisitResult.CONTINUE; // } // // @Override // public FileVisitResult postVisitDirectory(Path dir, IOException exc) // throws IOException { // Files.delete(dir); // if (!quietly) { // LOG.info("Removing directory: {}", dir.toAbsolutePath().toString()); // } // return FileVisitResult.CONTINUE; // } // }); // } catch (IOException e) { // LOG.error("FILEUTILS: Unable to remove {}", directory); // } // } // // public static void deleteFolder(String directory) { // deleteFolder(directory, false); // } // // @Override // public String toString() { // return "FileUtils"; // } // } // Path: hadoop-mini-clusters-hyperscaledb/src/main/java/com/github/sakserv/minicluster/impl/HsqldbLocalServer.java import java.io.File; import org.hsqldb.persist.HsqlProperties; import org.hsqldb.server.Server; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.sakserv.minicluster.MiniCluster; import com.github.sakserv.minicluster.util.FileUtils; server.start(); } @Override public void stop() throws Exception { stop(true); } @Override public void stop(boolean cleanUp) throws Exception { LOG.info("HSQLDB: Stopping HSQLDB"); server.stop(); if (cleanUp) { cleanUp(); } } @Override public void configure() throws Exception { hsqlProperties.setProperty("server.address", getHsqldbHostName()); hsqlProperties.setProperty("server.port", getHsqldbPort()); hsqlProperties.setProperty("server.database.0", "file:" + new File(getHsqldbTempDir()).getAbsolutePath()); hsqlProperties.setProperty("server.dbname.0", getHsqldbDatabaseName()); hsqlProperties.setProperty("server.remote_open", "true"); hsqlProperties.setProperty("server.max_allowed_packet", "32M"); } @Override public void cleanUp() throws Exception {
FileUtils.deleteFolder(getHsqldbTempDir() + ".tmp");
sakserv/hadoop-mini-clusters
hadoop-mini-clusters-hbase/src/main/java/com/github/sakserv/minicluster/impl/HbaseLocalCluster.java
// Path: hadoop-mini-clusters-common/src/main/java/com/github/sakserv/minicluster/util/FileUtils.java // public final class FileUtils { // // // Logger // private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(FileUtils.class); // // public static void deleteFolder(String directory, boolean quietly) { // try { // Path directoryPath = Paths.get(directory).toAbsolutePath(); // if (!quietly) { // LOG.info("FILEUTILS: Deleting contents of directory: {}", // directoryPath.toAbsolutePath().toString()); // } // Files.walkFileTree(directoryPath, new SimpleFileVisitor<Path>() { // @Override // public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) // throws IOException { // Files.delete(file); // if (!quietly) { // LOG.info("Removing file: {}", file.toAbsolutePath().toString()); // } // return FileVisitResult.CONTINUE; // } // // @Override // public FileVisitResult postVisitDirectory(Path dir, IOException exc) // throws IOException { // Files.delete(dir); // if (!quietly) { // LOG.info("Removing directory: {}", dir.toAbsolutePath().toString()); // } // return FileVisitResult.CONTINUE; // } // }); // } catch (IOException e) { // LOG.error("FILEUTILS: Unable to remove {}", directory); // } // } // // public static void deleteFolder(String directory) { // deleteFolder(directory, false); // } // // @Override // public String toString() { // return "FileUtils"; // } // } // // Path: hadoop-mini-clusters-common/src/main/java/com/github/sakserv/minicluster/util/WindowsLibsUtils.java // public class WindowsLibsUtils { // // // Logger // private static final Logger LOG = LoggerFactory.getLogger(WindowsLibsUtils.class); // // public static void setHadoopHome() { // // // Set hadoop.home.dir to point to the windows lib dir // if (System.getProperty("os.name").startsWith("Windows")) { // // String windowsLibDir = getHadoopHome(); // // LOG.info("WINDOWS: Setting hadoop.home.dir: {}", windowsLibDir); // System.setProperty("hadoop.home.dir", windowsLibDir); // System.load(new File(windowsLibDir + Path.SEPARATOR + "lib" + Path.SEPARATOR + "hadoop.dll").getAbsolutePath()); // System.load(new File(windowsLibDir + Path.SEPARATOR + "lib" + Path.SEPARATOR + "hdfs.dll").getAbsolutePath()); // // } // } // // public static String getHadoopHome() { // // if(System.getProperty("HADOOP_HOME") != null) { // LOG.info("HADOOP_HOME: " + System.getProperty("HADOOP_HOME")); // return System.getProperty("HADOOP_HOME"); // } else if (System.getenv("HADOOP_HOME") != null) { //takes the hadoop home from system environment variable // LOG.info("HADOOP_HOME: " + System.getenv("HADOOP_HOME")); // return System.getenv("HADOOP_HOME"); // } else { // // File windowsLibDir = new File("." + Path.SEPARATOR + "windows_libs" + // Path.SEPARATOR + System.getProperty("hdp.release.version")); // // if (!windowsLibDir.exists()) { // windowsLibDir = new File(".." + Path.SEPARATOR + windowsLibDir); // if (!windowsLibDir.exists()) { // LOG.error("WINDOWS: ERROR: Could not find windows native libs"); // } // } // return windowsLibDir.getAbsolutePath(); // } // // } // // }
import com.github.sakserv.minicluster.MiniCluster; import com.github.sakserv.minicluster.util.FileUtils; import com.github.sakserv.minicluster.util.WindowsLibsUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.MiniHBaseCluster; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
} @Override public void stop() throws Exception { stop(true); } @Override public void stop(boolean cleanUp) throws Exception { LOG.info("HBASE: Stopping MiniHBaseCluster"); if (isRestActivated()) { getHbaseRestLocalCluster().cleanUp(); getHbaseRestLocalCluster().stop(); } miniHBaseCluster.flushcache(); miniHBaseCluster.close(); miniHBaseCluster.shutdown(); miniHBaseCluster.waitUntilShutDown(); if (cleanUp) { cleanUp(); } } @Override public void configure() throws Exception { configure(hbaseConfiguration); // Handle Windows
// Path: hadoop-mini-clusters-common/src/main/java/com/github/sakserv/minicluster/util/FileUtils.java // public final class FileUtils { // // // Logger // private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(FileUtils.class); // // public static void deleteFolder(String directory, boolean quietly) { // try { // Path directoryPath = Paths.get(directory).toAbsolutePath(); // if (!quietly) { // LOG.info("FILEUTILS: Deleting contents of directory: {}", // directoryPath.toAbsolutePath().toString()); // } // Files.walkFileTree(directoryPath, new SimpleFileVisitor<Path>() { // @Override // public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) // throws IOException { // Files.delete(file); // if (!quietly) { // LOG.info("Removing file: {}", file.toAbsolutePath().toString()); // } // return FileVisitResult.CONTINUE; // } // // @Override // public FileVisitResult postVisitDirectory(Path dir, IOException exc) // throws IOException { // Files.delete(dir); // if (!quietly) { // LOG.info("Removing directory: {}", dir.toAbsolutePath().toString()); // } // return FileVisitResult.CONTINUE; // } // }); // } catch (IOException e) { // LOG.error("FILEUTILS: Unable to remove {}", directory); // } // } // // public static void deleteFolder(String directory) { // deleteFolder(directory, false); // } // // @Override // public String toString() { // return "FileUtils"; // } // } // // Path: hadoop-mini-clusters-common/src/main/java/com/github/sakserv/minicluster/util/WindowsLibsUtils.java // public class WindowsLibsUtils { // // // Logger // private static final Logger LOG = LoggerFactory.getLogger(WindowsLibsUtils.class); // // public static void setHadoopHome() { // // // Set hadoop.home.dir to point to the windows lib dir // if (System.getProperty("os.name").startsWith("Windows")) { // // String windowsLibDir = getHadoopHome(); // // LOG.info("WINDOWS: Setting hadoop.home.dir: {}", windowsLibDir); // System.setProperty("hadoop.home.dir", windowsLibDir); // System.load(new File(windowsLibDir + Path.SEPARATOR + "lib" + Path.SEPARATOR + "hadoop.dll").getAbsolutePath()); // System.load(new File(windowsLibDir + Path.SEPARATOR + "lib" + Path.SEPARATOR + "hdfs.dll").getAbsolutePath()); // // } // } // // public static String getHadoopHome() { // // if(System.getProperty("HADOOP_HOME") != null) { // LOG.info("HADOOP_HOME: " + System.getProperty("HADOOP_HOME")); // return System.getProperty("HADOOP_HOME"); // } else if (System.getenv("HADOOP_HOME") != null) { //takes the hadoop home from system environment variable // LOG.info("HADOOP_HOME: " + System.getenv("HADOOP_HOME")); // return System.getenv("HADOOP_HOME"); // } else { // // File windowsLibDir = new File("." + Path.SEPARATOR + "windows_libs" + // Path.SEPARATOR + System.getProperty("hdp.release.version")); // // if (!windowsLibDir.exists()) { // windowsLibDir = new File(".." + Path.SEPARATOR + windowsLibDir); // if (!windowsLibDir.exists()) { // LOG.error("WINDOWS: ERROR: Could not find windows native libs"); // } // } // return windowsLibDir.getAbsolutePath(); // } // // } // // } // Path: hadoop-mini-clusters-hbase/src/main/java/com/github/sakserv/minicluster/impl/HbaseLocalCluster.java import com.github.sakserv.minicluster.MiniCluster; import com.github.sakserv.minicluster.util.FileUtils; import com.github.sakserv.minicluster.util.WindowsLibsUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.MiniHBaseCluster; import org.slf4j.Logger; import org.slf4j.LoggerFactory; } @Override public void stop() throws Exception { stop(true); } @Override public void stop(boolean cleanUp) throws Exception { LOG.info("HBASE: Stopping MiniHBaseCluster"); if (isRestActivated()) { getHbaseRestLocalCluster().cleanUp(); getHbaseRestLocalCluster().stop(); } miniHBaseCluster.flushcache(); miniHBaseCluster.close(); miniHBaseCluster.shutdown(); miniHBaseCluster.waitUntilShutDown(); if (cleanUp) { cleanUp(); } } @Override public void configure() throws Exception { configure(hbaseConfiguration); // Handle Windows
WindowsLibsUtils.setHadoopHome();