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
eBay/mTracker
core/src/main/java/com/ccoe/build/core/filter/FilterMatcher.java
// Path: core/src/main/java/com/ccoe/build/core/filter/model/Cause.java // @XmlAccessorType(XmlAccessType.FIELD) // public class Cause { // // @XmlAttribute // private String source; // // @XmlAttribute // private String keyword; // // @XmlAttribute // private String pattern; // // @XmlAttribute // private String value; // // public String getSource() { // return source; // } // // public void setSource(String source) { // this.source = source; // } // // public String getKeyword() { // return keyword; // } // // public void setKeyword(String keyword) { // this.keyword = keyword; // } // // public String getPattern() { // return this.pattern; // } // // public void setPattern(String p) { // this.pattern = p; // } // // public String getValue() { // return value; // } // // public void setValue(String value) { // this.value = value; // } // } // // Path: core/src/main/java/com/ccoe/build/core/filter/model/Filter.java // @XmlAccessorType(XmlAccessType.FIELD) // public class Filter { // @XmlAttribute // private String name; // // @XmlAttribute // private String description; // // private String category; // // @XmlElement(name="cause") // private List<Cause> cause = new ArrayList<Cause>(); // // public List<Cause> getCause() { // return this.cause; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description= description; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public void setCauses(List<Cause> lsCause){ // this.cause = lsCause; // } // } // // Path: core/src/main/java/com/ccoe/build/core/utils/StringUtils.java // public class StringUtils { // // public static boolean isEmpty(String str) { // return (str == null) || (str.length() == 0); // } // // public static List<String> getFound(String contents, String regex, // boolean isCaseInsensitive) { // if (isEmpty(regex) || isEmpty(contents)) { // return new ArrayList<String>(); // } // List<String> results = new ArrayList<String>(); // Pattern pattern; // if (isCaseInsensitive) { // pattern = Pattern.compile(regex, Pattern.UNICODE_CASE // | Pattern.CASE_INSENSITIVE); // } else { // pattern = Pattern.compile(regex, Pattern.UNICODE_CASE); // } // Matcher matcher = pattern.matcher(contents); // while (matcher.find()) { // if (matcher.groupCount() > 0) { // for (int i = 1; i <= matcher.groupCount(); i++) { // if (!isEmpty(matcher.group(i))) { // results.add(matcher.group(i)); // } // } // } else { // if (!isEmpty(matcher.group())) { // results.add(matcher.group()); // } // } // } // return results; // } // // public static String getFirstFound(String contents, String regex, // boolean isCaseInsensitive) { // if (isEmpty(contents) || isEmpty(regex)) { // return null; // } // List<String> found = getFound(contents, regex, isCaseInsensitive); // if (found.size() > 0) { // return (String) found.iterator().next(); // } // return ""; // } // // public static Date setTime(Date date, String timeString) { // Calendar cal1 = Calendar.getInstance(); // cal1.setTime(date); // // Calendar cal2 = Calendar.getInstance(); // // String[] time = timeString.split(":"); // // cal2.set(cal1.get(Calendar.YEAR), // cal1.get(Calendar.MONTH), // cal1.get(Calendar.DAY_OF_MONTH), // Integer.parseInt(time[0]), // Integer.parseInt(time[1]), // Integer.parseInt(time[2])); // // return cal2.getTime(); // } // }
import java.util.HashMap; import java.util.regex.Pattern; import com.ccoe.build.core.filter.model.Cause; import com.ccoe.build.core.filter.model.Filter; import com.ccoe.build.core.utils.StringUtils;
String value = source.get(sourceName); //wouldn't cause error when sourceName is null; if(!isMatchCause(value, cause)) { return false; } } else { return false; } } return true; } public boolean isMatch(String fullstack, Filter filter) { for (Cause cause : filter.getCause()) { if (!isMatchCause(fullstack, cause)) { return false; } } return true; } protected boolean isMatchCause(String content, Cause cause) { if (isMatchContent(content, cause) || isMatchKeyword(content, cause) || isMatchPattern(content, cause)) { return true; } return false; } protected boolean isMatchContent(String content, Cause cause) {
// Path: core/src/main/java/com/ccoe/build/core/filter/model/Cause.java // @XmlAccessorType(XmlAccessType.FIELD) // public class Cause { // // @XmlAttribute // private String source; // // @XmlAttribute // private String keyword; // // @XmlAttribute // private String pattern; // // @XmlAttribute // private String value; // // public String getSource() { // return source; // } // // public void setSource(String source) { // this.source = source; // } // // public String getKeyword() { // return keyword; // } // // public void setKeyword(String keyword) { // this.keyword = keyword; // } // // public String getPattern() { // return this.pattern; // } // // public void setPattern(String p) { // this.pattern = p; // } // // public String getValue() { // return value; // } // // public void setValue(String value) { // this.value = value; // } // } // // Path: core/src/main/java/com/ccoe/build/core/filter/model/Filter.java // @XmlAccessorType(XmlAccessType.FIELD) // public class Filter { // @XmlAttribute // private String name; // // @XmlAttribute // private String description; // // private String category; // // @XmlElement(name="cause") // private List<Cause> cause = new ArrayList<Cause>(); // // public List<Cause> getCause() { // return this.cause; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description= description; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public void setCauses(List<Cause> lsCause){ // this.cause = lsCause; // } // } // // Path: core/src/main/java/com/ccoe/build/core/utils/StringUtils.java // public class StringUtils { // // public static boolean isEmpty(String str) { // return (str == null) || (str.length() == 0); // } // // public static List<String> getFound(String contents, String regex, // boolean isCaseInsensitive) { // if (isEmpty(regex) || isEmpty(contents)) { // return new ArrayList<String>(); // } // List<String> results = new ArrayList<String>(); // Pattern pattern; // if (isCaseInsensitive) { // pattern = Pattern.compile(regex, Pattern.UNICODE_CASE // | Pattern.CASE_INSENSITIVE); // } else { // pattern = Pattern.compile(regex, Pattern.UNICODE_CASE); // } // Matcher matcher = pattern.matcher(contents); // while (matcher.find()) { // if (matcher.groupCount() > 0) { // for (int i = 1; i <= matcher.groupCount(); i++) { // if (!isEmpty(matcher.group(i))) { // results.add(matcher.group(i)); // } // } // } else { // if (!isEmpty(matcher.group())) { // results.add(matcher.group()); // } // } // } // return results; // } // // public static String getFirstFound(String contents, String regex, // boolean isCaseInsensitive) { // if (isEmpty(contents) || isEmpty(regex)) { // return null; // } // List<String> found = getFound(contents, regex, isCaseInsensitive); // if (found.size() > 0) { // return (String) found.iterator().next(); // } // return ""; // } // // public static Date setTime(Date date, String timeString) { // Calendar cal1 = Calendar.getInstance(); // cal1.setTime(date); // // Calendar cal2 = Calendar.getInstance(); // // String[] time = timeString.split(":"); // // cal2.set(cal1.get(Calendar.YEAR), // cal1.get(Calendar.MONTH), // cal1.get(Calendar.DAY_OF_MONTH), // Integer.parseInt(time[0]), // Integer.parseInt(time[1]), // Integer.parseInt(time[2])); // // return cal2.getTime(); // } // } // Path: core/src/main/java/com/ccoe/build/core/filter/FilterMatcher.java import java.util.HashMap; import java.util.regex.Pattern; import com.ccoe.build.core.filter.model.Cause; import com.ccoe.build.core.filter.model.Filter; import com.ccoe.build.core.utils.StringUtils; String value = source.get(sourceName); //wouldn't cause error when sourceName is null; if(!isMatchCause(value, cause)) { return false; } } else { return false; } } return true; } public boolean isMatch(String fullstack, Filter filter) { for (Cause cause : filter.getCause()) { if (!isMatchCause(fullstack, cause)) { return false; } } return true; } protected boolean isMatchCause(String content, Cause cause) { if (isMatchContent(content, cause) || isMatchKeyword(content, cause) || isMatchPattern(content, cause)) { return true; } return false; } protected boolean isMatchContent(String content, Cause cause) {
if (!StringUtils.isEmpty(cause.getValue()) && content.equals(cause.getValue())) {
eBay/mTracker
core/src/main/java/com/ccoe/build/core/filter/ErrorClassifier.java
// Path: core/src/main/java/com/ccoe/build/core/filter/model/Filter.java // @XmlAccessorType(XmlAccessType.FIELD) // public class Filter { // @XmlAttribute // private String name; // // @XmlAttribute // private String description; // // private String category; // // @XmlElement(name="cause") // private List<Cause> cause = new ArrayList<Cause>(); // // public List<Cause> getCause() { // return this.cause; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description= description; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public void setCauses(List<Cause> lsCause){ // this.cause = lsCause; // } // }
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import com.ccoe.build.core.filter.model.Filter;
/* Copyright [2013-2014] eBay Software Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.ccoe.build.core.filter; public class ErrorClassifier { private UDCFilterFactory factory; public void setFactory(UDCFilterFactory factory) { this.factory = factory; filters.addAll(factory.getFilters()); Logger.getLogger(ErrorClassifier.class.getName()).log(Level.INFO, "Load " + filters.size() + " filter rules"); }
// Path: core/src/main/java/com/ccoe/build/core/filter/model/Filter.java // @XmlAccessorType(XmlAccessType.FIELD) // public class Filter { // @XmlAttribute // private String name; // // @XmlAttribute // private String description; // // private String category; // // @XmlElement(name="cause") // private List<Cause> cause = new ArrayList<Cause>(); // // public List<Cause> getCause() { // return this.cause; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description= description; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public void setCauses(List<Cause> lsCause){ // this.cause = lsCause; // } // } // Path: core/src/main/java/com/ccoe/build/core/filter/ErrorClassifier.java import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import com.ccoe.build.core.filter.model.Filter; /* Copyright [2013-2014] eBay Software Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.ccoe.build.core.filter; public class ErrorClassifier { private UDCFilterFactory factory; public void setFactory(UDCFilterFactory factory) { this.factory = factory; filters.addAll(factory.getFilters()); Logger.getLogger(ErrorClassifier.class.getName()).log(Level.INFO, "Load " + filters.size() + " filter rules"); }
protected List<Filter> filters = new ArrayList<Filter>();
eBay/mTracker
publisher/src/main/java/com/ccoe/build/dal/ProjectJDBCTemplate.java
// Path: core/src/main/java/com/ccoe/build/core/model/Project.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class Project extends TrackingModel { // private String name; // private String groupId; // private String artifactId; // private String type; // private String version; // // private String status; // // private String payload; // // private List<Phase> phases = new ArrayList<Phase>(); // // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // public String getVersion() { // return version; // } // public void setVersion(String version) { // this.version = version; // } // // public String getStatus() { // return status; // } // public void setStatus(String status) { // this.status = status; // } // public List<Phase> getPhases() { // return phases; // } // // public Phase getLastPhase() { // return phases.get(phases.size() - 1); // } // public String getGroupId() { // return groupId; // } // public void setGroupId(String groupId) { // this.groupId = groupId; // } // public String getArtifactId() { // return artifactId; // } // public void setArtifactId(String artifactId) { // this.artifactId = artifactId; // } // public String getType() { // return type; // } // public void setType(String type) { // this.type = type; // } // public String getPayload() { // return payload; // } // public void setPayload(String payload) { // this.payload = payload; // } // // public String toString() { // StringBuffer sBuffer = new StringBuffer(); // // appendTransacionStart(sBuffer, 2, "Project", getName()); // // for (Phase phase : getPhases()) { // appendLine(sBuffer, phase.toString()); // } // // appendTransacionEnd(sBuffer, 2, "Project", getName(), getStatus(), getDuration().toString(), getPayload()); // // return sBuffer.toString(); // } // }
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import javax.sql.DataSource; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.PreparedStatementCreator; import org.springframework.jdbc.support.GeneratedKeyHolder; import org.springframework.jdbc.support.KeyHolder; import com.ccoe.build.core.model.Project;
/* Copyright [2013-2014] eBay Software Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.ccoe.build.dal; public class ProjectJDBCTemplate { private DataSource dataSource; private JdbcTemplate jdbcTemplateObject; public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; this.jdbcTemplateObject = new JdbcTemplate(dataSource); }
// Path: core/src/main/java/com/ccoe/build/core/model/Project.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class Project extends TrackingModel { // private String name; // private String groupId; // private String artifactId; // private String type; // private String version; // // private String status; // // private String payload; // // private List<Phase> phases = new ArrayList<Phase>(); // // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // public String getVersion() { // return version; // } // public void setVersion(String version) { // this.version = version; // } // // public String getStatus() { // return status; // } // public void setStatus(String status) { // this.status = status; // } // public List<Phase> getPhases() { // return phases; // } // // public Phase getLastPhase() { // return phases.get(phases.size() - 1); // } // public String getGroupId() { // return groupId; // } // public void setGroupId(String groupId) { // this.groupId = groupId; // } // public String getArtifactId() { // return artifactId; // } // public void setArtifactId(String artifactId) { // this.artifactId = artifactId; // } // public String getType() { // return type; // } // public void setType(String type) { // this.type = type; // } // public String getPayload() { // return payload; // } // public void setPayload(String payload) { // this.payload = payload; // } // // public String toString() { // StringBuffer sBuffer = new StringBuffer(); // // appendTransacionStart(sBuffer, 2, "Project", getName()); // // for (Phase phase : getPhases()) { // appendLine(sBuffer, phase.toString()); // } // // appendTransacionEnd(sBuffer, 2, "Project", getName(), getStatus(), getDuration().toString(), getPayload()); // // return sBuffer.toString(); // } // } // Path: publisher/src/main/java/com/ccoe/build/dal/ProjectJDBCTemplate.java import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import javax.sql.DataSource; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.PreparedStatementCreator; import org.springframework.jdbc.support.GeneratedKeyHolder; import org.springframework.jdbc.support.KeyHolder; import com.ccoe.build.core.model.Project; /* Copyright [2013-2014] eBay Software Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.ccoe.build.dal; public class ProjectJDBCTemplate { private DataSource dataSource; private JdbcTemplate jdbcTemplateObject; public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; this.jdbcTemplateObject = new JdbcTemplate(dataSource); }
public int create(final Project project, final String appName) {
eBay/mTracker
build-service/src/main/java/com/ccoe/build/alerts/VelocityParse.java
// Path: build-service/src/main/java/com/ccoe/build/service/BuildServiceScheduler.java // public class BuildServiceScheduler implements ServletContextListener { // public static File contextPath; // // public static void setContextPath(String contextPath) { // File outputPath = new File(contextPath); // // if (!outputPath.exists()) { // outputPath.mkdirs(); // } // // BuildServiceScheduler.contextPath = outputPath.getAbsoluteFile(); // } // // @Override // public void contextDestroyed(ServletContextEvent arg0) { // System.out.println("BuildServiceScheduler exit."); // } // // @Override // public void contextInitialized(ServletContextEvent contextEvent) { // String path = contextEvent.getServletContext().getRealPath("generated-source"); // setContextPath(path); // // System.out.println("BuildServiceScheduler init start. output path: " + path); // // if (isSchedulerEnabled()) { // PfDashScheduler pfDashScheduler = new PfDashScheduler(); // DevxScheduler devxScheduler = new DevxScheduler(); // // try { // pfDashScheduler.run(); // devxScheduler.run(); // } catch (Exception e) { // e.printStackTrace(); // } // } // else { // System.out.println("Scheduler is disabled on this server."); // // TrackingScheduler tScheduler = new TrackingScheduler(); // // TODO: // // we enable this on the standby server, // // this is for test purpose, should be moved to the if block // try { // tScheduler.run(); // } catch (Exception e) { // e.printStackTrace(); // } // } // // } // // public boolean isSchedulerEnabled() { // String serverHostName = getHostName(); // if (serverHostName == null) { // return false; // } // try { // String siteService = new BuildServiceConfig().get("com.ccoe.build.reliability.email.scheduler").getSite(); // if (serverHostName.equals(siteService)) { // return true; // } // } catch (Exception e) { // System.out.println("Build Service Scheduler can not access Build Service due to " + e.getMessage()); // } // return false; // } // // public static String getHostName() { // InetAddress netAddress = null; // try { // netAddress = InetAddress.getLocalHost(); // if (null == netAddress) { // return null; // } // String name = netAddress.getCanonicalHostName(); // return name; // } catch (UnknownHostException e) { // e.printStackTrace(); // } // // return null; // } // // }
import com.ccoe.build.service.BuildServiceScheduler; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.List; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.Velocity; import org.apache.velocity.exception.ParseErrorException; import org.apache.velocity.exception.ResourceNotFoundException;
/* Copyright [2013-2014] eBay Software Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.ccoe.build.alerts; public class VelocityParse { public VelocityParse(String templateFile, AlertResult ar, Time time, File directory, String dateString) { try { Velocity.init(VelocityParse.class.getResource( "/velocity.properties").getFile()); VelocityContext context = new VelocityContext(); List<SingleResult> normalResultList = new ArrayList<SingleResult>(); List<SingleResult> colorResultList = new ArrayList<SingleResult>(); for (SingleResult result : ar.getResultlist()) { if (("#CACACA").equals(result.getColor())) { normalResultList.add(result); } else { colorResultList.add(result); } } context.put("normalResultList", normalResultList); context.put("colorResultList", colorResultList); context.put("time", time);
// Path: build-service/src/main/java/com/ccoe/build/service/BuildServiceScheduler.java // public class BuildServiceScheduler implements ServletContextListener { // public static File contextPath; // // public static void setContextPath(String contextPath) { // File outputPath = new File(contextPath); // // if (!outputPath.exists()) { // outputPath.mkdirs(); // } // // BuildServiceScheduler.contextPath = outputPath.getAbsoluteFile(); // } // // @Override // public void contextDestroyed(ServletContextEvent arg0) { // System.out.println("BuildServiceScheduler exit."); // } // // @Override // public void contextInitialized(ServletContextEvent contextEvent) { // String path = contextEvent.getServletContext().getRealPath("generated-source"); // setContextPath(path); // // System.out.println("BuildServiceScheduler init start. output path: " + path); // // if (isSchedulerEnabled()) { // PfDashScheduler pfDashScheduler = new PfDashScheduler(); // DevxScheduler devxScheduler = new DevxScheduler(); // // try { // pfDashScheduler.run(); // devxScheduler.run(); // } catch (Exception e) { // e.printStackTrace(); // } // } // else { // System.out.println("Scheduler is disabled on this server."); // // TrackingScheduler tScheduler = new TrackingScheduler(); // // TODO: // // we enable this on the standby server, // // this is for test purpose, should be moved to the if block // try { // tScheduler.run(); // } catch (Exception e) { // e.printStackTrace(); // } // } // // } // // public boolean isSchedulerEnabled() { // String serverHostName = getHostName(); // if (serverHostName == null) { // return false; // } // try { // String siteService = new BuildServiceConfig().get("com.ccoe.build.reliability.email.scheduler").getSite(); // if (serverHostName.equals(siteService)) { // return true; // } // } catch (Exception e) { // System.out.println("Build Service Scheduler can not access Build Service due to " + e.getMessage()); // } // return false; // } // // public static String getHostName() { // InetAddress netAddress = null; // try { // netAddress = InetAddress.getLocalHost(); // if (null == netAddress) { // return null; // } // String name = netAddress.getCanonicalHostName(); // return name; // } catch (UnknownHostException e) { // e.printStackTrace(); // } // // return null; // } // // } // Path: build-service/src/main/java/com/ccoe/build/alerts/VelocityParse.java import com.ccoe.build.service.BuildServiceScheduler; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.List; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.Velocity; import org.apache.velocity.exception.ParseErrorException; import org.apache.velocity.exception.ResourceNotFoundException; /* Copyright [2013-2014] eBay Software Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.ccoe.build.alerts; public class VelocityParse { public VelocityParse(String templateFile, AlertResult ar, Time time, File directory, String dateString) { try { Velocity.init(VelocityParse.class.getResource( "/velocity.properties").getFile()); VelocityContext context = new VelocityContext(); List<SingleResult> normalResultList = new ArrayList<SingleResult>(); List<SingleResult> colorResultList = new ArrayList<SingleResult>(); for (SingleResult result : ar.getResultlist()) { if (("#CACACA").equals(result.getColor())) { normalResultList.add(result); } else { colorResultList.add(result); } } context.put("normalResultList", normalResultList); context.put("colorResultList", colorResultList); context.put("time", time);
context.put("hostName", BuildServiceScheduler.getHostName());
eBay/mTracker
build-service/src/main/java/com/ccoe/build/service/BuildServiceScheduler.java
// Path: build-service/src/main/java/com/ccoe/build/alerts/devx/DevxScheduler.java // public class DevxScheduler { // // public void run() throws Exception { // Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); // JobDetail devxJob = newJob(DevxReportJob.class).withIdentity("devxJob", "group3").build(); // // Trigger devxTrigger = newTrigger() // .withIdentity("devxTrigger", "group3") // .withSchedule(cronSchedule(ServiceConfig.get("scheduler.devx.time"))).build(); // // scheduler.scheduleJob(devxJob, devxTrigger); // scheduler.start(); // } // // } // // Path: build-service/src/main/java/com/ccoe/build/alerts/pfdash/PfDashScheduler.java // public class PfDashScheduler { // public void run() throws Exception { // Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); // JobDetail pfDashJob = newJob(PfDashJob.class) // .withIdentity("pfDashJob", "group3").build(); // // Trigger pdDashTrigger = newTrigger() // .withIdentity("pdDashTrigger", "group3") // .withSchedule(cronSchedule(ServiceConfig.get("scheduler.pfdash.time"))).build(); // // scheduler.scheduleJob(pfDashJob, pdDashTrigger); // scheduler.start(); // } // } // // Path: core/src/main/java/com/ccoe/build/service/config/BuildServiceConfig.java // public class BuildServiceConfig { // // public BuildServiceConfigBean get(String configName) { // Client client = ClientBuilder.newClient(new ClientConfig()); // client.register(JacksonFeature.class); // // String target = "http://${HOSTNAME}/build-service/webapi/"; // String path = "/config/" + configName; // BuildServiceConfigBean configBean = client.target(target).path(path).request().get(BuildServiceConfigBean.class); // // return configBean; // } // // public static void main(String[] args) { // //System.out.println(new BuildServiceConfig().get("${CONFIG.NAME}").isGlobalSwitch()); // } // } // // Path: build-service/src/main/java/com/ccoe/build/tracking/TrackingScheduler.java // public class TrackingScheduler { // // public void run() throws Exception { // System.out.println("[INFO] Running TrackingScheduler... "); // // Grab the Scheduler instance from the Factory // Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); // // // define the job and tie it to our BatchUpdateReportJob class // JobDetail batchUpdateDurationJob = newJob(BatchUpdateDurationJob.class) // .withIdentity("batchUpdateDurationJob", "group1").build(); // // JobDetail batchUpdateCategoryJob = newJob(BatchUpdateCategoryJob.class) // .withIdentity("batchUpdateCategoryJob", "group1").build(); // // // Trigger the job to run now, and then repeat every 24 hours // Trigger budTrigger = newTrigger() // .withIdentity("batchUpdateDurationTrig", "group1") // .withSchedule(cronSchedule(ServiceConfig.get("scheduler.batchUpdateDuration.time"))).build(); // // Trigger bucTrigger = newTrigger() // .withIdentity("batchUpdateCategoryTrig", "group1") // .withSchedule(cronSchedule(ServiceConfig.get("scheduler.batchUpdateCategory.time"))).build(); // // // Tell quartz to schedule the job using our trigger // scheduler.scheduleJob(batchUpdateDurationJob, budTrigger); // scheduler.scheduleJob(batchUpdateCategoryJob, bucTrigger); // // // and start it off // scheduler.start(); // System.out.println("[INFO] TrackingScheduler started."); // } // // public static void main(String[] args) { // TrackingScheduler scheduler = new TrackingScheduler(); // try { // scheduler.run(); // } catch (Exception e) { // e.printStackTrace(); // } // } // }
import java.io.File; import java.net.InetAddress; import java.net.UnknownHostException; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import com.ccoe.build.alerts.devx.DevxScheduler; import com.ccoe.build.alerts.pfdash.PfDashScheduler; import com.ccoe.build.service.config.BuildServiceConfig; import com.ccoe.build.tracking.TrackingScheduler;
/* Copyright [2013-2014] eBay Software Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.ccoe.build.service; public class BuildServiceScheduler implements ServletContextListener { public static File contextPath; public static void setContextPath(String contextPath) { File outputPath = new File(contextPath); if (!outputPath.exists()) { outputPath.mkdirs(); } BuildServiceScheduler.contextPath = outputPath.getAbsoluteFile(); } @Override public void contextDestroyed(ServletContextEvent arg0) { System.out.println("BuildServiceScheduler exit."); } @Override public void contextInitialized(ServletContextEvent contextEvent) { String path = contextEvent.getServletContext().getRealPath("generated-source"); setContextPath(path); System.out.println("BuildServiceScheduler init start. output path: " + path); if (isSchedulerEnabled()) {
// Path: build-service/src/main/java/com/ccoe/build/alerts/devx/DevxScheduler.java // public class DevxScheduler { // // public void run() throws Exception { // Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); // JobDetail devxJob = newJob(DevxReportJob.class).withIdentity("devxJob", "group3").build(); // // Trigger devxTrigger = newTrigger() // .withIdentity("devxTrigger", "group3") // .withSchedule(cronSchedule(ServiceConfig.get("scheduler.devx.time"))).build(); // // scheduler.scheduleJob(devxJob, devxTrigger); // scheduler.start(); // } // // } // // Path: build-service/src/main/java/com/ccoe/build/alerts/pfdash/PfDashScheduler.java // public class PfDashScheduler { // public void run() throws Exception { // Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); // JobDetail pfDashJob = newJob(PfDashJob.class) // .withIdentity("pfDashJob", "group3").build(); // // Trigger pdDashTrigger = newTrigger() // .withIdentity("pdDashTrigger", "group3") // .withSchedule(cronSchedule(ServiceConfig.get("scheduler.pfdash.time"))).build(); // // scheduler.scheduleJob(pfDashJob, pdDashTrigger); // scheduler.start(); // } // } // // Path: core/src/main/java/com/ccoe/build/service/config/BuildServiceConfig.java // public class BuildServiceConfig { // // public BuildServiceConfigBean get(String configName) { // Client client = ClientBuilder.newClient(new ClientConfig()); // client.register(JacksonFeature.class); // // String target = "http://${HOSTNAME}/build-service/webapi/"; // String path = "/config/" + configName; // BuildServiceConfigBean configBean = client.target(target).path(path).request().get(BuildServiceConfigBean.class); // // return configBean; // } // // public static void main(String[] args) { // //System.out.println(new BuildServiceConfig().get("${CONFIG.NAME}").isGlobalSwitch()); // } // } // // Path: build-service/src/main/java/com/ccoe/build/tracking/TrackingScheduler.java // public class TrackingScheduler { // // public void run() throws Exception { // System.out.println("[INFO] Running TrackingScheduler... "); // // Grab the Scheduler instance from the Factory // Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); // // // define the job and tie it to our BatchUpdateReportJob class // JobDetail batchUpdateDurationJob = newJob(BatchUpdateDurationJob.class) // .withIdentity("batchUpdateDurationJob", "group1").build(); // // JobDetail batchUpdateCategoryJob = newJob(BatchUpdateCategoryJob.class) // .withIdentity("batchUpdateCategoryJob", "group1").build(); // // // Trigger the job to run now, and then repeat every 24 hours // Trigger budTrigger = newTrigger() // .withIdentity("batchUpdateDurationTrig", "group1") // .withSchedule(cronSchedule(ServiceConfig.get("scheduler.batchUpdateDuration.time"))).build(); // // Trigger bucTrigger = newTrigger() // .withIdentity("batchUpdateCategoryTrig", "group1") // .withSchedule(cronSchedule(ServiceConfig.get("scheduler.batchUpdateCategory.time"))).build(); // // // Tell quartz to schedule the job using our trigger // scheduler.scheduleJob(batchUpdateDurationJob, budTrigger); // scheduler.scheduleJob(batchUpdateCategoryJob, bucTrigger); // // // and start it off // scheduler.start(); // System.out.println("[INFO] TrackingScheduler started."); // } // // public static void main(String[] args) { // TrackingScheduler scheduler = new TrackingScheduler(); // try { // scheduler.run(); // } catch (Exception e) { // e.printStackTrace(); // } // } // } // Path: build-service/src/main/java/com/ccoe/build/service/BuildServiceScheduler.java import java.io.File; import java.net.InetAddress; import java.net.UnknownHostException; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import com.ccoe.build.alerts.devx.DevxScheduler; import com.ccoe.build.alerts.pfdash.PfDashScheduler; import com.ccoe.build.service.config.BuildServiceConfig; import com.ccoe.build.tracking.TrackingScheduler; /* Copyright [2013-2014] eBay Software Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.ccoe.build.service; public class BuildServiceScheduler implements ServletContextListener { public static File contextPath; public static void setContextPath(String contextPath) { File outputPath = new File(contextPath); if (!outputPath.exists()) { outputPath.mkdirs(); } BuildServiceScheduler.contextPath = outputPath.getAbsoluteFile(); } @Override public void contextDestroyed(ServletContextEvent arg0) { System.out.println("BuildServiceScheduler exit."); } @Override public void contextInitialized(ServletContextEvent contextEvent) { String path = contextEvent.getServletContext().getRealPath("generated-source"); setContextPath(path); System.out.println("BuildServiceScheduler init start. output path: " + path); if (isSchedulerEnabled()) {
PfDashScheduler pfDashScheduler = new PfDashScheduler();
eBay/mTracker
build-service/src/main/java/com/ccoe/build/service/BuildServiceScheduler.java
// Path: build-service/src/main/java/com/ccoe/build/alerts/devx/DevxScheduler.java // public class DevxScheduler { // // public void run() throws Exception { // Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); // JobDetail devxJob = newJob(DevxReportJob.class).withIdentity("devxJob", "group3").build(); // // Trigger devxTrigger = newTrigger() // .withIdentity("devxTrigger", "group3") // .withSchedule(cronSchedule(ServiceConfig.get("scheduler.devx.time"))).build(); // // scheduler.scheduleJob(devxJob, devxTrigger); // scheduler.start(); // } // // } // // Path: build-service/src/main/java/com/ccoe/build/alerts/pfdash/PfDashScheduler.java // public class PfDashScheduler { // public void run() throws Exception { // Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); // JobDetail pfDashJob = newJob(PfDashJob.class) // .withIdentity("pfDashJob", "group3").build(); // // Trigger pdDashTrigger = newTrigger() // .withIdentity("pdDashTrigger", "group3") // .withSchedule(cronSchedule(ServiceConfig.get("scheduler.pfdash.time"))).build(); // // scheduler.scheduleJob(pfDashJob, pdDashTrigger); // scheduler.start(); // } // } // // Path: core/src/main/java/com/ccoe/build/service/config/BuildServiceConfig.java // public class BuildServiceConfig { // // public BuildServiceConfigBean get(String configName) { // Client client = ClientBuilder.newClient(new ClientConfig()); // client.register(JacksonFeature.class); // // String target = "http://${HOSTNAME}/build-service/webapi/"; // String path = "/config/" + configName; // BuildServiceConfigBean configBean = client.target(target).path(path).request().get(BuildServiceConfigBean.class); // // return configBean; // } // // public static void main(String[] args) { // //System.out.println(new BuildServiceConfig().get("${CONFIG.NAME}").isGlobalSwitch()); // } // } // // Path: build-service/src/main/java/com/ccoe/build/tracking/TrackingScheduler.java // public class TrackingScheduler { // // public void run() throws Exception { // System.out.println("[INFO] Running TrackingScheduler... "); // // Grab the Scheduler instance from the Factory // Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); // // // define the job and tie it to our BatchUpdateReportJob class // JobDetail batchUpdateDurationJob = newJob(BatchUpdateDurationJob.class) // .withIdentity("batchUpdateDurationJob", "group1").build(); // // JobDetail batchUpdateCategoryJob = newJob(BatchUpdateCategoryJob.class) // .withIdentity("batchUpdateCategoryJob", "group1").build(); // // // Trigger the job to run now, and then repeat every 24 hours // Trigger budTrigger = newTrigger() // .withIdentity("batchUpdateDurationTrig", "group1") // .withSchedule(cronSchedule(ServiceConfig.get("scheduler.batchUpdateDuration.time"))).build(); // // Trigger bucTrigger = newTrigger() // .withIdentity("batchUpdateCategoryTrig", "group1") // .withSchedule(cronSchedule(ServiceConfig.get("scheduler.batchUpdateCategory.time"))).build(); // // // Tell quartz to schedule the job using our trigger // scheduler.scheduleJob(batchUpdateDurationJob, budTrigger); // scheduler.scheduleJob(batchUpdateCategoryJob, bucTrigger); // // // and start it off // scheduler.start(); // System.out.println("[INFO] TrackingScheduler started."); // } // // public static void main(String[] args) { // TrackingScheduler scheduler = new TrackingScheduler(); // try { // scheduler.run(); // } catch (Exception e) { // e.printStackTrace(); // } // } // }
import java.io.File; import java.net.InetAddress; import java.net.UnknownHostException; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import com.ccoe.build.alerts.devx.DevxScheduler; import com.ccoe.build.alerts.pfdash.PfDashScheduler; import com.ccoe.build.service.config.BuildServiceConfig; import com.ccoe.build.tracking.TrackingScheduler;
/* Copyright [2013-2014] eBay Software Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.ccoe.build.service; public class BuildServiceScheduler implements ServletContextListener { public static File contextPath; public static void setContextPath(String contextPath) { File outputPath = new File(contextPath); if (!outputPath.exists()) { outputPath.mkdirs(); } BuildServiceScheduler.contextPath = outputPath.getAbsoluteFile(); } @Override public void contextDestroyed(ServletContextEvent arg0) { System.out.println("BuildServiceScheduler exit."); } @Override public void contextInitialized(ServletContextEvent contextEvent) { String path = contextEvent.getServletContext().getRealPath("generated-source"); setContextPath(path); System.out.println("BuildServiceScheduler init start. output path: " + path); if (isSchedulerEnabled()) { PfDashScheduler pfDashScheduler = new PfDashScheduler();
// Path: build-service/src/main/java/com/ccoe/build/alerts/devx/DevxScheduler.java // public class DevxScheduler { // // public void run() throws Exception { // Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); // JobDetail devxJob = newJob(DevxReportJob.class).withIdentity("devxJob", "group3").build(); // // Trigger devxTrigger = newTrigger() // .withIdentity("devxTrigger", "group3") // .withSchedule(cronSchedule(ServiceConfig.get("scheduler.devx.time"))).build(); // // scheduler.scheduleJob(devxJob, devxTrigger); // scheduler.start(); // } // // } // // Path: build-service/src/main/java/com/ccoe/build/alerts/pfdash/PfDashScheduler.java // public class PfDashScheduler { // public void run() throws Exception { // Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); // JobDetail pfDashJob = newJob(PfDashJob.class) // .withIdentity("pfDashJob", "group3").build(); // // Trigger pdDashTrigger = newTrigger() // .withIdentity("pdDashTrigger", "group3") // .withSchedule(cronSchedule(ServiceConfig.get("scheduler.pfdash.time"))).build(); // // scheduler.scheduleJob(pfDashJob, pdDashTrigger); // scheduler.start(); // } // } // // Path: core/src/main/java/com/ccoe/build/service/config/BuildServiceConfig.java // public class BuildServiceConfig { // // public BuildServiceConfigBean get(String configName) { // Client client = ClientBuilder.newClient(new ClientConfig()); // client.register(JacksonFeature.class); // // String target = "http://${HOSTNAME}/build-service/webapi/"; // String path = "/config/" + configName; // BuildServiceConfigBean configBean = client.target(target).path(path).request().get(BuildServiceConfigBean.class); // // return configBean; // } // // public static void main(String[] args) { // //System.out.println(new BuildServiceConfig().get("${CONFIG.NAME}").isGlobalSwitch()); // } // } // // Path: build-service/src/main/java/com/ccoe/build/tracking/TrackingScheduler.java // public class TrackingScheduler { // // public void run() throws Exception { // System.out.println("[INFO] Running TrackingScheduler... "); // // Grab the Scheduler instance from the Factory // Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); // // // define the job and tie it to our BatchUpdateReportJob class // JobDetail batchUpdateDurationJob = newJob(BatchUpdateDurationJob.class) // .withIdentity("batchUpdateDurationJob", "group1").build(); // // JobDetail batchUpdateCategoryJob = newJob(BatchUpdateCategoryJob.class) // .withIdentity("batchUpdateCategoryJob", "group1").build(); // // // Trigger the job to run now, and then repeat every 24 hours // Trigger budTrigger = newTrigger() // .withIdentity("batchUpdateDurationTrig", "group1") // .withSchedule(cronSchedule(ServiceConfig.get("scheduler.batchUpdateDuration.time"))).build(); // // Trigger bucTrigger = newTrigger() // .withIdentity("batchUpdateCategoryTrig", "group1") // .withSchedule(cronSchedule(ServiceConfig.get("scheduler.batchUpdateCategory.time"))).build(); // // // Tell quartz to schedule the job using our trigger // scheduler.scheduleJob(batchUpdateDurationJob, budTrigger); // scheduler.scheduleJob(batchUpdateCategoryJob, bucTrigger); // // // and start it off // scheduler.start(); // System.out.println("[INFO] TrackingScheduler started."); // } // // public static void main(String[] args) { // TrackingScheduler scheduler = new TrackingScheduler(); // try { // scheduler.run(); // } catch (Exception e) { // e.printStackTrace(); // } // } // } // Path: build-service/src/main/java/com/ccoe/build/service/BuildServiceScheduler.java import java.io.File; import java.net.InetAddress; import java.net.UnknownHostException; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import com.ccoe.build.alerts.devx.DevxScheduler; import com.ccoe.build.alerts.pfdash.PfDashScheduler; import com.ccoe.build.service.config.BuildServiceConfig; import com.ccoe.build.tracking.TrackingScheduler; /* Copyright [2013-2014] eBay Software Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.ccoe.build.service; public class BuildServiceScheduler implements ServletContextListener { public static File contextPath; public static void setContextPath(String contextPath) { File outputPath = new File(contextPath); if (!outputPath.exists()) { outputPath.mkdirs(); } BuildServiceScheduler.contextPath = outputPath.getAbsoluteFile(); } @Override public void contextDestroyed(ServletContextEvent arg0) { System.out.println("BuildServiceScheduler exit."); } @Override public void contextInitialized(ServletContextEvent contextEvent) { String path = contextEvent.getServletContext().getRealPath("generated-source"); setContextPath(path); System.out.println("BuildServiceScheduler init start. output path: " + path); if (isSchedulerEnabled()) { PfDashScheduler pfDashScheduler = new PfDashScheduler();
DevxScheduler devxScheduler = new DevxScheduler();
eBay/mTracker
build-service/src/main/java/com/ccoe/build/service/BuildServiceScheduler.java
// Path: build-service/src/main/java/com/ccoe/build/alerts/devx/DevxScheduler.java // public class DevxScheduler { // // public void run() throws Exception { // Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); // JobDetail devxJob = newJob(DevxReportJob.class).withIdentity("devxJob", "group3").build(); // // Trigger devxTrigger = newTrigger() // .withIdentity("devxTrigger", "group3") // .withSchedule(cronSchedule(ServiceConfig.get("scheduler.devx.time"))).build(); // // scheduler.scheduleJob(devxJob, devxTrigger); // scheduler.start(); // } // // } // // Path: build-service/src/main/java/com/ccoe/build/alerts/pfdash/PfDashScheduler.java // public class PfDashScheduler { // public void run() throws Exception { // Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); // JobDetail pfDashJob = newJob(PfDashJob.class) // .withIdentity("pfDashJob", "group3").build(); // // Trigger pdDashTrigger = newTrigger() // .withIdentity("pdDashTrigger", "group3") // .withSchedule(cronSchedule(ServiceConfig.get("scheduler.pfdash.time"))).build(); // // scheduler.scheduleJob(pfDashJob, pdDashTrigger); // scheduler.start(); // } // } // // Path: core/src/main/java/com/ccoe/build/service/config/BuildServiceConfig.java // public class BuildServiceConfig { // // public BuildServiceConfigBean get(String configName) { // Client client = ClientBuilder.newClient(new ClientConfig()); // client.register(JacksonFeature.class); // // String target = "http://${HOSTNAME}/build-service/webapi/"; // String path = "/config/" + configName; // BuildServiceConfigBean configBean = client.target(target).path(path).request().get(BuildServiceConfigBean.class); // // return configBean; // } // // public static void main(String[] args) { // //System.out.println(new BuildServiceConfig().get("${CONFIG.NAME}").isGlobalSwitch()); // } // } // // Path: build-service/src/main/java/com/ccoe/build/tracking/TrackingScheduler.java // public class TrackingScheduler { // // public void run() throws Exception { // System.out.println("[INFO] Running TrackingScheduler... "); // // Grab the Scheduler instance from the Factory // Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); // // // define the job and tie it to our BatchUpdateReportJob class // JobDetail batchUpdateDurationJob = newJob(BatchUpdateDurationJob.class) // .withIdentity("batchUpdateDurationJob", "group1").build(); // // JobDetail batchUpdateCategoryJob = newJob(BatchUpdateCategoryJob.class) // .withIdentity("batchUpdateCategoryJob", "group1").build(); // // // Trigger the job to run now, and then repeat every 24 hours // Trigger budTrigger = newTrigger() // .withIdentity("batchUpdateDurationTrig", "group1") // .withSchedule(cronSchedule(ServiceConfig.get("scheduler.batchUpdateDuration.time"))).build(); // // Trigger bucTrigger = newTrigger() // .withIdentity("batchUpdateCategoryTrig", "group1") // .withSchedule(cronSchedule(ServiceConfig.get("scheduler.batchUpdateCategory.time"))).build(); // // // Tell quartz to schedule the job using our trigger // scheduler.scheduleJob(batchUpdateDurationJob, budTrigger); // scheduler.scheduleJob(batchUpdateCategoryJob, bucTrigger); // // // and start it off // scheduler.start(); // System.out.println("[INFO] TrackingScheduler started."); // } // // public static void main(String[] args) { // TrackingScheduler scheduler = new TrackingScheduler(); // try { // scheduler.run(); // } catch (Exception e) { // e.printStackTrace(); // } // } // }
import java.io.File; import java.net.InetAddress; import java.net.UnknownHostException; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import com.ccoe.build.alerts.devx.DevxScheduler; import com.ccoe.build.alerts.pfdash.PfDashScheduler; import com.ccoe.build.service.config.BuildServiceConfig; import com.ccoe.build.tracking.TrackingScheduler;
BuildServiceScheduler.contextPath = outputPath.getAbsoluteFile(); } @Override public void contextDestroyed(ServletContextEvent arg0) { System.out.println("BuildServiceScheduler exit."); } @Override public void contextInitialized(ServletContextEvent contextEvent) { String path = contextEvent.getServletContext().getRealPath("generated-source"); setContextPath(path); System.out.println("BuildServiceScheduler init start. output path: " + path); if (isSchedulerEnabled()) { PfDashScheduler pfDashScheduler = new PfDashScheduler(); DevxScheduler devxScheduler = new DevxScheduler(); try { pfDashScheduler.run(); devxScheduler.run(); } catch (Exception e) { e.printStackTrace(); } } else { System.out.println("Scheduler is disabled on this server.");
// Path: build-service/src/main/java/com/ccoe/build/alerts/devx/DevxScheduler.java // public class DevxScheduler { // // public void run() throws Exception { // Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); // JobDetail devxJob = newJob(DevxReportJob.class).withIdentity("devxJob", "group3").build(); // // Trigger devxTrigger = newTrigger() // .withIdentity("devxTrigger", "group3") // .withSchedule(cronSchedule(ServiceConfig.get("scheduler.devx.time"))).build(); // // scheduler.scheduleJob(devxJob, devxTrigger); // scheduler.start(); // } // // } // // Path: build-service/src/main/java/com/ccoe/build/alerts/pfdash/PfDashScheduler.java // public class PfDashScheduler { // public void run() throws Exception { // Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); // JobDetail pfDashJob = newJob(PfDashJob.class) // .withIdentity("pfDashJob", "group3").build(); // // Trigger pdDashTrigger = newTrigger() // .withIdentity("pdDashTrigger", "group3") // .withSchedule(cronSchedule(ServiceConfig.get("scheduler.pfdash.time"))).build(); // // scheduler.scheduleJob(pfDashJob, pdDashTrigger); // scheduler.start(); // } // } // // Path: core/src/main/java/com/ccoe/build/service/config/BuildServiceConfig.java // public class BuildServiceConfig { // // public BuildServiceConfigBean get(String configName) { // Client client = ClientBuilder.newClient(new ClientConfig()); // client.register(JacksonFeature.class); // // String target = "http://${HOSTNAME}/build-service/webapi/"; // String path = "/config/" + configName; // BuildServiceConfigBean configBean = client.target(target).path(path).request().get(BuildServiceConfigBean.class); // // return configBean; // } // // public static void main(String[] args) { // //System.out.println(new BuildServiceConfig().get("${CONFIG.NAME}").isGlobalSwitch()); // } // } // // Path: build-service/src/main/java/com/ccoe/build/tracking/TrackingScheduler.java // public class TrackingScheduler { // // public void run() throws Exception { // System.out.println("[INFO] Running TrackingScheduler... "); // // Grab the Scheduler instance from the Factory // Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); // // // define the job and tie it to our BatchUpdateReportJob class // JobDetail batchUpdateDurationJob = newJob(BatchUpdateDurationJob.class) // .withIdentity("batchUpdateDurationJob", "group1").build(); // // JobDetail batchUpdateCategoryJob = newJob(BatchUpdateCategoryJob.class) // .withIdentity("batchUpdateCategoryJob", "group1").build(); // // // Trigger the job to run now, and then repeat every 24 hours // Trigger budTrigger = newTrigger() // .withIdentity("batchUpdateDurationTrig", "group1") // .withSchedule(cronSchedule(ServiceConfig.get("scheduler.batchUpdateDuration.time"))).build(); // // Trigger bucTrigger = newTrigger() // .withIdentity("batchUpdateCategoryTrig", "group1") // .withSchedule(cronSchedule(ServiceConfig.get("scheduler.batchUpdateCategory.time"))).build(); // // // Tell quartz to schedule the job using our trigger // scheduler.scheduleJob(batchUpdateDurationJob, budTrigger); // scheduler.scheduleJob(batchUpdateCategoryJob, bucTrigger); // // // and start it off // scheduler.start(); // System.out.println("[INFO] TrackingScheduler started."); // } // // public static void main(String[] args) { // TrackingScheduler scheduler = new TrackingScheduler(); // try { // scheduler.run(); // } catch (Exception e) { // e.printStackTrace(); // } // } // } // Path: build-service/src/main/java/com/ccoe/build/service/BuildServiceScheduler.java import java.io.File; import java.net.InetAddress; import java.net.UnknownHostException; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import com.ccoe.build.alerts.devx.DevxScheduler; import com.ccoe.build.alerts.pfdash.PfDashScheduler; import com.ccoe.build.service.config.BuildServiceConfig; import com.ccoe.build.tracking.TrackingScheduler; BuildServiceScheduler.contextPath = outputPath.getAbsoluteFile(); } @Override public void contextDestroyed(ServletContextEvent arg0) { System.out.println("BuildServiceScheduler exit."); } @Override public void contextInitialized(ServletContextEvent contextEvent) { String path = contextEvent.getServletContext().getRealPath("generated-source"); setContextPath(path); System.out.println("BuildServiceScheduler init start. output path: " + path); if (isSchedulerEnabled()) { PfDashScheduler pfDashScheduler = new PfDashScheduler(); DevxScheduler devxScheduler = new DevxScheduler(); try { pfDashScheduler.run(); devxScheduler.run(); } catch (Exception e) { e.printStackTrace(); } } else { System.out.println("Scheduler is disabled on this server.");
TrackingScheduler tScheduler = new TrackingScheduler();
eBay/mTracker
build-service/src/main/java/com/ccoe/build/service/BuildServiceScheduler.java
// Path: build-service/src/main/java/com/ccoe/build/alerts/devx/DevxScheduler.java // public class DevxScheduler { // // public void run() throws Exception { // Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); // JobDetail devxJob = newJob(DevxReportJob.class).withIdentity("devxJob", "group3").build(); // // Trigger devxTrigger = newTrigger() // .withIdentity("devxTrigger", "group3") // .withSchedule(cronSchedule(ServiceConfig.get("scheduler.devx.time"))).build(); // // scheduler.scheduleJob(devxJob, devxTrigger); // scheduler.start(); // } // // } // // Path: build-service/src/main/java/com/ccoe/build/alerts/pfdash/PfDashScheduler.java // public class PfDashScheduler { // public void run() throws Exception { // Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); // JobDetail pfDashJob = newJob(PfDashJob.class) // .withIdentity("pfDashJob", "group3").build(); // // Trigger pdDashTrigger = newTrigger() // .withIdentity("pdDashTrigger", "group3") // .withSchedule(cronSchedule(ServiceConfig.get("scheduler.pfdash.time"))).build(); // // scheduler.scheduleJob(pfDashJob, pdDashTrigger); // scheduler.start(); // } // } // // Path: core/src/main/java/com/ccoe/build/service/config/BuildServiceConfig.java // public class BuildServiceConfig { // // public BuildServiceConfigBean get(String configName) { // Client client = ClientBuilder.newClient(new ClientConfig()); // client.register(JacksonFeature.class); // // String target = "http://${HOSTNAME}/build-service/webapi/"; // String path = "/config/" + configName; // BuildServiceConfigBean configBean = client.target(target).path(path).request().get(BuildServiceConfigBean.class); // // return configBean; // } // // public static void main(String[] args) { // //System.out.println(new BuildServiceConfig().get("${CONFIG.NAME}").isGlobalSwitch()); // } // } // // Path: build-service/src/main/java/com/ccoe/build/tracking/TrackingScheduler.java // public class TrackingScheduler { // // public void run() throws Exception { // System.out.println("[INFO] Running TrackingScheduler... "); // // Grab the Scheduler instance from the Factory // Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); // // // define the job and tie it to our BatchUpdateReportJob class // JobDetail batchUpdateDurationJob = newJob(BatchUpdateDurationJob.class) // .withIdentity("batchUpdateDurationJob", "group1").build(); // // JobDetail batchUpdateCategoryJob = newJob(BatchUpdateCategoryJob.class) // .withIdentity("batchUpdateCategoryJob", "group1").build(); // // // Trigger the job to run now, and then repeat every 24 hours // Trigger budTrigger = newTrigger() // .withIdentity("batchUpdateDurationTrig", "group1") // .withSchedule(cronSchedule(ServiceConfig.get("scheduler.batchUpdateDuration.time"))).build(); // // Trigger bucTrigger = newTrigger() // .withIdentity("batchUpdateCategoryTrig", "group1") // .withSchedule(cronSchedule(ServiceConfig.get("scheduler.batchUpdateCategory.time"))).build(); // // // Tell quartz to schedule the job using our trigger // scheduler.scheduleJob(batchUpdateDurationJob, budTrigger); // scheduler.scheduleJob(batchUpdateCategoryJob, bucTrigger); // // // and start it off // scheduler.start(); // System.out.println("[INFO] TrackingScheduler started."); // } // // public static void main(String[] args) { // TrackingScheduler scheduler = new TrackingScheduler(); // try { // scheduler.run(); // } catch (Exception e) { // e.printStackTrace(); // } // } // }
import java.io.File; import java.net.InetAddress; import java.net.UnknownHostException; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import com.ccoe.build.alerts.devx.DevxScheduler; import com.ccoe.build.alerts.pfdash.PfDashScheduler; import com.ccoe.build.service.config.BuildServiceConfig; import com.ccoe.build.tracking.TrackingScheduler;
try { pfDashScheduler.run(); devxScheduler.run(); } catch (Exception e) { e.printStackTrace(); } } else { System.out.println("Scheduler is disabled on this server."); TrackingScheduler tScheduler = new TrackingScheduler(); // TODO: // we enable this on the standby server, // this is for test purpose, should be moved to the if block try { tScheduler.run(); } catch (Exception e) { e.printStackTrace(); } } } public boolean isSchedulerEnabled() { String serverHostName = getHostName(); if (serverHostName == null) { return false; } try {
// Path: build-service/src/main/java/com/ccoe/build/alerts/devx/DevxScheduler.java // public class DevxScheduler { // // public void run() throws Exception { // Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); // JobDetail devxJob = newJob(DevxReportJob.class).withIdentity("devxJob", "group3").build(); // // Trigger devxTrigger = newTrigger() // .withIdentity("devxTrigger", "group3") // .withSchedule(cronSchedule(ServiceConfig.get("scheduler.devx.time"))).build(); // // scheduler.scheduleJob(devxJob, devxTrigger); // scheduler.start(); // } // // } // // Path: build-service/src/main/java/com/ccoe/build/alerts/pfdash/PfDashScheduler.java // public class PfDashScheduler { // public void run() throws Exception { // Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); // JobDetail pfDashJob = newJob(PfDashJob.class) // .withIdentity("pfDashJob", "group3").build(); // // Trigger pdDashTrigger = newTrigger() // .withIdentity("pdDashTrigger", "group3") // .withSchedule(cronSchedule(ServiceConfig.get("scheduler.pfdash.time"))).build(); // // scheduler.scheduleJob(pfDashJob, pdDashTrigger); // scheduler.start(); // } // } // // Path: core/src/main/java/com/ccoe/build/service/config/BuildServiceConfig.java // public class BuildServiceConfig { // // public BuildServiceConfigBean get(String configName) { // Client client = ClientBuilder.newClient(new ClientConfig()); // client.register(JacksonFeature.class); // // String target = "http://${HOSTNAME}/build-service/webapi/"; // String path = "/config/" + configName; // BuildServiceConfigBean configBean = client.target(target).path(path).request().get(BuildServiceConfigBean.class); // // return configBean; // } // // public static void main(String[] args) { // //System.out.println(new BuildServiceConfig().get("${CONFIG.NAME}").isGlobalSwitch()); // } // } // // Path: build-service/src/main/java/com/ccoe/build/tracking/TrackingScheduler.java // public class TrackingScheduler { // // public void run() throws Exception { // System.out.println("[INFO] Running TrackingScheduler... "); // // Grab the Scheduler instance from the Factory // Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); // // // define the job and tie it to our BatchUpdateReportJob class // JobDetail batchUpdateDurationJob = newJob(BatchUpdateDurationJob.class) // .withIdentity("batchUpdateDurationJob", "group1").build(); // // JobDetail batchUpdateCategoryJob = newJob(BatchUpdateCategoryJob.class) // .withIdentity("batchUpdateCategoryJob", "group1").build(); // // // Trigger the job to run now, and then repeat every 24 hours // Trigger budTrigger = newTrigger() // .withIdentity("batchUpdateDurationTrig", "group1") // .withSchedule(cronSchedule(ServiceConfig.get("scheduler.batchUpdateDuration.time"))).build(); // // Trigger bucTrigger = newTrigger() // .withIdentity("batchUpdateCategoryTrig", "group1") // .withSchedule(cronSchedule(ServiceConfig.get("scheduler.batchUpdateCategory.time"))).build(); // // // Tell quartz to schedule the job using our trigger // scheduler.scheduleJob(batchUpdateDurationJob, budTrigger); // scheduler.scheduleJob(batchUpdateCategoryJob, bucTrigger); // // // and start it off // scheduler.start(); // System.out.println("[INFO] TrackingScheduler started."); // } // // public static void main(String[] args) { // TrackingScheduler scheduler = new TrackingScheduler(); // try { // scheduler.run(); // } catch (Exception e) { // e.printStackTrace(); // } // } // } // Path: build-service/src/main/java/com/ccoe/build/service/BuildServiceScheduler.java import java.io.File; import java.net.InetAddress; import java.net.UnknownHostException; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import com.ccoe.build.alerts.devx.DevxScheduler; import com.ccoe.build.alerts.pfdash.PfDashScheduler; import com.ccoe.build.service.config.BuildServiceConfig; import com.ccoe.build.tracking.TrackingScheduler; try { pfDashScheduler.run(); devxScheduler.run(); } catch (Exception e) { e.printStackTrace(); } } else { System.out.println("Scheduler is disabled on this server."); TrackingScheduler tScheduler = new TrackingScheduler(); // TODO: // we enable this on the standby server, // this is for test purpose, should be moved to the if block try { tScheduler.run(); } catch (Exception e) { e.printStackTrace(); } } } public boolean isSchedulerEnabled() { String serverHostName = getHostName(); if (serverHostName == null) { return false; } try {
String siteService = new BuildServiceConfig().get("com.ccoe.build.reliability.email.scheduler").getSite();
eBay/mTracker
build-service/src/main/java/com/ccoe/build/tracking/TrackingScheduler.java
// Path: build-service/src/main/java/com/ccoe/build/utils/ServiceConfig.java // public class ServiceConfig { // private static java.util.Properties prop = new java.util.Properties(); // // private static void loadProperties() { // // get class loader // ClassLoader loader = ServiceConfig.class.getClassLoader(); // if (loader == null) { // loader = ClassLoader.getSystemClassLoader(); // } // // load application.properties located in WEB-INF/classes/ // String propFile = "application.properties"; // java.net.URL url = loader.getResource(propFile); // try { // prop.load(url.openStream()); // } catch (Exception e) { // System.err // .println("Could not load configuration file: " + propFile); // } // } // // public static String get(String key) { // return prop.getProperty(key); // } // // public static int getInt(String key) { // return getInt(key, "3600"); // } // // public static int getInt(String key, String defaultValue) { // return Integer.parseInt(prop.getProperty(key, defaultValue)); // } // // // load the properties when class is accessed // static { // loadProperties(); // } // }
import static org.quartz.CronScheduleBuilder.cronSchedule; import static org.quartz.JobBuilder.newJob; import static org.quartz.TriggerBuilder.newTrigger; import org.quartz.JobDetail; import org.quartz.Scheduler; import org.quartz.Trigger; import org.quartz.impl.StdSchedulerFactory; import com.ccoe.build.utils.ServiceConfig;
/* Copyright [2013-2014] eBay Software Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.ccoe.build.tracking; public class TrackingScheduler { public void run() throws Exception { System.out.println("[INFO] Running TrackingScheduler... "); // Grab the Scheduler instance from the Factory Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); // define the job and tie it to our BatchUpdateReportJob class JobDetail batchUpdateDurationJob = newJob(BatchUpdateDurationJob.class) .withIdentity("batchUpdateDurationJob", "group1").build(); JobDetail batchUpdateCategoryJob = newJob(BatchUpdateCategoryJob.class) .withIdentity("batchUpdateCategoryJob", "group1").build(); // Trigger the job to run now, and then repeat every 24 hours Trigger budTrigger = newTrigger() .withIdentity("batchUpdateDurationTrig", "group1")
// Path: build-service/src/main/java/com/ccoe/build/utils/ServiceConfig.java // public class ServiceConfig { // private static java.util.Properties prop = new java.util.Properties(); // // private static void loadProperties() { // // get class loader // ClassLoader loader = ServiceConfig.class.getClassLoader(); // if (loader == null) { // loader = ClassLoader.getSystemClassLoader(); // } // // load application.properties located in WEB-INF/classes/ // String propFile = "application.properties"; // java.net.URL url = loader.getResource(propFile); // try { // prop.load(url.openStream()); // } catch (Exception e) { // System.err // .println("Could not load configuration file: " + propFile); // } // } // // public static String get(String key) { // return prop.getProperty(key); // } // // public static int getInt(String key) { // return getInt(key, "3600"); // } // // public static int getInt(String key, String defaultValue) { // return Integer.parseInt(prop.getProperty(key, defaultValue)); // } // // // load the properties when class is accessed // static { // loadProperties(); // } // } // Path: build-service/src/main/java/com/ccoe/build/tracking/TrackingScheduler.java import static org.quartz.CronScheduleBuilder.cronSchedule; import static org.quartz.JobBuilder.newJob; import static org.quartz.TriggerBuilder.newTrigger; import org.quartz.JobDetail; import org.quartz.Scheduler; import org.quartz.Trigger; import org.quartz.impl.StdSchedulerFactory; import com.ccoe.build.utils.ServiceConfig; /* Copyright [2013-2014] eBay Software Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.ccoe.build.tracking; public class TrackingScheduler { public void run() throws Exception { System.out.println("[INFO] Running TrackingScheduler... "); // Grab the Scheduler instance from the Factory Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); // define the job and tie it to our BatchUpdateReportJob class JobDetail batchUpdateDurationJob = newJob(BatchUpdateDurationJob.class) .withIdentity("batchUpdateDurationJob", "group1").build(); JobDetail batchUpdateCategoryJob = newJob(BatchUpdateCategoryJob.class) .withIdentity("batchUpdateCategoryJob", "group1").build(); // Trigger the job to run now, and then repeat every 24 hours Trigger budTrigger = newTrigger() .withIdentity("batchUpdateDurationTrig", "group1")
.withSchedule(cronSchedule(ServiceConfig.get("scheduler.batchUpdateDuration.time"))).build();
eBay/mTracker
build-service/src/main/java/com/ccoe/build/alerts/devx/DevxScheduler.java
// Path: build-service/src/main/java/com/ccoe/build/utils/ServiceConfig.java // public class ServiceConfig { // private static java.util.Properties prop = new java.util.Properties(); // // private static void loadProperties() { // // get class loader // ClassLoader loader = ServiceConfig.class.getClassLoader(); // if (loader == null) { // loader = ClassLoader.getSystemClassLoader(); // } // // load application.properties located in WEB-INF/classes/ // String propFile = "application.properties"; // java.net.URL url = loader.getResource(propFile); // try { // prop.load(url.openStream()); // } catch (Exception e) { // System.err // .println("Could not load configuration file: " + propFile); // } // } // // public static String get(String key) { // return prop.getProperty(key); // } // // public static int getInt(String key) { // return getInt(key, "3600"); // } // // public static int getInt(String key, String defaultValue) { // return Integer.parseInt(prop.getProperty(key, defaultValue)); // } // // // load the properties when class is accessed // static { // loadProperties(); // } // }
import static org.quartz.CronScheduleBuilder.cronSchedule; import static org.quartz.JobBuilder.newJob; import static org.quartz.TriggerBuilder.newTrigger; import org.quartz.JobDetail; import org.quartz.Scheduler; import org.quartz.Trigger; import org.quartz.impl.StdSchedulerFactory; import com.ccoe.build.utils.ServiceConfig;
/* Copyright [2013-2014] eBay Software Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.ccoe.build.alerts.devx; public class DevxScheduler { public void run() throws Exception { Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); JobDetail devxJob = newJob(DevxReportJob.class).withIdentity("devxJob", "group3").build(); Trigger devxTrigger = newTrigger() .withIdentity("devxTrigger", "group3")
// Path: build-service/src/main/java/com/ccoe/build/utils/ServiceConfig.java // public class ServiceConfig { // private static java.util.Properties prop = new java.util.Properties(); // // private static void loadProperties() { // // get class loader // ClassLoader loader = ServiceConfig.class.getClassLoader(); // if (loader == null) { // loader = ClassLoader.getSystemClassLoader(); // } // // load application.properties located in WEB-INF/classes/ // String propFile = "application.properties"; // java.net.URL url = loader.getResource(propFile); // try { // prop.load(url.openStream()); // } catch (Exception e) { // System.err // .println("Could not load configuration file: " + propFile); // } // } // // public static String get(String key) { // return prop.getProperty(key); // } // // public static int getInt(String key) { // return getInt(key, "3600"); // } // // public static int getInt(String key, String defaultValue) { // return Integer.parseInt(prop.getProperty(key, defaultValue)); // } // // // load the properties when class is accessed // static { // loadProperties(); // } // } // Path: build-service/src/main/java/com/ccoe/build/alerts/devx/DevxScheduler.java import static org.quartz.CronScheduleBuilder.cronSchedule; import static org.quartz.JobBuilder.newJob; import static org.quartz.TriggerBuilder.newTrigger; import org.quartz.JobDetail; import org.quartz.Scheduler; import org.quartz.Trigger; import org.quartz.impl.StdSchedulerFactory; import com.ccoe.build.utils.ServiceConfig; /* Copyright [2013-2014] eBay Software Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.ccoe.build.alerts.devx; public class DevxScheduler { public void run() throws Exception { Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); JobDetail devxJob = newJob(DevxReportJob.class).withIdentity("devxJob", "group3").build(); Trigger devxTrigger = newTrigger() .withIdentity("devxTrigger", "group3")
.withSchedule(cronSchedule(ServiceConfig.get("scheduler.devx.time"))).build();
eBay/mTracker
core/src/main/java/com/ccoe/build/core/filter/FilterFactory.java
// Path: core/src/main/java/com/ccoe/build/core/filter/model/Category.java // @XmlAccessorType(XmlAccessType.FIELD) // public class Category { // @XmlAttribute // private String name; // // @XmlElement(name="filter") // private List<Filter> filters = new ArrayList<Filter>(); // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public List<Filter> getFilter() { // return this.filters; // } // } // // Path: core/src/main/java/com/ccoe/build/core/filter/model/Filter.java // @XmlAccessorType(XmlAccessType.FIELD) // public class Filter { // @XmlAttribute // private String name; // // @XmlAttribute // private String description; // // private String category; // // @XmlElement(name="cause") // private List<Cause> cause = new ArrayList<Cause>(); // // public List<Cause> getCause() { // return this.cause; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description= description; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public void setCauses(List<Cause> lsCause){ // this.cause = lsCause; // } // } // // Path: core/src/main/java/com/ccoe/build/core/filter/model/Filters.java // @XmlRootElement(name = "filters") // public class Filters { // @XmlElement(name="category") // List<Category> categories = new ArrayList<Category>(); // // public List<Category> getCategory() { // return this.categories; // } // }
import com.ccoe.build.core.filter.model.Category; import com.ccoe.build.core.filter.model.Filter; import com.ccoe.build.core.filter.model.Filters; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.List; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller;
/* Copyright [2013-2014] eBay Software Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.ccoe.build.core.filter; public abstract class FilterFactory { public final static String BASE_FILTER_LIST_IN_GIT = "https://github.com/eBay/mTracker/raw/master/core/src/main/resources"; public abstract URL getRemoteFilterURL(); public abstract URL getLocalFilterURL();
// Path: core/src/main/java/com/ccoe/build/core/filter/model/Category.java // @XmlAccessorType(XmlAccessType.FIELD) // public class Category { // @XmlAttribute // private String name; // // @XmlElement(name="filter") // private List<Filter> filters = new ArrayList<Filter>(); // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public List<Filter> getFilter() { // return this.filters; // } // } // // Path: core/src/main/java/com/ccoe/build/core/filter/model/Filter.java // @XmlAccessorType(XmlAccessType.FIELD) // public class Filter { // @XmlAttribute // private String name; // // @XmlAttribute // private String description; // // private String category; // // @XmlElement(name="cause") // private List<Cause> cause = new ArrayList<Cause>(); // // public List<Cause> getCause() { // return this.cause; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description= description; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public void setCauses(List<Cause> lsCause){ // this.cause = lsCause; // } // } // // Path: core/src/main/java/com/ccoe/build/core/filter/model/Filters.java // @XmlRootElement(name = "filters") // public class Filters { // @XmlElement(name="category") // List<Category> categories = new ArrayList<Category>(); // // public List<Category> getCategory() { // return this.categories; // } // } // Path: core/src/main/java/com/ccoe/build/core/filter/FilterFactory.java import com.ccoe.build.core.filter.model.Category; import com.ccoe.build.core.filter.model.Filter; import com.ccoe.build.core.filter.model.Filters; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.List; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; /* Copyright [2013-2014] eBay Software Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.ccoe.build.core.filter; public abstract class FilterFactory { public final static String BASE_FILTER_LIST_IN_GIT = "https://github.com/eBay/mTracker/raw/master/core/src/main/resources"; public abstract URL getRemoteFilterURL(); public abstract URL getLocalFilterURL();
protected void marshal(File reportFile, Filters filters){
eBay/mTracker
core/src/main/java/com/ccoe/build/core/filter/FilterFactory.java
// Path: core/src/main/java/com/ccoe/build/core/filter/model/Category.java // @XmlAccessorType(XmlAccessType.FIELD) // public class Category { // @XmlAttribute // private String name; // // @XmlElement(name="filter") // private List<Filter> filters = new ArrayList<Filter>(); // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public List<Filter> getFilter() { // return this.filters; // } // } // // Path: core/src/main/java/com/ccoe/build/core/filter/model/Filter.java // @XmlAccessorType(XmlAccessType.FIELD) // public class Filter { // @XmlAttribute // private String name; // // @XmlAttribute // private String description; // // private String category; // // @XmlElement(name="cause") // private List<Cause> cause = new ArrayList<Cause>(); // // public List<Cause> getCause() { // return this.cause; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description= description; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public void setCauses(List<Cause> lsCause){ // this.cause = lsCause; // } // } // // Path: core/src/main/java/com/ccoe/build/core/filter/model/Filters.java // @XmlRootElement(name = "filters") // public class Filters { // @XmlElement(name="category") // List<Category> categories = new ArrayList<Category>(); // // public List<Category> getCategory() { // return this.categories; // } // }
import com.ccoe.build.core.filter.model.Category; import com.ccoe.build.core.filter.model.Filter; import com.ccoe.build.core.filter.model.Filters; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.List; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller;
} protected Filters unmarshal(File reportFile) { JAXBContext jc; try { jc = JAXBContext.newInstance(Filters.class); Unmarshaller u = jc.createUnmarshaller(); return (Filters) u.unmarshal(new FileInputStream(reportFile)); } catch (JAXBException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } return new Filters(); } protected Filters unmarshal(InputStream is) throws JAXBException { JAXBContext jc; jc = JAXBContext.newInstance(Filters.class); Unmarshaller u = jc.createUnmarshaller(); return (Filters) u.unmarshal(is); } protected Filters unmarshal(URL aURL) throws JAXBException { JAXBContext jc; jc = JAXBContext.newInstance(Filters.class); Unmarshaller u = jc.createUnmarshaller(); return (Filters) u.unmarshal(aURL); }
// Path: core/src/main/java/com/ccoe/build/core/filter/model/Category.java // @XmlAccessorType(XmlAccessType.FIELD) // public class Category { // @XmlAttribute // private String name; // // @XmlElement(name="filter") // private List<Filter> filters = new ArrayList<Filter>(); // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public List<Filter> getFilter() { // return this.filters; // } // } // // Path: core/src/main/java/com/ccoe/build/core/filter/model/Filter.java // @XmlAccessorType(XmlAccessType.FIELD) // public class Filter { // @XmlAttribute // private String name; // // @XmlAttribute // private String description; // // private String category; // // @XmlElement(name="cause") // private List<Cause> cause = new ArrayList<Cause>(); // // public List<Cause> getCause() { // return this.cause; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description= description; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public void setCauses(List<Cause> lsCause){ // this.cause = lsCause; // } // } // // Path: core/src/main/java/com/ccoe/build/core/filter/model/Filters.java // @XmlRootElement(name = "filters") // public class Filters { // @XmlElement(name="category") // List<Category> categories = new ArrayList<Category>(); // // public List<Category> getCategory() { // return this.categories; // } // } // Path: core/src/main/java/com/ccoe/build/core/filter/FilterFactory.java import com.ccoe.build.core.filter.model.Category; import com.ccoe.build.core.filter.model.Filter; import com.ccoe.build.core.filter.model.Filters; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.List; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; } protected Filters unmarshal(File reportFile) { JAXBContext jc; try { jc = JAXBContext.newInstance(Filters.class); Unmarshaller u = jc.createUnmarshaller(); return (Filters) u.unmarshal(new FileInputStream(reportFile)); } catch (JAXBException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } return new Filters(); } protected Filters unmarshal(InputStream is) throws JAXBException { JAXBContext jc; jc = JAXBContext.newInstance(Filters.class); Unmarshaller u = jc.createUnmarshaller(); return (Filters) u.unmarshal(is); } protected Filters unmarshal(URL aURL) throws JAXBException { JAXBContext jc; jc = JAXBContext.newInstance(Filters.class); Unmarshaller u = jc.createUnmarshaller(); return (Filters) u.unmarshal(aURL); }
protected List<Filter> build(URL url, URL defaultFilterList) {
eBay/mTracker
core/src/main/java/com/ccoe/build/core/filter/FilterFactory.java
// Path: core/src/main/java/com/ccoe/build/core/filter/model/Category.java // @XmlAccessorType(XmlAccessType.FIELD) // public class Category { // @XmlAttribute // private String name; // // @XmlElement(name="filter") // private List<Filter> filters = new ArrayList<Filter>(); // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public List<Filter> getFilter() { // return this.filters; // } // } // // Path: core/src/main/java/com/ccoe/build/core/filter/model/Filter.java // @XmlAccessorType(XmlAccessType.FIELD) // public class Filter { // @XmlAttribute // private String name; // // @XmlAttribute // private String description; // // private String category; // // @XmlElement(name="cause") // private List<Cause> cause = new ArrayList<Cause>(); // // public List<Cause> getCause() { // return this.cause; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description= description; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public void setCauses(List<Cause> lsCause){ // this.cause = lsCause; // } // } // // Path: core/src/main/java/com/ccoe/build/core/filter/model/Filters.java // @XmlRootElement(name = "filters") // public class Filters { // @XmlElement(name="category") // List<Category> categories = new ArrayList<Category>(); // // public List<Category> getCategory() { // return this.categories; // } // }
import com.ccoe.build.core.filter.model.Category; import com.ccoe.build.core.filter.model.Filter; import com.ccoe.build.core.filter.model.Filters; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.List; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller;
protected Filters unmarshal(InputStream is) throws JAXBException { JAXBContext jc; jc = JAXBContext.newInstance(Filters.class); Unmarshaller u = jc.createUnmarshaller(); return (Filters) u.unmarshal(is); } protected Filters unmarshal(URL aURL) throws JAXBException { JAXBContext jc; jc = JAXBContext.newInstance(Filters.class); Unmarshaller u = jc.createUnmarshaller(); return (Filters) u.unmarshal(aURL); } protected List<Filter> build(URL url, URL defaultFilterList) { Filters filters = new Filters(); try { filters = unmarshal(url); } catch (Exception e) { System.err.println("Can not unmarshall the remote file " + url + " Caused by " + e.getMessage()); try { filters = unmarshal(defaultFilterList); } catch (JAXBException e1) { System.err.println("Can not unmarshall the local file " + defaultFilterList + " Caused by " + e.getMessage()); } } List<Filter> results = new ArrayList<Filter>();
// Path: core/src/main/java/com/ccoe/build/core/filter/model/Category.java // @XmlAccessorType(XmlAccessType.FIELD) // public class Category { // @XmlAttribute // private String name; // // @XmlElement(name="filter") // private List<Filter> filters = new ArrayList<Filter>(); // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public List<Filter> getFilter() { // return this.filters; // } // } // // Path: core/src/main/java/com/ccoe/build/core/filter/model/Filter.java // @XmlAccessorType(XmlAccessType.FIELD) // public class Filter { // @XmlAttribute // private String name; // // @XmlAttribute // private String description; // // private String category; // // @XmlElement(name="cause") // private List<Cause> cause = new ArrayList<Cause>(); // // public List<Cause> getCause() { // return this.cause; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description= description; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public void setCauses(List<Cause> lsCause){ // this.cause = lsCause; // } // } // // Path: core/src/main/java/com/ccoe/build/core/filter/model/Filters.java // @XmlRootElement(name = "filters") // public class Filters { // @XmlElement(name="category") // List<Category> categories = new ArrayList<Category>(); // // public List<Category> getCategory() { // return this.categories; // } // } // Path: core/src/main/java/com/ccoe/build/core/filter/FilterFactory.java import com.ccoe.build.core.filter.model.Category; import com.ccoe.build.core.filter.model.Filter; import com.ccoe.build.core.filter.model.Filters; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.List; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; protected Filters unmarshal(InputStream is) throws JAXBException { JAXBContext jc; jc = JAXBContext.newInstance(Filters.class); Unmarshaller u = jc.createUnmarshaller(); return (Filters) u.unmarshal(is); } protected Filters unmarshal(URL aURL) throws JAXBException { JAXBContext jc; jc = JAXBContext.newInstance(Filters.class); Unmarshaller u = jc.createUnmarshaller(); return (Filters) u.unmarshal(aURL); } protected List<Filter> build(URL url, URL defaultFilterList) { Filters filters = new Filters(); try { filters = unmarshal(url); } catch (Exception e) { System.err.println("Can not unmarshall the remote file " + url + " Caused by " + e.getMessage()); try { filters = unmarshal(defaultFilterList); } catch (JAXBException e1) { System.err.println("Can not unmarshall the local file " + defaultFilterList + " Caused by " + e.getMessage()); } } List<Filter> results = new ArrayList<Filter>();
for (Category category : filters.getCategory()) {
eBay/mTracker
core/src/test/java/com/ccoe/build/core/filter/FilterMatcherTest.java
// Path: core/src/main/java/com/ccoe/build/core/filter/FilterMatcher.java // public class FilterMatcher { // // public boolean isMatch(HashMap<String, String> source, Filter filter) { // for (Cause cause : filter.getCause()) { // String sourceName = cause.getSource(); // //whether sourceName is null or not, there should be a key with value sourceName in source // //or the record can't match, that means returning false; // if(source.containsKey(sourceName)) { // String value = source.get(sourceName); //wouldn't cause error when sourceName is null; // if(!isMatchCause(value, cause)) { // return false; // } // } else { // return false; // } // } // return true; // } // // public boolean isMatch(String fullstack, Filter filter) { // for (Cause cause : filter.getCause()) { // if (!isMatchCause(fullstack, cause)) { // return false; // } // } // return true; // } // // protected boolean isMatchCause(String content, Cause cause) { // if (isMatchContent(content, cause) // || isMatchKeyword(content, cause) // || isMatchPattern(content, cause)) { // return true; // } // return false; // } // // protected boolean isMatchContent(String content, Cause cause) { // if (!StringUtils.isEmpty(cause.getValue()) && content.equals(cause.getValue())) { // return true; // } // return false; // } // // protected boolean isMatchKeyword(String content, Cause cause) { // if (!StringUtils.isEmpty(cause.getKeyword()) && content.contains(cause.getKeyword())) { // return true; // } // return false; // } // // protected boolean isMatchPattern(String content, Cause cause) { // if (!StringUtils.isEmpty(cause.getPattern())) { // if (Pattern.compile(cause.getPattern(), Pattern.DOTALL).matcher(content).matches()) { // //if (StringUtils.isEmpty(StringUtils.getFirstFound(fullstack, cause.getPattern(), true))) { // return true; // } // } // return false; // } // } // // Path: core/src/main/java/com/ccoe/build/core/filter/model/Cause.java // @XmlAccessorType(XmlAccessType.FIELD) // public class Cause { // // @XmlAttribute // private String source; // // @XmlAttribute // private String keyword; // // @XmlAttribute // private String pattern; // // @XmlAttribute // private String value; // // public String getSource() { // return source; // } // // public void setSource(String source) { // this.source = source; // } // // public String getKeyword() { // return keyword; // } // // public void setKeyword(String keyword) { // this.keyword = keyword; // } // // public String getPattern() { // return this.pattern; // } // // public void setPattern(String p) { // this.pattern = p; // } // // public String getValue() { // return value; // } // // public void setValue(String value) { // this.value = value; // } // } // // Path: core/src/main/java/com/ccoe/build/core/filter/model/Filter.java // @XmlAccessorType(XmlAccessType.FIELD) // public class Filter { // @XmlAttribute // private String name; // // @XmlAttribute // private String description; // // private String category; // // @XmlElement(name="cause") // private List<Cause> cause = new ArrayList<Cause>(); // // public List<Cause> getCause() { // return this.cause; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description= description; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public void setCauses(List<Cause> lsCause){ // this.cause = lsCause; // } // }
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import junit.framework.Assert; import org.junit.BeforeClass; import org.junit.Test; import com.ccoe.build.core.filter.FilterMatcher; import com.ccoe.build.core.filter.model.Cause; import com.ccoe.build.core.filter.model.Filter;
/* Copyright [2013-2014] eBay Software Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.ccoe.build.core.filter; public class FilterMatcherTest { static FilterMatcher matcher; @BeforeClass public static void setUpBeforeClass() throws Exception { matcher = new FilterMatcher(); } @Test public void testIsMatchHashMapOfStringStringFilter() {
// Path: core/src/main/java/com/ccoe/build/core/filter/FilterMatcher.java // public class FilterMatcher { // // public boolean isMatch(HashMap<String, String> source, Filter filter) { // for (Cause cause : filter.getCause()) { // String sourceName = cause.getSource(); // //whether sourceName is null or not, there should be a key with value sourceName in source // //or the record can't match, that means returning false; // if(source.containsKey(sourceName)) { // String value = source.get(sourceName); //wouldn't cause error when sourceName is null; // if(!isMatchCause(value, cause)) { // return false; // } // } else { // return false; // } // } // return true; // } // // public boolean isMatch(String fullstack, Filter filter) { // for (Cause cause : filter.getCause()) { // if (!isMatchCause(fullstack, cause)) { // return false; // } // } // return true; // } // // protected boolean isMatchCause(String content, Cause cause) { // if (isMatchContent(content, cause) // || isMatchKeyword(content, cause) // || isMatchPattern(content, cause)) { // return true; // } // return false; // } // // protected boolean isMatchContent(String content, Cause cause) { // if (!StringUtils.isEmpty(cause.getValue()) && content.equals(cause.getValue())) { // return true; // } // return false; // } // // protected boolean isMatchKeyword(String content, Cause cause) { // if (!StringUtils.isEmpty(cause.getKeyword()) && content.contains(cause.getKeyword())) { // return true; // } // return false; // } // // protected boolean isMatchPattern(String content, Cause cause) { // if (!StringUtils.isEmpty(cause.getPattern())) { // if (Pattern.compile(cause.getPattern(), Pattern.DOTALL).matcher(content).matches()) { // //if (StringUtils.isEmpty(StringUtils.getFirstFound(fullstack, cause.getPattern(), true))) { // return true; // } // } // return false; // } // } // // Path: core/src/main/java/com/ccoe/build/core/filter/model/Cause.java // @XmlAccessorType(XmlAccessType.FIELD) // public class Cause { // // @XmlAttribute // private String source; // // @XmlAttribute // private String keyword; // // @XmlAttribute // private String pattern; // // @XmlAttribute // private String value; // // public String getSource() { // return source; // } // // public void setSource(String source) { // this.source = source; // } // // public String getKeyword() { // return keyword; // } // // public void setKeyword(String keyword) { // this.keyword = keyword; // } // // public String getPattern() { // return this.pattern; // } // // public void setPattern(String p) { // this.pattern = p; // } // // public String getValue() { // return value; // } // // public void setValue(String value) { // this.value = value; // } // } // // Path: core/src/main/java/com/ccoe/build/core/filter/model/Filter.java // @XmlAccessorType(XmlAccessType.FIELD) // public class Filter { // @XmlAttribute // private String name; // // @XmlAttribute // private String description; // // private String category; // // @XmlElement(name="cause") // private List<Cause> cause = new ArrayList<Cause>(); // // public List<Cause> getCause() { // return this.cause; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description= description; // } // // public String getCategory() { // return category; // } // // public void setCategory(String category) { // this.category = category; // } // // public void setCauses(List<Cause> lsCause){ // this.cause = lsCause; // } // } // Path: core/src/test/java/com/ccoe/build/core/filter/FilterMatcherTest.java import java.util.ArrayList; import java.util.HashMap; import java.util.List; import junit.framework.Assert; import org.junit.BeforeClass; import org.junit.Test; import com.ccoe.build.core.filter.FilterMatcher; import com.ccoe.build.core.filter.model.Cause; import com.ccoe.build.core.filter.model.Filter; /* Copyright [2013-2014] eBay Software Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.ccoe.build.core.filter; public class FilterMatcherTest { static FilterMatcher matcher; @BeforeClass public static void setUpBeforeClass() throws Exception { matcher = new FilterMatcher(); } @Test public void testIsMatchHashMapOfStringStringFilter() {
List<Cause> lsCause = new ArrayList<Cause>();
eBay/mTracker
profiler/src/main/java/com/ccoe/build/profiler/profile/SessionProfile.java
// Path: profiler/src/main/java/com/ccoe/build/profiler/util/Timer.java // public class Timer { // // public static final int MS_PER_SEC = 1000; // public static final int SEC_PER_MIN = 60; // // private long start; // private long elaspsedTime; // // public Timer() { // start = System.currentTimeMillis(); // } // // public void stop() { // elaspsedTime = elapsedTime(); // } // // public long getTime() { // return elaspsedTime; // } // // public long getStartTime() { // return this.start; // } // // private long elapsedTime() { // return System.currentTimeMillis() - start; // } // // public static String formatTime(long ms) { // long secs = ms / MS_PER_SEC; // long mins = secs / SEC_PER_MIN; // secs = secs % SEC_PER_MIN; // long fractionOfASecond = ms - (secs * 1000); // // String msg = mins + "m " + secs + "." + fractionOfASecond; // // if (msg.length() == 3) { // msg += "00s"; // } else if (msg.length() == 4) { // msg += "0s"; // } else { // msg += "s"; // } // // msg = ms + " ms ( " + msg + " )"; // // return msg; // } // }
import java.util.ArrayList; import java.util.List; import org.apache.maven.eventspy.EventSpy.Context; import org.apache.maven.execution.ExecutionEvent; import com.ccoe.build.profiler.util.Timer;
/* Copyright [2013-2014] eBay Software Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.ccoe.build.profiler.profile; public class SessionProfile extends Profile { private List<ProjectProfile> projectProfiles; private boolean settingChanged = true; public boolean settingChanged() { return settingChanged; } public SessionProfile(Context c, ExecutionEvent event, boolean debug) {
// Path: profiler/src/main/java/com/ccoe/build/profiler/util/Timer.java // public class Timer { // // public static final int MS_PER_SEC = 1000; // public static final int SEC_PER_MIN = 60; // // private long start; // private long elaspsedTime; // // public Timer() { // start = System.currentTimeMillis(); // } // // public void stop() { // elaspsedTime = elapsedTime(); // } // // public long getTime() { // return elaspsedTime; // } // // public long getStartTime() { // return this.start; // } // // private long elapsedTime() { // return System.currentTimeMillis() - start; // } // // public static String formatTime(long ms) { // long secs = ms / MS_PER_SEC; // long mins = secs / SEC_PER_MIN; // secs = secs % SEC_PER_MIN; // long fractionOfASecond = ms - (secs * 1000); // // String msg = mins + "m " + secs + "." + fractionOfASecond; // // if (msg.length() == 3) { // msg += "00s"; // } else if (msg.length() == 4) { // msg += "0s"; // } else { // msg += "s"; // } // // msg = ms + " ms ( " + msg + " )"; // // return msg; // } // } // Path: profiler/src/main/java/com/ccoe/build/profiler/profile/SessionProfile.java import java.util.ArrayList; import java.util.List; import org.apache.maven.eventspy.EventSpy.Context; import org.apache.maven.execution.ExecutionEvent; import com.ccoe.build.profiler.util.Timer; /* Copyright [2013-2014] eBay Software Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.ccoe.build.profiler.profile; public class SessionProfile extends Profile { private List<ProjectProfile> projectProfiles; private boolean settingChanged = true; public boolean settingChanged() { return settingChanged; } public SessionProfile(Context c, ExecutionEvent event, boolean debug) {
super(new Timer(), event, c);
eBay/mTracker
profiler/src/main/java/com/ccoe/build/profiler/profile/MojoProfile.java
// Path: core/src/main/java/com/ccoe/build/core/model/Plugin.java // public class Plugin extends TrackingModel { // private String groupId; // private String artifactId; // private String version; // // private String status; // private String executionId; // // private String phaseName; // private String pluginKey; // // private int id; // // private String payload; // // public String getGroupId() { // return groupId; // } // // public void setGroupId(String groupId) { // this.groupId = groupId; // } // // public String getArtifactId() { // return artifactId; // } // // public void setArtifactId(String artifactId) { // this.artifactId = artifactId; // } // // public String getVersion() { // return version; // } // // public void setVersion(String version) { // this.version = version; // } // // public String getStatus() { // return status; // } // // public void setStatus(String status) { // this.status = status; // } // // public String getExecutionId() { // return executionId; // } // // public void setExecutionId(String executionId) { // this.executionId = executionId; // } // // public String getPhaseName() { // return phaseName; // } // // public void setPhaseName(String phaseName) { // this.phaseName = phaseName; // } // // public String getPluginKey() { // return pluginKey; // } // // public void setPluginKey(String pluginKey) { // this.pluginKey = pluginKey; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getPayload() { // return payload; // } // // public void setPayload(String payload) { // this.payload = payload; // } // // public String toString() { // StringBuffer sBuffer = new StringBuffer(); // appendTransactionAtom(sBuffer, 4, "Plugin", getPluginKey(), this.getStatus(), getDuration().toString(), getPayload()); // return sBuffer.toString(); // } // } // // Path: profiler/src/main/java/com/ccoe/build/profiler/util/Timer.java // public class Timer { // // public static final int MS_PER_SEC = 1000; // public static final int SEC_PER_MIN = 60; // // private long start; // private long elaspsedTime; // // public Timer() { // start = System.currentTimeMillis(); // } // // public void stop() { // elaspsedTime = elapsedTime(); // } // // public long getTime() { // return elaspsedTime; // } // // public long getStartTime() { // return this.start; // } // // private long elapsedTime() { // return System.currentTimeMillis() - start; // } // // public static String formatTime(long ms) { // long secs = ms / MS_PER_SEC; // long mins = secs / SEC_PER_MIN; // secs = secs % SEC_PER_MIN; // long fractionOfASecond = ms - (secs * 1000); // // String msg = mins + "m " + secs + "." + fractionOfASecond; // // if (msg.length() == 3) { // msg += "00s"; // } else if (msg.length() == 4) { // msg += "0s"; // } else { // msg += "s"; // } // // msg = ms + " ms ( " + msg + " )"; // // return msg; // } // }
import java.util.Date; import org.apache.maven.eventspy.EventSpy.Context; import org.apache.maven.execution.ExecutionEvent; import org.apache.maven.plugin.MojoExecution; import com.ccoe.build.core.model.Plugin; import com.ccoe.build.profiler.util.Timer;
/* Copyright [2013-2014] eBay Software Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.ccoe.build.profiler.profile; /** * * This Class holds the Mojo profiling information * * @author kmuralidharan * */ public class MojoProfile extends Profile { private MojoExecution mojoExecution; private String status; private String executionMsg; private String pluginGroupID; private String pluginArtifactID; private String pluginVersion; private String pluginExecutionId;
// Path: core/src/main/java/com/ccoe/build/core/model/Plugin.java // public class Plugin extends TrackingModel { // private String groupId; // private String artifactId; // private String version; // // private String status; // private String executionId; // // private String phaseName; // private String pluginKey; // // private int id; // // private String payload; // // public String getGroupId() { // return groupId; // } // // public void setGroupId(String groupId) { // this.groupId = groupId; // } // // public String getArtifactId() { // return artifactId; // } // // public void setArtifactId(String artifactId) { // this.artifactId = artifactId; // } // // public String getVersion() { // return version; // } // // public void setVersion(String version) { // this.version = version; // } // // public String getStatus() { // return status; // } // // public void setStatus(String status) { // this.status = status; // } // // public String getExecutionId() { // return executionId; // } // // public void setExecutionId(String executionId) { // this.executionId = executionId; // } // // public String getPhaseName() { // return phaseName; // } // // public void setPhaseName(String phaseName) { // this.phaseName = phaseName; // } // // public String getPluginKey() { // return pluginKey; // } // // public void setPluginKey(String pluginKey) { // this.pluginKey = pluginKey; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getPayload() { // return payload; // } // // public void setPayload(String payload) { // this.payload = payload; // } // // public String toString() { // StringBuffer sBuffer = new StringBuffer(); // appendTransactionAtom(sBuffer, 4, "Plugin", getPluginKey(), this.getStatus(), getDuration().toString(), getPayload()); // return sBuffer.toString(); // } // } // // Path: profiler/src/main/java/com/ccoe/build/profiler/util/Timer.java // public class Timer { // // public static final int MS_PER_SEC = 1000; // public static final int SEC_PER_MIN = 60; // // private long start; // private long elaspsedTime; // // public Timer() { // start = System.currentTimeMillis(); // } // // public void stop() { // elaspsedTime = elapsedTime(); // } // // public long getTime() { // return elaspsedTime; // } // // public long getStartTime() { // return this.start; // } // // private long elapsedTime() { // return System.currentTimeMillis() - start; // } // // public static String formatTime(long ms) { // long secs = ms / MS_PER_SEC; // long mins = secs / SEC_PER_MIN; // secs = secs % SEC_PER_MIN; // long fractionOfASecond = ms - (secs * 1000); // // String msg = mins + "m " + secs + "." + fractionOfASecond; // // if (msg.length() == 3) { // msg += "00s"; // } else if (msg.length() == 4) { // msg += "0s"; // } else { // msg += "s"; // } // // msg = ms + " ms ( " + msg + " )"; // // return msg; // } // } // Path: profiler/src/main/java/com/ccoe/build/profiler/profile/MojoProfile.java import java.util.Date; import org.apache.maven.eventspy.EventSpy.Context; import org.apache.maven.execution.ExecutionEvent; import org.apache.maven.plugin.MojoExecution; import com.ccoe.build.core.model.Plugin; import com.ccoe.build.profiler.util.Timer; /* Copyright [2013-2014] eBay Software Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.ccoe.build.profiler.profile; /** * * This Class holds the Mojo profiling information * * @author kmuralidharan * */ public class MojoProfile extends Profile { private MojoExecution mojoExecution; private String status; private String executionMsg; private String pluginGroupID; private String pluginArtifactID; private String pluginVersion; private String pluginExecutionId;
private Plugin plugin = new Plugin();
eBay/mTracker
profiler/src/main/java/com/ccoe/build/profiler/profile/MojoProfile.java
// Path: core/src/main/java/com/ccoe/build/core/model/Plugin.java // public class Plugin extends TrackingModel { // private String groupId; // private String artifactId; // private String version; // // private String status; // private String executionId; // // private String phaseName; // private String pluginKey; // // private int id; // // private String payload; // // public String getGroupId() { // return groupId; // } // // public void setGroupId(String groupId) { // this.groupId = groupId; // } // // public String getArtifactId() { // return artifactId; // } // // public void setArtifactId(String artifactId) { // this.artifactId = artifactId; // } // // public String getVersion() { // return version; // } // // public void setVersion(String version) { // this.version = version; // } // // public String getStatus() { // return status; // } // // public void setStatus(String status) { // this.status = status; // } // // public String getExecutionId() { // return executionId; // } // // public void setExecutionId(String executionId) { // this.executionId = executionId; // } // // public String getPhaseName() { // return phaseName; // } // // public void setPhaseName(String phaseName) { // this.phaseName = phaseName; // } // // public String getPluginKey() { // return pluginKey; // } // // public void setPluginKey(String pluginKey) { // this.pluginKey = pluginKey; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getPayload() { // return payload; // } // // public void setPayload(String payload) { // this.payload = payload; // } // // public String toString() { // StringBuffer sBuffer = new StringBuffer(); // appendTransactionAtom(sBuffer, 4, "Plugin", getPluginKey(), this.getStatus(), getDuration().toString(), getPayload()); // return sBuffer.toString(); // } // } // // Path: profiler/src/main/java/com/ccoe/build/profiler/util/Timer.java // public class Timer { // // public static final int MS_PER_SEC = 1000; // public static final int SEC_PER_MIN = 60; // // private long start; // private long elaspsedTime; // // public Timer() { // start = System.currentTimeMillis(); // } // // public void stop() { // elaspsedTime = elapsedTime(); // } // // public long getTime() { // return elaspsedTime; // } // // public long getStartTime() { // return this.start; // } // // private long elapsedTime() { // return System.currentTimeMillis() - start; // } // // public static String formatTime(long ms) { // long secs = ms / MS_PER_SEC; // long mins = secs / SEC_PER_MIN; // secs = secs % SEC_PER_MIN; // long fractionOfASecond = ms - (secs * 1000); // // String msg = mins + "m " + secs + "." + fractionOfASecond; // // if (msg.length() == 3) { // msg += "00s"; // } else if (msg.length() == 4) { // msg += "0s"; // } else { // msg += "s"; // } // // msg = ms + " ms ( " + msg + " )"; // // return msg; // } // }
import java.util.Date; import org.apache.maven.eventspy.EventSpy.Context; import org.apache.maven.execution.ExecutionEvent; import org.apache.maven.plugin.MojoExecution; import com.ccoe.build.core.model.Plugin; import com.ccoe.build.profiler.util.Timer;
/* Copyright [2013-2014] eBay Software Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.ccoe.build.profiler.profile; /** * * This Class holds the Mojo profiling information * * @author kmuralidharan * */ public class MojoProfile extends Profile { private MojoExecution mojoExecution; private String status; private String executionMsg; private String pluginGroupID; private String pluginArtifactID; private String pluginVersion; private String pluginExecutionId; private Plugin plugin = new Plugin(); public MojoProfile(Context c, MojoExecution mojoExecution, ExecutionEvent event) {
// Path: core/src/main/java/com/ccoe/build/core/model/Plugin.java // public class Plugin extends TrackingModel { // private String groupId; // private String artifactId; // private String version; // // private String status; // private String executionId; // // private String phaseName; // private String pluginKey; // // private int id; // // private String payload; // // public String getGroupId() { // return groupId; // } // // public void setGroupId(String groupId) { // this.groupId = groupId; // } // // public String getArtifactId() { // return artifactId; // } // // public void setArtifactId(String artifactId) { // this.artifactId = artifactId; // } // // public String getVersion() { // return version; // } // // public void setVersion(String version) { // this.version = version; // } // // public String getStatus() { // return status; // } // // public void setStatus(String status) { // this.status = status; // } // // public String getExecutionId() { // return executionId; // } // // public void setExecutionId(String executionId) { // this.executionId = executionId; // } // // public String getPhaseName() { // return phaseName; // } // // public void setPhaseName(String phaseName) { // this.phaseName = phaseName; // } // // public String getPluginKey() { // return pluginKey; // } // // public void setPluginKey(String pluginKey) { // this.pluginKey = pluginKey; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getPayload() { // return payload; // } // // public void setPayload(String payload) { // this.payload = payload; // } // // public String toString() { // StringBuffer sBuffer = new StringBuffer(); // appendTransactionAtom(sBuffer, 4, "Plugin", getPluginKey(), this.getStatus(), getDuration().toString(), getPayload()); // return sBuffer.toString(); // } // } // // Path: profiler/src/main/java/com/ccoe/build/profiler/util/Timer.java // public class Timer { // // public static final int MS_PER_SEC = 1000; // public static final int SEC_PER_MIN = 60; // // private long start; // private long elaspsedTime; // // public Timer() { // start = System.currentTimeMillis(); // } // // public void stop() { // elaspsedTime = elapsedTime(); // } // // public long getTime() { // return elaspsedTime; // } // // public long getStartTime() { // return this.start; // } // // private long elapsedTime() { // return System.currentTimeMillis() - start; // } // // public static String formatTime(long ms) { // long secs = ms / MS_PER_SEC; // long mins = secs / SEC_PER_MIN; // secs = secs % SEC_PER_MIN; // long fractionOfASecond = ms - (secs * 1000); // // String msg = mins + "m " + secs + "." + fractionOfASecond; // // if (msg.length() == 3) { // msg += "00s"; // } else if (msg.length() == 4) { // msg += "0s"; // } else { // msg += "s"; // } // // msg = ms + " ms ( " + msg + " )"; // // return msg; // } // } // Path: profiler/src/main/java/com/ccoe/build/profiler/profile/MojoProfile.java import java.util.Date; import org.apache.maven.eventspy.EventSpy.Context; import org.apache.maven.execution.ExecutionEvent; import org.apache.maven.plugin.MojoExecution; import com.ccoe.build.core.model.Plugin; import com.ccoe.build.profiler.util.Timer; /* Copyright [2013-2014] eBay Software Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.ccoe.build.profiler.profile; /** * * This Class holds the Mojo profiling information * * @author kmuralidharan * */ public class MojoProfile extends Profile { private MojoExecution mojoExecution; private String status; private String executionMsg; private String pluginGroupID; private String pluginArtifactID; private String pluginVersion; private String pluginExecutionId; private Plugin plugin = new Plugin(); public MojoProfile(Context c, MojoExecution mojoExecution, ExecutionEvent event) {
super(new Timer(), event, c);
eBay/mTracker
build-service/src/main/java/com/ccoe/build/service/track/QueueService.java
// Path: build-service/src/main/java/com/ccoe/build/utils/ServiceConfig.java // public class ServiceConfig { // private static java.util.Properties prop = new java.util.Properties(); // // private static void loadProperties() { // // get class loader // ClassLoader loader = ServiceConfig.class.getClassLoader(); // if (loader == null) { // loader = ClassLoader.getSystemClassLoader(); // } // // load application.properties located in WEB-INF/classes/ // String propFile = "application.properties"; // java.net.URL url = loader.getResource(propFile); // try { // prop.load(url.openStream()); // } catch (Exception e) { // System.err // .println("Could not load configuration file: " + propFile); // } // } // // public static String get(String key) { // return prop.getProperty(key); // } // // public static int getInt(String key) { // return getInt(key, "3600"); // } // // public static int getInt(String key, String defaultValue) { // return Integer.parseInt(prop.getProperty(key, defaultValue)); // } // // // load the properties when class is accessed // static { // loadProperties(); // } // }
import java.io.File; import java.io.IOException; import java.net.UnknownHostException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.ws.rs.Consumes; import javax.ws.rs.HeaderParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.apache.commons.io.FileUtils; import org.glassfish.jersey.media.multipart.BodyPart; import org.glassfish.jersey.media.multipart.FormDataBodyPart; import org.glassfish.jersey.media.multipart.FormDataMultiPart; import com.ccoe.build.utils.ServiceConfig;
/* Copyright [2013-2014] eBay Software Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.ccoe.build.service.track; @Path("") public class QueueService { private final SimpleDateFormat actionDatePattern = new SimpleDateFormat("MM-dd-yyyy_HH-mm-ss-SSS");
// Path: build-service/src/main/java/com/ccoe/build/utils/ServiceConfig.java // public class ServiceConfig { // private static java.util.Properties prop = new java.util.Properties(); // // private static void loadProperties() { // // get class loader // ClassLoader loader = ServiceConfig.class.getClassLoader(); // if (loader == null) { // loader = ClassLoader.getSystemClassLoader(); // } // // load application.properties located in WEB-INF/classes/ // String propFile = "application.properties"; // java.net.URL url = loader.getResource(propFile); // try { // prop.load(url.openStream()); // } catch (Exception e) { // System.err // .println("Could not load configuration file: " + propFile); // } // } // // public static String get(String key) { // return prop.getProperty(key); // } // // public static int getInt(String key) { // return getInt(key, "3600"); // } // // public static int getInt(String key, String defaultValue) { // return Integer.parseInt(prop.getProperty(key, defaultValue)); // } // // // load the properties when class is accessed // static { // loadProperties(); // } // } // Path: build-service/src/main/java/com/ccoe/build/service/track/QueueService.java import java.io.File; import java.io.IOException; import java.net.UnknownHostException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.ws.rs.Consumes; import javax.ws.rs.HeaderParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.apache.commons.io.FileUtils; import org.glassfish.jersey.media.multipart.BodyPart; import org.glassfish.jersey.media.multipart.FormDataBodyPart; import org.glassfish.jersey.media.multipart.FormDataMultiPart; import com.ccoe.build.utils.ServiceConfig; /* Copyright [2013-2014] eBay Software Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.ccoe.build.service.track; @Path("") public class QueueService { private final SimpleDateFormat actionDatePattern = new SimpleDateFormat("MM-dd-yyyy_HH-mm-ss-SSS");
private final File queueRoot = new File(ServiceConfig.get("queue_root_dir"));
eBay/mTracker
build-service/src/main/java/com/ccoe/build/alerts/pfdash/PfDashScheduler.java
// Path: build-service/src/main/java/com/ccoe/build/utils/ServiceConfig.java // public class ServiceConfig { // private static java.util.Properties prop = new java.util.Properties(); // // private static void loadProperties() { // // get class loader // ClassLoader loader = ServiceConfig.class.getClassLoader(); // if (loader == null) { // loader = ClassLoader.getSystemClassLoader(); // } // // load application.properties located in WEB-INF/classes/ // String propFile = "application.properties"; // java.net.URL url = loader.getResource(propFile); // try { // prop.load(url.openStream()); // } catch (Exception e) { // System.err // .println("Could not load configuration file: " + propFile); // } // } // // public static String get(String key) { // return prop.getProperty(key); // } // // public static int getInt(String key) { // return getInt(key, "3600"); // } // // public static int getInt(String key, String defaultValue) { // return Integer.parseInt(prop.getProperty(key, defaultValue)); // } // // // load the properties when class is accessed // static { // loadProperties(); // } // }
import static org.quartz.JobBuilder.newJob; import static org.quartz.TriggerBuilder.newTrigger; import static org.quartz.CronScheduleBuilder.*; import org.quartz.JobDetail; import org.quartz.Scheduler; import org.quartz.Trigger; import org.quartz.impl.StdSchedulerFactory; import com.ccoe.build.utils.ServiceConfig;
/* Copyright [2013-2014] eBay Software Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.ccoe.build.alerts.pfdash; public class PfDashScheduler { public void run() throws Exception { Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); JobDetail pfDashJob = newJob(PfDashJob.class) .withIdentity("pfDashJob", "group3").build(); Trigger pdDashTrigger = newTrigger() .withIdentity("pdDashTrigger", "group3")
// Path: build-service/src/main/java/com/ccoe/build/utils/ServiceConfig.java // public class ServiceConfig { // private static java.util.Properties prop = new java.util.Properties(); // // private static void loadProperties() { // // get class loader // ClassLoader loader = ServiceConfig.class.getClassLoader(); // if (loader == null) { // loader = ClassLoader.getSystemClassLoader(); // } // // load application.properties located in WEB-INF/classes/ // String propFile = "application.properties"; // java.net.URL url = loader.getResource(propFile); // try { // prop.load(url.openStream()); // } catch (Exception e) { // System.err // .println("Could not load configuration file: " + propFile); // } // } // // public static String get(String key) { // return prop.getProperty(key); // } // // public static int getInt(String key) { // return getInt(key, "3600"); // } // // public static int getInt(String key, String defaultValue) { // return Integer.parseInt(prop.getProperty(key, defaultValue)); // } // // // load the properties when class is accessed // static { // loadProperties(); // } // } // Path: build-service/src/main/java/com/ccoe/build/alerts/pfdash/PfDashScheduler.java import static org.quartz.JobBuilder.newJob; import static org.quartz.TriggerBuilder.newTrigger; import static org.quartz.CronScheduleBuilder.*; import org.quartz.JobDetail; import org.quartz.Scheduler; import org.quartz.Trigger; import org.quartz.impl.StdSchedulerFactory; import com.ccoe.build.utils.ServiceConfig; /* Copyright [2013-2014] eBay Software Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.ccoe.build.alerts.pfdash; public class PfDashScheduler { public void run() throws Exception { Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); JobDetail pfDashJob = newJob(PfDashJob.class) .withIdentity("pfDashJob", "group3").build(); Trigger pdDashTrigger = newTrigger() .withIdentity("pdDashTrigger", "group3")
.withSchedule(cronSchedule(ServiceConfig.get("scheduler.pfdash.time"))).build();
eBay/mTracker
profiler/src/test/java/com/ccoe/build/profiler/util/GitUtilsTest.java
// Path: profiler/src/main/java/com/ccoe/build/profiler/util/GitUtil.java // public class GitUtil { // // public static File findGitRepository( File currentDir ) { // // File gitFolder=null; // File workDir = currentDir; // // while( workDir != null && workDir.exists() ){ // if( isValidGitDir(workDir) ){ // gitFolder = workDir; // break; // }else{ // workDir = workDir.getParentFile(); // } // } // // return gitFolder; // } // // // private static boolean isValidGitDir( File dir ){ // boolean result = false; // // File gitDir = new File( dir, ".git"); // // if( gitDir.exists() ){ // if( gitDir.isDirectory() ){ // if( gitDir.canRead() ){ // result = true; // } // } // } // // return result; // } // // public static String getRepoName(File gitConfigFile) { // String repourl=null; // try { // BufferedReader br = new BufferedReader(new FileReader(gitConfigFile)); // String line = ""; // while((line = br.readLine()) != null) { // //System.out.println(line); // if(line.trim().startsWith("url")) { // //System.out.println("Inisde IF"); // repourl = line.split("=")[1].trim(); // } // } // } catch (FileNotFoundException e) { // // } catch (IOException e) { // // } // // return repourl; // } // // }
import com.ccoe.build.profiler.util.GitUtil; import static org.junit.Assert.assertEquals; import java.io.File; import org.junit.Test;
/* Copyright [2013-2014] eBay Software Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.ccoe.build.profiler.util; public class GitUtilsTest { @Test public void testIsValidGitDir() { File currentFolder = new File(getClass().getResource("/").getFile()); File gitBase = currentFolder.getParentFile().getParentFile().getParentFile();
// Path: profiler/src/main/java/com/ccoe/build/profiler/util/GitUtil.java // public class GitUtil { // // public static File findGitRepository( File currentDir ) { // // File gitFolder=null; // File workDir = currentDir; // // while( workDir != null && workDir.exists() ){ // if( isValidGitDir(workDir) ){ // gitFolder = workDir; // break; // }else{ // workDir = workDir.getParentFile(); // } // } // // return gitFolder; // } // // // private static boolean isValidGitDir( File dir ){ // boolean result = false; // // File gitDir = new File( dir, ".git"); // // if( gitDir.exists() ){ // if( gitDir.isDirectory() ){ // if( gitDir.canRead() ){ // result = true; // } // } // } // // return result; // } // // public static String getRepoName(File gitConfigFile) { // String repourl=null; // try { // BufferedReader br = new BufferedReader(new FileReader(gitConfigFile)); // String line = ""; // while((line = br.readLine()) != null) { // //System.out.println(line); // if(line.trim().startsWith("url")) { // //System.out.println("Inisde IF"); // repourl = line.split("=")[1].trim(); // } // } // } catch (FileNotFoundException e) { // // } catch (IOException e) { // // } // // return repourl; // } // // } // Path: profiler/src/test/java/com/ccoe/build/profiler/util/GitUtilsTest.java import com.ccoe.build.profiler.util.GitUtil; import static org.junit.Assert.assertEquals; import java.io.File; import org.junit.Test; /* Copyright [2013-2014] eBay Software Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.ccoe.build.profiler.util; public class GitUtilsTest { @Test public void testIsValidGitDir() { File currentFolder = new File(getClass().getResource("/").getFile()); File gitBase = currentFolder.getParentFile().getParentFile().getParentFile();
File gitMeta = GitUtil.findGitRepository(gitBase);
eBay/mTracker
profiler/src/main/java/com/ccoe/build/profiler/profile/PhaseProfile.java
// Path: core/src/main/java/com/ccoe/build/core/model/Phase.java // public class Phase extends TrackingModel { // private String name; // // private List<Plugin> plugins = new ArrayList<Plugin>(); // // private String status; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public List<Plugin> getPlugins() { // return plugins; // } // // public void setPlugins(List<Plugin> plugins) { // this.plugins = plugins; // } // // public String getStatus() { // return status; // } // // public void setStatus(String status) { // this.status = status; // } // // public String toString() { // StringBuffer sBuffer = new StringBuffer(); // appendTransacionStart(sBuffer, 3, "Phase", getName()); // for (Plugin plugin : this.getPlugins()) { // appendLine(sBuffer, plugin.toString()); // } // appendTransacionEnd(sBuffer, 3, "Phase", getName(), getStatus(), getDuration().toString()); // return sBuffer.toString(); // } // } // // Path: core/src/main/java/com/ccoe/build/core/model/Project.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class Project extends TrackingModel { // private String name; // private String groupId; // private String artifactId; // private String type; // private String version; // // private String status; // // private String payload; // // private List<Phase> phases = new ArrayList<Phase>(); // // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // public String getVersion() { // return version; // } // public void setVersion(String version) { // this.version = version; // } // // public String getStatus() { // return status; // } // public void setStatus(String status) { // this.status = status; // } // public List<Phase> getPhases() { // return phases; // } // // public Phase getLastPhase() { // return phases.get(phases.size() - 1); // } // public String getGroupId() { // return groupId; // } // public void setGroupId(String groupId) { // this.groupId = groupId; // } // public String getArtifactId() { // return artifactId; // } // public void setArtifactId(String artifactId) { // this.artifactId = artifactId; // } // public String getType() { // return type; // } // public void setType(String type) { // this.type = type; // } // public String getPayload() { // return payload; // } // public void setPayload(String payload) { // this.payload = payload; // } // // public String toString() { // StringBuffer sBuffer = new StringBuffer(); // // appendTransacionStart(sBuffer, 2, "Project", getName()); // // for (Phase phase : getPhases()) { // appendLine(sBuffer, phase.toString()); // } // // appendTransacionEnd(sBuffer, 2, "Project", getName(), getStatus(), getDuration().toString(), getPayload()); // // return sBuffer.toString(); // } // } // // Path: profiler/src/main/java/com/ccoe/build/profiler/util/Timer.java // public class Timer { // // public static final int MS_PER_SEC = 1000; // public static final int SEC_PER_MIN = 60; // // private long start; // private long elaspsedTime; // // public Timer() { // start = System.currentTimeMillis(); // } // // public void stop() { // elaspsedTime = elapsedTime(); // } // // public long getTime() { // return elaspsedTime; // } // // public long getStartTime() { // return this.start; // } // // private long elapsedTime() { // return System.currentTimeMillis() - start; // } // // public static String formatTime(long ms) { // long secs = ms / MS_PER_SEC; // long mins = secs / SEC_PER_MIN; // secs = secs % SEC_PER_MIN; // long fractionOfASecond = ms - (secs * 1000); // // String msg = mins + "m " + secs + "." + fractionOfASecond; // // if (msg.length() == 3) { // msg += "00s"; // } else if (msg.length() == 4) { // msg += "0s"; // } else { // msg += "s"; // } // // msg = ms + " ms ( " + msg + " )"; // // return msg; // } // }
import java.util.ArrayList; import java.util.Date; import java.util.List; import org.apache.maven.eventspy.EventSpy.Context; import org.apache.maven.execution.ExecutionEvent; import com.ccoe.build.core.model.Phase; import com.ccoe.build.core.model.Project; import com.ccoe.build.profiler.util.Timer;
/* Copyright [2013-2014] eBay Software Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.ccoe.build.profiler.profile; public class PhaseProfile extends Profile { private String phaseName; private List<MojoProfile> mojoProfiles;
// Path: core/src/main/java/com/ccoe/build/core/model/Phase.java // public class Phase extends TrackingModel { // private String name; // // private List<Plugin> plugins = new ArrayList<Plugin>(); // // private String status; // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public List<Plugin> getPlugins() { // return plugins; // } // // public void setPlugins(List<Plugin> plugins) { // this.plugins = plugins; // } // // public String getStatus() { // return status; // } // // public void setStatus(String status) { // this.status = status; // } // // public String toString() { // StringBuffer sBuffer = new StringBuffer(); // appendTransacionStart(sBuffer, 3, "Phase", getName()); // for (Plugin plugin : this.getPlugins()) { // appendLine(sBuffer, plugin.toString()); // } // appendTransacionEnd(sBuffer, 3, "Phase", getName(), getStatus(), getDuration().toString()); // return sBuffer.toString(); // } // } // // Path: core/src/main/java/com/ccoe/build/core/model/Project.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class Project extends TrackingModel { // private String name; // private String groupId; // private String artifactId; // private String type; // private String version; // // private String status; // // private String payload; // // private List<Phase> phases = new ArrayList<Phase>(); // // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // public String getVersion() { // return version; // } // public void setVersion(String version) { // this.version = version; // } // // public String getStatus() { // return status; // } // public void setStatus(String status) { // this.status = status; // } // public List<Phase> getPhases() { // return phases; // } // // public Phase getLastPhase() { // return phases.get(phases.size() - 1); // } // public String getGroupId() { // return groupId; // } // public void setGroupId(String groupId) { // this.groupId = groupId; // } // public String getArtifactId() { // return artifactId; // } // public void setArtifactId(String artifactId) { // this.artifactId = artifactId; // } // public String getType() { // return type; // } // public void setType(String type) { // this.type = type; // } // public String getPayload() { // return payload; // } // public void setPayload(String payload) { // this.payload = payload; // } // // public String toString() { // StringBuffer sBuffer = new StringBuffer(); // // appendTransacionStart(sBuffer, 2, "Project", getName()); // // for (Phase phase : getPhases()) { // appendLine(sBuffer, phase.toString()); // } // // appendTransacionEnd(sBuffer, 2, "Project", getName(), getStatus(), getDuration().toString(), getPayload()); // // return sBuffer.toString(); // } // } // // Path: profiler/src/main/java/com/ccoe/build/profiler/util/Timer.java // public class Timer { // // public static final int MS_PER_SEC = 1000; // public static final int SEC_PER_MIN = 60; // // private long start; // private long elaspsedTime; // // public Timer() { // start = System.currentTimeMillis(); // } // // public void stop() { // elaspsedTime = elapsedTime(); // } // // public long getTime() { // return elaspsedTime; // } // // public long getStartTime() { // return this.start; // } // // private long elapsedTime() { // return System.currentTimeMillis() - start; // } // // public static String formatTime(long ms) { // long secs = ms / MS_PER_SEC; // long mins = secs / SEC_PER_MIN; // secs = secs % SEC_PER_MIN; // long fractionOfASecond = ms - (secs * 1000); // // String msg = mins + "m " + secs + "." + fractionOfASecond; // // if (msg.length() == 3) { // msg += "00s"; // } else if (msg.length() == 4) { // msg += "0s"; // } else { // msg += "s"; // } // // msg = ms + " ms ( " + msg + " )"; // // return msg; // } // } // Path: profiler/src/main/java/com/ccoe/build/profiler/profile/PhaseProfile.java import java.util.ArrayList; import java.util.Date; import java.util.List; import org.apache.maven.eventspy.EventSpy.Context; import org.apache.maven.execution.ExecutionEvent; import com.ccoe.build.core.model.Phase; import com.ccoe.build.core.model.Project; import com.ccoe.build.profiler.util.Timer; /* Copyright [2013-2014] eBay Software Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.ccoe.build.profiler.profile; public class PhaseProfile extends Profile { private String phaseName; private List<MojoProfile> mojoProfiles;
private Phase phase = new Phase();
eBay/mTracker
build-service/src/test/java/com/ccoe/build/service/track/MyResourceTest.java
// Path: build-service/src/main/java/com/ccoe/build/service/track/Main.java // public class Main { // // Base URI the Grizzly HTTP server will listen on // public static final String BASE_URI = "http://localhost:7070/myapp"; // // /** // * Starts Grizzly HTTP server exposing JAX-RS resources defined in this application. // * @return Grizzly HTTP server. // */ // public static HttpServer startServer() { // // create a resource config that scans for JAX-RS resources and providers // // in com.ccoe.build.service.health package // final ResourceConfig rc = new ResourceConfig().packages("com.ccoe.build.service"); // // // uncomment the following line if you want to enable // // support for JSON on the service (you also have to uncomment // // dependency on jersey-media-json module in pom.xml) // // -- // //rc.addBinder(org.glassfish.jersey.media.json.JsonJaxbBinder); // // rc.register(MoxyJsonFeature.class); // rc.register(MultiPartFeature.class); // rc.register(JsonMoxyConfigurationContextResolver.class); // // // // create and start a new instance of grizzly http server // // exposing the Jersey application at BASE_URI // return GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc); // } // // /** // * Main method. // * @param args // * @throws IOException // */ // public static void main(String[] args) throws IOException { // final HttpServer server = startServer(); // System.out.println(String.format("Jersey app started with WADL available at " // + "%sapplication.wadl\nHit enter to stop it...", BASE_URI)); // // System.in.read(); // server.stop(); // } // // @Provider // final static class JsonMoxyConfigurationContextResolver implements ContextResolver<MoxyJsonConfiguration> { // // @Override // public MoxyJsonConfiguration getContext(Class<?> objectType) { // final MoxyJsonConfiguration configuration = new MoxyJsonConfiguration(); // // Map<String, String> namespacePrefixMapper = new HashMap<String, String>(1); // namespacePrefixMapper.put("http://www.w3.org/2001/XMLSchema-instance", "xsi"); // // configuration.setNamespacePrefixMapper(namespacePrefixMapper); // configuration.setNamespaceSeparator(':'); // // return configuration; // } // } // }
import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.WebTarget; import org.glassfish.grizzly.http.server.HttpServer; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.ccoe.build.service.track.Main; import static org.junit.Assert.assertEquals;
/* Copyright [2013-2014] eBay Software Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.ccoe.build.service.track; public class MyResourceTest { private HttpServer server; private WebTarget target; @Before public void setUp() throws Exception { // start the server
// Path: build-service/src/main/java/com/ccoe/build/service/track/Main.java // public class Main { // // Base URI the Grizzly HTTP server will listen on // public static final String BASE_URI = "http://localhost:7070/myapp"; // // /** // * Starts Grizzly HTTP server exposing JAX-RS resources defined in this application. // * @return Grizzly HTTP server. // */ // public static HttpServer startServer() { // // create a resource config that scans for JAX-RS resources and providers // // in com.ccoe.build.service.health package // final ResourceConfig rc = new ResourceConfig().packages("com.ccoe.build.service"); // // // uncomment the following line if you want to enable // // support for JSON on the service (you also have to uncomment // // dependency on jersey-media-json module in pom.xml) // // -- // //rc.addBinder(org.glassfish.jersey.media.json.JsonJaxbBinder); // // rc.register(MoxyJsonFeature.class); // rc.register(MultiPartFeature.class); // rc.register(JsonMoxyConfigurationContextResolver.class); // // // // create and start a new instance of grizzly http server // // exposing the Jersey application at BASE_URI // return GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc); // } // // /** // * Main method. // * @param args // * @throws IOException // */ // public static void main(String[] args) throws IOException { // final HttpServer server = startServer(); // System.out.println(String.format("Jersey app started with WADL available at " // + "%sapplication.wadl\nHit enter to stop it...", BASE_URI)); // // System.in.read(); // server.stop(); // } // // @Provider // final static class JsonMoxyConfigurationContextResolver implements ContextResolver<MoxyJsonConfiguration> { // // @Override // public MoxyJsonConfiguration getContext(Class<?> objectType) { // final MoxyJsonConfiguration configuration = new MoxyJsonConfiguration(); // // Map<String, String> namespacePrefixMapper = new HashMap<String, String>(1); // namespacePrefixMapper.put("http://www.w3.org/2001/XMLSchema-instance", "xsi"); // // configuration.setNamespacePrefixMapper(namespacePrefixMapper); // configuration.setNamespaceSeparator(':'); // // return configuration; // } // } // } // Path: build-service/src/test/java/com/ccoe/build/service/track/MyResourceTest.java import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.WebTarget; import org.glassfish.grizzly.http.server.HttpServer; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.ccoe.build.service.track.Main; import static org.junit.Assert.assertEquals; /* Copyright [2013-2014] eBay Software Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.ccoe.build.service.track; public class MyResourceTest { private HttpServer server; private WebTarget target; @Before public void setUp() throws Exception { // start the server
server = Main.startServer();
eBay/mTracker
build-service/src/test/java/com/ccoe/build/service/BuildServiceSchedulerTest.java
// Path: build-service/src/main/java/com/ccoe/build/service/BuildServiceScheduler.java // public class BuildServiceScheduler implements ServletContextListener { // public static File contextPath; // // public static void setContextPath(String contextPath) { // File outputPath = new File(contextPath); // // if (!outputPath.exists()) { // outputPath.mkdirs(); // } // // BuildServiceScheduler.contextPath = outputPath.getAbsoluteFile(); // } // // @Override // public void contextDestroyed(ServletContextEvent arg0) { // System.out.println("BuildServiceScheduler exit."); // } // // @Override // public void contextInitialized(ServletContextEvent contextEvent) { // String path = contextEvent.getServletContext().getRealPath("generated-source"); // setContextPath(path); // // System.out.println("BuildServiceScheduler init start. output path: " + path); // // if (isSchedulerEnabled()) { // PfDashScheduler pfDashScheduler = new PfDashScheduler(); // DevxScheduler devxScheduler = new DevxScheduler(); // // try { // pfDashScheduler.run(); // devxScheduler.run(); // } catch (Exception e) { // e.printStackTrace(); // } // } // else { // System.out.println("Scheduler is disabled on this server."); // // TrackingScheduler tScheduler = new TrackingScheduler(); // // TODO: // // we enable this on the standby server, // // this is for test purpose, should be moved to the if block // try { // tScheduler.run(); // } catch (Exception e) { // e.printStackTrace(); // } // } // // } // // public boolean isSchedulerEnabled() { // String serverHostName = getHostName(); // if (serverHostName == null) { // return false; // } // try { // String siteService = new BuildServiceConfig().get("com.ccoe.build.reliability.email.scheduler").getSite(); // if (serverHostName.equals(siteService)) { // return true; // } // } catch (Exception e) { // System.out.println("Build Service Scheduler can not access Build Service due to " + e.getMessage()); // } // return false; // } // // public static String getHostName() { // InetAddress netAddress = null; // try { // netAddress = InetAddress.getLocalHost(); // if (null == netAddress) { // return null; // } // String name = netAddress.getCanonicalHostName(); // return name; // } catch (UnknownHostException e) { // e.printStackTrace(); // } // // return null; // } // // }
import static org.junit.Assert.assertEquals; import org.junit.Test; import com.ccoe.build.service.BuildServiceScheduler;
/* Copyright [2013-2014] eBay Software Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.ccoe.build.service; public class BuildServiceSchedulerTest { @Test public void testIsSchedulerEnabled() {
// Path: build-service/src/main/java/com/ccoe/build/service/BuildServiceScheduler.java // public class BuildServiceScheduler implements ServletContextListener { // public static File contextPath; // // public static void setContextPath(String contextPath) { // File outputPath = new File(contextPath); // // if (!outputPath.exists()) { // outputPath.mkdirs(); // } // // BuildServiceScheduler.contextPath = outputPath.getAbsoluteFile(); // } // // @Override // public void contextDestroyed(ServletContextEvent arg0) { // System.out.println("BuildServiceScheduler exit."); // } // // @Override // public void contextInitialized(ServletContextEvent contextEvent) { // String path = contextEvent.getServletContext().getRealPath("generated-source"); // setContextPath(path); // // System.out.println("BuildServiceScheduler init start. output path: " + path); // // if (isSchedulerEnabled()) { // PfDashScheduler pfDashScheduler = new PfDashScheduler(); // DevxScheduler devxScheduler = new DevxScheduler(); // // try { // pfDashScheduler.run(); // devxScheduler.run(); // } catch (Exception e) { // e.printStackTrace(); // } // } // else { // System.out.println("Scheduler is disabled on this server."); // // TrackingScheduler tScheduler = new TrackingScheduler(); // // TODO: // // we enable this on the standby server, // // this is for test purpose, should be moved to the if block // try { // tScheduler.run(); // } catch (Exception e) { // e.printStackTrace(); // } // } // // } // // public boolean isSchedulerEnabled() { // String serverHostName = getHostName(); // if (serverHostName == null) { // return false; // } // try { // String siteService = new BuildServiceConfig().get("com.ccoe.build.reliability.email.scheduler").getSite(); // if (serverHostName.equals(siteService)) { // return true; // } // } catch (Exception e) { // System.out.println("Build Service Scheduler can not access Build Service due to " + e.getMessage()); // } // return false; // } // // public static String getHostName() { // InetAddress netAddress = null; // try { // netAddress = InetAddress.getLocalHost(); // if (null == netAddress) { // return null; // } // String name = netAddress.getCanonicalHostName(); // return name; // } catch (UnknownHostException e) { // e.printStackTrace(); // } // // return null; // } // // } // Path: build-service/src/test/java/com/ccoe/build/service/BuildServiceSchedulerTest.java import static org.junit.Assert.assertEquals; import org.junit.Test; import com.ccoe.build.service.BuildServiceScheduler; /* Copyright [2013-2014] eBay Software Foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.ccoe.build.service; public class BuildServiceSchedulerTest { @Test public void testIsSchedulerEnabled() {
BuildServiceScheduler buildServiceScheduler = new BuildServiceScheduler();
pfstrack/eldamo
src/main/java/xdb/renderer/RendererInit.java
// Path: src/main/java/xdb/control/Renderer.java // public interface Renderer { // // /** // * Mime type generated by this renderer (text/html, text/xml, etc.). // * // * @return The mime type. // */ // public String getMimeType(); // // /** // * Write query results to an output stream. // * // * @param results // * The list of results to render. // * @param out // * The output stream. // * @param params // * The query parameters. // * @throws java.io.IOException // * For errors. // */ // public void render(List<Node> results, PrintWriter out, Map<String, String[]> params) // throws IOException; // }
import java.io.IOException; import org.w3c.dom.Element; import xdb.control.Renderer;
package xdb.renderer; /** * Class for initializing renderers from their configuration. */ public final class RendererInit { private RendererInit() { } /** * Init the renderer from its configuration. * * @param configElement * The configuration element. * @param fileName * The file name. * @return The renderer. * @throws IOException * For errors. */
// Path: src/main/java/xdb/control/Renderer.java // public interface Renderer { // // /** // * Mime type generated by this renderer (text/html, text/xml, etc.). // * // * @return The mime type. // */ // public String getMimeType(); // // /** // * Write query results to an output stream. // * // * @param results // * The list of results to render. // * @param out // * The output stream. // * @param params // * The query parameters. // * @throws java.io.IOException // * For errors. // */ // public void render(List<Node> results, PrintWriter out, Map<String, String[]> params) // throws IOException; // } // Path: src/main/java/xdb/renderer/RendererInit.java import java.io.IOException; import org.w3c.dom.Element; import xdb.control.Renderer; package xdb.renderer; /** * Class for initializing renderers from their configuration. */ public final class RendererInit { private RendererInit() { } /** * Init the renderer from its configuration. * * @param configElement * The configuration element. * @param fileName * The file name. * @return The renderer. * @throws IOException * For errors. */
public static Renderer init(Element configElement, String fileName) throws IOException {
pfstrack/eldamo
src/main/java/xdb/query/QueryInit.java
// Path: src/main/java/xdb/control/Query.java // public interface Query { // // /** // * Execute the query. // * // * @param doc // * The document being queried. // * @param params // * Query parameters. // * @return The list of nodes in the results. // * @throws xdb.control.QueryException // * For errors. // */ // public List<Node> query(Document doc, Map<String, String[]> params) throws QueryException; // }
import org.w3c.dom.Element; import xdb.control.Query;
package xdb.query; /** * Class for initializing queries from their configuration. */ public final class QueryInit { private QueryInit() { } /** * Init the query from its configuration. * * @param configElement * The configuration element. * @param fileName * The file name. * @return The query. */
// Path: src/main/java/xdb/control/Query.java // public interface Query { // // /** // * Execute the query. // * // * @param doc // * The document being queried. // * @param params // * Query parameters. // * @return The list of nodes in the results. // * @throws xdb.control.QueryException // * For errors. // */ // public List<Node> query(Document doc, Map<String, String[]> params) throws QueryException; // } // Path: src/main/java/xdb/query/QueryInit.java import org.w3c.dom.Element; import xdb.control.Query; package xdb.query; /** * Class for initializing queries from their configuration. */ public final class QueryInit { private QueryInit() { } /** * Init the query from its configuration. * * @param configElement * The configuration element. * @param fileName * The file name. * @return The query. */
public static Query init(Element configElement, String fileName) {
pfstrack/eldamo
src/test/java/xdb/test/TestUtil.java
// Path: src/main/java/xdb/dom/XmlParser.java // public class XmlParser extends DocumentBuilder { // private ErrorHandler eh = null; // // @Override // public DOMImplementation getDOMImplementation() { // return DocumentImpl.IMPLEMENTATION; // } // // @Override // public boolean isNamespaceAware() { // return false; // } // // @Override // public boolean isValidating() { // return false; // } // // @Override // public Document newDocument() { // throw new UnsupportedOperationException(); // } // // @Override // public void setEntityResolver(EntityResolver er) { // } // // @Override // public void setErrorHandler(ErrorHandler errorHandler) { // this.eh = errorHandler; // } // // @Override // public Document parse(InputSource is) throws SAXException, IOException { // try { // SAXParserFactory factor = SAXParserFactory.newInstance(); // SAXParser parser = factor.newSAXParser(); // XMLReader reader = parser.getXMLReader(); // if (eh != null) { // reader.setErrorHandler(eh); // } // DomHandler handler = new DomHandler(); // reader.setContentHandler(handler); // reader.parse(is); // return handler.getDoc(); // } catch (ParserConfigurationException ex) { // throw new SAXException(ex); // } // } // }
import java.io.StringReader; import org.w3c.dom.Document; import org.xml.sax.InputSource; import xdb.dom.XmlParser;
package xdb.test; public class TestUtil { public static Document parse(String xml) throws Exception { StringReader reader = new StringReader(xml); InputSource is = new InputSource(reader);
// Path: src/main/java/xdb/dom/XmlParser.java // public class XmlParser extends DocumentBuilder { // private ErrorHandler eh = null; // // @Override // public DOMImplementation getDOMImplementation() { // return DocumentImpl.IMPLEMENTATION; // } // // @Override // public boolean isNamespaceAware() { // return false; // } // // @Override // public boolean isValidating() { // return false; // } // // @Override // public Document newDocument() { // throw new UnsupportedOperationException(); // } // // @Override // public void setEntityResolver(EntityResolver er) { // } // // @Override // public void setErrorHandler(ErrorHandler errorHandler) { // this.eh = errorHandler; // } // // @Override // public Document parse(InputSource is) throws SAXException, IOException { // try { // SAXParserFactory factor = SAXParserFactory.newInstance(); // SAXParser parser = factor.newSAXParser(); // XMLReader reader = parser.getXMLReader(); // if (eh != null) { // reader.setErrorHandler(eh); // } // DomHandler handler = new DomHandler(); // reader.setContentHandler(handler); // reader.parse(is); // return handler.getDoc(); // } catch (ParserConfigurationException ex) { // throw new SAXException(ex); // } // } // } // Path: src/test/java/xdb/test/TestUtil.java import java.io.StringReader; import org.w3c.dom.Document; import org.xml.sax.InputSource; import xdb.dom.XmlParser; package xdb.test; public class TestUtil { public static Document parse(String xml) throws Exception { StringReader reader = new StringReader(xml); InputSource is = new InputSource(reader);
return new XmlParser().parse(is);
pfstrack/eldamo
src/main/java/xdb/query/WholeDocQuery.java
// Path: src/main/java/xdb/control/Query.java // public interface Query { // // /** // * Execute the query. // * // * @param doc // * The document being queried. // * @param params // * Query parameters. // * @return The list of nodes in the results. // * @throws xdb.control.QueryException // * For errors. // */ // public List<Node> query(Document doc, Map<String, String[]> params) throws QueryException; // } // // Path: src/main/java/xdb/control/QueryException.java // @SuppressWarnings("serial") // public class QueryException extends Exception { // // /** // * Constructor. // * // * @param message // * The error message. // * @param rootCause // * The true cause of the exception. // */ // public QueryException(String message, Exception rootCause) { // super(message, rootCause); // } // }
import java.util.Collections; import java.util.List; import java.util.Map; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import xdb.control.Query; import xdb.control.QueryException;
package xdb.query; /** * A "query" that simply returns the entire document. For global XML processing such as XQuery. * * @author ps142237 */ public class WholeDocQuery implements Query { /** * Init the query from its configuration. * * @param configElement * The configuration element. * @return The query. */ public static WholeDocQuery init(Element configElement) { return new WholeDocQuery(); } /** Constructor. */ public WholeDocQuery() { } @Override
// Path: src/main/java/xdb/control/Query.java // public interface Query { // // /** // * Execute the query. // * // * @param doc // * The document being queried. // * @param params // * Query parameters. // * @return The list of nodes in the results. // * @throws xdb.control.QueryException // * For errors. // */ // public List<Node> query(Document doc, Map<String, String[]> params) throws QueryException; // } // // Path: src/main/java/xdb/control/QueryException.java // @SuppressWarnings("serial") // public class QueryException extends Exception { // // /** // * Constructor. // * // * @param message // * The error message. // * @param rootCause // * The true cause of the exception. // */ // public QueryException(String message, Exception rootCause) { // super(message, rootCause); // } // } // Path: src/main/java/xdb/query/WholeDocQuery.java import java.util.Collections; import java.util.List; import java.util.Map; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import xdb.control.Query; import xdb.control.QueryException; package xdb.query; /** * A "query" that simply returns the entire document. For global XML processing such as XQuery. * * @author ps142237 */ public class WholeDocQuery implements Query { /** * Init the query from its configuration. * * @param configElement * The configuration element. * @return The query. */ public static WholeDocQuery init(Element configElement) { return new WholeDocQuery(); } /** Constructor. */ public WholeDocQuery() { } @Override
public List<Node> query(Document doc, Map<String, String[]> params) throws QueryException {
pfstrack/eldamo
src/test/java/xdb/query/MultiIdQueryTest.java
// Path: src/main/java/xdb/control/Query.java // public interface Query { // // /** // * Execute the query. // * // * @param doc // * The document being queried. // * @param params // * Query parameters. // * @return The list of nodes in the results. // * @throws xdb.control.QueryException // * For errors. // */ // public List<Node> query(Document doc, Map<String, String[]> params) throws QueryException; // } // // Path: src/main/java/xdb/dom/XmlParser.java // public class XmlParser extends DocumentBuilder { // private ErrorHandler eh = null; // // @Override // public DOMImplementation getDOMImplementation() { // return DocumentImpl.IMPLEMENTATION; // } // // @Override // public boolean isNamespaceAware() { // return false; // } // // @Override // public boolean isValidating() { // return false; // } // // @Override // public Document newDocument() { // throw new UnsupportedOperationException(); // } // // @Override // public void setEntityResolver(EntityResolver er) { // } // // @Override // public void setErrorHandler(ErrorHandler errorHandler) { // this.eh = errorHandler; // } // // @Override // public Document parse(InputSource is) throws SAXException, IOException { // try { // SAXParserFactory factor = SAXParserFactory.newInstance(); // SAXParser parser = factor.newSAXParser(); // XMLReader reader = parser.getXMLReader(); // if (eh != null) { // reader.setErrorHandler(eh); // } // DomHandler handler = new DomHandler(); // reader.setContentHandler(handler); // reader.parse(is); // return handler.getDoc(); // } catch (ParserConfigurationException ex) { // throw new SAXException(ex); // } // } // } // // Path: src/main/java/xdb/query/MultiIdQuery.java // public class MultiIdQuery implements Query { // private final String entityType; // // /** // * Init the query from its configuration. // * // * @param configElement // * The configuration element. // * @return The query. // */ // public static MultiIdQuery init(Element configElement) { // String entityType = configElement.getAttribute("entity-type"); // return new MultiIdQuery(entityType); // } // // /** // * Constructor. // * // * @param entityType // * The entity type to be retrieve, null for any entity. // */ // public MultiIdQuery(String entityType) { // this.entityType = entityType; // } // // @Override // public List<Node> query(Document doc, Map<String, String[]> params) throws QueryException { // List<Node> result = new LinkedList<Node>(); // String[] ids = params.get("id"); // for (String id : ids) { // Element element = doc.getElementById(id); // if (element != null) { // if (entityType != null && entityType.length() > 0) { // if (!entityType.equals(element.getNodeName())) { // continue; // Skip // } // } // result.add(element); // } // } // return result; // } // } // // Path: src/main/java/xdb/query/QueryInit.java // public final class QueryInit { // // private QueryInit() { // } // // /** // * Init the query from its configuration. // * // * @param configElement // * The configuration element. // * @param fileName // * The file name. // * @return The query. // */ // public static Query init(Element configElement, String fileName) { // if ("xpath-query".equals(configElement.getNodeName())) { // return XPathQuery.init(configElement); // } else if ("multi-id-query".equals(configElement.getNodeName())) { // return MultiIdQuery.init(configElement); // } else if ("multi-key-query".equals(configElement.getNodeName())) { // return MultiKeyQuery.init(configElement); // } else if ("whole-doc-query".equals(configElement.getNodeName())) { // return WholeDocQuery.init(configElement); // } else { // String msg = "Unknown query in " + fileName + " - " + configElement.getNodeName(); // throw new IllegalStateException(msg); // } // } // }
import java.io.StringReader; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import junit.framework.TestCase; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import xdb.control.Query; import xdb.dom.XmlParser; import xdb.query.MultiIdQuery; import xdb.query.QueryInit;
package xdb.query; public class MultiIdQueryTest extends TestCase { public MultiIdQueryTest(String testName) { super(testName); } /** * Test of init method, of class MultiIdQuery. */ public void testInit() throws Exception { String xml = "<multi-id-query entity-type=\"part\" />"; Element config = parse(xml).getDocumentElement();
// Path: src/main/java/xdb/control/Query.java // public interface Query { // // /** // * Execute the query. // * // * @param doc // * The document being queried. // * @param params // * Query parameters. // * @return The list of nodes in the results. // * @throws xdb.control.QueryException // * For errors. // */ // public List<Node> query(Document doc, Map<String, String[]> params) throws QueryException; // } // // Path: src/main/java/xdb/dom/XmlParser.java // public class XmlParser extends DocumentBuilder { // private ErrorHandler eh = null; // // @Override // public DOMImplementation getDOMImplementation() { // return DocumentImpl.IMPLEMENTATION; // } // // @Override // public boolean isNamespaceAware() { // return false; // } // // @Override // public boolean isValidating() { // return false; // } // // @Override // public Document newDocument() { // throw new UnsupportedOperationException(); // } // // @Override // public void setEntityResolver(EntityResolver er) { // } // // @Override // public void setErrorHandler(ErrorHandler errorHandler) { // this.eh = errorHandler; // } // // @Override // public Document parse(InputSource is) throws SAXException, IOException { // try { // SAXParserFactory factor = SAXParserFactory.newInstance(); // SAXParser parser = factor.newSAXParser(); // XMLReader reader = parser.getXMLReader(); // if (eh != null) { // reader.setErrorHandler(eh); // } // DomHandler handler = new DomHandler(); // reader.setContentHandler(handler); // reader.parse(is); // return handler.getDoc(); // } catch (ParserConfigurationException ex) { // throw new SAXException(ex); // } // } // } // // Path: src/main/java/xdb/query/MultiIdQuery.java // public class MultiIdQuery implements Query { // private final String entityType; // // /** // * Init the query from its configuration. // * // * @param configElement // * The configuration element. // * @return The query. // */ // public static MultiIdQuery init(Element configElement) { // String entityType = configElement.getAttribute("entity-type"); // return new MultiIdQuery(entityType); // } // // /** // * Constructor. // * // * @param entityType // * The entity type to be retrieve, null for any entity. // */ // public MultiIdQuery(String entityType) { // this.entityType = entityType; // } // // @Override // public List<Node> query(Document doc, Map<String, String[]> params) throws QueryException { // List<Node> result = new LinkedList<Node>(); // String[] ids = params.get("id"); // for (String id : ids) { // Element element = doc.getElementById(id); // if (element != null) { // if (entityType != null && entityType.length() > 0) { // if (!entityType.equals(element.getNodeName())) { // continue; // Skip // } // } // result.add(element); // } // } // return result; // } // } // // Path: src/main/java/xdb/query/QueryInit.java // public final class QueryInit { // // private QueryInit() { // } // // /** // * Init the query from its configuration. // * // * @param configElement // * The configuration element. // * @param fileName // * The file name. // * @return The query. // */ // public static Query init(Element configElement, String fileName) { // if ("xpath-query".equals(configElement.getNodeName())) { // return XPathQuery.init(configElement); // } else if ("multi-id-query".equals(configElement.getNodeName())) { // return MultiIdQuery.init(configElement); // } else if ("multi-key-query".equals(configElement.getNodeName())) { // return MultiKeyQuery.init(configElement); // } else if ("whole-doc-query".equals(configElement.getNodeName())) { // return WholeDocQuery.init(configElement); // } else { // String msg = "Unknown query in " + fileName + " - " + configElement.getNodeName(); // throw new IllegalStateException(msg); // } // } // } // Path: src/test/java/xdb/query/MultiIdQueryTest.java import java.io.StringReader; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import junit.framework.TestCase; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import xdb.control.Query; import xdb.dom.XmlParser; import xdb.query.MultiIdQuery; import xdb.query.QueryInit; package xdb.query; public class MultiIdQueryTest extends TestCase { public MultiIdQueryTest(String testName) { super(testName); } /** * Test of init method, of class MultiIdQuery. */ public void testInit() throws Exception { String xml = "<multi-id-query entity-type=\"part\" />"; Element config = parse(xml).getDocumentElement();
Query instance = QueryInit.init(config, "test-config.xml");
pfstrack/eldamo
src/test/java/xdb/query/MultiIdQueryTest.java
// Path: src/main/java/xdb/control/Query.java // public interface Query { // // /** // * Execute the query. // * // * @param doc // * The document being queried. // * @param params // * Query parameters. // * @return The list of nodes in the results. // * @throws xdb.control.QueryException // * For errors. // */ // public List<Node> query(Document doc, Map<String, String[]> params) throws QueryException; // } // // Path: src/main/java/xdb/dom/XmlParser.java // public class XmlParser extends DocumentBuilder { // private ErrorHandler eh = null; // // @Override // public DOMImplementation getDOMImplementation() { // return DocumentImpl.IMPLEMENTATION; // } // // @Override // public boolean isNamespaceAware() { // return false; // } // // @Override // public boolean isValidating() { // return false; // } // // @Override // public Document newDocument() { // throw new UnsupportedOperationException(); // } // // @Override // public void setEntityResolver(EntityResolver er) { // } // // @Override // public void setErrorHandler(ErrorHandler errorHandler) { // this.eh = errorHandler; // } // // @Override // public Document parse(InputSource is) throws SAXException, IOException { // try { // SAXParserFactory factor = SAXParserFactory.newInstance(); // SAXParser parser = factor.newSAXParser(); // XMLReader reader = parser.getXMLReader(); // if (eh != null) { // reader.setErrorHandler(eh); // } // DomHandler handler = new DomHandler(); // reader.setContentHandler(handler); // reader.parse(is); // return handler.getDoc(); // } catch (ParserConfigurationException ex) { // throw new SAXException(ex); // } // } // } // // Path: src/main/java/xdb/query/MultiIdQuery.java // public class MultiIdQuery implements Query { // private final String entityType; // // /** // * Init the query from its configuration. // * // * @param configElement // * The configuration element. // * @return The query. // */ // public static MultiIdQuery init(Element configElement) { // String entityType = configElement.getAttribute("entity-type"); // return new MultiIdQuery(entityType); // } // // /** // * Constructor. // * // * @param entityType // * The entity type to be retrieve, null for any entity. // */ // public MultiIdQuery(String entityType) { // this.entityType = entityType; // } // // @Override // public List<Node> query(Document doc, Map<String, String[]> params) throws QueryException { // List<Node> result = new LinkedList<Node>(); // String[] ids = params.get("id"); // for (String id : ids) { // Element element = doc.getElementById(id); // if (element != null) { // if (entityType != null && entityType.length() > 0) { // if (!entityType.equals(element.getNodeName())) { // continue; // Skip // } // } // result.add(element); // } // } // return result; // } // } // // Path: src/main/java/xdb/query/QueryInit.java // public final class QueryInit { // // private QueryInit() { // } // // /** // * Init the query from its configuration. // * // * @param configElement // * The configuration element. // * @param fileName // * The file name. // * @return The query. // */ // public static Query init(Element configElement, String fileName) { // if ("xpath-query".equals(configElement.getNodeName())) { // return XPathQuery.init(configElement); // } else if ("multi-id-query".equals(configElement.getNodeName())) { // return MultiIdQuery.init(configElement); // } else if ("multi-key-query".equals(configElement.getNodeName())) { // return MultiKeyQuery.init(configElement); // } else if ("whole-doc-query".equals(configElement.getNodeName())) { // return WholeDocQuery.init(configElement); // } else { // String msg = "Unknown query in " + fileName + " - " + configElement.getNodeName(); // throw new IllegalStateException(msg); // } // } // }
import java.io.StringReader; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import junit.framework.TestCase; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import xdb.control.Query; import xdb.dom.XmlParser; import xdb.query.MultiIdQuery; import xdb.query.QueryInit;
package xdb.query; public class MultiIdQueryTest extends TestCase { public MultiIdQueryTest(String testName) { super(testName); } /** * Test of init method, of class MultiIdQuery. */ public void testInit() throws Exception { String xml = "<multi-id-query entity-type=\"part\" />"; Element config = parse(xml).getDocumentElement();
// Path: src/main/java/xdb/control/Query.java // public interface Query { // // /** // * Execute the query. // * // * @param doc // * The document being queried. // * @param params // * Query parameters. // * @return The list of nodes in the results. // * @throws xdb.control.QueryException // * For errors. // */ // public List<Node> query(Document doc, Map<String, String[]> params) throws QueryException; // } // // Path: src/main/java/xdb/dom/XmlParser.java // public class XmlParser extends DocumentBuilder { // private ErrorHandler eh = null; // // @Override // public DOMImplementation getDOMImplementation() { // return DocumentImpl.IMPLEMENTATION; // } // // @Override // public boolean isNamespaceAware() { // return false; // } // // @Override // public boolean isValidating() { // return false; // } // // @Override // public Document newDocument() { // throw new UnsupportedOperationException(); // } // // @Override // public void setEntityResolver(EntityResolver er) { // } // // @Override // public void setErrorHandler(ErrorHandler errorHandler) { // this.eh = errorHandler; // } // // @Override // public Document parse(InputSource is) throws SAXException, IOException { // try { // SAXParserFactory factor = SAXParserFactory.newInstance(); // SAXParser parser = factor.newSAXParser(); // XMLReader reader = parser.getXMLReader(); // if (eh != null) { // reader.setErrorHandler(eh); // } // DomHandler handler = new DomHandler(); // reader.setContentHandler(handler); // reader.parse(is); // return handler.getDoc(); // } catch (ParserConfigurationException ex) { // throw new SAXException(ex); // } // } // } // // Path: src/main/java/xdb/query/MultiIdQuery.java // public class MultiIdQuery implements Query { // private final String entityType; // // /** // * Init the query from its configuration. // * // * @param configElement // * The configuration element. // * @return The query. // */ // public static MultiIdQuery init(Element configElement) { // String entityType = configElement.getAttribute("entity-type"); // return new MultiIdQuery(entityType); // } // // /** // * Constructor. // * // * @param entityType // * The entity type to be retrieve, null for any entity. // */ // public MultiIdQuery(String entityType) { // this.entityType = entityType; // } // // @Override // public List<Node> query(Document doc, Map<String, String[]> params) throws QueryException { // List<Node> result = new LinkedList<Node>(); // String[] ids = params.get("id"); // for (String id : ids) { // Element element = doc.getElementById(id); // if (element != null) { // if (entityType != null && entityType.length() > 0) { // if (!entityType.equals(element.getNodeName())) { // continue; // Skip // } // } // result.add(element); // } // } // return result; // } // } // // Path: src/main/java/xdb/query/QueryInit.java // public final class QueryInit { // // private QueryInit() { // } // // /** // * Init the query from its configuration. // * // * @param configElement // * The configuration element. // * @param fileName // * The file name. // * @return The query. // */ // public static Query init(Element configElement, String fileName) { // if ("xpath-query".equals(configElement.getNodeName())) { // return XPathQuery.init(configElement); // } else if ("multi-id-query".equals(configElement.getNodeName())) { // return MultiIdQuery.init(configElement); // } else if ("multi-key-query".equals(configElement.getNodeName())) { // return MultiKeyQuery.init(configElement); // } else if ("whole-doc-query".equals(configElement.getNodeName())) { // return WholeDocQuery.init(configElement); // } else { // String msg = "Unknown query in " + fileName + " - " + configElement.getNodeName(); // throw new IllegalStateException(msg); // } // } // } // Path: src/test/java/xdb/query/MultiIdQueryTest.java import java.io.StringReader; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import junit.framework.TestCase; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import xdb.control.Query; import xdb.dom.XmlParser; import xdb.query.MultiIdQuery; import xdb.query.QueryInit; package xdb.query; public class MultiIdQueryTest extends TestCase { public MultiIdQueryTest(String testName) { super(testName); } /** * Test of init method, of class MultiIdQuery. */ public void testInit() throws Exception { String xml = "<multi-id-query entity-type=\"part\" />"; Element config = parse(xml).getDocumentElement();
Query instance = QueryInit.init(config, "test-config.xml");
pfstrack/eldamo
src/test/java/xdb/query/MultiIdQueryTest.java
// Path: src/main/java/xdb/control/Query.java // public interface Query { // // /** // * Execute the query. // * // * @param doc // * The document being queried. // * @param params // * Query parameters. // * @return The list of nodes in the results. // * @throws xdb.control.QueryException // * For errors. // */ // public List<Node> query(Document doc, Map<String, String[]> params) throws QueryException; // } // // Path: src/main/java/xdb/dom/XmlParser.java // public class XmlParser extends DocumentBuilder { // private ErrorHandler eh = null; // // @Override // public DOMImplementation getDOMImplementation() { // return DocumentImpl.IMPLEMENTATION; // } // // @Override // public boolean isNamespaceAware() { // return false; // } // // @Override // public boolean isValidating() { // return false; // } // // @Override // public Document newDocument() { // throw new UnsupportedOperationException(); // } // // @Override // public void setEntityResolver(EntityResolver er) { // } // // @Override // public void setErrorHandler(ErrorHandler errorHandler) { // this.eh = errorHandler; // } // // @Override // public Document parse(InputSource is) throws SAXException, IOException { // try { // SAXParserFactory factor = SAXParserFactory.newInstance(); // SAXParser parser = factor.newSAXParser(); // XMLReader reader = parser.getXMLReader(); // if (eh != null) { // reader.setErrorHandler(eh); // } // DomHandler handler = new DomHandler(); // reader.setContentHandler(handler); // reader.parse(is); // return handler.getDoc(); // } catch (ParserConfigurationException ex) { // throw new SAXException(ex); // } // } // } // // Path: src/main/java/xdb/query/MultiIdQuery.java // public class MultiIdQuery implements Query { // private final String entityType; // // /** // * Init the query from its configuration. // * // * @param configElement // * The configuration element. // * @return The query. // */ // public static MultiIdQuery init(Element configElement) { // String entityType = configElement.getAttribute("entity-type"); // return new MultiIdQuery(entityType); // } // // /** // * Constructor. // * // * @param entityType // * The entity type to be retrieve, null for any entity. // */ // public MultiIdQuery(String entityType) { // this.entityType = entityType; // } // // @Override // public List<Node> query(Document doc, Map<String, String[]> params) throws QueryException { // List<Node> result = new LinkedList<Node>(); // String[] ids = params.get("id"); // for (String id : ids) { // Element element = doc.getElementById(id); // if (element != null) { // if (entityType != null && entityType.length() > 0) { // if (!entityType.equals(element.getNodeName())) { // continue; // Skip // } // } // result.add(element); // } // } // return result; // } // } // // Path: src/main/java/xdb/query/QueryInit.java // public final class QueryInit { // // private QueryInit() { // } // // /** // * Init the query from its configuration. // * // * @param configElement // * The configuration element. // * @param fileName // * The file name. // * @return The query. // */ // public static Query init(Element configElement, String fileName) { // if ("xpath-query".equals(configElement.getNodeName())) { // return XPathQuery.init(configElement); // } else if ("multi-id-query".equals(configElement.getNodeName())) { // return MultiIdQuery.init(configElement); // } else if ("multi-key-query".equals(configElement.getNodeName())) { // return MultiKeyQuery.init(configElement); // } else if ("whole-doc-query".equals(configElement.getNodeName())) { // return WholeDocQuery.init(configElement); // } else { // String msg = "Unknown query in " + fileName + " - " + configElement.getNodeName(); // throw new IllegalStateException(msg); // } // } // }
import java.io.StringReader; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import junit.framework.TestCase; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import xdb.control.Query; import xdb.dom.XmlParser; import xdb.query.MultiIdQuery; import xdb.query.QueryInit;
package xdb.query; public class MultiIdQueryTest extends TestCase { public MultiIdQueryTest(String testName) { super(testName); } /** * Test of init method, of class MultiIdQuery. */ public void testInit() throws Exception { String xml = "<multi-id-query entity-type=\"part\" />"; Element config = parse(xml).getDocumentElement(); Query instance = QueryInit.init(config, "test-config.xml");
// Path: src/main/java/xdb/control/Query.java // public interface Query { // // /** // * Execute the query. // * // * @param doc // * The document being queried. // * @param params // * Query parameters. // * @return The list of nodes in the results. // * @throws xdb.control.QueryException // * For errors. // */ // public List<Node> query(Document doc, Map<String, String[]> params) throws QueryException; // } // // Path: src/main/java/xdb/dom/XmlParser.java // public class XmlParser extends DocumentBuilder { // private ErrorHandler eh = null; // // @Override // public DOMImplementation getDOMImplementation() { // return DocumentImpl.IMPLEMENTATION; // } // // @Override // public boolean isNamespaceAware() { // return false; // } // // @Override // public boolean isValidating() { // return false; // } // // @Override // public Document newDocument() { // throw new UnsupportedOperationException(); // } // // @Override // public void setEntityResolver(EntityResolver er) { // } // // @Override // public void setErrorHandler(ErrorHandler errorHandler) { // this.eh = errorHandler; // } // // @Override // public Document parse(InputSource is) throws SAXException, IOException { // try { // SAXParserFactory factor = SAXParserFactory.newInstance(); // SAXParser parser = factor.newSAXParser(); // XMLReader reader = parser.getXMLReader(); // if (eh != null) { // reader.setErrorHandler(eh); // } // DomHandler handler = new DomHandler(); // reader.setContentHandler(handler); // reader.parse(is); // return handler.getDoc(); // } catch (ParserConfigurationException ex) { // throw new SAXException(ex); // } // } // } // // Path: src/main/java/xdb/query/MultiIdQuery.java // public class MultiIdQuery implements Query { // private final String entityType; // // /** // * Init the query from its configuration. // * // * @param configElement // * The configuration element. // * @return The query. // */ // public static MultiIdQuery init(Element configElement) { // String entityType = configElement.getAttribute("entity-type"); // return new MultiIdQuery(entityType); // } // // /** // * Constructor. // * // * @param entityType // * The entity type to be retrieve, null for any entity. // */ // public MultiIdQuery(String entityType) { // this.entityType = entityType; // } // // @Override // public List<Node> query(Document doc, Map<String, String[]> params) throws QueryException { // List<Node> result = new LinkedList<Node>(); // String[] ids = params.get("id"); // for (String id : ids) { // Element element = doc.getElementById(id); // if (element != null) { // if (entityType != null && entityType.length() > 0) { // if (!entityType.equals(element.getNodeName())) { // continue; // Skip // } // } // result.add(element); // } // } // return result; // } // } // // Path: src/main/java/xdb/query/QueryInit.java // public final class QueryInit { // // private QueryInit() { // } // // /** // * Init the query from its configuration. // * // * @param configElement // * The configuration element. // * @param fileName // * The file name. // * @return The query. // */ // public static Query init(Element configElement, String fileName) { // if ("xpath-query".equals(configElement.getNodeName())) { // return XPathQuery.init(configElement); // } else if ("multi-id-query".equals(configElement.getNodeName())) { // return MultiIdQuery.init(configElement); // } else if ("multi-key-query".equals(configElement.getNodeName())) { // return MultiKeyQuery.init(configElement); // } else if ("whole-doc-query".equals(configElement.getNodeName())) { // return WholeDocQuery.init(configElement); // } else { // String msg = "Unknown query in " + fileName + " - " + configElement.getNodeName(); // throw new IllegalStateException(msg); // } // } // } // Path: src/test/java/xdb/query/MultiIdQueryTest.java import java.io.StringReader; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import junit.framework.TestCase; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import xdb.control.Query; import xdb.dom.XmlParser; import xdb.query.MultiIdQuery; import xdb.query.QueryInit; package xdb.query; public class MultiIdQueryTest extends TestCase { public MultiIdQueryTest(String testName) { super(testName); } /** * Test of init method, of class MultiIdQuery. */ public void testInit() throws Exception { String xml = "<multi-id-query entity-type=\"part\" />"; Element config = parse(xml).getDocumentElement(); Query instance = QueryInit.init(config, "test-config.xml");
assertTrue(instance instanceof MultiIdQuery);
pfstrack/eldamo
src/test/java/xdb/query/MultiIdQueryTest.java
// Path: src/main/java/xdb/control/Query.java // public interface Query { // // /** // * Execute the query. // * // * @param doc // * The document being queried. // * @param params // * Query parameters. // * @return The list of nodes in the results. // * @throws xdb.control.QueryException // * For errors. // */ // public List<Node> query(Document doc, Map<String, String[]> params) throws QueryException; // } // // Path: src/main/java/xdb/dom/XmlParser.java // public class XmlParser extends DocumentBuilder { // private ErrorHandler eh = null; // // @Override // public DOMImplementation getDOMImplementation() { // return DocumentImpl.IMPLEMENTATION; // } // // @Override // public boolean isNamespaceAware() { // return false; // } // // @Override // public boolean isValidating() { // return false; // } // // @Override // public Document newDocument() { // throw new UnsupportedOperationException(); // } // // @Override // public void setEntityResolver(EntityResolver er) { // } // // @Override // public void setErrorHandler(ErrorHandler errorHandler) { // this.eh = errorHandler; // } // // @Override // public Document parse(InputSource is) throws SAXException, IOException { // try { // SAXParserFactory factor = SAXParserFactory.newInstance(); // SAXParser parser = factor.newSAXParser(); // XMLReader reader = parser.getXMLReader(); // if (eh != null) { // reader.setErrorHandler(eh); // } // DomHandler handler = new DomHandler(); // reader.setContentHandler(handler); // reader.parse(is); // return handler.getDoc(); // } catch (ParserConfigurationException ex) { // throw new SAXException(ex); // } // } // } // // Path: src/main/java/xdb/query/MultiIdQuery.java // public class MultiIdQuery implements Query { // private final String entityType; // // /** // * Init the query from its configuration. // * // * @param configElement // * The configuration element. // * @return The query. // */ // public static MultiIdQuery init(Element configElement) { // String entityType = configElement.getAttribute("entity-type"); // return new MultiIdQuery(entityType); // } // // /** // * Constructor. // * // * @param entityType // * The entity type to be retrieve, null for any entity. // */ // public MultiIdQuery(String entityType) { // this.entityType = entityType; // } // // @Override // public List<Node> query(Document doc, Map<String, String[]> params) throws QueryException { // List<Node> result = new LinkedList<Node>(); // String[] ids = params.get("id"); // for (String id : ids) { // Element element = doc.getElementById(id); // if (element != null) { // if (entityType != null && entityType.length() > 0) { // if (!entityType.equals(element.getNodeName())) { // continue; // Skip // } // } // result.add(element); // } // } // return result; // } // } // // Path: src/main/java/xdb/query/QueryInit.java // public final class QueryInit { // // private QueryInit() { // } // // /** // * Init the query from its configuration. // * // * @param configElement // * The configuration element. // * @param fileName // * The file name. // * @return The query. // */ // public static Query init(Element configElement, String fileName) { // if ("xpath-query".equals(configElement.getNodeName())) { // return XPathQuery.init(configElement); // } else if ("multi-id-query".equals(configElement.getNodeName())) { // return MultiIdQuery.init(configElement); // } else if ("multi-key-query".equals(configElement.getNodeName())) { // return MultiKeyQuery.init(configElement); // } else if ("whole-doc-query".equals(configElement.getNodeName())) { // return WholeDocQuery.init(configElement); // } else { // String msg = "Unknown query in " + fileName + " - " + configElement.getNodeName(); // throw new IllegalStateException(msg); // } // } // }
import java.io.StringReader; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import junit.framework.TestCase; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import xdb.control.Query; import xdb.dom.XmlParser; import xdb.query.MultiIdQuery; import xdb.query.QueryInit;
expResult.add(nodeList.item(2)); assertEquals(expResult, result); } /** * Test of query method, of class MultiIdQuery. */ public void testQueryWithoutEntityType() throws Exception { String configXml = "<multi-id-query />"; Element config = parse(configXml).getDocumentElement(); MultiIdQuery instance = MultiIdQuery.init(config); String xml = "<x><a id='1'/><a id='2'/><a id='3'/><b id='4'/><b id='5'/></x>"; Document doc = parse(xml); String[] array = { "1", "3", "5", "7" }; Map<String, String[]> params = Collections.singletonMap("id", array); List<Node> result = instance.query(doc, params); assertEquals(3, result.size()); NodeList nodeList = doc.getDocumentElement().getChildNodes(); List<Node> expResult = new LinkedList<Node>(); expResult.add(nodeList.item(0)); expResult.add(nodeList.item(2)); expResult.add(nodeList.item(4)); assertEquals(expResult, result); } private static Document parse(String xml) throws Exception { StringReader reader = new StringReader(xml); InputSource is = new InputSource(reader);
// Path: src/main/java/xdb/control/Query.java // public interface Query { // // /** // * Execute the query. // * // * @param doc // * The document being queried. // * @param params // * Query parameters. // * @return The list of nodes in the results. // * @throws xdb.control.QueryException // * For errors. // */ // public List<Node> query(Document doc, Map<String, String[]> params) throws QueryException; // } // // Path: src/main/java/xdb/dom/XmlParser.java // public class XmlParser extends DocumentBuilder { // private ErrorHandler eh = null; // // @Override // public DOMImplementation getDOMImplementation() { // return DocumentImpl.IMPLEMENTATION; // } // // @Override // public boolean isNamespaceAware() { // return false; // } // // @Override // public boolean isValidating() { // return false; // } // // @Override // public Document newDocument() { // throw new UnsupportedOperationException(); // } // // @Override // public void setEntityResolver(EntityResolver er) { // } // // @Override // public void setErrorHandler(ErrorHandler errorHandler) { // this.eh = errorHandler; // } // // @Override // public Document parse(InputSource is) throws SAXException, IOException { // try { // SAXParserFactory factor = SAXParserFactory.newInstance(); // SAXParser parser = factor.newSAXParser(); // XMLReader reader = parser.getXMLReader(); // if (eh != null) { // reader.setErrorHandler(eh); // } // DomHandler handler = new DomHandler(); // reader.setContentHandler(handler); // reader.parse(is); // return handler.getDoc(); // } catch (ParserConfigurationException ex) { // throw new SAXException(ex); // } // } // } // // Path: src/main/java/xdb/query/MultiIdQuery.java // public class MultiIdQuery implements Query { // private final String entityType; // // /** // * Init the query from its configuration. // * // * @param configElement // * The configuration element. // * @return The query. // */ // public static MultiIdQuery init(Element configElement) { // String entityType = configElement.getAttribute("entity-type"); // return new MultiIdQuery(entityType); // } // // /** // * Constructor. // * // * @param entityType // * The entity type to be retrieve, null for any entity. // */ // public MultiIdQuery(String entityType) { // this.entityType = entityType; // } // // @Override // public List<Node> query(Document doc, Map<String, String[]> params) throws QueryException { // List<Node> result = new LinkedList<Node>(); // String[] ids = params.get("id"); // for (String id : ids) { // Element element = doc.getElementById(id); // if (element != null) { // if (entityType != null && entityType.length() > 0) { // if (!entityType.equals(element.getNodeName())) { // continue; // Skip // } // } // result.add(element); // } // } // return result; // } // } // // Path: src/main/java/xdb/query/QueryInit.java // public final class QueryInit { // // private QueryInit() { // } // // /** // * Init the query from its configuration. // * // * @param configElement // * The configuration element. // * @param fileName // * The file name. // * @return The query. // */ // public static Query init(Element configElement, String fileName) { // if ("xpath-query".equals(configElement.getNodeName())) { // return XPathQuery.init(configElement); // } else if ("multi-id-query".equals(configElement.getNodeName())) { // return MultiIdQuery.init(configElement); // } else if ("multi-key-query".equals(configElement.getNodeName())) { // return MultiKeyQuery.init(configElement); // } else if ("whole-doc-query".equals(configElement.getNodeName())) { // return WholeDocQuery.init(configElement); // } else { // String msg = "Unknown query in " + fileName + " - " + configElement.getNodeName(); // throw new IllegalStateException(msg); // } // } // } // Path: src/test/java/xdb/query/MultiIdQueryTest.java import java.io.StringReader; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import junit.framework.TestCase; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import xdb.control.Query; import xdb.dom.XmlParser; import xdb.query.MultiIdQuery; import xdb.query.QueryInit; expResult.add(nodeList.item(2)); assertEquals(expResult, result); } /** * Test of query method, of class MultiIdQuery. */ public void testQueryWithoutEntityType() throws Exception { String configXml = "<multi-id-query />"; Element config = parse(configXml).getDocumentElement(); MultiIdQuery instance = MultiIdQuery.init(config); String xml = "<x><a id='1'/><a id='2'/><a id='3'/><b id='4'/><b id='5'/></x>"; Document doc = parse(xml); String[] array = { "1", "3", "5", "7" }; Map<String, String[]> params = Collections.singletonMap("id", array); List<Node> result = instance.query(doc, params); assertEquals(3, result.size()); NodeList nodeList = doc.getDocumentElement().getChildNodes(); List<Node> expResult = new LinkedList<Node>(); expResult.add(nodeList.item(0)); expResult.add(nodeList.item(2)); expResult.add(nodeList.item(4)); assertEquals(expResult, result); } private static Document parse(String xml) throws Exception { StringReader reader = new StringReader(xml); InputSource is = new InputSource(reader);
return new XmlParser().parse(is);
pfstrack/eldamo
src/test/java/xdb/layout/LayoutFilterTest.java
// Path: src/main/java/xdb/layout/LayoutFilter.java // public class LayoutFilter implements Filter { // private ServletContext servletContext; // private int contextLength; // // /** // * Initialize. // * // * @param config // * The config. // */ // public void init(FilterConfig config) { // servletContext = config.getServletContext(); // String contextPath = servletContext.getContextPath(); // contextLength = contextPath.length(); // } // // /** // * Do filtering. // * // * @param req // * The request. // * @param res // * The response. // * @param chain // * The filter chain. // * @throws IOException // * For errors. // * @throws ServletException // * For errors. // */ // public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) // throws IOException, ServletException { // HttpServletRequest request = (HttpServletRequest) req; // HttpServletResponse response = (HttpServletResponse) res; // // String uri = request.getRequestURI(); // NodeInfo node = findNode(uri); // if (node == null) { // chain.doFilter(req, res); // return; // } // uri = node.getUri(); // String text = getText(node, request, response, chain); // if (request.getAttribute("no-layout") != null) { // res.getWriter().print(text); // return; // } // String body = getTextBody(text); // request.setAttribute("page-body", body); // request.setAttribute("page-node", node); // RequestDispatcher rd = request.getRequestDispatcher("/layout/layout.jsp"); // rd.forward(request, response); // } // // /** Destroy. */ // public void destroy() { // // Do nothing // } // // static String getTextBody(String text) { // String bodyElement = "<body>"; // int bodyElementLength = bodyElement.length(); // int startBody = text.indexOf(bodyElement); // int endBody = text.indexOf("</body>"); // if (!(startBody >= 0 && endBody > startBody + bodyElementLength)) { // return ""; // } // text = text.substring(startBody + bodyElementLength, endBody); // text = text.trim(); // if (text.startsWith("<h1>")) { // String endH1Element = "</h1>"; // int endH1 = text.indexOf(endH1Element); // text = text.substring(endH1 + endH1Element.length()); // text = text.trim(); // } // return text; // } // // private NodeInfo findNode(String uri) { // NodeInfoManager nim = NodeInfoManager.getInstance(); // NodeInfo node = nim.getNode(uri); // if (node == null && uri.endsWith("/")) { // node = nim.getNode(uri + "index.html"); // if (node == null) { // node = nim.getNode(uri + "index.jsp"); // } // } // return node; // } // // private String getText(NodeInfo node, ServletRequest req, HttpServletResponse response, // FilterChain chain) throws IOException, ServletException { // String uri = node.getUri(); // String text = ""; // if (uri.endsWith(".jsp")) { // BufferedResponseWrapper brw = new BufferedResponseWrapper(response); // chain.doFilter(req, brw); // text = brw.getBuffer(); // } else if (uri.endsWith(".html")) { // String shortUri = uri.substring(contextLength); // String realPath = servletContext.getRealPath(shortUri); // text = FileUtil.loadText(new File(realPath)); // } // return text; // } // }
import xdb.layout.LayoutFilter; import junit.framework.TestCase;
package xdb.layout; public class LayoutFilterTest extends TestCase { public LayoutFilterTest(String testName) { super(testName); } public void testGetTextBody() { String text = "<html><body> The body </body></html>"; String expResult = "The body";
// Path: src/main/java/xdb/layout/LayoutFilter.java // public class LayoutFilter implements Filter { // private ServletContext servletContext; // private int contextLength; // // /** // * Initialize. // * // * @param config // * The config. // */ // public void init(FilterConfig config) { // servletContext = config.getServletContext(); // String contextPath = servletContext.getContextPath(); // contextLength = contextPath.length(); // } // // /** // * Do filtering. // * // * @param req // * The request. // * @param res // * The response. // * @param chain // * The filter chain. // * @throws IOException // * For errors. // * @throws ServletException // * For errors. // */ // public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) // throws IOException, ServletException { // HttpServletRequest request = (HttpServletRequest) req; // HttpServletResponse response = (HttpServletResponse) res; // // String uri = request.getRequestURI(); // NodeInfo node = findNode(uri); // if (node == null) { // chain.doFilter(req, res); // return; // } // uri = node.getUri(); // String text = getText(node, request, response, chain); // if (request.getAttribute("no-layout") != null) { // res.getWriter().print(text); // return; // } // String body = getTextBody(text); // request.setAttribute("page-body", body); // request.setAttribute("page-node", node); // RequestDispatcher rd = request.getRequestDispatcher("/layout/layout.jsp"); // rd.forward(request, response); // } // // /** Destroy. */ // public void destroy() { // // Do nothing // } // // static String getTextBody(String text) { // String bodyElement = "<body>"; // int bodyElementLength = bodyElement.length(); // int startBody = text.indexOf(bodyElement); // int endBody = text.indexOf("</body>"); // if (!(startBody >= 0 && endBody > startBody + bodyElementLength)) { // return ""; // } // text = text.substring(startBody + bodyElementLength, endBody); // text = text.trim(); // if (text.startsWith("<h1>")) { // String endH1Element = "</h1>"; // int endH1 = text.indexOf(endH1Element); // text = text.substring(endH1 + endH1Element.length()); // text = text.trim(); // } // return text; // } // // private NodeInfo findNode(String uri) { // NodeInfoManager nim = NodeInfoManager.getInstance(); // NodeInfo node = nim.getNode(uri); // if (node == null && uri.endsWith("/")) { // node = nim.getNode(uri + "index.html"); // if (node == null) { // node = nim.getNode(uri + "index.jsp"); // } // } // return node; // } // // private String getText(NodeInfo node, ServletRequest req, HttpServletResponse response, // FilterChain chain) throws IOException, ServletException { // String uri = node.getUri(); // String text = ""; // if (uri.endsWith(".jsp")) { // BufferedResponseWrapper brw = new BufferedResponseWrapper(response); // chain.doFilter(req, brw); // text = brw.getBuffer(); // } else if (uri.endsWith(".html")) { // String shortUri = uri.substring(contextLength); // String realPath = servletContext.getRealPath(shortUri); // text = FileUtil.loadText(new File(realPath)); // } // return text; // } // } // Path: src/test/java/xdb/layout/LayoutFilterTest.java import xdb.layout.LayoutFilter; import junit.framework.TestCase; package xdb.layout; public class LayoutFilterTest extends TestCase { public LayoutFilterTest(String testName) { super(testName); } public void testGetTextBody() { String text = "<html><body> The body </body></html>"; String expResult = "The body";
String result = LayoutFilter.getTextBody(text);
pfstrack/eldamo
src/test/java/xdb/renderer/RendererInitTest.java
// Path: src/test/java/xdb/test/TestUtil.java // public class TestUtil { // // public static Document parse(String xml) throws Exception { // StringReader reader = new StringReader(xml); // InputSource is = new InputSource(reader); // return new XmlParser().parse(is); // } // }
import junit.framework.TestCase; import org.w3c.dom.Element; import xdb.test.TestUtil;
package xdb.renderer; public class RendererInitTest extends TestCase { public RendererInitTest(String testName) { super(testName); } public void testInit() throws Exception { Element configElement = getConfigElement(); String fileName = "test-config.xml"; try { RendererInit.init(configElement, fileName); fail("Exception expected for bogus renderer type"); } catch (Exception ex) { // Expected } } private Element getConfigElement() throws Exception { String xml = "<bogus-renderer-type />";
// Path: src/test/java/xdb/test/TestUtil.java // public class TestUtil { // // public static Document parse(String xml) throws Exception { // StringReader reader = new StringReader(xml); // InputSource is = new InputSource(reader); // return new XmlParser().parse(is); // } // } // Path: src/test/java/xdb/renderer/RendererInitTest.java import junit.framework.TestCase; import org.w3c.dom.Element; import xdb.test.TestUtil; package xdb.renderer; public class RendererInitTest extends TestCase { public RendererInitTest(String testName) { super(testName); } public void testInit() throws Exception { Element configElement = getConfigElement(); String fileName = "test-config.xml"; try { RendererInit.init(configElement, fileName); fail("Exception expected for bogus renderer type"); } catch (Exception ex) { // Expected } } private Element getConfigElement() throws Exception { String xml = "<bogus-renderer-type />";
return TestUtil.parse(xml).getDocumentElement();
pfstrack/eldamo
src/main/java/xdb/request/RequestParserInit.java
// Path: src/main/java/xdb/control/RequestParser.java // public interface RequestParser { // // /** // * Derive content type (xml, html) from the URI (for example, by file extension). // * // * @param request // * The request. // * @return The content type. // */ // public String deriveContentType(HttpServletRequest request); // // /** // * Derive parameter list from the request (for example, using request parameters). // * // * @param request // * The request. // * @return The parameters for this request. // */ // public Map<String, String[]> deriveParameters(HttpServletRequest request); // }
import org.w3c.dom.Element; import xdb.control.RequestParser;
package xdb.request; /** * Class for initializing request parsers from their configurations. */ public final class RequestParserInit { private RequestParserInit() { } /** * Initialize request parser from configuration. * * @param configElement * The configuration. * @param fileName * The name of the configuration file. * @return The request parser. */
// Path: src/main/java/xdb/control/RequestParser.java // public interface RequestParser { // // /** // * Derive content type (xml, html) from the URI (for example, by file extension). // * // * @param request // * The request. // * @return The content type. // */ // public String deriveContentType(HttpServletRequest request); // // /** // * Derive parameter list from the request (for example, using request parameters). // * // * @param request // * The request. // * @return The parameters for this request. // */ // public Map<String, String[]> deriveParameters(HttpServletRequest request); // } // Path: src/main/java/xdb/request/RequestParserInit.java import org.w3c.dom.Element; import xdb.control.RequestParser; package xdb.request; /** * Class for initializing request parsers from their configurations. */ public final class RequestParserInit { private RequestParserInit() { } /** * Initialize request parser from configuration. * * @param configElement * The configuration. * @param fileName * The name of the configuration file. * @return The request parser. */
public static RequestParser init(Element configElement, String fileName) {
pfstrack/eldamo
src/test/java/xdb/query/XPathQueryTest.java
// Path: src/main/java/xdb/control/Query.java // public interface Query { // // /** // * Execute the query. // * // * @param doc // * The document being queried. // * @param params // * Query parameters. // * @return The list of nodes in the results. // * @throws xdb.control.QueryException // * For errors. // */ // public List<Node> query(Document doc, Map<String, String[]> params) throws QueryException; // } // // Path: src/main/java/xdb/dom/XmlParser.java // public class XmlParser extends DocumentBuilder { // private ErrorHandler eh = null; // // @Override // public DOMImplementation getDOMImplementation() { // return DocumentImpl.IMPLEMENTATION; // } // // @Override // public boolean isNamespaceAware() { // return false; // } // // @Override // public boolean isValidating() { // return false; // } // // @Override // public Document newDocument() { // throw new UnsupportedOperationException(); // } // // @Override // public void setEntityResolver(EntityResolver er) { // } // // @Override // public void setErrorHandler(ErrorHandler errorHandler) { // this.eh = errorHandler; // } // // @Override // public Document parse(InputSource is) throws SAXException, IOException { // try { // SAXParserFactory factor = SAXParserFactory.newInstance(); // SAXParser parser = factor.newSAXParser(); // XMLReader reader = parser.getXMLReader(); // if (eh != null) { // reader.setErrorHandler(eh); // } // DomHandler handler = new DomHandler(); // reader.setContentHandler(handler); // reader.parse(is); // return handler.getDoc(); // } catch (ParserConfigurationException ex) { // throw new SAXException(ex); // } // } // } // // Path: src/main/java/xdb/query/QueryInit.java // public final class QueryInit { // // private QueryInit() { // } // // /** // * Init the query from its configuration. // * // * @param configElement // * The configuration element. // * @param fileName // * The file name. // * @return The query. // */ // public static Query init(Element configElement, String fileName) { // if ("xpath-query".equals(configElement.getNodeName())) { // return XPathQuery.init(configElement); // } else if ("multi-id-query".equals(configElement.getNodeName())) { // return MultiIdQuery.init(configElement); // } else if ("multi-key-query".equals(configElement.getNodeName())) { // return MultiKeyQuery.init(configElement); // } else if ("whole-doc-query".equals(configElement.getNodeName())) { // return WholeDocQuery.init(configElement); // } else { // String msg = "Unknown query in " + fileName + " - " + configElement.getNodeName(); // throw new IllegalStateException(msg); // } // } // } // // Path: src/main/java/xdb/query/XPathQuery.java // public class XPathQuery implements Query { // private final String xpath; // // /** // * Init the query from its configuration. // * // * @param configElement // * The configuration element. // * @return The query. // */ // public static XPathQuery init(Element configElement) { // String xpath = configElement.getAttribute("xpath"); // return new XPathQuery(xpath); // } // // /** // * Constructor. // * // * @param xpath // * The xpath. // */ // public XPathQuery(String xpath) { // this.xpath = xpath; // } // // @Override // public List<Node> query(Document doc, Map<String, String[]> params) throws QueryException { // try { // return XPathEngine.query(doc, xpath, CollectionsUtil.flatten(params)); // } catch (XPathExpressionException ex) { // throw new QueryException(ex.getMessage(), ex); // } // } // }
import java.io.StringReader; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import junit.framework.TestCase; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import xdb.control.Query; import xdb.dom.XmlParser; import xdb.query.QueryInit; import xdb.query.XPathQuery;
package xdb.query; public class XPathQueryTest extends TestCase { public XPathQueryTest(String testName) { super(testName); } public void testInit() throws Exception { String xml = "<xpath-query xpath=\"id($id)\" />"; Element config = parse(xml).getDocumentElement();
// Path: src/main/java/xdb/control/Query.java // public interface Query { // // /** // * Execute the query. // * // * @param doc // * The document being queried. // * @param params // * Query parameters. // * @return The list of nodes in the results. // * @throws xdb.control.QueryException // * For errors. // */ // public List<Node> query(Document doc, Map<String, String[]> params) throws QueryException; // } // // Path: src/main/java/xdb/dom/XmlParser.java // public class XmlParser extends DocumentBuilder { // private ErrorHandler eh = null; // // @Override // public DOMImplementation getDOMImplementation() { // return DocumentImpl.IMPLEMENTATION; // } // // @Override // public boolean isNamespaceAware() { // return false; // } // // @Override // public boolean isValidating() { // return false; // } // // @Override // public Document newDocument() { // throw new UnsupportedOperationException(); // } // // @Override // public void setEntityResolver(EntityResolver er) { // } // // @Override // public void setErrorHandler(ErrorHandler errorHandler) { // this.eh = errorHandler; // } // // @Override // public Document parse(InputSource is) throws SAXException, IOException { // try { // SAXParserFactory factor = SAXParserFactory.newInstance(); // SAXParser parser = factor.newSAXParser(); // XMLReader reader = parser.getXMLReader(); // if (eh != null) { // reader.setErrorHandler(eh); // } // DomHandler handler = new DomHandler(); // reader.setContentHandler(handler); // reader.parse(is); // return handler.getDoc(); // } catch (ParserConfigurationException ex) { // throw new SAXException(ex); // } // } // } // // Path: src/main/java/xdb/query/QueryInit.java // public final class QueryInit { // // private QueryInit() { // } // // /** // * Init the query from its configuration. // * // * @param configElement // * The configuration element. // * @param fileName // * The file name. // * @return The query. // */ // public static Query init(Element configElement, String fileName) { // if ("xpath-query".equals(configElement.getNodeName())) { // return XPathQuery.init(configElement); // } else if ("multi-id-query".equals(configElement.getNodeName())) { // return MultiIdQuery.init(configElement); // } else if ("multi-key-query".equals(configElement.getNodeName())) { // return MultiKeyQuery.init(configElement); // } else if ("whole-doc-query".equals(configElement.getNodeName())) { // return WholeDocQuery.init(configElement); // } else { // String msg = "Unknown query in " + fileName + " - " + configElement.getNodeName(); // throw new IllegalStateException(msg); // } // } // } // // Path: src/main/java/xdb/query/XPathQuery.java // public class XPathQuery implements Query { // private final String xpath; // // /** // * Init the query from its configuration. // * // * @param configElement // * The configuration element. // * @return The query. // */ // public static XPathQuery init(Element configElement) { // String xpath = configElement.getAttribute("xpath"); // return new XPathQuery(xpath); // } // // /** // * Constructor. // * // * @param xpath // * The xpath. // */ // public XPathQuery(String xpath) { // this.xpath = xpath; // } // // @Override // public List<Node> query(Document doc, Map<String, String[]> params) throws QueryException { // try { // return XPathEngine.query(doc, xpath, CollectionsUtil.flatten(params)); // } catch (XPathExpressionException ex) { // throw new QueryException(ex.getMessage(), ex); // } // } // } // Path: src/test/java/xdb/query/XPathQueryTest.java import java.io.StringReader; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import junit.framework.TestCase; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import xdb.control.Query; import xdb.dom.XmlParser; import xdb.query.QueryInit; import xdb.query.XPathQuery; package xdb.query; public class XPathQueryTest extends TestCase { public XPathQueryTest(String testName) { super(testName); } public void testInit() throws Exception { String xml = "<xpath-query xpath=\"id($id)\" />"; Element config = parse(xml).getDocumentElement();
Query instance = QueryInit.init(config, "test-config.xml");
pfstrack/eldamo
src/test/java/xdb/query/XPathQueryTest.java
// Path: src/main/java/xdb/control/Query.java // public interface Query { // // /** // * Execute the query. // * // * @param doc // * The document being queried. // * @param params // * Query parameters. // * @return The list of nodes in the results. // * @throws xdb.control.QueryException // * For errors. // */ // public List<Node> query(Document doc, Map<String, String[]> params) throws QueryException; // } // // Path: src/main/java/xdb/dom/XmlParser.java // public class XmlParser extends DocumentBuilder { // private ErrorHandler eh = null; // // @Override // public DOMImplementation getDOMImplementation() { // return DocumentImpl.IMPLEMENTATION; // } // // @Override // public boolean isNamespaceAware() { // return false; // } // // @Override // public boolean isValidating() { // return false; // } // // @Override // public Document newDocument() { // throw new UnsupportedOperationException(); // } // // @Override // public void setEntityResolver(EntityResolver er) { // } // // @Override // public void setErrorHandler(ErrorHandler errorHandler) { // this.eh = errorHandler; // } // // @Override // public Document parse(InputSource is) throws SAXException, IOException { // try { // SAXParserFactory factor = SAXParserFactory.newInstance(); // SAXParser parser = factor.newSAXParser(); // XMLReader reader = parser.getXMLReader(); // if (eh != null) { // reader.setErrorHandler(eh); // } // DomHandler handler = new DomHandler(); // reader.setContentHandler(handler); // reader.parse(is); // return handler.getDoc(); // } catch (ParserConfigurationException ex) { // throw new SAXException(ex); // } // } // } // // Path: src/main/java/xdb/query/QueryInit.java // public final class QueryInit { // // private QueryInit() { // } // // /** // * Init the query from its configuration. // * // * @param configElement // * The configuration element. // * @param fileName // * The file name. // * @return The query. // */ // public static Query init(Element configElement, String fileName) { // if ("xpath-query".equals(configElement.getNodeName())) { // return XPathQuery.init(configElement); // } else if ("multi-id-query".equals(configElement.getNodeName())) { // return MultiIdQuery.init(configElement); // } else if ("multi-key-query".equals(configElement.getNodeName())) { // return MultiKeyQuery.init(configElement); // } else if ("whole-doc-query".equals(configElement.getNodeName())) { // return WholeDocQuery.init(configElement); // } else { // String msg = "Unknown query in " + fileName + " - " + configElement.getNodeName(); // throw new IllegalStateException(msg); // } // } // } // // Path: src/main/java/xdb/query/XPathQuery.java // public class XPathQuery implements Query { // private final String xpath; // // /** // * Init the query from its configuration. // * // * @param configElement // * The configuration element. // * @return The query. // */ // public static XPathQuery init(Element configElement) { // String xpath = configElement.getAttribute("xpath"); // return new XPathQuery(xpath); // } // // /** // * Constructor. // * // * @param xpath // * The xpath. // */ // public XPathQuery(String xpath) { // this.xpath = xpath; // } // // @Override // public List<Node> query(Document doc, Map<String, String[]> params) throws QueryException { // try { // return XPathEngine.query(doc, xpath, CollectionsUtil.flatten(params)); // } catch (XPathExpressionException ex) { // throw new QueryException(ex.getMessage(), ex); // } // } // }
import java.io.StringReader; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import junit.framework.TestCase; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import xdb.control.Query; import xdb.dom.XmlParser; import xdb.query.QueryInit; import xdb.query.XPathQuery;
package xdb.query; public class XPathQueryTest extends TestCase { public XPathQueryTest(String testName) { super(testName); } public void testInit() throws Exception { String xml = "<xpath-query xpath=\"id($id)\" />"; Element config = parse(xml).getDocumentElement();
// Path: src/main/java/xdb/control/Query.java // public interface Query { // // /** // * Execute the query. // * // * @param doc // * The document being queried. // * @param params // * Query parameters. // * @return The list of nodes in the results. // * @throws xdb.control.QueryException // * For errors. // */ // public List<Node> query(Document doc, Map<String, String[]> params) throws QueryException; // } // // Path: src/main/java/xdb/dom/XmlParser.java // public class XmlParser extends DocumentBuilder { // private ErrorHandler eh = null; // // @Override // public DOMImplementation getDOMImplementation() { // return DocumentImpl.IMPLEMENTATION; // } // // @Override // public boolean isNamespaceAware() { // return false; // } // // @Override // public boolean isValidating() { // return false; // } // // @Override // public Document newDocument() { // throw new UnsupportedOperationException(); // } // // @Override // public void setEntityResolver(EntityResolver er) { // } // // @Override // public void setErrorHandler(ErrorHandler errorHandler) { // this.eh = errorHandler; // } // // @Override // public Document parse(InputSource is) throws SAXException, IOException { // try { // SAXParserFactory factor = SAXParserFactory.newInstance(); // SAXParser parser = factor.newSAXParser(); // XMLReader reader = parser.getXMLReader(); // if (eh != null) { // reader.setErrorHandler(eh); // } // DomHandler handler = new DomHandler(); // reader.setContentHandler(handler); // reader.parse(is); // return handler.getDoc(); // } catch (ParserConfigurationException ex) { // throw new SAXException(ex); // } // } // } // // Path: src/main/java/xdb/query/QueryInit.java // public final class QueryInit { // // private QueryInit() { // } // // /** // * Init the query from its configuration. // * // * @param configElement // * The configuration element. // * @param fileName // * The file name. // * @return The query. // */ // public static Query init(Element configElement, String fileName) { // if ("xpath-query".equals(configElement.getNodeName())) { // return XPathQuery.init(configElement); // } else if ("multi-id-query".equals(configElement.getNodeName())) { // return MultiIdQuery.init(configElement); // } else if ("multi-key-query".equals(configElement.getNodeName())) { // return MultiKeyQuery.init(configElement); // } else if ("whole-doc-query".equals(configElement.getNodeName())) { // return WholeDocQuery.init(configElement); // } else { // String msg = "Unknown query in " + fileName + " - " + configElement.getNodeName(); // throw new IllegalStateException(msg); // } // } // } // // Path: src/main/java/xdb/query/XPathQuery.java // public class XPathQuery implements Query { // private final String xpath; // // /** // * Init the query from its configuration. // * // * @param configElement // * The configuration element. // * @return The query. // */ // public static XPathQuery init(Element configElement) { // String xpath = configElement.getAttribute("xpath"); // return new XPathQuery(xpath); // } // // /** // * Constructor. // * // * @param xpath // * The xpath. // */ // public XPathQuery(String xpath) { // this.xpath = xpath; // } // // @Override // public List<Node> query(Document doc, Map<String, String[]> params) throws QueryException { // try { // return XPathEngine.query(doc, xpath, CollectionsUtil.flatten(params)); // } catch (XPathExpressionException ex) { // throw new QueryException(ex.getMessage(), ex); // } // } // } // Path: src/test/java/xdb/query/XPathQueryTest.java import java.io.StringReader; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import junit.framework.TestCase; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import xdb.control.Query; import xdb.dom.XmlParser; import xdb.query.QueryInit; import xdb.query.XPathQuery; package xdb.query; public class XPathQueryTest extends TestCase { public XPathQueryTest(String testName) { super(testName); } public void testInit() throws Exception { String xml = "<xpath-query xpath=\"id($id)\" />"; Element config = parse(xml).getDocumentElement();
Query instance = QueryInit.init(config, "test-config.xml");
pfstrack/eldamo
src/test/java/xdb/query/XPathQueryTest.java
// Path: src/main/java/xdb/control/Query.java // public interface Query { // // /** // * Execute the query. // * // * @param doc // * The document being queried. // * @param params // * Query parameters. // * @return The list of nodes in the results. // * @throws xdb.control.QueryException // * For errors. // */ // public List<Node> query(Document doc, Map<String, String[]> params) throws QueryException; // } // // Path: src/main/java/xdb/dom/XmlParser.java // public class XmlParser extends DocumentBuilder { // private ErrorHandler eh = null; // // @Override // public DOMImplementation getDOMImplementation() { // return DocumentImpl.IMPLEMENTATION; // } // // @Override // public boolean isNamespaceAware() { // return false; // } // // @Override // public boolean isValidating() { // return false; // } // // @Override // public Document newDocument() { // throw new UnsupportedOperationException(); // } // // @Override // public void setEntityResolver(EntityResolver er) { // } // // @Override // public void setErrorHandler(ErrorHandler errorHandler) { // this.eh = errorHandler; // } // // @Override // public Document parse(InputSource is) throws SAXException, IOException { // try { // SAXParserFactory factor = SAXParserFactory.newInstance(); // SAXParser parser = factor.newSAXParser(); // XMLReader reader = parser.getXMLReader(); // if (eh != null) { // reader.setErrorHandler(eh); // } // DomHandler handler = new DomHandler(); // reader.setContentHandler(handler); // reader.parse(is); // return handler.getDoc(); // } catch (ParserConfigurationException ex) { // throw new SAXException(ex); // } // } // } // // Path: src/main/java/xdb/query/QueryInit.java // public final class QueryInit { // // private QueryInit() { // } // // /** // * Init the query from its configuration. // * // * @param configElement // * The configuration element. // * @param fileName // * The file name. // * @return The query. // */ // public static Query init(Element configElement, String fileName) { // if ("xpath-query".equals(configElement.getNodeName())) { // return XPathQuery.init(configElement); // } else if ("multi-id-query".equals(configElement.getNodeName())) { // return MultiIdQuery.init(configElement); // } else if ("multi-key-query".equals(configElement.getNodeName())) { // return MultiKeyQuery.init(configElement); // } else if ("whole-doc-query".equals(configElement.getNodeName())) { // return WholeDocQuery.init(configElement); // } else { // String msg = "Unknown query in " + fileName + " - " + configElement.getNodeName(); // throw new IllegalStateException(msg); // } // } // } // // Path: src/main/java/xdb/query/XPathQuery.java // public class XPathQuery implements Query { // private final String xpath; // // /** // * Init the query from its configuration. // * // * @param configElement // * The configuration element. // * @return The query. // */ // public static XPathQuery init(Element configElement) { // String xpath = configElement.getAttribute("xpath"); // return new XPathQuery(xpath); // } // // /** // * Constructor. // * // * @param xpath // * The xpath. // */ // public XPathQuery(String xpath) { // this.xpath = xpath; // } // // @Override // public List<Node> query(Document doc, Map<String, String[]> params) throws QueryException { // try { // return XPathEngine.query(doc, xpath, CollectionsUtil.flatten(params)); // } catch (XPathExpressionException ex) { // throw new QueryException(ex.getMessage(), ex); // } // } // }
import java.io.StringReader; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import junit.framework.TestCase; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import xdb.control.Query; import xdb.dom.XmlParser; import xdb.query.QueryInit; import xdb.query.XPathQuery;
package xdb.query; public class XPathQueryTest extends TestCase { public XPathQueryTest(String testName) { super(testName); } public void testInit() throws Exception { String xml = "<xpath-query xpath=\"id($id)\" />"; Element config = parse(xml).getDocumentElement(); Query instance = QueryInit.init(config, "test-config.xml");
// Path: src/main/java/xdb/control/Query.java // public interface Query { // // /** // * Execute the query. // * // * @param doc // * The document being queried. // * @param params // * Query parameters. // * @return The list of nodes in the results. // * @throws xdb.control.QueryException // * For errors. // */ // public List<Node> query(Document doc, Map<String, String[]> params) throws QueryException; // } // // Path: src/main/java/xdb/dom/XmlParser.java // public class XmlParser extends DocumentBuilder { // private ErrorHandler eh = null; // // @Override // public DOMImplementation getDOMImplementation() { // return DocumentImpl.IMPLEMENTATION; // } // // @Override // public boolean isNamespaceAware() { // return false; // } // // @Override // public boolean isValidating() { // return false; // } // // @Override // public Document newDocument() { // throw new UnsupportedOperationException(); // } // // @Override // public void setEntityResolver(EntityResolver er) { // } // // @Override // public void setErrorHandler(ErrorHandler errorHandler) { // this.eh = errorHandler; // } // // @Override // public Document parse(InputSource is) throws SAXException, IOException { // try { // SAXParserFactory factor = SAXParserFactory.newInstance(); // SAXParser parser = factor.newSAXParser(); // XMLReader reader = parser.getXMLReader(); // if (eh != null) { // reader.setErrorHandler(eh); // } // DomHandler handler = new DomHandler(); // reader.setContentHandler(handler); // reader.parse(is); // return handler.getDoc(); // } catch (ParserConfigurationException ex) { // throw new SAXException(ex); // } // } // } // // Path: src/main/java/xdb/query/QueryInit.java // public final class QueryInit { // // private QueryInit() { // } // // /** // * Init the query from its configuration. // * // * @param configElement // * The configuration element. // * @param fileName // * The file name. // * @return The query. // */ // public static Query init(Element configElement, String fileName) { // if ("xpath-query".equals(configElement.getNodeName())) { // return XPathQuery.init(configElement); // } else if ("multi-id-query".equals(configElement.getNodeName())) { // return MultiIdQuery.init(configElement); // } else if ("multi-key-query".equals(configElement.getNodeName())) { // return MultiKeyQuery.init(configElement); // } else if ("whole-doc-query".equals(configElement.getNodeName())) { // return WholeDocQuery.init(configElement); // } else { // String msg = "Unknown query in " + fileName + " - " + configElement.getNodeName(); // throw new IllegalStateException(msg); // } // } // } // // Path: src/main/java/xdb/query/XPathQuery.java // public class XPathQuery implements Query { // private final String xpath; // // /** // * Init the query from its configuration. // * // * @param configElement // * The configuration element. // * @return The query. // */ // public static XPathQuery init(Element configElement) { // String xpath = configElement.getAttribute("xpath"); // return new XPathQuery(xpath); // } // // /** // * Constructor. // * // * @param xpath // * The xpath. // */ // public XPathQuery(String xpath) { // this.xpath = xpath; // } // // @Override // public List<Node> query(Document doc, Map<String, String[]> params) throws QueryException { // try { // return XPathEngine.query(doc, xpath, CollectionsUtil.flatten(params)); // } catch (XPathExpressionException ex) { // throw new QueryException(ex.getMessage(), ex); // } // } // } // Path: src/test/java/xdb/query/XPathQueryTest.java import java.io.StringReader; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import junit.framework.TestCase; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import xdb.control.Query; import xdb.dom.XmlParser; import xdb.query.QueryInit; import xdb.query.XPathQuery; package xdb.query; public class XPathQueryTest extends TestCase { public XPathQueryTest(String testName) { super(testName); } public void testInit() throws Exception { String xml = "<xpath-query xpath=\"id($id)\" />"; Element config = parse(xml).getDocumentElement(); Query instance = QueryInit.init(config, "test-config.xml");
assertTrue(instance instanceof XPathQuery);
pfstrack/eldamo
src/test/java/xdb/query/XPathQueryTest.java
// Path: src/main/java/xdb/control/Query.java // public interface Query { // // /** // * Execute the query. // * // * @param doc // * The document being queried. // * @param params // * Query parameters. // * @return The list of nodes in the results. // * @throws xdb.control.QueryException // * For errors. // */ // public List<Node> query(Document doc, Map<String, String[]> params) throws QueryException; // } // // Path: src/main/java/xdb/dom/XmlParser.java // public class XmlParser extends DocumentBuilder { // private ErrorHandler eh = null; // // @Override // public DOMImplementation getDOMImplementation() { // return DocumentImpl.IMPLEMENTATION; // } // // @Override // public boolean isNamespaceAware() { // return false; // } // // @Override // public boolean isValidating() { // return false; // } // // @Override // public Document newDocument() { // throw new UnsupportedOperationException(); // } // // @Override // public void setEntityResolver(EntityResolver er) { // } // // @Override // public void setErrorHandler(ErrorHandler errorHandler) { // this.eh = errorHandler; // } // // @Override // public Document parse(InputSource is) throws SAXException, IOException { // try { // SAXParserFactory factor = SAXParserFactory.newInstance(); // SAXParser parser = factor.newSAXParser(); // XMLReader reader = parser.getXMLReader(); // if (eh != null) { // reader.setErrorHandler(eh); // } // DomHandler handler = new DomHandler(); // reader.setContentHandler(handler); // reader.parse(is); // return handler.getDoc(); // } catch (ParserConfigurationException ex) { // throw new SAXException(ex); // } // } // } // // Path: src/main/java/xdb/query/QueryInit.java // public final class QueryInit { // // private QueryInit() { // } // // /** // * Init the query from its configuration. // * // * @param configElement // * The configuration element. // * @param fileName // * The file name. // * @return The query. // */ // public static Query init(Element configElement, String fileName) { // if ("xpath-query".equals(configElement.getNodeName())) { // return XPathQuery.init(configElement); // } else if ("multi-id-query".equals(configElement.getNodeName())) { // return MultiIdQuery.init(configElement); // } else if ("multi-key-query".equals(configElement.getNodeName())) { // return MultiKeyQuery.init(configElement); // } else if ("whole-doc-query".equals(configElement.getNodeName())) { // return WholeDocQuery.init(configElement); // } else { // String msg = "Unknown query in " + fileName + " - " + configElement.getNodeName(); // throw new IllegalStateException(msg); // } // } // } // // Path: src/main/java/xdb/query/XPathQuery.java // public class XPathQuery implements Query { // private final String xpath; // // /** // * Init the query from its configuration. // * // * @param configElement // * The configuration element. // * @return The query. // */ // public static XPathQuery init(Element configElement) { // String xpath = configElement.getAttribute("xpath"); // return new XPathQuery(xpath); // } // // /** // * Constructor. // * // * @param xpath // * The xpath. // */ // public XPathQuery(String xpath) { // this.xpath = xpath; // } // // @Override // public List<Node> query(Document doc, Map<String, String[]> params) throws QueryException { // try { // return XPathEngine.query(doc, xpath, CollectionsUtil.flatten(params)); // } catch (XPathExpressionException ex) { // throw new QueryException(ex.getMessage(), ex); // } // } // }
import java.io.StringReader; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import junit.framework.TestCase; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import xdb.control.Query; import xdb.dom.XmlParser; import xdb.query.QueryInit; import xdb.query.XPathQuery;
package xdb.query; public class XPathQueryTest extends TestCase { public XPathQueryTest(String testName) { super(testName); } public void testInit() throws Exception { String xml = "<xpath-query xpath=\"id($id)\" />"; Element config = parse(xml).getDocumentElement(); Query instance = QueryInit.init(config, "test-config.xml"); assertTrue(instance instanceof XPathQuery); } public void testQuery() throws Exception { String xml = "<x><a id='1'/><a id='2'/><a id='3'/><b id='4'/><b id='5'/></x>"; Document doc = parse(xml); XPathQuery instance = new XPathQuery("id($id)"); String[] array = { "3" }; Map<String, String[]> params = Collections.singletonMap("id", array); List<Node> result = instance.query(doc, params); NodeList nodeList = doc.getDocumentElement().getChildNodes(); List<Node> expResult = new LinkedList<Node>(); expResult.add(nodeList.item(2)); assertEquals(expResult, result); } private static Document parse(String xml) throws Exception { StringReader reader = new StringReader(xml); InputSource is = new InputSource(reader);
// Path: src/main/java/xdb/control/Query.java // public interface Query { // // /** // * Execute the query. // * // * @param doc // * The document being queried. // * @param params // * Query parameters. // * @return The list of nodes in the results. // * @throws xdb.control.QueryException // * For errors. // */ // public List<Node> query(Document doc, Map<String, String[]> params) throws QueryException; // } // // Path: src/main/java/xdb/dom/XmlParser.java // public class XmlParser extends DocumentBuilder { // private ErrorHandler eh = null; // // @Override // public DOMImplementation getDOMImplementation() { // return DocumentImpl.IMPLEMENTATION; // } // // @Override // public boolean isNamespaceAware() { // return false; // } // // @Override // public boolean isValidating() { // return false; // } // // @Override // public Document newDocument() { // throw new UnsupportedOperationException(); // } // // @Override // public void setEntityResolver(EntityResolver er) { // } // // @Override // public void setErrorHandler(ErrorHandler errorHandler) { // this.eh = errorHandler; // } // // @Override // public Document parse(InputSource is) throws SAXException, IOException { // try { // SAXParserFactory factor = SAXParserFactory.newInstance(); // SAXParser parser = factor.newSAXParser(); // XMLReader reader = parser.getXMLReader(); // if (eh != null) { // reader.setErrorHandler(eh); // } // DomHandler handler = new DomHandler(); // reader.setContentHandler(handler); // reader.parse(is); // return handler.getDoc(); // } catch (ParserConfigurationException ex) { // throw new SAXException(ex); // } // } // } // // Path: src/main/java/xdb/query/QueryInit.java // public final class QueryInit { // // private QueryInit() { // } // // /** // * Init the query from its configuration. // * // * @param configElement // * The configuration element. // * @param fileName // * The file name. // * @return The query. // */ // public static Query init(Element configElement, String fileName) { // if ("xpath-query".equals(configElement.getNodeName())) { // return XPathQuery.init(configElement); // } else if ("multi-id-query".equals(configElement.getNodeName())) { // return MultiIdQuery.init(configElement); // } else if ("multi-key-query".equals(configElement.getNodeName())) { // return MultiKeyQuery.init(configElement); // } else if ("whole-doc-query".equals(configElement.getNodeName())) { // return WholeDocQuery.init(configElement); // } else { // String msg = "Unknown query in " + fileName + " - " + configElement.getNodeName(); // throw new IllegalStateException(msg); // } // } // } // // Path: src/main/java/xdb/query/XPathQuery.java // public class XPathQuery implements Query { // private final String xpath; // // /** // * Init the query from its configuration. // * // * @param configElement // * The configuration element. // * @return The query. // */ // public static XPathQuery init(Element configElement) { // String xpath = configElement.getAttribute("xpath"); // return new XPathQuery(xpath); // } // // /** // * Constructor. // * // * @param xpath // * The xpath. // */ // public XPathQuery(String xpath) { // this.xpath = xpath; // } // // @Override // public List<Node> query(Document doc, Map<String, String[]> params) throws QueryException { // try { // return XPathEngine.query(doc, xpath, CollectionsUtil.flatten(params)); // } catch (XPathExpressionException ex) { // throw new QueryException(ex.getMessage(), ex); // } // } // } // Path: src/test/java/xdb/query/XPathQueryTest.java import java.io.StringReader; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import junit.framework.TestCase; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import xdb.control.Query; import xdb.dom.XmlParser; import xdb.query.QueryInit; import xdb.query.XPathQuery; package xdb.query; public class XPathQueryTest extends TestCase { public XPathQueryTest(String testName) { super(testName); } public void testInit() throws Exception { String xml = "<xpath-query xpath=\"id($id)\" />"; Element config = parse(xml).getDocumentElement(); Query instance = QueryInit.init(config, "test-config.xml"); assertTrue(instance instanceof XPathQuery); } public void testQuery() throws Exception { String xml = "<x><a id='1'/><a id='2'/><a id='3'/><b id='4'/><b id='5'/></x>"; Document doc = parse(xml); XPathQuery instance = new XPathQuery("id($id)"); String[] array = { "3" }; Map<String, String[]> params = Collections.singletonMap("id", array); List<Node> result = instance.query(doc, params); NodeList nodeList = doc.getDocumentElement().getChildNodes(); List<Node> expResult = new LinkedList<Node>(); expResult.add(nodeList.item(2)); assertEquals(expResult, result); } private static Document parse(String xml) throws Exception { StringReader reader = new StringReader(xml); InputSource is = new InputSource(reader);
return new XmlParser().parse(is);
pfstrack/eldamo
src/test/java/xdb/query/WholeDocQueryTest.java
// Path: src/main/java/xdb/control/Query.java // public interface Query { // // /** // * Execute the query. // * // * @param doc // * The document being queried. // * @param params // * Query parameters. // * @return The list of nodes in the results. // * @throws xdb.control.QueryException // * For errors. // */ // public List<Node> query(Document doc, Map<String, String[]> params) throws QueryException; // } // // Path: src/main/java/xdb/query/QueryInit.java // public final class QueryInit { // // private QueryInit() { // } // // /** // * Init the query from its configuration. // * // * @param configElement // * The configuration element. // * @param fileName // * The file name. // * @return The query. // */ // public static Query init(Element configElement, String fileName) { // if ("xpath-query".equals(configElement.getNodeName())) { // return XPathQuery.init(configElement); // } else if ("multi-id-query".equals(configElement.getNodeName())) { // return MultiIdQuery.init(configElement); // } else if ("multi-key-query".equals(configElement.getNodeName())) { // return MultiKeyQuery.init(configElement); // } else if ("whole-doc-query".equals(configElement.getNodeName())) { // return WholeDocQuery.init(configElement); // } else { // String msg = "Unknown query in " + fileName + " - " + configElement.getNodeName(); // throw new IllegalStateException(msg); // } // } // } // // Path: src/main/java/xdb/query/WholeDocQuery.java // public class WholeDocQuery implements Query { // // /** // * Init the query from its configuration. // * // * @param configElement // * The configuration element. // * @return The query. // */ // public static WholeDocQuery init(Element configElement) { // return new WholeDocQuery(); // } // // /** Constructor. */ // public WholeDocQuery() { // } // // @Override // public List<Node> query(Document doc, Map<String, String[]> params) throws QueryException { // return Collections.singletonList((Node) doc); // } // } // // Path: src/test/java/xdb/test/TestUtil.java // public class TestUtil { // // public static Document parse(String xml) throws Exception { // StringReader reader = new StringReader(xml); // InputSource is = new InputSource(reader); // return new XmlParser().parse(is); // } // }
import java.util.Collections; import java.util.List; import junit.framework.TestCase; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import xdb.control.Query; import xdb.query.QueryInit; import xdb.query.WholeDocQuery; import xdb.test.TestUtil;
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package xdb.query; /** * * @author ps142237 */ public class WholeDocQueryTest extends TestCase { public WholeDocQueryTest(String testName) { super(testName); } public void testInit() throws Exception { String xml = "<whole-doc-query />";
// Path: src/main/java/xdb/control/Query.java // public interface Query { // // /** // * Execute the query. // * // * @param doc // * The document being queried. // * @param params // * Query parameters. // * @return The list of nodes in the results. // * @throws xdb.control.QueryException // * For errors. // */ // public List<Node> query(Document doc, Map<String, String[]> params) throws QueryException; // } // // Path: src/main/java/xdb/query/QueryInit.java // public final class QueryInit { // // private QueryInit() { // } // // /** // * Init the query from its configuration. // * // * @param configElement // * The configuration element. // * @param fileName // * The file name. // * @return The query. // */ // public static Query init(Element configElement, String fileName) { // if ("xpath-query".equals(configElement.getNodeName())) { // return XPathQuery.init(configElement); // } else if ("multi-id-query".equals(configElement.getNodeName())) { // return MultiIdQuery.init(configElement); // } else if ("multi-key-query".equals(configElement.getNodeName())) { // return MultiKeyQuery.init(configElement); // } else if ("whole-doc-query".equals(configElement.getNodeName())) { // return WholeDocQuery.init(configElement); // } else { // String msg = "Unknown query in " + fileName + " - " + configElement.getNodeName(); // throw new IllegalStateException(msg); // } // } // } // // Path: src/main/java/xdb/query/WholeDocQuery.java // public class WholeDocQuery implements Query { // // /** // * Init the query from its configuration. // * // * @param configElement // * The configuration element. // * @return The query. // */ // public static WholeDocQuery init(Element configElement) { // return new WholeDocQuery(); // } // // /** Constructor. */ // public WholeDocQuery() { // } // // @Override // public List<Node> query(Document doc, Map<String, String[]> params) throws QueryException { // return Collections.singletonList((Node) doc); // } // } // // Path: src/test/java/xdb/test/TestUtil.java // public class TestUtil { // // public static Document parse(String xml) throws Exception { // StringReader reader = new StringReader(xml); // InputSource is = new InputSource(reader); // return new XmlParser().parse(is); // } // } // Path: src/test/java/xdb/query/WholeDocQueryTest.java import java.util.Collections; import java.util.List; import junit.framework.TestCase; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import xdb.control.Query; import xdb.query.QueryInit; import xdb.query.WholeDocQuery; import xdb.test.TestUtil; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package xdb.query; /** * * @author ps142237 */ public class WholeDocQueryTest extends TestCase { public WholeDocQueryTest(String testName) { super(testName); } public void testInit() throws Exception { String xml = "<whole-doc-query />";
Element config = TestUtil.parse(xml).getDocumentElement();
pfstrack/eldamo
src/test/java/xdb/query/WholeDocQueryTest.java
// Path: src/main/java/xdb/control/Query.java // public interface Query { // // /** // * Execute the query. // * // * @param doc // * The document being queried. // * @param params // * Query parameters. // * @return The list of nodes in the results. // * @throws xdb.control.QueryException // * For errors. // */ // public List<Node> query(Document doc, Map<String, String[]> params) throws QueryException; // } // // Path: src/main/java/xdb/query/QueryInit.java // public final class QueryInit { // // private QueryInit() { // } // // /** // * Init the query from its configuration. // * // * @param configElement // * The configuration element. // * @param fileName // * The file name. // * @return The query. // */ // public static Query init(Element configElement, String fileName) { // if ("xpath-query".equals(configElement.getNodeName())) { // return XPathQuery.init(configElement); // } else if ("multi-id-query".equals(configElement.getNodeName())) { // return MultiIdQuery.init(configElement); // } else if ("multi-key-query".equals(configElement.getNodeName())) { // return MultiKeyQuery.init(configElement); // } else if ("whole-doc-query".equals(configElement.getNodeName())) { // return WholeDocQuery.init(configElement); // } else { // String msg = "Unknown query in " + fileName + " - " + configElement.getNodeName(); // throw new IllegalStateException(msg); // } // } // } // // Path: src/main/java/xdb/query/WholeDocQuery.java // public class WholeDocQuery implements Query { // // /** // * Init the query from its configuration. // * // * @param configElement // * The configuration element. // * @return The query. // */ // public static WholeDocQuery init(Element configElement) { // return new WholeDocQuery(); // } // // /** Constructor. */ // public WholeDocQuery() { // } // // @Override // public List<Node> query(Document doc, Map<String, String[]> params) throws QueryException { // return Collections.singletonList((Node) doc); // } // } // // Path: src/test/java/xdb/test/TestUtil.java // public class TestUtil { // // public static Document parse(String xml) throws Exception { // StringReader reader = new StringReader(xml); // InputSource is = new InputSource(reader); // return new XmlParser().parse(is); // } // }
import java.util.Collections; import java.util.List; import junit.framework.TestCase; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import xdb.control.Query; import xdb.query.QueryInit; import xdb.query.WholeDocQuery; import xdb.test.TestUtil;
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package xdb.query; /** * * @author ps142237 */ public class WholeDocQueryTest extends TestCase { public WholeDocQueryTest(String testName) { super(testName); } public void testInit() throws Exception { String xml = "<whole-doc-query />"; Element config = TestUtil.parse(xml).getDocumentElement();
// Path: src/main/java/xdb/control/Query.java // public interface Query { // // /** // * Execute the query. // * // * @param doc // * The document being queried. // * @param params // * Query parameters. // * @return The list of nodes in the results. // * @throws xdb.control.QueryException // * For errors. // */ // public List<Node> query(Document doc, Map<String, String[]> params) throws QueryException; // } // // Path: src/main/java/xdb/query/QueryInit.java // public final class QueryInit { // // private QueryInit() { // } // // /** // * Init the query from its configuration. // * // * @param configElement // * The configuration element. // * @param fileName // * The file name. // * @return The query. // */ // public static Query init(Element configElement, String fileName) { // if ("xpath-query".equals(configElement.getNodeName())) { // return XPathQuery.init(configElement); // } else if ("multi-id-query".equals(configElement.getNodeName())) { // return MultiIdQuery.init(configElement); // } else if ("multi-key-query".equals(configElement.getNodeName())) { // return MultiKeyQuery.init(configElement); // } else if ("whole-doc-query".equals(configElement.getNodeName())) { // return WholeDocQuery.init(configElement); // } else { // String msg = "Unknown query in " + fileName + " - " + configElement.getNodeName(); // throw new IllegalStateException(msg); // } // } // } // // Path: src/main/java/xdb/query/WholeDocQuery.java // public class WholeDocQuery implements Query { // // /** // * Init the query from its configuration. // * // * @param configElement // * The configuration element. // * @return The query. // */ // public static WholeDocQuery init(Element configElement) { // return new WholeDocQuery(); // } // // /** Constructor. */ // public WholeDocQuery() { // } // // @Override // public List<Node> query(Document doc, Map<String, String[]> params) throws QueryException { // return Collections.singletonList((Node) doc); // } // } // // Path: src/test/java/xdb/test/TestUtil.java // public class TestUtil { // // public static Document parse(String xml) throws Exception { // StringReader reader = new StringReader(xml); // InputSource is = new InputSource(reader); // return new XmlParser().parse(is); // } // } // Path: src/test/java/xdb/query/WholeDocQueryTest.java import java.util.Collections; import java.util.List; import junit.framework.TestCase; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import xdb.control.Query; import xdb.query.QueryInit; import xdb.query.WholeDocQuery; import xdb.test.TestUtil; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package xdb.query; /** * * @author ps142237 */ public class WholeDocQueryTest extends TestCase { public WholeDocQueryTest(String testName) { super(testName); } public void testInit() throws Exception { String xml = "<whole-doc-query />"; Element config = TestUtil.parse(xml).getDocumentElement();
Query instance = QueryInit.init(config, "test-config.xml");
pfstrack/eldamo
src/test/java/xdb/query/WholeDocQueryTest.java
// Path: src/main/java/xdb/control/Query.java // public interface Query { // // /** // * Execute the query. // * // * @param doc // * The document being queried. // * @param params // * Query parameters. // * @return The list of nodes in the results. // * @throws xdb.control.QueryException // * For errors. // */ // public List<Node> query(Document doc, Map<String, String[]> params) throws QueryException; // } // // Path: src/main/java/xdb/query/QueryInit.java // public final class QueryInit { // // private QueryInit() { // } // // /** // * Init the query from its configuration. // * // * @param configElement // * The configuration element. // * @param fileName // * The file name. // * @return The query. // */ // public static Query init(Element configElement, String fileName) { // if ("xpath-query".equals(configElement.getNodeName())) { // return XPathQuery.init(configElement); // } else if ("multi-id-query".equals(configElement.getNodeName())) { // return MultiIdQuery.init(configElement); // } else if ("multi-key-query".equals(configElement.getNodeName())) { // return MultiKeyQuery.init(configElement); // } else if ("whole-doc-query".equals(configElement.getNodeName())) { // return WholeDocQuery.init(configElement); // } else { // String msg = "Unknown query in " + fileName + " - " + configElement.getNodeName(); // throw new IllegalStateException(msg); // } // } // } // // Path: src/main/java/xdb/query/WholeDocQuery.java // public class WholeDocQuery implements Query { // // /** // * Init the query from its configuration. // * // * @param configElement // * The configuration element. // * @return The query. // */ // public static WholeDocQuery init(Element configElement) { // return new WholeDocQuery(); // } // // /** Constructor. */ // public WholeDocQuery() { // } // // @Override // public List<Node> query(Document doc, Map<String, String[]> params) throws QueryException { // return Collections.singletonList((Node) doc); // } // } // // Path: src/test/java/xdb/test/TestUtil.java // public class TestUtil { // // public static Document parse(String xml) throws Exception { // StringReader reader = new StringReader(xml); // InputSource is = new InputSource(reader); // return new XmlParser().parse(is); // } // }
import java.util.Collections; import java.util.List; import junit.framework.TestCase; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import xdb.control.Query; import xdb.query.QueryInit; import xdb.query.WholeDocQuery; import xdb.test.TestUtil;
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package xdb.query; /** * * @author ps142237 */ public class WholeDocQueryTest extends TestCase { public WholeDocQueryTest(String testName) { super(testName); } public void testInit() throws Exception { String xml = "<whole-doc-query />"; Element config = TestUtil.parse(xml).getDocumentElement();
// Path: src/main/java/xdb/control/Query.java // public interface Query { // // /** // * Execute the query. // * // * @param doc // * The document being queried. // * @param params // * Query parameters. // * @return The list of nodes in the results. // * @throws xdb.control.QueryException // * For errors. // */ // public List<Node> query(Document doc, Map<String, String[]> params) throws QueryException; // } // // Path: src/main/java/xdb/query/QueryInit.java // public final class QueryInit { // // private QueryInit() { // } // // /** // * Init the query from its configuration. // * // * @param configElement // * The configuration element. // * @param fileName // * The file name. // * @return The query. // */ // public static Query init(Element configElement, String fileName) { // if ("xpath-query".equals(configElement.getNodeName())) { // return XPathQuery.init(configElement); // } else if ("multi-id-query".equals(configElement.getNodeName())) { // return MultiIdQuery.init(configElement); // } else if ("multi-key-query".equals(configElement.getNodeName())) { // return MultiKeyQuery.init(configElement); // } else if ("whole-doc-query".equals(configElement.getNodeName())) { // return WholeDocQuery.init(configElement); // } else { // String msg = "Unknown query in " + fileName + " - " + configElement.getNodeName(); // throw new IllegalStateException(msg); // } // } // } // // Path: src/main/java/xdb/query/WholeDocQuery.java // public class WholeDocQuery implements Query { // // /** // * Init the query from its configuration. // * // * @param configElement // * The configuration element. // * @return The query. // */ // public static WholeDocQuery init(Element configElement) { // return new WholeDocQuery(); // } // // /** Constructor. */ // public WholeDocQuery() { // } // // @Override // public List<Node> query(Document doc, Map<String, String[]> params) throws QueryException { // return Collections.singletonList((Node) doc); // } // } // // Path: src/test/java/xdb/test/TestUtil.java // public class TestUtil { // // public static Document parse(String xml) throws Exception { // StringReader reader = new StringReader(xml); // InputSource is = new InputSource(reader); // return new XmlParser().parse(is); // } // } // Path: src/test/java/xdb/query/WholeDocQueryTest.java import java.util.Collections; import java.util.List; import junit.framework.TestCase; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import xdb.control.Query; import xdb.query.QueryInit; import xdb.query.WholeDocQuery; import xdb.test.TestUtil; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package xdb.query; /** * * @author ps142237 */ public class WholeDocQueryTest extends TestCase { public WholeDocQueryTest(String testName) { super(testName); } public void testInit() throws Exception { String xml = "<whole-doc-query />"; Element config = TestUtil.parse(xml).getDocumentElement();
Query instance = QueryInit.init(config, "test-config.xml");
pfstrack/eldamo
src/test/java/xdb/query/WholeDocQueryTest.java
// Path: src/main/java/xdb/control/Query.java // public interface Query { // // /** // * Execute the query. // * // * @param doc // * The document being queried. // * @param params // * Query parameters. // * @return The list of nodes in the results. // * @throws xdb.control.QueryException // * For errors. // */ // public List<Node> query(Document doc, Map<String, String[]> params) throws QueryException; // } // // Path: src/main/java/xdb/query/QueryInit.java // public final class QueryInit { // // private QueryInit() { // } // // /** // * Init the query from its configuration. // * // * @param configElement // * The configuration element. // * @param fileName // * The file name. // * @return The query. // */ // public static Query init(Element configElement, String fileName) { // if ("xpath-query".equals(configElement.getNodeName())) { // return XPathQuery.init(configElement); // } else if ("multi-id-query".equals(configElement.getNodeName())) { // return MultiIdQuery.init(configElement); // } else if ("multi-key-query".equals(configElement.getNodeName())) { // return MultiKeyQuery.init(configElement); // } else if ("whole-doc-query".equals(configElement.getNodeName())) { // return WholeDocQuery.init(configElement); // } else { // String msg = "Unknown query in " + fileName + " - " + configElement.getNodeName(); // throw new IllegalStateException(msg); // } // } // } // // Path: src/main/java/xdb/query/WholeDocQuery.java // public class WholeDocQuery implements Query { // // /** // * Init the query from its configuration. // * // * @param configElement // * The configuration element. // * @return The query. // */ // public static WholeDocQuery init(Element configElement) { // return new WholeDocQuery(); // } // // /** Constructor. */ // public WholeDocQuery() { // } // // @Override // public List<Node> query(Document doc, Map<String, String[]> params) throws QueryException { // return Collections.singletonList((Node) doc); // } // } // // Path: src/test/java/xdb/test/TestUtil.java // public class TestUtil { // // public static Document parse(String xml) throws Exception { // StringReader reader = new StringReader(xml); // InputSource is = new InputSource(reader); // return new XmlParser().parse(is); // } // }
import java.util.Collections; import java.util.List; import junit.framework.TestCase; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import xdb.control.Query; import xdb.query.QueryInit; import xdb.query.WholeDocQuery; import xdb.test.TestUtil;
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package xdb.query; /** * * @author ps142237 */ public class WholeDocQueryTest extends TestCase { public WholeDocQueryTest(String testName) { super(testName); } public void testInit() throws Exception { String xml = "<whole-doc-query />"; Element config = TestUtil.parse(xml).getDocumentElement(); Query instance = QueryInit.init(config, "test-config.xml");
// Path: src/main/java/xdb/control/Query.java // public interface Query { // // /** // * Execute the query. // * // * @param doc // * The document being queried. // * @param params // * Query parameters. // * @return The list of nodes in the results. // * @throws xdb.control.QueryException // * For errors. // */ // public List<Node> query(Document doc, Map<String, String[]> params) throws QueryException; // } // // Path: src/main/java/xdb/query/QueryInit.java // public final class QueryInit { // // private QueryInit() { // } // // /** // * Init the query from its configuration. // * // * @param configElement // * The configuration element. // * @param fileName // * The file name. // * @return The query. // */ // public static Query init(Element configElement, String fileName) { // if ("xpath-query".equals(configElement.getNodeName())) { // return XPathQuery.init(configElement); // } else if ("multi-id-query".equals(configElement.getNodeName())) { // return MultiIdQuery.init(configElement); // } else if ("multi-key-query".equals(configElement.getNodeName())) { // return MultiKeyQuery.init(configElement); // } else if ("whole-doc-query".equals(configElement.getNodeName())) { // return WholeDocQuery.init(configElement); // } else { // String msg = "Unknown query in " + fileName + " - " + configElement.getNodeName(); // throw new IllegalStateException(msg); // } // } // } // // Path: src/main/java/xdb/query/WholeDocQuery.java // public class WholeDocQuery implements Query { // // /** // * Init the query from its configuration. // * // * @param configElement // * The configuration element. // * @return The query. // */ // public static WholeDocQuery init(Element configElement) { // return new WholeDocQuery(); // } // // /** Constructor. */ // public WholeDocQuery() { // } // // @Override // public List<Node> query(Document doc, Map<String, String[]> params) throws QueryException { // return Collections.singletonList((Node) doc); // } // } // // Path: src/test/java/xdb/test/TestUtil.java // public class TestUtil { // // public static Document parse(String xml) throws Exception { // StringReader reader = new StringReader(xml); // InputSource is = new InputSource(reader); // return new XmlParser().parse(is); // } // } // Path: src/test/java/xdb/query/WholeDocQueryTest.java import java.util.Collections; import java.util.List; import junit.framework.TestCase; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import xdb.control.Query; import xdb.query.QueryInit; import xdb.query.WholeDocQuery; import xdb.test.TestUtil; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package xdb.query; /** * * @author ps142237 */ public class WholeDocQueryTest extends TestCase { public WholeDocQueryTest(String testName) { super(testName); } public void testInit() throws Exception { String xml = "<whole-doc-query />"; Element config = TestUtil.parse(xml).getDocumentElement(); Query instance = QueryInit.init(config, "test-config.xml");
assertTrue(instance instanceof WholeDocQuery);
pfstrack/eldamo
src/test/java/xdb/renderer/XQueryRendererTest.java
// Path: src/main/java/xdb/control/Renderer.java // public interface Renderer { // // /** // * Mime type generated by this renderer (text/html, text/xml, etc.). // * // * @return The mime type. // */ // public String getMimeType(); // // /** // * Write query results to an output stream. // * // * @param results // * The list of results to render. // * @param out // * The output stream. // * @param params // * The query parameters. // * @throws java.io.IOException // * For errors. // */ // public void render(List<Node> results, PrintWriter out, Map<String, String[]> params) // throws IOException; // } // // Path: src/main/java/xdb/renderer/RendererInit.java // public final class RendererInit { // // private RendererInit() { // } // // /** // * Init the renderer from its configuration. // * // * @param configElement // * The configuration element. // * @param fileName // * The file name. // * @return The renderer. // * @throws IOException // * For errors. // */ // public static Renderer init(Element configElement, String fileName) throws IOException { // if ("xquery-renderer".equals(configElement.getNodeName())) { // return XQueryRenderer.init(configElement); // } else if ("xsl-renderer".equals(configElement.getNodeName())) { // return XslRenderer.init(configElement); // } else { // String msg = "Unknown renderer in " + fileName + " - " + configElement.getNodeName(); // throw new IllegalStateException(msg); // } // } // } // // Path: src/main/java/xdb/renderer/XQueryRenderer.java // public class XQueryRenderer implements Renderer { // private final String xquery; // private final String mimeType; // private final String outputType; // // /** // * Initialize the renderer from its configuration. // * // * @param configElement // * The configuration element. // * @return The renderer. // * @throws IOException // */ // public static XQueryRenderer init(Element configElement) throws IOException { // String mimeType = configElement.getAttribute("mime-type"); // String xquery = configElement.getTextContent(); // String file = configElement.getAttribute("file"); // if (file != null) { // String path = QueryConfigManager.getConfigRoot() + "/" + file; // xquery = FileUtil.loadText(new File(path)); // } // return new XQueryRenderer(xquery, mimeType); // } // // /** // * Constructor. // * // * @param xquery // * The query. // * @param mimeType // * The output mime type. // */ // public XQueryRenderer(String xquery, String mimeType) { // this.xquery = xquery; // this.mimeType = mimeType; // if (mimeType.endsWith("xml")) { // outputType = "xml"; // } else if (mimeType.endsWith("html")) { // outputType = "html"; // } else { // outputType = "text"; // } // } // // @Override // public String getMimeType() { // return this.mimeType; // } // // @Override // public void render(List<Node> results, PrintWriter out, Map<String, String[]> params) throws IOException { // try { // Map<String, String> flatMap = CollectionsUtil.flatten(params); // XQueryEngine.query(results.get(0), xquery, flatMap, out, outputType); // } catch (Exception ex) { // throw new IOException(ex.getMessage()); // } // } // } // // Path: src/test/java/xdb/test/TestUtil.java // public class TestUtil { // // public static Document parse(String xml) throws Exception { // StringReader reader = new StringReader(xml); // InputSource is = new InputSource(reader); // return new XmlParser().parse(is); // } // }
import java.io.PrintWriter; import java.io.StringWriter; import java.util.Collections; import java.util.List; import java.util.Map; import junit.framework.TestCase; import org.w3c.dom.Element; import xdb.control.Renderer; import xdb.renderer.RendererInit; import xdb.renderer.XQueryRenderer; import xdb.test.TestUtil;
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package xdb.renderer; /** * * @author ps142237 */ public class XQueryRendererTest extends TestCase { public XQueryRendererTest(String testName) { super(testName); } public void testInit() throws Exception {
// Path: src/main/java/xdb/control/Renderer.java // public interface Renderer { // // /** // * Mime type generated by this renderer (text/html, text/xml, etc.). // * // * @return The mime type. // */ // public String getMimeType(); // // /** // * Write query results to an output stream. // * // * @param results // * The list of results to render. // * @param out // * The output stream. // * @param params // * The query parameters. // * @throws java.io.IOException // * For errors. // */ // public void render(List<Node> results, PrintWriter out, Map<String, String[]> params) // throws IOException; // } // // Path: src/main/java/xdb/renderer/RendererInit.java // public final class RendererInit { // // private RendererInit() { // } // // /** // * Init the renderer from its configuration. // * // * @param configElement // * The configuration element. // * @param fileName // * The file name. // * @return The renderer. // * @throws IOException // * For errors. // */ // public static Renderer init(Element configElement, String fileName) throws IOException { // if ("xquery-renderer".equals(configElement.getNodeName())) { // return XQueryRenderer.init(configElement); // } else if ("xsl-renderer".equals(configElement.getNodeName())) { // return XslRenderer.init(configElement); // } else { // String msg = "Unknown renderer in " + fileName + " - " + configElement.getNodeName(); // throw new IllegalStateException(msg); // } // } // } // // Path: src/main/java/xdb/renderer/XQueryRenderer.java // public class XQueryRenderer implements Renderer { // private final String xquery; // private final String mimeType; // private final String outputType; // // /** // * Initialize the renderer from its configuration. // * // * @param configElement // * The configuration element. // * @return The renderer. // * @throws IOException // */ // public static XQueryRenderer init(Element configElement) throws IOException { // String mimeType = configElement.getAttribute("mime-type"); // String xquery = configElement.getTextContent(); // String file = configElement.getAttribute("file"); // if (file != null) { // String path = QueryConfigManager.getConfigRoot() + "/" + file; // xquery = FileUtil.loadText(new File(path)); // } // return new XQueryRenderer(xquery, mimeType); // } // // /** // * Constructor. // * // * @param xquery // * The query. // * @param mimeType // * The output mime type. // */ // public XQueryRenderer(String xquery, String mimeType) { // this.xquery = xquery; // this.mimeType = mimeType; // if (mimeType.endsWith("xml")) { // outputType = "xml"; // } else if (mimeType.endsWith("html")) { // outputType = "html"; // } else { // outputType = "text"; // } // } // // @Override // public String getMimeType() { // return this.mimeType; // } // // @Override // public void render(List<Node> results, PrintWriter out, Map<String, String[]> params) throws IOException { // try { // Map<String, String> flatMap = CollectionsUtil.flatten(params); // XQueryEngine.query(results.get(0), xquery, flatMap, out, outputType); // } catch (Exception ex) { // throw new IOException(ex.getMessage()); // } // } // } // // Path: src/test/java/xdb/test/TestUtil.java // public class TestUtil { // // public static Document parse(String xml) throws Exception { // StringReader reader = new StringReader(xml); // InputSource is = new InputSource(reader); // return new XmlParser().parse(is); // } // } // Path: src/test/java/xdb/renderer/XQueryRendererTest.java import java.io.PrintWriter; import java.io.StringWriter; import java.util.Collections; import java.util.List; import java.util.Map; import junit.framework.TestCase; import org.w3c.dom.Element; import xdb.control.Renderer; import xdb.renderer.RendererInit; import xdb.renderer.XQueryRenderer; import xdb.test.TestUtil; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package xdb.renderer; /** * * @author ps142237 */ public class XQueryRendererTest extends TestCase { public XQueryRendererTest(String testName) { super(testName); } public void testInit() throws Exception {
Renderer renderer = initRenderer();
pfstrack/eldamo
src/test/java/xdb/renderer/XQueryRendererTest.java
// Path: src/main/java/xdb/control/Renderer.java // public interface Renderer { // // /** // * Mime type generated by this renderer (text/html, text/xml, etc.). // * // * @return The mime type. // */ // public String getMimeType(); // // /** // * Write query results to an output stream. // * // * @param results // * The list of results to render. // * @param out // * The output stream. // * @param params // * The query parameters. // * @throws java.io.IOException // * For errors. // */ // public void render(List<Node> results, PrintWriter out, Map<String, String[]> params) // throws IOException; // } // // Path: src/main/java/xdb/renderer/RendererInit.java // public final class RendererInit { // // private RendererInit() { // } // // /** // * Init the renderer from its configuration. // * // * @param configElement // * The configuration element. // * @param fileName // * The file name. // * @return The renderer. // * @throws IOException // * For errors. // */ // public static Renderer init(Element configElement, String fileName) throws IOException { // if ("xquery-renderer".equals(configElement.getNodeName())) { // return XQueryRenderer.init(configElement); // } else if ("xsl-renderer".equals(configElement.getNodeName())) { // return XslRenderer.init(configElement); // } else { // String msg = "Unknown renderer in " + fileName + " - " + configElement.getNodeName(); // throw new IllegalStateException(msg); // } // } // } // // Path: src/main/java/xdb/renderer/XQueryRenderer.java // public class XQueryRenderer implements Renderer { // private final String xquery; // private final String mimeType; // private final String outputType; // // /** // * Initialize the renderer from its configuration. // * // * @param configElement // * The configuration element. // * @return The renderer. // * @throws IOException // */ // public static XQueryRenderer init(Element configElement) throws IOException { // String mimeType = configElement.getAttribute("mime-type"); // String xquery = configElement.getTextContent(); // String file = configElement.getAttribute("file"); // if (file != null) { // String path = QueryConfigManager.getConfigRoot() + "/" + file; // xquery = FileUtil.loadText(new File(path)); // } // return new XQueryRenderer(xquery, mimeType); // } // // /** // * Constructor. // * // * @param xquery // * The query. // * @param mimeType // * The output mime type. // */ // public XQueryRenderer(String xquery, String mimeType) { // this.xquery = xquery; // this.mimeType = mimeType; // if (mimeType.endsWith("xml")) { // outputType = "xml"; // } else if (mimeType.endsWith("html")) { // outputType = "html"; // } else { // outputType = "text"; // } // } // // @Override // public String getMimeType() { // return this.mimeType; // } // // @Override // public void render(List<Node> results, PrintWriter out, Map<String, String[]> params) throws IOException { // try { // Map<String, String> flatMap = CollectionsUtil.flatten(params); // XQueryEngine.query(results.get(0), xquery, flatMap, out, outputType); // } catch (Exception ex) { // throw new IOException(ex.getMessage()); // } // } // } // // Path: src/test/java/xdb/test/TestUtil.java // public class TestUtil { // // public static Document parse(String xml) throws Exception { // StringReader reader = new StringReader(xml); // InputSource is = new InputSource(reader); // return new XmlParser().parse(is); // } // }
import java.io.PrintWriter; import java.io.StringWriter; import java.util.Collections; import java.util.List; import java.util.Map; import junit.framework.TestCase; import org.w3c.dom.Element; import xdb.control.Renderer; import xdb.renderer.RendererInit; import xdb.renderer.XQueryRenderer; import xdb.test.TestUtil;
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package xdb.renderer; /** * * @author ps142237 */ public class XQueryRendererTest extends TestCase { public XQueryRendererTest(String testName) { super(testName); } public void testInit() throws Exception { Renderer renderer = initRenderer();
// Path: src/main/java/xdb/control/Renderer.java // public interface Renderer { // // /** // * Mime type generated by this renderer (text/html, text/xml, etc.). // * // * @return The mime type. // */ // public String getMimeType(); // // /** // * Write query results to an output stream. // * // * @param results // * The list of results to render. // * @param out // * The output stream. // * @param params // * The query parameters. // * @throws java.io.IOException // * For errors. // */ // public void render(List<Node> results, PrintWriter out, Map<String, String[]> params) // throws IOException; // } // // Path: src/main/java/xdb/renderer/RendererInit.java // public final class RendererInit { // // private RendererInit() { // } // // /** // * Init the renderer from its configuration. // * // * @param configElement // * The configuration element. // * @param fileName // * The file name. // * @return The renderer. // * @throws IOException // * For errors. // */ // public static Renderer init(Element configElement, String fileName) throws IOException { // if ("xquery-renderer".equals(configElement.getNodeName())) { // return XQueryRenderer.init(configElement); // } else if ("xsl-renderer".equals(configElement.getNodeName())) { // return XslRenderer.init(configElement); // } else { // String msg = "Unknown renderer in " + fileName + " - " + configElement.getNodeName(); // throw new IllegalStateException(msg); // } // } // } // // Path: src/main/java/xdb/renderer/XQueryRenderer.java // public class XQueryRenderer implements Renderer { // private final String xquery; // private final String mimeType; // private final String outputType; // // /** // * Initialize the renderer from its configuration. // * // * @param configElement // * The configuration element. // * @return The renderer. // * @throws IOException // */ // public static XQueryRenderer init(Element configElement) throws IOException { // String mimeType = configElement.getAttribute("mime-type"); // String xquery = configElement.getTextContent(); // String file = configElement.getAttribute("file"); // if (file != null) { // String path = QueryConfigManager.getConfigRoot() + "/" + file; // xquery = FileUtil.loadText(new File(path)); // } // return new XQueryRenderer(xquery, mimeType); // } // // /** // * Constructor. // * // * @param xquery // * The query. // * @param mimeType // * The output mime type. // */ // public XQueryRenderer(String xquery, String mimeType) { // this.xquery = xquery; // this.mimeType = mimeType; // if (mimeType.endsWith("xml")) { // outputType = "xml"; // } else if (mimeType.endsWith("html")) { // outputType = "html"; // } else { // outputType = "text"; // } // } // // @Override // public String getMimeType() { // return this.mimeType; // } // // @Override // public void render(List<Node> results, PrintWriter out, Map<String, String[]> params) throws IOException { // try { // Map<String, String> flatMap = CollectionsUtil.flatten(params); // XQueryEngine.query(results.get(0), xquery, flatMap, out, outputType); // } catch (Exception ex) { // throw new IOException(ex.getMessage()); // } // } // } // // Path: src/test/java/xdb/test/TestUtil.java // public class TestUtil { // // public static Document parse(String xml) throws Exception { // StringReader reader = new StringReader(xml); // InputSource is = new InputSource(reader); // return new XmlParser().parse(is); // } // } // Path: src/test/java/xdb/renderer/XQueryRendererTest.java import java.io.PrintWriter; import java.io.StringWriter; import java.util.Collections; import java.util.List; import java.util.Map; import junit.framework.TestCase; import org.w3c.dom.Element; import xdb.control.Renderer; import xdb.renderer.RendererInit; import xdb.renderer.XQueryRenderer; import xdb.test.TestUtil; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package xdb.renderer; /** * * @author ps142237 */ public class XQueryRendererTest extends TestCase { public XQueryRendererTest(String testName) { super(testName); } public void testInit() throws Exception { Renderer renderer = initRenderer();
assertTrue(renderer instanceof XQueryRenderer);
pfstrack/eldamo
src/test/java/xdb/renderer/XQueryRendererTest.java
// Path: src/main/java/xdb/control/Renderer.java // public interface Renderer { // // /** // * Mime type generated by this renderer (text/html, text/xml, etc.). // * // * @return The mime type. // */ // public String getMimeType(); // // /** // * Write query results to an output stream. // * // * @param results // * The list of results to render. // * @param out // * The output stream. // * @param params // * The query parameters. // * @throws java.io.IOException // * For errors. // */ // public void render(List<Node> results, PrintWriter out, Map<String, String[]> params) // throws IOException; // } // // Path: src/main/java/xdb/renderer/RendererInit.java // public final class RendererInit { // // private RendererInit() { // } // // /** // * Init the renderer from its configuration. // * // * @param configElement // * The configuration element. // * @param fileName // * The file name. // * @return The renderer. // * @throws IOException // * For errors. // */ // public static Renderer init(Element configElement, String fileName) throws IOException { // if ("xquery-renderer".equals(configElement.getNodeName())) { // return XQueryRenderer.init(configElement); // } else if ("xsl-renderer".equals(configElement.getNodeName())) { // return XslRenderer.init(configElement); // } else { // String msg = "Unknown renderer in " + fileName + " - " + configElement.getNodeName(); // throw new IllegalStateException(msg); // } // } // } // // Path: src/main/java/xdb/renderer/XQueryRenderer.java // public class XQueryRenderer implements Renderer { // private final String xquery; // private final String mimeType; // private final String outputType; // // /** // * Initialize the renderer from its configuration. // * // * @param configElement // * The configuration element. // * @return The renderer. // * @throws IOException // */ // public static XQueryRenderer init(Element configElement) throws IOException { // String mimeType = configElement.getAttribute("mime-type"); // String xquery = configElement.getTextContent(); // String file = configElement.getAttribute("file"); // if (file != null) { // String path = QueryConfigManager.getConfigRoot() + "/" + file; // xquery = FileUtil.loadText(new File(path)); // } // return new XQueryRenderer(xquery, mimeType); // } // // /** // * Constructor. // * // * @param xquery // * The query. // * @param mimeType // * The output mime type. // */ // public XQueryRenderer(String xquery, String mimeType) { // this.xquery = xquery; // this.mimeType = mimeType; // if (mimeType.endsWith("xml")) { // outputType = "xml"; // } else if (mimeType.endsWith("html")) { // outputType = "html"; // } else { // outputType = "text"; // } // } // // @Override // public String getMimeType() { // return this.mimeType; // } // // @Override // public void render(List<Node> results, PrintWriter out, Map<String, String[]> params) throws IOException { // try { // Map<String, String> flatMap = CollectionsUtil.flatten(params); // XQueryEngine.query(results.get(0), xquery, flatMap, out, outputType); // } catch (Exception ex) { // throw new IOException(ex.getMessage()); // } // } // } // // Path: src/test/java/xdb/test/TestUtil.java // public class TestUtil { // // public static Document parse(String xml) throws Exception { // StringReader reader = new StringReader(xml); // InputSource is = new InputSource(reader); // return new XmlParser().parse(is); // } // }
import java.io.PrintWriter; import java.io.StringWriter; import java.util.Collections; import java.util.List; import java.util.Map; import junit.framework.TestCase; import org.w3c.dom.Element; import xdb.control.Renderer; import xdb.renderer.RendererInit; import xdb.renderer.XQueryRenderer; import xdb.test.TestUtil;
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package xdb.renderer; /** * * @author ps142237 */ public class XQueryRendererTest extends TestCase { public XQueryRendererTest(String testName) { super(testName); } public void testInit() throws Exception { Renderer renderer = initRenderer(); assertTrue(renderer instanceof XQueryRenderer); } public void testGetMimeType() throws Exception { Renderer instance = initRenderer(); String expResult = "text/plain"; String result = instance.getMimeType(); assertEquals(expResult, result); } @SuppressWarnings({ "rawtypes", "unchecked" }) public void testRender() throws Exception { String xml = "<parts>"; xml += "<part id='1' description='Part 1' />"; xml += "<part id='2' description='Part 2 with &quot;' />"; xml += "</parts>";
// Path: src/main/java/xdb/control/Renderer.java // public interface Renderer { // // /** // * Mime type generated by this renderer (text/html, text/xml, etc.). // * // * @return The mime type. // */ // public String getMimeType(); // // /** // * Write query results to an output stream. // * // * @param results // * The list of results to render. // * @param out // * The output stream. // * @param params // * The query parameters. // * @throws java.io.IOException // * For errors. // */ // public void render(List<Node> results, PrintWriter out, Map<String, String[]> params) // throws IOException; // } // // Path: src/main/java/xdb/renderer/RendererInit.java // public final class RendererInit { // // private RendererInit() { // } // // /** // * Init the renderer from its configuration. // * // * @param configElement // * The configuration element. // * @param fileName // * The file name. // * @return The renderer. // * @throws IOException // * For errors. // */ // public static Renderer init(Element configElement, String fileName) throws IOException { // if ("xquery-renderer".equals(configElement.getNodeName())) { // return XQueryRenderer.init(configElement); // } else if ("xsl-renderer".equals(configElement.getNodeName())) { // return XslRenderer.init(configElement); // } else { // String msg = "Unknown renderer in " + fileName + " - " + configElement.getNodeName(); // throw new IllegalStateException(msg); // } // } // } // // Path: src/main/java/xdb/renderer/XQueryRenderer.java // public class XQueryRenderer implements Renderer { // private final String xquery; // private final String mimeType; // private final String outputType; // // /** // * Initialize the renderer from its configuration. // * // * @param configElement // * The configuration element. // * @return The renderer. // * @throws IOException // */ // public static XQueryRenderer init(Element configElement) throws IOException { // String mimeType = configElement.getAttribute("mime-type"); // String xquery = configElement.getTextContent(); // String file = configElement.getAttribute("file"); // if (file != null) { // String path = QueryConfigManager.getConfigRoot() + "/" + file; // xquery = FileUtil.loadText(new File(path)); // } // return new XQueryRenderer(xquery, mimeType); // } // // /** // * Constructor. // * // * @param xquery // * The query. // * @param mimeType // * The output mime type. // */ // public XQueryRenderer(String xquery, String mimeType) { // this.xquery = xquery; // this.mimeType = mimeType; // if (mimeType.endsWith("xml")) { // outputType = "xml"; // } else if (mimeType.endsWith("html")) { // outputType = "html"; // } else { // outputType = "text"; // } // } // // @Override // public String getMimeType() { // return this.mimeType; // } // // @Override // public void render(List<Node> results, PrintWriter out, Map<String, String[]> params) throws IOException { // try { // Map<String, String> flatMap = CollectionsUtil.flatten(params); // XQueryEngine.query(results.get(0), xquery, flatMap, out, outputType); // } catch (Exception ex) { // throw new IOException(ex.getMessage()); // } // } // } // // Path: src/test/java/xdb/test/TestUtil.java // public class TestUtil { // // public static Document parse(String xml) throws Exception { // StringReader reader = new StringReader(xml); // InputSource is = new InputSource(reader); // return new XmlParser().parse(is); // } // } // Path: src/test/java/xdb/renderer/XQueryRendererTest.java import java.io.PrintWriter; import java.io.StringWriter; import java.util.Collections; import java.util.List; import java.util.Map; import junit.framework.TestCase; import org.w3c.dom.Element; import xdb.control.Renderer; import xdb.renderer.RendererInit; import xdb.renderer.XQueryRenderer; import xdb.test.TestUtil; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package xdb.renderer; /** * * @author ps142237 */ public class XQueryRendererTest extends TestCase { public XQueryRendererTest(String testName) { super(testName); } public void testInit() throws Exception { Renderer renderer = initRenderer(); assertTrue(renderer instanceof XQueryRenderer); } public void testGetMimeType() throws Exception { Renderer instance = initRenderer(); String expResult = "text/plain"; String result = instance.getMimeType(); assertEquals(expResult, result); } @SuppressWarnings({ "rawtypes", "unchecked" }) public void testRender() throws Exception { String xml = "<parts>"; xml += "<part id='1' description='Part 1' />"; xml += "<part id='2' description='Part 2 with &quot;' />"; xml += "</parts>";
List results = Collections.singletonList(TestUtil.parse(xml));
pfstrack/eldamo
src/test/java/xdb/renderer/XQueryRendererTest.java
// Path: src/main/java/xdb/control/Renderer.java // public interface Renderer { // // /** // * Mime type generated by this renderer (text/html, text/xml, etc.). // * // * @return The mime type. // */ // public String getMimeType(); // // /** // * Write query results to an output stream. // * // * @param results // * The list of results to render. // * @param out // * The output stream. // * @param params // * The query parameters. // * @throws java.io.IOException // * For errors. // */ // public void render(List<Node> results, PrintWriter out, Map<String, String[]> params) // throws IOException; // } // // Path: src/main/java/xdb/renderer/RendererInit.java // public final class RendererInit { // // private RendererInit() { // } // // /** // * Init the renderer from its configuration. // * // * @param configElement // * The configuration element. // * @param fileName // * The file name. // * @return The renderer. // * @throws IOException // * For errors. // */ // public static Renderer init(Element configElement, String fileName) throws IOException { // if ("xquery-renderer".equals(configElement.getNodeName())) { // return XQueryRenderer.init(configElement); // } else if ("xsl-renderer".equals(configElement.getNodeName())) { // return XslRenderer.init(configElement); // } else { // String msg = "Unknown renderer in " + fileName + " - " + configElement.getNodeName(); // throw new IllegalStateException(msg); // } // } // } // // Path: src/main/java/xdb/renderer/XQueryRenderer.java // public class XQueryRenderer implements Renderer { // private final String xquery; // private final String mimeType; // private final String outputType; // // /** // * Initialize the renderer from its configuration. // * // * @param configElement // * The configuration element. // * @return The renderer. // * @throws IOException // */ // public static XQueryRenderer init(Element configElement) throws IOException { // String mimeType = configElement.getAttribute("mime-type"); // String xquery = configElement.getTextContent(); // String file = configElement.getAttribute("file"); // if (file != null) { // String path = QueryConfigManager.getConfigRoot() + "/" + file; // xquery = FileUtil.loadText(new File(path)); // } // return new XQueryRenderer(xquery, mimeType); // } // // /** // * Constructor. // * // * @param xquery // * The query. // * @param mimeType // * The output mime type. // */ // public XQueryRenderer(String xquery, String mimeType) { // this.xquery = xquery; // this.mimeType = mimeType; // if (mimeType.endsWith("xml")) { // outputType = "xml"; // } else if (mimeType.endsWith("html")) { // outputType = "html"; // } else { // outputType = "text"; // } // } // // @Override // public String getMimeType() { // return this.mimeType; // } // // @Override // public void render(List<Node> results, PrintWriter out, Map<String, String[]> params) throws IOException { // try { // Map<String, String> flatMap = CollectionsUtil.flatten(params); // XQueryEngine.query(results.get(0), xquery, flatMap, out, outputType); // } catch (Exception ex) { // throw new IOException(ex.getMessage()); // } // } // } // // Path: src/test/java/xdb/test/TestUtil.java // public class TestUtil { // // public static Document parse(String xml) throws Exception { // StringReader reader = new StringReader(xml); // InputSource is = new InputSource(reader); // return new XmlParser().parse(is); // } // }
import java.io.PrintWriter; import java.io.StringWriter; import java.util.Collections; import java.util.List; import java.util.Map; import junit.framework.TestCase; import org.w3c.dom.Element; import xdb.control.Renderer; import xdb.renderer.RendererInit; import xdb.renderer.XQueryRenderer; import xdb.test.TestUtil;
PrintWriter out = new PrintWriter(sw); Map<String, String[]> params = Collections.emptyMap(); Renderer instance = initRenderer(); instance.render(results, out, params); String expected = "2"; assertEquals(expected, sw.toString()); } @SuppressWarnings({ "rawtypes", "unchecked" }) public void testBogusRender() throws Exception { String xml = "<parts>"; xml += "<part id='1' description='Part 1' />"; xml += "<part id='2' description='Part 2 with &quot;' />"; xml += "</parts>"; List results = Collections.singletonList(TestUtil.parse(xml)); StringWriter sw = new StringWriter(); PrintWriter out = new PrintWriter(sw); Map<String, String[]> params = Collections.emptyMap(); Renderer instance = initBogusRenderer(); try { instance.render(results, out, params); fail("Should throw an error"); } catch (Exception ex) { // Expected } } private Renderer initRenderer() throws Exception { String xml = "<xquery-renderer content-type='txt' mime-type='text/plain'>count(/*/part)</xquery-renderer>"; Element configElement = TestUtil.parse(xml).getDocumentElement();
// Path: src/main/java/xdb/control/Renderer.java // public interface Renderer { // // /** // * Mime type generated by this renderer (text/html, text/xml, etc.). // * // * @return The mime type. // */ // public String getMimeType(); // // /** // * Write query results to an output stream. // * // * @param results // * The list of results to render. // * @param out // * The output stream. // * @param params // * The query parameters. // * @throws java.io.IOException // * For errors. // */ // public void render(List<Node> results, PrintWriter out, Map<String, String[]> params) // throws IOException; // } // // Path: src/main/java/xdb/renderer/RendererInit.java // public final class RendererInit { // // private RendererInit() { // } // // /** // * Init the renderer from its configuration. // * // * @param configElement // * The configuration element. // * @param fileName // * The file name. // * @return The renderer. // * @throws IOException // * For errors. // */ // public static Renderer init(Element configElement, String fileName) throws IOException { // if ("xquery-renderer".equals(configElement.getNodeName())) { // return XQueryRenderer.init(configElement); // } else if ("xsl-renderer".equals(configElement.getNodeName())) { // return XslRenderer.init(configElement); // } else { // String msg = "Unknown renderer in " + fileName + " - " + configElement.getNodeName(); // throw new IllegalStateException(msg); // } // } // } // // Path: src/main/java/xdb/renderer/XQueryRenderer.java // public class XQueryRenderer implements Renderer { // private final String xquery; // private final String mimeType; // private final String outputType; // // /** // * Initialize the renderer from its configuration. // * // * @param configElement // * The configuration element. // * @return The renderer. // * @throws IOException // */ // public static XQueryRenderer init(Element configElement) throws IOException { // String mimeType = configElement.getAttribute("mime-type"); // String xquery = configElement.getTextContent(); // String file = configElement.getAttribute("file"); // if (file != null) { // String path = QueryConfigManager.getConfigRoot() + "/" + file; // xquery = FileUtil.loadText(new File(path)); // } // return new XQueryRenderer(xquery, mimeType); // } // // /** // * Constructor. // * // * @param xquery // * The query. // * @param mimeType // * The output mime type. // */ // public XQueryRenderer(String xquery, String mimeType) { // this.xquery = xquery; // this.mimeType = mimeType; // if (mimeType.endsWith("xml")) { // outputType = "xml"; // } else if (mimeType.endsWith("html")) { // outputType = "html"; // } else { // outputType = "text"; // } // } // // @Override // public String getMimeType() { // return this.mimeType; // } // // @Override // public void render(List<Node> results, PrintWriter out, Map<String, String[]> params) throws IOException { // try { // Map<String, String> flatMap = CollectionsUtil.flatten(params); // XQueryEngine.query(results.get(0), xquery, flatMap, out, outputType); // } catch (Exception ex) { // throw new IOException(ex.getMessage()); // } // } // } // // Path: src/test/java/xdb/test/TestUtil.java // public class TestUtil { // // public static Document parse(String xml) throws Exception { // StringReader reader = new StringReader(xml); // InputSource is = new InputSource(reader); // return new XmlParser().parse(is); // } // } // Path: src/test/java/xdb/renderer/XQueryRendererTest.java import java.io.PrintWriter; import java.io.StringWriter; import java.util.Collections; import java.util.List; import java.util.Map; import junit.framework.TestCase; import org.w3c.dom.Element; import xdb.control.Renderer; import xdb.renderer.RendererInit; import xdb.renderer.XQueryRenderer; import xdb.test.TestUtil; PrintWriter out = new PrintWriter(sw); Map<String, String[]> params = Collections.emptyMap(); Renderer instance = initRenderer(); instance.render(results, out, params); String expected = "2"; assertEquals(expected, sw.toString()); } @SuppressWarnings({ "rawtypes", "unchecked" }) public void testBogusRender() throws Exception { String xml = "<parts>"; xml += "<part id='1' description='Part 1' />"; xml += "<part id='2' description='Part 2 with &quot;' />"; xml += "</parts>"; List results = Collections.singletonList(TestUtil.parse(xml)); StringWriter sw = new StringWriter(); PrintWriter out = new PrintWriter(sw); Map<String, String[]> params = Collections.emptyMap(); Renderer instance = initBogusRenderer(); try { instance.render(results, out, params); fail("Should throw an error"); } catch (Exception ex) { // Expected } } private Renderer initRenderer() throws Exception { String xml = "<xquery-renderer content-type='txt' mime-type='text/plain'>count(/*/part)</xquery-renderer>"; Element configElement = TestUtil.parse(xml).getDocumentElement();
Renderer renderer = RendererInit.init(configElement, "test-config.xml");
pfstrack/eldamo
src/main/java/xdb/query/MultiIdQuery.java
// Path: src/main/java/xdb/control/Query.java // public interface Query { // // /** // * Execute the query. // * // * @param doc // * The document being queried. // * @param params // * Query parameters. // * @return The list of nodes in the results. // * @throws xdb.control.QueryException // * For errors. // */ // public List<Node> query(Document doc, Map<String, String[]> params) throws QueryException; // } // // Path: src/main/java/xdb/control/QueryException.java // @SuppressWarnings("serial") // public class QueryException extends Exception { // // /** // * Constructor. // * // * @param message // * The error message. // * @param rootCause // * The true cause of the exception. // */ // public QueryException(String message, Exception rootCause) { // super(message, rootCause); // } // }
import java.util.LinkedList; import java.util.List; import java.util.Map; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import xdb.control.Query; import xdb.control.QueryException;
package xdb.query; /** * An optimized query processor to retrieve entity elements using their ids. This query accepts * multiple "id" parameters and returns the list of nodes matching those ids. */ public class MultiIdQuery implements Query { private final String entityType; /** * Init the query from its configuration. * * @param configElement * The configuration element. * @return The query. */ public static MultiIdQuery init(Element configElement) { String entityType = configElement.getAttribute("entity-type"); return new MultiIdQuery(entityType); } /** * Constructor. * * @param entityType * The entity type to be retrieve, null for any entity. */ public MultiIdQuery(String entityType) { this.entityType = entityType; } @Override
// Path: src/main/java/xdb/control/Query.java // public interface Query { // // /** // * Execute the query. // * // * @param doc // * The document being queried. // * @param params // * Query parameters. // * @return The list of nodes in the results. // * @throws xdb.control.QueryException // * For errors. // */ // public List<Node> query(Document doc, Map<String, String[]> params) throws QueryException; // } // // Path: src/main/java/xdb/control/QueryException.java // @SuppressWarnings("serial") // public class QueryException extends Exception { // // /** // * Constructor. // * // * @param message // * The error message. // * @param rootCause // * The true cause of the exception. // */ // public QueryException(String message, Exception rootCause) { // super(message, rootCause); // } // } // Path: src/main/java/xdb/query/MultiIdQuery.java import java.util.LinkedList; import java.util.List; import java.util.Map; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import xdb.control.Query; import xdb.control.QueryException; package xdb.query; /** * An optimized query processor to retrieve entity elements using their ids. This query accepts * multiple "id" parameters and returns the list of nodes matching those ids. */ public class MultiIdQuery implements Query { private final String entityType; /** * Init the query from its configuration. * * @param configElement * The configuration element. * @return The query. */ public static MultiIdQuery init(Element configElement) { String entityType = configElement.getAttribute("entity-type"); return new MultiIdQuery(entityType); } /** * Constructor. * * @param entityType * The entity type to be retrieve, null for any entity. */ public MultiIdQuery(String entityType) { this.entityType = entityType; } @Override
public List<Node> query(Document doc, Map<String, String[]> params) throws QueryException {
pfstrack/eldamo
src/test/java/xdb/query/QueryInitTest.java
// Path: src/test/java/xdb/test/TestUtil.java // public class TestUtil { // // public static Document parse(String xml) throws Exception { // StringReader reader = new StringReader(xml); // InputSource is = new InputSource(reader); // return new XmlParser().parse(is); // } // }
import org.w3c.dom.Element; import xdb.test.TestUtil; import junit.framework.TestCase;
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package xdb.query; /** * * @author ps142237 */ public class QueryInitTest extends TestCase { public QueryInitTest(String testName) { super(testName); } public void testInit() throws Exception { String xml = "<bogus-query />";
// Path: src/test/java/xdb/test/TestUtil.java // public class TestUtil { // // public static Document parse(String xml) throws Exception { // StringReader reader = new StringReader(xml); // InputSource is = new InputSource(reader); // return new XmlParser().parse(is); // } // } // Path: src/test/java/xdb/query/QueryInitTest.java import org.w3c.dom.Element; import xdb.test.TestUtil; import junit.framework.TestCase; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package xdb.query; /** * * @author ps142237 */ public class QueryInitTest extends TestCase { public QueryInitTest(String testName) { super(testName); } public void testInit() throws Exception { String xml = "<bogus-query />";
Element config = TestUtil.parse(xml).getDocumentElement();
mtimmerm/dfalex
test/com/nobigsoftware/dfalex/BuilderCacheTest.java
// Path: src/com/nobigsoftware/util/BuilderCache.java // public interface BuilderCache // { // /** // * Get a cached item. // * // * @param key The key used to identify the item. The key uniquely identifies all // * of the source information that will go into building the item if this call fails // * to retrieve a cached version. Typically this will be a cryptographic hash of // * the serialized form of that information. // * // * @return the item that was previously cached under the key, or null if no such item // * can be retrieved. // */ // Serializable getCachedItem(String key); // // /** // * This method may be called when an item is built, providing an opportunity to // * cache it. // * // * @param key The key that will be used to identify the item in future calls to {@link #getCachedItem(String)}. // * Only letters, digits, and underscores are valid in keys, and key length is limited to 32 characters. // * The behaviour of this method for invalid keys is undefined. // * <P> // * Keys that differ only by case may or may not be considered equal by this class. // * @param item The item to cache, if desired // */ // void maybeCacheItem(String key, Serializable item); // }
import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.EnumSet; import java.util.HashMap; import java.util.Map; import org.junit.Assert; import org.junit.Test; import com.nobigsoftware.util.BuilderCache;
package com.nobigsoftware.dfalex; public class BuilderCacheTest extends TestBase { @Test public void test() throws Exception { InMemoryBuilderCache cache = new InMemoryBuilderCache(); DfaBuilder<JavaToken> builder = new DfaBuilder<>(cache); _build(builder); Assert.assertEquals(1, cache.m_cache.size()); Assert.assertEquals(0, cache.m_hits); builder.clear(); _build(builder); Assert.assertEquals(1, cache.m_cache.size()); Assert.assertEquals(1, cache.m_hits); builder = new DfaBuilder<>(cache); _build(builder); Assert.assertEquals(1, cache.m_cache.size()); Assert.assertEquals(2, cache.m_hits); } private void _build(DfaBuilder<JavaToken> builder) throws Exception { for (JavaToken tok : JavaToken.values()) { builder.addPattern(tok.m_pattern, tok); } EnumSet<JavaToken> lang = EnumSet.allOf(JavaToken.class); DfaState<?> start = builder.build(lang, null); _checkDfa(start, "JavaTest.out.txt", false); }
// Path: src/com/nobigsoftware/util/BuilderCache.java // public interface BuilderCache // { // /** // * Get a cached item. // * // * @param key The key used to identify the item. The key uniquely identifies all // * of the source information that will go into building the item if this call fails // * to retrieve a cached version. Typically this will be a cryptographic hash of // * the serialized form of that information. // * // * @return the item that was previously cached under the key, or null if no such item // * can be retrieved. // */ // Serializable getCachedItem(String key); // // /** // * This method may be called when an item is built, providing an opportunity to // * cache it. // * // * @param key The key that will be used to identify the item in future calls to {@link #getCachedItem(String)}. // * Only letters, digits, and underscores are valid in keys, and key length is limited to 32 characters. // * The behaviour of this method for invalid keys is undefined. // * <P> // * Keys that differ only by case may or may not be considered equal by this class. // * @param item The item to cache, if desired // */ // void maybeCacheItem(String key, Serializable item); // } // Path: test/com/nobigsoftware/dfalex/BuilderCacheTest.java import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.EnumSet; import java.util.HashMap; import java.util.Map; import org.junit.Assert; import org.junit.Test; import com.nobigsoftware.util.BuilderCache; package com.nobigsoftware.dfalex; public class BuilderCacheTest extends TestBase { @Test public void test() throws Exception { InMemoryBuilderCache cache = new InMemoryBuilderCache(); DfaBuilder<JavaToken> builder = new DfaBuilder<>(cache); _build(builder); Assert.assertEquals(1, cache.m_cache.size()); Assert.assertEquals(0, cache.m_hits); builder.clear(); _build(builder); Assert.assertEquals(1, cache.m_cache.size()); Assert.assertEquals(1, cache.m_hits); builder = new DfaBuilder<>(cache); _build(builder); Assert.assertEquals(1, cache.m_cache.size()); Assert.assertEquals(2, cache.m_hits); } private void _build(DfaBuilder<JavaToken> builder) throws Exception { for (JavaToken tok : JavaToken.values()) { builder.addPattern(tok.m_pattern, tok); } EnumSet<JavaToken> lang = EnumSet.allOf(JavaToken.class); DfaState<?> start = builder.build(lang, null); _checkDfa(start, "JavaTest.out.txt", false); }
private static class InMemoryBuilderCache implements BuilderCache
mtimmerm/dfalex
src/com/nobigsoftware/dfalex/SearchAndReplaceBuilder.java
// Path: src/com/nobigsoftware/util/BuilderCache.java // public interface BuilderCache // { // /** // * Get a cached item. // * // * @param key The key used to identify the item. The key uniquely identifies all // * of the source information that will go into building the item if this call fails // * to retrieve a cached version. Typically this will be a cryptographic hash of // * the serialized form of that information. // * // * @return the item that was previously cached under the key, or null if no such item // * can be retrieved. // */ // Serializable getCachedItem(String key); // // /** // * This method may be called when an item is built, providing an opportunity to // * cache it. // * // * @param key The key that will be used to identify the item in future calls to {@link #getCachedItem(String)}. // * Only letters, digits, and underscores are valid in keys, and key length is limited to 32 characters. // * The behaviour of this method for invalid keys is undefined. // * <P> // * Keys that differ only by case may or may not be considered equal by this class. // * @param item The item to cache, if desired // */ // void maybeCacheItem(String key, Serializable item); // }
import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.function.Function; import com.nobigsoftware.util.BuilderCache;
/* * Copyright 2015 Matthew Timmermans * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nobigsoftware.dfalex; /** * Builds search and replace functions that finds patterns in strings and replaces them * <P> * Given a set of patterns and associated {@link StringReplacement} functions, you can produce an * optimized, thread-safe Function&lt;String,String&gt; that will find all occurrences of those patterns and replace * them with their replacements. * <P> * The returned function is thread-safe. * <P> * NOTE that building a search and replace function is a relatively complex procedure. You should typically do it only once for each * pattern set you want to use. Usually you would do this in a static initializer. * <P> * You can provide a cache that can remember and recall built functions, which allows you to build * them during your build process in various ways, instead of building them at runtime. Or you can use * the cache to store built functions on the first run of your program so they don't need to be built * the next time... But this is usually unnecessary, since building them is more than fast enough to * do during runtime initialization. */ public class SearchAndReplaceBuilder { private final DfaBuilder<Integer> m_dfaBuilder; private final ArrayList<StringReplacement> m_replacements = new ArrayList<>(); private DfaState<Integer> m_dfaMemo = null; private DfaState<Boolean> m_reverseFinderMemo = null; /** * Create a new SearchAndReplaceBuilder without a {@link BuilderCache} */ public SearchAndReplaceBuilder() { m_dfaBuilder = new DfaBuilder<>(); } /** * Create a new SearchAndReplaceBuilder, with a builder cache to bypass recalculation of pre-built functions * * @param cache The BuilderCache to use */
// Path: src/com/nobigsoftware/util/BuilderCache.java // public interface BuilderCache // { // /** // * Get a cached item. // * // * @param key The key used to identify the item. The key uniquely identifies all // * of the source information that will go into building the item if this call fails // * to retrieve a cached version. Typically this will be a cryptographic hash of // * the serialized form of that information. // * // * @return the item that was previously cached under the key, or null if no such item // * can be retrieved. // */ // Serializable getCachedItem(String key); // // /** // * This method may be called when an item is built, providing an opportunity to // * cache it. // * // * @param key The key that will be used to identify the item in future calls to {@link #getCachedItem(String)}. // * Only letters, digits, and underscores are valid in keys, and key length is limited to 32 characters. // * The behaviour of this method for invalid keys is undefined. // * <P> // * Keys that differ only by case may or may not be considered equal by this class. // * @param item The item to cache, if desired // */ // void maybeCacheItem(String key, Serializable item); // } // Path: src/com/nobigsoftware/dfalex/SearchAndReplaceBuilder.java import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.function.Function; import com.nobigsoftware.util.BuilderCache; /* * Copyright 2015 Matthew Timmermans * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nobigsoftware.dfalex; /** * Builds search and replace functions that finds patterns in strings and replaces them * <P> * Given a set of patterns and associated {@link StringReplacement} functions, you can produce an * optimized, thread-safe Function&lt;String,String&gt; that will find all occurrences of those patterns and replace * them with their replacements. * <P> * The returned function is thread-safe. * <P> * NOTE that building a search and replace function is a relatively complex procedure. You should typically do it only once for each * pattern set you want to use. Usually you would do this in a static initializer. * <P> * You can provide a cache that can remember and recall built functions, which allows you to build * them during your build process in various ways, instead of building them at runtime. Or you can use * the cache to store built functions on the first run of your program so they don't need to be built * the next time... But this is usually unnecessary, since building them is more than fast enough to * do during runtime initialization. */ public class SearchAndReplaceBuilder { private final DfaBuilder<Integer> m_dfaBuilder; private final ArrayList<StringReplacement> m_replacements = new ArrayList<>(); private DfaState<Integer> m_dfaMemo = null; private DfaState<Boolean> m_reverseFinderMemo = null; /** * Create a new SearchAndReplaceBuilder without a {@link BuilderCache} */ public SearchAndReplaceBuilder() { m_dfaBuilder = new DfaBuilder<>(); } /** * Create a new SearchAndReplaceBuilder, with a builder cache to bypass recalculation of pre-built functions * * @param cache The BuilderCache to use */
public SearchAndReplaceBuilder(BuilderCache cache)
mtimmerm/dfalex
src/com/nobigsoftware/dfalex/DfaBuilder.java
// Path: src/com/nobigsoftware/util/BuilderCache.java // public interface BuilderCache // { // /** // * Get a cached item. // * // * @param key The key used to identify the item. The key uniquely identifies all // * of the source information that will go into building the item if this call fails // * to retrieve a cached version. Typically this will be a cryptographic hash of // * the serialized form of that information. // * // * @return the item that was previously cached under the key, or null if no such item // * can be retrieved. // */ // Serializable getCachedItem(String key); // // /** // * This method may be called when an item is built, providing an opportunity to // * cache it. // * // * @param key The key that will be used to identify the item in future calls to {@link #getCachedItem(String)}. // * Only letters, digits, and underscores are valid in keys, and key length is limited to 32 characters. // * The behaviour of this method for invalid keys is undefined. // * <P> // * Keys that differ only by case may or may not be considered equal by this class. // * @param item The item to cache, if desired // */ // void maybeCacheItem(String key, Serializable item); // } // // Path: src/com/nobigsoftware/util/SHAOutputStream.java // public class SHAOutputStream extends DigestOutputStream // { // private static NullOutputStream NULL_OUTPUT_STREAM = new NullOutputStream(); // private static char[] DIGITS_36 = "0123456789abcdefghijklmnopqrstuvwxyz".toCharArray(); // // public SHAOutputStream() // { // super(NULL_OUTPUT_STREAM, _initDigest()); // } // // /** // * @return a base-32 version of the digest, consisting of 32 letters and digits // */ // public String getBase32Digest() // { // StringBuilder sb = new StringBuilder(); // int bits = 0, nbits = 0; // for (byte b : getMessageDigest().digest()) // { // bits |= (((int)b)&255)<<nbits; // nbits+=8; // while(nbits >= 5) // { // sb.append(DIGITS_36[bits&31]); // bits>>>=5; // nbits-=5; // } // } // return sb.toString(); // } // // private static class NullOutputStream extends OutputStream // { // @Override // public void close() throws IOException // { // } // @Override // public void flush() throws IOException // { // } // @Override // public void write(byte[] arg0, int arg1, int arg2) throws IOException // { // } // @Override // public void write(byte[] arg0) throws IOException // { // } // @Override // public void write(int arg0) throws IOException // { // } // } // private static MessageDigest _initDigest() // { // try // { // return MessageDigest.getInstance("SHA-1"); // } // catch(NoSuchAlgorithmException e) // { // throw new RuntimeException("JRE is broken - it's supposed to support SHA-1, but does not"); // } // } // }
import java.io.IOException; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import com.nobigsoftware.util.BuilderCache; import com.nobigsoftware.util.SHAOutputStream;
/* * Copyright 2015 Matthew Timmermans * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nobigsoftware.dfalex; /** * Builds deterministic finite automata (google phrase) or DFAs that find patterns in strings * <P> * Given a set of patterns and the desired result of matching each pattern, you can produce a * DFA that will simultaneously match a sequence of characters against all of those patterns. * <P> * You can also build DFAs for multiple sets of patterns simultaneously. The resulting DFAs will * be optimized to share states wherever possible. * <P> * When you build a DFA to match a set of patterns, you get a "start state" (a {@link DfaState}) for * that pattern set. Each character of a string can be passed in turn to {@link DfaState#getNextState(char)}, * which will return a new {@link DfaState}. * <P> * {@link DfaState#getMatch()} can be called at any time to get the MATCHRESULT (if any) for * the patterns that match the characters processed so far. * <P> * A {@link DfaState} can be used with a {@link StringMatcher} to find instances of patterns in strings, * or with other pattern-matching classes. * <P> * NOTE that building a Dfa is a complex procedure. You should typically do it only once for each * pattern set you want to use. Usually you would do this in a static initializer. * <P> * You can provide a cache that can remember and recall built DFAs, which allows you to build DFAs * during your build process in various ways, instead of building them at runtime. Or you can use * the cache to store built DFAs on the first run of your program so they don't need to be built * the next time... But this is usually unnecessary, since building DFAs is more than fast enough to * do during runtime initialization. * * @param MATCHRESULT The type of result to produce by matching a pattern. This must be serializable * to support caching of built DFAs */ public class DfaBuilder<MATCHRESULT extends Serializable> { //dfa types for cache keys private static final int DFATYPE_MATCHER = 0; private static final int DFATYPE_REVERSEFINDER = 1;
// Path: src/com/nobigsoftware/util/BuilderCache.java // public interface BuilderCache // { // /** // * Get a cached item. // * // * @param key The key used to identify the item. The key uniquely identifies all // * of the source information that will go into building the item if this call fails // * to retrieve a cached version. Typically this will be a cryptographic hash of // * the serialized form of that information. // * // * @return the item that was previously cached under the key, or null if no such item // * can be retrieved. // */ // Serializable getCachedItem(String key); // // /** // * This method may be called when an item is built, providing an opportunity to // * cache it. // * // * @param key The key that will be used to identify the item in future calls to {@link #getCachedItem(String)}. // * Only letters, digits, and underscores are valid in keys, and key length is limited to 32 characters. // * The behaviour of this method for invalid keys is undefined. // * <P> // * Keys that differ only by case may or may not be considered equal by this class. // * @param item The item to cache, if desired // */ // void maybeCacheItem(String key, Serializable item); // } // // Path: src/com/nobigsoftware/util/SHAOutputStream.java // public class SHAOutputStream extends DigestOutputStream // { // private static NullOutputStream NULL_OUTPUT_STREAM = new NullOutputStream(); // private static char[] DIGITS_36 = "0123456789abcdefghijklmnopqrstuvwxyz".toCharArray(); // // public SHAOutputStream() // { // super(NULL_OUTPUT_STREAM, _initDigest()); // } // // /** // * @return a base-32 version of the digest, consisting of 32 letters and digits // */ // public String getBase32Digest() // { // StringBuilder sb = new StringBuilder(); // int bits = 0, nbits = 0; // for (byte b : getMessageDigest().digest()) // { // bits |= (((int)b)&255)<<nbits; // nbits+=8; // while(nbits >= 5) // { // sb.append(DIGITS_36[bits&31]); // bits>>>=5; // nbits-=5; // } // } // return sb.toString(); // } // // private static class NullOutputStream extends OutputStream // { // @Override // public void close() throws IOException // { // } // @Override // public void flush() throws IOException // { // } // @Override // public void write(byte[] arg0, int arg1, int arg2) throws IOException // { // } // @Override // public void write(byte[] arg0) throws IOException // { // } // @Override // public void write(int arg0) throws IOException // { // } // } // private static MessageDigest _initDigest() // { // try // { // return MessageDigest.getInstance("SHA-1"); // } // catch(NoSuchAlgorithmException e) // { // throw new RuntimeException("JRE is broken - it's supposed to support SHA-1, but does not"); // } // } // } // Path: src/com/nobigsoftware/dfalex/DfaBuilder.java import java.io.IOException; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import com.nobigsoftware.util.BuilderCache; import com.nobigsoftware.util.SHAOutputStream; /* * Copyright 2015 Matthew Timmermans * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nobigsoftware.dfalex; /** * Builds deterministic finite automata (google phrase) or DFAs that find patterns in strings * <P> * Given a set of patterns and the desired result of matching each pattern, you can produce a * DFA that will simultaneously match a sequence of characters against all of those patterns. * <P> * You can also build DFAs for multiple sets of patterns simultaneously. The resulting DFAs will * be optimized to share states wherever possible. * <P> * When you build a DFA to match a set of patterns, you get a "start state" (a {@link DfaState}) for * that pattern set. Each character of a string can be passed in turn to {@link DfaState#getNextState(char)}, * which will return a new {@link DfaState}. * <P> * {@link DfaState#getMatch()} can be called at any time to get the MATCHRESULT (if any) for * the patterns that match the characters processed so far. * <P> * A {@link DfaState} can be used with a {@link StringMatcher} to find instances of patterns in strings, * or with other pattern-matching classes. * <P> * NOTE that building a Dfa is a complex procedure. You should typically do it only once for each * pattern set you want to use. Usually you would do this in a static initializer. * <P> * You can provide a cache that can remember and recall built DFAs, which allows you to build DFAs * during your build process in various ways, instead of building them at runtime. Or you can use * the cache to store built DFAs on the first run of your program so they don't need to be built * the next time... But this is usually unnecessary, since building DFAs is more than fast enough to * do during runtime initialization. * * @param MATCHRESULT The type of result to produce by matching a pattern. This must be serializable * to support caching of built DFAs */ public class DfaBuilder<MATCHRESULT extends Serializable> { //dfa types for cache keys private static final int DFATYPE_MATCHER = 0; private static final int DFATYPE_REVERSEFINDER = 1;
private final BuilderCache m_cache;
mtimmerm/dfalex
src/com/nobigsoftware/dfalex/DfaBuilder.java
// Path: src/com/nobigsoftware/util/BuilderCache.java // public interface BuilderCache // { // /** // * Get a cached item. // * // * @param key The key used to identify the item. The key uniquely identifies all // * of the source information that will go into building the item if this call fails // * to retrieve a cached version. Typically this will be a cryptographic hash of // * the serialized form of that information. // * // * @return the item that was previously cached under the key, or null if no such item // * can be retrieved. // */ // Serializable getCachedItem(String key); // // /** // * This method may be called when an item is built, providing an opportunity to // * cache it. // * // * @param key The key that will be used to identify the item in future calls to {@link #getCachedItem(String)}. // * Only letters, digits, and underscores are valid in keys, and key length is limited to 32 characters. // * The behaviour of this method for invalid keys is undefined. // * <P> // * Keys that differ only by case may or may not be considered equal by this class. // * @param item The item to cache, if desired // */ // void maybeCacheItem(String key, Serializable item); // } // // Path: src/com/nobigsoftware/util/SHAOutputStream.java // public class SHAOutputStream extends DigestOutputStream // { // private static NullOutputStream NULL_OUTPUT_STREAM = new NullOutputStream(); // private static char[] DIGITS_36 = "0123456789abcdefghijklmnopqrstuvwxyz".toCharArray(); // // public SHAOutputStream() // { // super(NULL_OUTPUT_STREAM, _initDigest()); // } // // /** // * @return a base-32 version of the digest, consisting of 32 letters and digits // */ // public String getBase32Digest() // { // StringBuilder sb = new StringBuilder(); // int bits = 0, nbits = 0; // for (byte b : getMessageDigest().digest()) // { // bits |= (((int)b)&255)<<nbits; // nbits+=8; // while(nbits >= 5) // { // sb.append(DIGITS_36[bits&31]); // bits>>>=5; // nbits-=5; // } // } // return sb.toString(); // } // // private static class NullOutputStream extends OutputStream // { // @Override // public void close() throws IOException // { // } // @Override // public void flush() throws IOException // { // } // @Override // public void write(byte[] arg0, int arg1, int arg2) throws IOException // { // } // @Override // public void write(byte[] arg0) throws IOException // { // } // @Override // public void write(int arg0) throws IOException // { // } // } // private static MessageDigest _initDigest() // { // try // { // return MessageDigest.getInstance("SHA-1"); // } // catch(NoSuchAlgorithmException e) // { // throw new RuntimeException("JRE is broken - it's supposed to support SHA-1, but does not"); // } // } // }
import java.io.IOException; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import com.nobigsoftware.util.BuilderCache; import com.nobigsoftware.util.SHAOutputStream;
} /** * Build DFAs from a provided NFA * <P> * This method is used when you want to build the NFA yourself instead of letting * this class do it. * <P> * Languages built simultaneously will be globally minimized and will share as many states as possible. * * @param nfa The NFA * @param nfaStartStates The return value will include the DFA states corresponding to these NFA states, in the same order * @param ambiguityResolver When patterns for multiple results match the same string, this is called to * combine the multiple results into one. If this is null, then a DfaAmbiguityException * will be thrown in that case. * @param cache If this cache is non-null, it will be checked for a memoized result for this NFA, and will be populated * with a memoized result when the call is complete. * @return DFA start states that are equivalent to the given NFA start states. This will have the same length as nfaStartStates, with * corresponding start states in corresponding positions. */ @SuppressWarnings("unchecked") public static <MR> List<DfaState<MR>> buildFromNfa(Nfa<MR> nfa, int[] nfaStartStates, DfaAmbiguityResolver<? super MR> ambiguityResolver, BuilderCache cache ) { String cacheKey = null; SerializableDfa<MR> serializableDfa = null; if (cache != null) { try { //generate the cache key by serializing key info into an SHA hash
// Path: src/com/nobigsoftware/util/BuilderCache.java // public interface BuilderCache // { // /** // * Get a cached item. // * // * @param key The key used to identify the item. The key uniquely identifies all // * of the source information that will go into building the item if this call fails // * to retrieve a cached version. Typically this will be a cryptographic hash of // * the serialized form of that information. // * // * @return the item that was previously cached under the key, or null if no such item // * can be retrieved. // */ // Serializable getCachedItem(String key); // // /** // * This method may be called when an item is built, providing an opportunity to // * cache it. // * // * @param key The key that will be used to identify the item in future calls to {@link #getCachedItem(String)}. // * Only letters, digits, and underscores are valid in keys, and key length is limited to 32 characters. // * The behaviour of this method for invalid keys is undefined. // * <P> // * Keys that differ only by case may or may not be considered equal by this class. // * @param item The item to cache, if desired // */ // void maybeCacheItem(String key, Serializable item); // } // // Path: src/com/nobigsoftware/util/SHAOutputStream.java // public class SHAOutputStream extends DigestOutputStream // { // private static NullOutputStream NULL_OUTPUT_STREAM = new NullOutputStream(); // private static char[] DIGITS_36 = "0123456789abcdefghijklmnopqrstuvwxyz".toCharArray(); // // public SHAOutputStream() // { // super(NULL_OUTPUT_STREAM, _initDigest()); // } // // /** // * @return a base-32 version of the digest, consisting of 32 letters and digits // */ // public String getBase32Digest() // { // StringBuilder sb = new StringBuilder(); // int bits = 0, nbits = 0; // for (byte b : getMessageDigest().digest()) // { // bits |= (((int)b)&255)<<nbits; // nbits+=8; // while(nbits >= 5) // { // sb.append(DIGITS_36[bits&31]); // bits>>>=5; // nbits-=5; // } // } // return sb.toString(); // } // // private static class NullOutputStream extends OutputStream // { // @Override // public void close() throws IOException // { // } // @Override // public void flush() throws IOException // { // } // @Override // public void write(byte[] arg0, int arg1, int arg2) throws IOException // { // } // @Override // public void write(byte[] arg0) throws IOException // { // } // @Override // public void write(int arg0) throws IOException // { // } // } // private static MessageDigest _initDigest() // { // try // { // return MessageDigest.getInstance("SHA-1"); // } // catch(NoSuchAlgorithmException e) // { // throw new RuntimeException("JRE is broken - it's supposed to support SHA-1, but does not"); // } // } // } // Path: src/com/nobigsoftware/dfalex/DfaBuilder.java import java.io.IOException; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import com.nobigsoftware.util.BuilderCache; import com.nobigsoftware.util.SHAOutputStream; } /** * Build DFAs from a provided NFA * <P> * This method is used when you want to build the NFA yourself instead of letting * this class do it. * <P> * Languages built simultaneously will be globally minimized and will share as many states as possible. * * @param nfa The NFA * @param nfaStartStates The return value will include the DFA states corresponding to these NFA states, in the same order * @param ambiguityResolver When patterns for multiple results match the same string, this is called to * combine the multiple results into one. If this is null, then a DfaAmbiguityException * will be thrown in that case. * @param cache If this cache is non-null, it will be checked for a memoized result for this NFA, and will be populated * with a memoized result when the call is complete. * @return DFA start states that are equivalent to the given NFA start states. This will have the same length as nfaStartStates, with * corresponding start states in corresponding positions. */ @SuppressWarnings("unchecked") public static <MR> List<DfaState<MR>> buildFromNfa(Nfa<MR> nfa, int[] nfaStartStates, DfaAmbiguityResolver<? super MR> ambiguityResolver, BuilderCache cache ) { String cacheKey = null; SerializableDfa<MR> serializableDfa = null; if (cache != null) { try { //generate the cache key by serializing key info into an SHA hash
SHAOutputStream sha = new SHAOutputStream();
y1j2x34/spring-influxdb-orm
spring-influxdb-orm/src/test/java/com/vgerbot/test/orm/influxdb/intergration/entity/CensusMeasurementUsingEnum.java
// Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/EnumType.java // public interface EnumType { // String name(); // // String getDisplayName(); // // Object getValue(); // }
import com.vgerbot.orm.influxdb.EnumType; import com.vgerbot.orm.influxdb.annotations.FieldColumn; import com.vgerbot.orm.influxdb.annotations.InfluxDBMeasurement; import com.vgerbot.orm.influxdb.annotations.TagColumn; import java.io.Serializable; import java.util.Date; import java.util.Objects;
package com.vgerbot.test.orm.influxdb.intergration.entity; @InfluxDBMeasurement("census") public class CensusMeasurementUsingEnum implements Serializable {
// Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/EnumType.java // public interface EnumType { // String name(); // // String getDisplayName(); // // Object getValue(); // } // Path: spring-influxdb-orm/src/test/java/com/vgerbot/test/orm/influxdb/intergration/entity/CensusMeasurementUsingEnum.java import com.vgerbot.orm.influxdb.EnumType; import com.vgerbot.orm.influxdb.annotations.FieldColumn; import com.vgerbot.orm.influxdb.annotations.InfluxDBMeasurement; import com.vgerbot.orm.influxdb.annotations.TagColumn; import java.io.Serializable; import java.util.Date; import java.util.Objects; package com.vgerbot.test.orm.influxdb.intergration.entity; @InfluxDBMeasurement("census") public class CensusMeasurementUsingEnum implements Serializable {
public static enum ScientistName implements EnumType {
y1j2x34/spring-influxdb-orm
spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/factory/ClassPathMeasurementScannerFactoryBean.java
// Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/utils/StringUtils.java // public class StringUtils extends org.apache.commons.lang3.StringUtils { // // /** // * 正则匹配替换,类似js中的replace // * // * @param source // * @param regex // * @param func // * @return // */ // public static final String replace(String source, String regex, ReplaceCallback func) { // return replace(source, regex, 0, func); // } // // public static final String replace(String source, String regex, int group, ReplaceCallback func) { // Pattern pattern = Pattern.compile(regex); // Matcher m = pattern.matcher(source); // if (m.find()) { // StringBuffer sb = new StringBuffer(); // int i = 0; // do { // String grp = m.group(group); // int index = source.indexOf(grp, i); // m.appendReplacement(sb, func.replace(grp, index, source)); // i = index + 1; // } while (m.find()); // m.appendTail(sb); // return sb.toString(); // } // return source; // } // // /** // * 替换回调函数接口 // * // * @author y1j2x34 // * @date 2014-7-24 // */ // public static interface ReplaceCallback { // String replace(String word, int index, String source); // } // // }
import com.vgerbot.orm.influxdb.utils.StringUtils; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.context.EnvironmentAware; import org.springframework.core.env.Environment;
package com.vgerbot.orm.influxdb.factory; public class ClassPathMeasurementScannerFactoryBean implements FactoryBean<ClassPathMeasurementScanner>, InitializingBean, EnvironmentAware { public static final String MEASUREMENT_PACKAGE = "entityPackage"; private Environment environment; private String entityPackage; @Override public ClassPathMeasurementScanner getObject() { ClassPathMeasurementScanner scanner = new ClassPathMeasurementScanner(this.environment);
// Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/utils/StringUtils.java // public class StringUtils extends org.apache.commons.lang3.StringUtils { // // /** // * 正则匹配替换,类似js中的replace // * // * @param source // * @param regex // * @param func // * @return // */ // public static final String replace(String source, String regex, ReplaceCallback func) { // return replace(source, regex, 0, func); // } // // public static final String replace(String source, String regex, int group, ReplaceCallback func) { // Pattern pattern = Pattern.compile(regex); // Matcher m = pattern.matcher(source); // if (m.find()) { // StringBuffer sb = new StringBuffer(); // int i = 0; // do { // String grp = m.group(group); // int index = source.indexOf(grp, i); // m.appendReplacement(sb, func.replace(grp, index, source)); // i = index + 1; // } while (m.find()); // m.appendTail(sb); // return sb.toString(); // } // return source; // } // // /** // * 替换回调函数接口 // * // * @author y1j2x34 // * @date 2014-7-24 // */ // public static interface ReplaceCallback { // String replace(String word, int index, String source); // } // // } // Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/factory/ClassPathMeasurementScannerFactoryBean.java import com.vgerbot.orm.influxdb.utils.StringUtils; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.context.EnvironmentAware; import org.springframework.core.env.Environment; package com.vgerbot.orm.influxdb.factory; public class ClassPathMeasurementScannerFactoryBean implements FactoryBean<ClassPathMeasurementScanner>, InitializingBean, EnvironmentAware { public static final String MEASUREMENT_PACKAGE = "entityPackage"; private Environment environment; private String entityPackage; @Override public ClassPathMeasurementScanner getObject() { ClassPathMeasurementScanner scanner = new ClassPathMeasurementScanner(this.environment);
if(!StringUtils.isBlank(entityPackage)) {
y1j2x34/spring-influxdb-orm
spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/utils/CommandUtils.java
// Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/param/ParameterValue.java // public class ParameterValue { // private final Object value; // private final ParameterSignature signature; // // public ParameterValue(Object value, ParameterSignature signature) { // super(); // this.value = value; // this.signature = signature; // } // // public Object getValue() { // return value; // } // // public ParameterSignature getSignature() { // return signature; // } // // } // // Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/utils/StringUtils.java // public static interface ReplaceCallback { // String replace(String word, int index, String source); // }
import java.util.Date; import java.util.Map; import java.util.concurrent.TimeUnit; import com.vgerbot.orm.influxdb.param.ParameterValue; import com.vgerbot.orm.influxdb.utils.StringUtils.ReplaceCallback;
package com.vgerbot.orm.influxdb.utils; public class CommandUtils { public static String parseCommand(String command, final Map<String, ParameterValue> parameters) {
// Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/param/ParameterValue.java // public class ParameterValue { // private final Object value; // private final ParameterSignature signature; // // public ParameterValue(Object value, ParameterSignature signature) { // super(); // this.value = value; // this.signature = signature; // } // // public Object getValue() { // return value; // } // // public ParameterSignature getSignature() { // return signature; // } // // } // // Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/utils/StringUtils.java // public static interface ReplaceCallback { // String replace(String word, int index, String source); // } // Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/utils/CommandUtils.java import java.util.Date; import java.util.Map; import java.util.concurrent.TimeUnit; import com.vgerbot.orm.influxdb.param.ParameterValue; import com.vgerbot.orm.influxdb.utils.StringUtils.ReplaceCallback; package com.vgerbot.orm.influxdb.utils; public class CommandUtils { public static String parseCommand(String command, final Map<String, ParameterValue> parameters) {
command = StringUtils.replace(command, "\\$\\{([^\\}]+)\\}", 1, new ReplaceCallback() {
y1j2x34/spring-influxdb-orm
spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/annotations/InfluxDBExecute.java
// Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/exec/ExecuteExecutor.java // public class ExecuteExecutor extends AnnotationExecutor<InfluxDBExecute> { // // public ExecuteExecutor(InfluxDBRepository repository, InfluxDBExecute annotation) { // super(repository, annotation); // } // // @Override // public ResultContext execute(MapperMethod method, Map<String, ParameterValue> parameters) { // String command = super.annotation.value(); // repository.execute(command, parameters); // return ResultContext.VOID; // } // // }
import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import com.vgerbot.orm.influxdb.exec.ExecuteExecutor;
package com.vgerbot.orm.influxdb.annotations; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD)
// Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/exec/ExecuteExecutor.java // public class ExecuteExecutor extends AnnotationExecutor<InfluxDBExecute> { // // public ExecuteExecutor(InfluxDBRepository repository, InfluxDBExecute annotation) { // super(repository, annotation); // } // // @Override // public ResultContext execute(MapperMethod method, Map<String, ParameterValue> parameters) { // String command = super.annotation.value(); // repository.execute(command, parameters); // return ResultContext.VOID; // } // // } // Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/annotations/InfluxDBExecute.java import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import com.vgerbot.orm.influxdb.exec.ExecuteExecutor; package com.vgerbot.orm.influxdb.annotations; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD)
@AnnotateExecutor(ExecuteExecutor.class)
y1j2x34/spring-influxdb-orm
spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/annotations/InfluxDBSelect.java
// Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/exec/SelectExecutor.java // public class SelectExecutor extends AnnotationExecutor<InfluxDBSelect> { // public SelectExecutor(InfluxDBRepository repository, InfluxDBSelect selectAnnotation) { // super(repository, selectAnnotation); // } // // @Override // public ResultContext execute(MapperMethod method, Map<String, ParameterValue> parameters) { // String command = super.annotation.value(); // return repository.query(command, parameters); // } // // }
import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import com.vgerbot.orm.influxdb.exec.SelectExecutor;
package com.vgerbot.orm.influxdb.annotations; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD)
// Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/exec/SelectExecutor.java // public class SelectExecutor extends AnnotationExecutor<InfluxDBSelect> { // public SelectExecutor(InfluxDBRepository repository, InfluxDBSelect selectAnnotation) { // super(repository, selectAnnotation); // } // // @Override // public ResultContext execute(MapperMethod method, Map<String, ParameterValue> parameters) { // String command = super.annotation.value(); // return repository.query(command, parameters); // } // // } // Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/annotations/InfluxDBSelect.java import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import com.vgerbot.orm.influxdb.exec.SelectExecutor; package com.vgerbot.orm.influxdb.annotations; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD)
@AnnotateExecutor(SelectExecutor.class)
y1j2x34/spring-influxdb-orm
spring-influxdb-orm-autoconfigure/src/test/java/com/vgerbot/orm/influxdb/test/testcase/TestCase.java
// Path: spring-influxdb-orm-autoconfigure/src/test/java/com/vgerbot/orm/influxdb/test/dao/CensusDao.java // public interface CensusDao extends InfluxDBDao<CensusMeasurement> { // // @InfluxDBSelect("select * from census where scientist = #{scientist}") // public List<CensusMeasurement> selectByScientist(@InfluxDBParam("scientist") String scientist); // // @InfluxDBExecute("DROP SERIES FROM census where scientist=#{scientist} and location=#{location}") // public void deleteSeries( // // @InfluxDBParam("scientist") String scientist, // // @InfluxDBParam("location") Integer location // // ); // // @InfluxDBSelect("select scientist,location,butterflies from census where scientist = #{scientist}") // public List<Map<String, Integer>> selectButterflies( // // @InfluxDBParam("scientist") String scientist, // // @InfluxDBParam("location") Integer location // // ); // // @SpecifiedExecutor(HelloWorldExecutor.class) // public void hello(); // // @InfluxQL // public List<Map<String, Object>> findByScientist(@InfluxDBParam("scientist") String scientist); // // class HelloWorldExecutor extends Executor { // // public HelloWorldExecutor(InfluxDBRepository repository) { // super(repository); // } // // @Override // public ResultContext execute(MapperMethod method, Map<String, ParameterValue> parameters) { // System.out.println("hello world"); // return ResultContext.VOID; // } // } // } // // Path: spring-influxdb-orm-autoconfigure/src/test/java/com/vgerbot/orm/influxdb/test/entity/CensusMeasurement.java // @InfluxDBMeasurement("census") // public class CensusMeasurement implements Serializable { // private static final long serialVersionUID = 8260424450884444916L; // // private Date time; // // @TagColumn("location") // private String location; // @TagColumn("scientist") // private String scientist; // // @FieldColumn("butterflies") // private Integer butterflies; // @FieldColumn("honeybees") // private Integer honeybees; // // public Date getTime() { // return time; // } // // public void setTime(Date time) { // this.time = time; // } // // public String getLocation() { // return location; // } // // public void setLocation(String location) { // this.location = location; // } // // public String getScientist() { // return scientist; // } // // public void setScientist(String scientist) { // this.scientist = scientist; // } // // public Integer getButterflies() { // return butterflies; // } // // public void setButterflies(Integer butterflies) { // this.butterflies = butterflies; // } // // public Integer getHoneybees() { // return honeybees; // } // // public void setHoneybees(Integer honeybees) { // this.honeybees = honeybees; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((location == null) ? 0 : location.hashCode()); // result = prime * result + ((scientist == null) ? 0 : scientist.hashCode()); // result = prime * result + ((time == null) ? 0 : time.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // CensusMeasurement other = (CensusMeasurement) obj; // if (location == null) { // if (other.location != null) { // return false; // } // } else if (!location.equals(other.location)) { // return false; // } // if (scientist == null) { // if (other.scientist != null) { // return false; // } // } else if (!scientist.equals(other.scientist)) { // return false; // } // if (time == null) { // if (other.time != null) { // return false; // } // } else if (!time.equals(other.time)) { // return false; // } // return true; // } // // public String toString() { // return "[time: " + time.getTime() + ", location: " + location + ", scientist: " + scientist + ", butterflies: " + butterflies // + ", honeybees: " + honeybees + "]"; // } // }
import com.vgerbot.orm.influxdb.test.dao.CensusDao; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; import com.vgerbot.orm.influxdb.test.entity.CensusMeasurement; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.MethodSorters; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import javax.annotation.Resource; import java.util.List;
package com.vgerbot.orm.influxdb.test.testcase; @RunWith(SpringRunner.class) @SpringBootTest @FixMethodOrder(value= MethodSorters.NAME_ASCENDING) public class TestCase { @Resource
// Path: spring-influxdb-orm-autoconfigure/src/test/java/com/vgerbot/orm/influxdb/test/dao/CensusDao.java // public interface CensusDao extends InfluxDBDao<CensusMeasurement> { // // @InfluxDBSelect("select * from census where scientist = #{scientist}") // public List<CensusMeasurement> selectByScientist(@InfluxDBParam("scientist") String scientist); // // @InfluxDBExecute("DROP SERIES FROM census where scientist=#{scientist} and location=#{location}") // public void deleteSeries( // // @InfluxDBParam("scientist") String scientist, // // @InfluxDBParam("location") Integer location // // ); // // @InfluxDBSelect("select scientist,location,butterflies from census where scientist = #{scientist}") // public List<Map<String, Integer>> selectButterflies( // // @InfluxDBParam("scientist") String scientist, // // @InfluxDBParam("location") Integer location // // ); // // @SpecifiedExecutor(HelloWorldExecutor.class) // public void hello(); // // @InfluxQL // public List<Map<String, Object>> findByScientist(@InfluxDBParam("scientist") String scientist); // // class HelloWorldExecutor extends Executor { // // public HelloWorldExecutor(InfluxDBRepository repository) { // super(repository); // } // // @Override // public ResultContext execute(MapperMethod method, Map<String, ParameterValue> parameters) { // System.out.println("hello world"); // return ResultContext.VOID; // } // } // } // // Path: spring-influxdb-orm-autoconfigure/src/test/java/com/vgerbot/orm/influxdb/test/entity/CensusMeasurement.java // @InfluxDBMeasurement("census") // public class CensusMeasurement implements Serializable { // private static final long serialVersionUID = 8260424450884444916L; // // private Date time; // // @TagColumn("location") // private String location; // @TagColumn("scientist") // private String scientist; // // @FieldColumn("butterflies") // private Integer butterflies; // @FieldColumn("honeybees") // private Integer honeybees; // // public Date getTime() { // return time; // } // // public void setTime(Date time) { // this.time = time; // } // // public String getLocation() { // return location; // } // // public void setLocation(String location) { // this.location = location; // } // // public String getScientist() { // return scientist; // } // // public void setScientist(String scientist) { // this.scientist = scientist; // } // // public Integer getButterflies() { // return butterflies; // } // // public void setButterflies(Integer butterflies) { // this.butterflies = butterflies; // } // // public Integer getHoneybees() { // return honeybees; // } // // public void setHoneybees(Integer honeybees) { // this.honeybees = honeybees; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((location == null) ? 0 : location.hashCode()); // result = prime * result + ((scientist == null) ? 0 : scientist.hashCode()); // result = prime * result + ((time == null) ? 0 : time.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // CensusMeasurement other = (CensusMeasurement) obj; // if (location == null) { // if (other.location != null) { // return false; // } // } else if (!location.equals(other.location)) { // return false; // } // if (scientist == null) { // if (other.scientist != null) { // return false; // } // } else if (!scientist.equals(other.scientist)) { // return false; // } // if (time == null) { // if (other.time != null) { // return false; // } // } else if (!time.equals(other.time)) { // return false; // } // return true; // } // // public String toString() { // return "[time: " + time.getTime() + ", location: " + location + ", scientist: " + scientist + ", butterflies: " + butterflies // + ", honeybees: " + honeybees + "]"; // } // } // Path: spring-influxdb-orm-autoconfigure/src/test/java/com/vgerbot/orm/influxdb/test/testcase/TestCase.java import com.vgerbot.orm.influxdb.test.dao.CensusDao; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; import com.vgerbot.orm.influxdb.test.entity.CensusMeasurement; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.MethodSorters; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import javax.annotation.Resource; import java.util.List; package com.vgerbot.orm.influxdb.test.testcase; @RunWith(SpringRunner.class) @SpringBootTest @FixMethodOrder(value= MethodSorters.NAME_ASCENDING) public class TestCase { @Resource
private CensusDao dao;
y1j2x34/spring-influxdb-orm
spring-influxdb-orm-autoconfigure/src/test/java/com/vgerbot/orm/influxdb/test/testcase/TestCase.java
// Path: spring-influxdb-orm-autoconfigure/src/test/java/com/vgerbot/orm/influxdb/test/dao/CensusDao.java // public interface CensusDao extends InfluxDBDao<CensusMeasurement> { // // @InfluxDBSelect("select * from census where scientist = #{scientist}") // public List<CensusMeasurement> selectByScientist(@InfluxDBParam("scientist") String scientist); // // @InfluxDBExecute("DROP SERIES FROM census where scientist=#{scientist} and location=#{location}") // public void deleteSeries( // // @InfluxDBParam("scientist") String scientist, // // @InfluxDBParam("location") Integer location // // ); // // @InfluxDBSelect("select scientist,location,butterflies from census where scientist = #{scientist}") // public List<Map<String, Integer>> selectButterflies( // // @InfluxDBParam("scientist") String scientist, // // @InfluxDBParam("location") Integer location // // ); // // @SpecifiedExecutor(HelloWorldExecutor.class) // public void hello(); // // @InfluxQL // public List<Map<String, Object>> findByScientist(@InfluxDBParam("scientist") String scientist); // // class HelloWorldExecutor extends Executor { // // public HelloWorldExecutor(InfluxDBRepository repository) { // super(repository); // } // // @Override // public ResultContext execute(MapperMethod method, Map<String, ParameterValue> parameters) { // System.out.println("hello world"); // return ResultContext.VOID; // } // } // } // // Path: spring-influxdb-orm-autoconfigure/src/test/java/com/vgerbot/orm/influxdb/test/entity/CensusMeasurement.java // @InfluxDBMeasurement("census") // public class CensusMeasurement implements Serializable { // private static final long serialVersionUID = 8260424450884444916L; // // private Date time; // // @TagColumn("location") // private String location; // @TagColumn("scientist") // private String scientist; // // @FieldColumn("butterflies") // private Integer butterflies; // @FieldColumn("honeybees") // private Integer honeybees; // // public Date getTime() { // return time; // } // // public void setTime(Date time) { // this.time = time; // } // // public String getLocation() { // return location; // } // // public void setLocation(String location) { // this.location = location; // } // // public String getScientist() { // return scientist; // } // // public void setScientist(String scientist) { // this.scientist = scientist; // } // // public Integer getButterflies() { // return butterflies; // } // // public void setButterflies(Integer butterflies) { // this.butterflies = butterflies; // } // // public Integer getHoneybees() { // return honeybees; // } // // public void setHoneybees(Integer honeybees) { // this.honeybees = honeybees; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((location == null) ? 0 : location.hashCode()); // result = prime * result + ((scientist == null) ? 0 : scientist.hashCode()); // result = prime * result + ((time == null) ? 0 : time.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // CensusMeasurement other = (CensusMeasurement) obj; // if (location == null) { // if (other.location != null) { // return false; // } // } else if (!location.equals(other.location)) { // return false; // } // if (scientist == null) { // if (other.scientist != null) { // return false; // } // } else if (!scientist.equals(other.scientist)) { // return false; // } // if (time == null) { // if (other.time != null) { // return false; // } // } else if (!time.equals(other.time)) { // return false; // } // return true; // } // // public String toString() { // return "[time: " + time.getTime() + ", location: " + location + ", scientist: " + scientist + ", butterflies: " + butterflies // + ", honeybees: " + honeybees + "]"; // } // }
import com.vgerbot.orm.influxdb.test.dao.CensusDao; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; import com.vgerbot.orm.influxdb.test.entity.CensusMeasurement; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.MethodSorters; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import javax.annotation.Resource; import java.util.List;
package com.vgerbot.orm.influxdb.test.testcase; @RunWith(SpringRunner.class) @SpringBootTest @FixMethodOrder(value= MethodSorters.NAME_ASCENDING) public class TestCase { @Resource private CensusDao dao; @Test public void test1DaoNotNull() { assertThat(dao, notNullValue()); } @Test public void test2Query() {
// Path: spring-influxdb-orm-autoconfigure/src/test/java/com/vgerbot/orm/influxdb/test/dao/CensusDao.java // public interface CensusDao extends InfluxDBDao<CensusMeasurement> { // // @InfluxDBSelect("select * from census where scientist = #{scientist}") // public List<CensusMeasurement> selectByScientist(@InfluxDBParam("scientist") String scientist); // // @InfluxDBExecute("DROP SERIES FROM census where scientist=#{scientist} and location=#{location}") // public void deleteSeries( // // @InfluxDBParam("scientist") String scientist, // // @InfluxDBParam("location") Integer location // // ); // // @InfluxDBSelect("select scientist,location,butterflies from census where scientist = #{scientist}") // public List<Map<String, Integer>> selectButterflies( // // @InfluxDBParam("scientist") String scientist, // // @InfluxDBParam("location") Integer location // // ); // // @SpecifiedExecutor(HelloWorldExecutor.class) // public void hello(); // // @InfluxQL // public List<Map<String, Object>> findByScientist(@InfluxDBParam("scientist") String scientist); // // class HelloWorldExecutor extends Executor { // // public HelloWorldExecutor(InfluxDBRepository repository) { // super(repository); // } // // @Override // public ResultContext execute(MapperMethod method, Map<String, ParameterValue> parameters) { // System.out.println("hello world"); // return ResultContext.VOID; // } // } // } // // Path: spring-influxdb-orm-autoconfigure/src/test/java/com/vgerbot/orm/influxdb/test/entity/CensusMeasurement.java // @InfluxDBMeasurement("census") // public class CensusMeasurement implements Serializable { // private static final long serialVersionUID = 8260424450884444916L; // // private Date time; // // @TagColumn("location") // private String location; // @TagColumn("scientist") // private String scientist; // // @FieldColumn("butterflies") // private Integer butterflies; // @FieldColumn("honeybees") // private Integer honeybees; // // public Date getTime() { // return time; // } // // public void setTime(Date time) { // this.time = time; // } // // public String getLocation() { // return location; // } // // public void setLocation(String location) { // this.location = location; // } // // public String getScientist() { // return scientist; // } // // public void setScientist(String scientist) { // this.scientist = scientist; // } // // public Integer getButterflies() { // return butterflies; // } // // public void setButterflies(Integer butterflies) { // this.butterflies = butterflies; // } // // public Integer getHoneybees() { // return honeybees; // } // // public void setHoneybees(Integer honeybees) { // this.honeybees = honeybees; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((location == null) ? 0 : location.hashCode()); // result = prime * result + ((scientist == null) ? 0 : scientist.hashCode()); // result = prime * result + ((time == null) ? 0 : time.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // CensusMeasurement other = (CensusMeasurement) obj; // if (location == null) { // if (other.location != null) { // return false; // } // } else if (!location.equals(other.location)) { // return false; // } // if (scientist == null) { // if (other.scientist != null) { // return false; // } // } else if (!scientist.equals(other.scientist)) { // return false; // } // if (time == null) { // if (other.time != null) { // return false; // } // } else if (!time.equals(other.time)) { // return false; // } // return true; // } // // public String toString() { // return "[time: " + time.getTime() + ", location: " + location + ", scientist: " + scientist + ", butterflies: " + butterflies // + ", honeybees: " + honeybees + "]"; // } // } // Path: spring-influxdb-orm-autoconfigure/src/test/java/com/vgerbot/orm/influxdb/test/testcase/TestCase.java import com.vgerbot.orm.influxdb.test.dao.CensusDao; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; import com.vgerbot.orm.influxdb.test.entity.CensusMeasurement; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.MethodSorters; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import javax.annotation.Resource; import java.util.List; package com.vgerbot.orm.influxdb.test.testcase; @RunWith(SpringRunner.class) @SpringBootTest @FixMethodOrder(value= MethodSorters.NAME_ASCENDING) public class TestCase { @Resource private CensusDao dao; @Test public void test1DaoNotNull() { assertThat(dao, notNullValue()); } @Test public void test2Query() {
List<CensusMeasurement> scientists = dao.selectByScientist("lanstroth");
y1j2x34/spring-influxdb-orm
spring-influxdb-orm/src/test/java/com/vgerbot/test/orm/influxdb/common/MockParameterMap.java
// Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/param/ParameterSignature.java // public class ParameterSignature { // private final int index; // private final String name; // private final Class<?> type; // // private ParameterSignature(int index, String name, Class<?> type) { // super(); // this.index = index; // this.name = name; // this.type = type; // } // // public static ParameterSignature signature(int index, Parameter parameter, String aliasName) { // Class<?> type = parameter.getType(); // return new ParameterSignature(index, aliasName, type); // } // // public static ParameterSignature signature(int index, Parameter parameter) { // String name = parameter.getName(); // Class<?> type = parameter.getType(); // return new ParameterSignature(index, name, type); // } // // public static List<ParameterSignature> signatures(Method method) { // Parameter[] parameters = method.getParameters(); // List<ParameterSignature> signatures = new ArrayList<>(parameters.length); // // for (int i = 0; i < parameters.length; i++) { // Parameter parameter = parameters[i]; // signatures.add(signature(i, parameter)); // } // // return signatures; // } // // public int getIndex() { // return index; // } // // public String getName() { // return name; // } // // public Class<?> getType() { // return type; // } // // public ParameterValue value(Object value) { // return new ParameterValue(value, this); // } // } // // Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/param/ParameterValue.java // public class ParameterValue { // private final Object value; // private final ParameterSignature signature; // // public ParameterValue(Object value, ParameterSignature signature) { // super(); // this.value = value; // this.signature = signature; // } // // public Object getValue() { // return value; // } // // public ParameterSignature getSignature() { // return signature; // } // // }
import com.vgerbot.orm.influxdb.param.ParameterSignature; import com.vgerbot.orm.influxdb.param.ParameterValue; import java.util.HashMap; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
package com.vgerbot.test.orm.influxdb.common; public class MockParameterMap extends HashMap<String, ParameterValue> { public <T> ParameterValue putParameter(int index, String name, Class<T> type, T value) {
// Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/param/ParameterSignature.java // public class ParameterSignature { // private final int index; // private final String name; // private final Class<?> type; // // private ParameterSignature(int index, String name, Class<?> type) { // super(); // this.index = index; // this.name = name; // this.type = type; // } // // public static ParameterSignature signature(int index, Parameter parameter, String aliasName) { // Class<?> type = parameter.getType(); // return new ParameterSignature(index, aliasName, type); // } // // public static ParameterSignature signature(int index, Parameter parameter) { // String name = parameter.getName(); // Class<?> type = parameter.getType(); // return new ParameterSignature(index, name, type); // } // // public static List<ParameterSignature> signatures(Method method) { // Parameter[] parameters = method.getParameters(); // List<ParameterSignature> signatures = new ArrayList<>(parameters.length); // // for (int i = 0; i < parameters.length; i++) { // Parameter parameter = parameters[i]; // signatures.add(signature(i, parameter)); // } // // return signatures; // } // // public int getIndex() { // return index; // } // // public String getName() { // return name; // } // // public Class<?> getType() { // return type; // } // // public ParameterValue value(Object value) { // return new ParameterValue(value, this); // } // } // // Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/param/ParameterValue.java // public class ParameterValue { // private final Object value; // private final ParameterSignature signature; // // public ParameterValue(Object value, ParameterSignature signature) { // super(); // this.value = value; // this.signature = signature; // } // // public Object getValue() { // return value; // } // // public ParameterSignature getSignature() { // return signature; // } // // } // Path: spring-influxdb-orm/src/test/java/com/vgerbot/test/orm/influxdb/common/MockParameterMap.java import com.vgerbot.orm.influxdb.param.ParameterSignature; import com.vgerbot.orm.influxdb.param.ParameterValue; import java.util.HashMap; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; package com.vgerbot.test.orm.influxdb.common; public class MockParameterMap extends HashMap<String, ParameterValue> { public <T> ParameterValue putParameter(int index, String name, Class<T> type, T value) {
ParameterSignature signature = createMockParameterSignature(index, name, type);
y1j2x34/spring-influxdb-orm
spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/ql/InfluxQLMapper.java
// Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/InfluxDBException.java // public class InfluxDBException extends RuntimeException { // // private static final long serialVersionUID = -4410268653794610252L; // // public InfluxDBException() { // super(); // } // // public InfluxDBException(String message, Throwable cause) { // super(message, cause); // } // // public InfluxDBException(String message) { // super(message); // } // // public InfluxDBException(Throwable cause) { // super(cause); // } // } // // Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/ql/InfluxQLStatement.java // public static enum ACTION { // SELECT, EXECUTE // }
import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import org.springframework.beans.factory.xml.DefaultDocumentLoader; import org.springframework.beans.factory.xml.DocumentLoader; import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.InputStreamResource; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.util.xml.XmlValidationModeDetector; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import com.vgerbot.orm.influxdb.InfluxDBException; import com.vgerbot.orm.influxdb.ql.InfluxQLStatement.ACTION;
@Override public void fatalError(SAXParseException exception) throws SAXException { logger.log(Level.SEVERE, exception.getMessage(), exception); } @Override public void error(SAXParseException exception) throws SAXException { logger.log(Level.OFF, exception.getMessage(), exception); } }; private InfluxQLMapper() { } public InfluxQLStatement getStatement(String key) { return statementsMap.get(key); } public InfluxQLMapper union(InfluxQLMapper other) { InfluxQLMapper newmapper = new InfluxQLMapper(); newmapper.statementsMap.putAll(this.statementsMap); newmapper.statementsMap.putAll(other.statementsMap); return newmapper; } public static final InfluxQLMapper empty() { return new InfluxQLMapper(); }
// Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/InfluxDBException.java // public class InfluxDBException extends RuntimeException { // // private static final long serialVersionUID = -4410268653794610252L; // // public InfluxDBException() { // super(); // } // // public InfluxDBException(String message, Throwable cause) { // super(message, cause); // } // // public InfluxDBException(String message) { // super(message); // } // // public InfluxDBException(Throwable cause) { // super(cause); // } // } // // Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/ql/InfluxQLStatement.java // public static enum ACTION { // SELECT, EXECUTE // } // Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/ql/InfluxQLMapper.java import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import org.springframework.beans.factory.xml.DefaultDocumentLoader; import org.springframework.beans.factory.xml.DocumentLoader; import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.InputStreamResource; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.util.xml.XmlValidationModeDetector; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import com.vgerbot.orm.influxdb.InfluxDBException; import com.vgerbot.orm.influxdb.ql.InfluxQLStatement.ACTION; @Override public void fatalError(SAXParseException exception) throws SAXException { logger.log(Level.SEVERE, exception.getMessage(), exception); } @Override public void error(SAXParseException exception) throws SAXException { logger.log(Level.OFF, exception.getMessage(), exception); } }; private InfluxQLMapper() { } public InfluxQLStatement getStatement(String key) { return statementsMap.get(key); } public InfluxQLMapper union(InfluxQLMapper other) { InfluxQLMapper newmapper = new InfluxQLMapper(); newmapper.statementsMap.putAll(this.statementsMap); newmapper.statementsMap.putAll(other.statementsMap); return newmapper; } public static final InfluxQLMapper empty() { return new InfluxQLMapper(); }
public static final InfluxQLMapper parseFrom(String resourceLocation) throws InfluxDBException {
y1j2x34/spring-influxdb-orm
spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/ql/InfluxQLMapper.java
// Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/InfluxDBException.java // public class InfluxDBException extends RuntimeException { // // private static final long serialVersionUID = -4410268653794610252L; // // public InfluxDBException() { // super(); // } // // public InfluxDBException(String message, Throwable cause) { // super(message, cause); // } // // public InfluxDBException(String message) { // super(message); // } // // public InfluxDBException(Throwable cause) { // super(cause); // } // } // // Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/ql/InfluxQLStatement.java // public static enum ACTION { // SELECT, EXECUTE // }
import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import org.springframework.beans.factory.xml.DefaultDocumentLoader; import org.springframework.beans.factory.xml.DocumentLoader; import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.InputStreamResource; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.util.xml.XmlValidationModeDetector; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import com.vgerbot.orm.influxdb.InfluxDBException; import com.vgerbot.orm.influxdb.ql.InfluxQLStatement.ACTION;
} Element root = document.getDocumentElement(); NodeList includeNodeList = root.getElementsByTagName("include"); InfluxQLMapper mapper = new InfluxQLMapper(); for (int i = 0; i < includeNodeList.getLength(); i++) { Node item = includeNodeList.item(i); String location = item.getAttributes().getNamedItem("path").getNodeValue(); Resource includedResource = resourceLoader.getResource(location); InfluxQLMapper includedMapper = parseFrom(includedResource); mapper = mapper.union(includedMapper); } mapper.statementsMap.putAll(parseQLTag(root, "select")); mapper.statementsMap.putAll(parseQLTag(root, "execute")); return mapper; } private static Map<String, InfluxQLStatement> parseQLTag(Element root, String tagName) { NodeList nodeList = root.getElementsByTagName(tagName); Map<String, InfluxQLStatement> map = new HashMap<>(); for (int i = 0; i < nodeList.getLength(); i++) { Node item = nodeList.item(i); String id = item.getAttributes().getNamedItem("id").getNodeValue(); String ql = item.getTextContent().trim(); if (map.containsKey(id)) { throw new InfluxDBException("Duplicate " + tagName + " ql id: " + id); }
// Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/InfluxDBException.java // public class InfluxDBException extends RuntimeException { // // private static final long serialVersionUID = -4410268653794610252L; // // public InfluxDBException() { // super(); // } // // public InfluxDBException(String message, Throwable cause) { // super(message, cause); // } // // public InfluxDBException(String message) { // super(message); // } // // public InfluxDBException(Throwable cause) { // super(cause); // } // } // // Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/ql/InfluxQLStatement.java // public static enum ACTION { // SELECT, EXECUTE // } // Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/ql/InfluxQLMapper.java import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import org.springframework.beans.factory.xml.DefaultDocumentLoader; import org.springframework.beans.factory.xml.DocumentLoader; import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.InputStreamResource; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.util.xml.XmlValidationModeDetector; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import com.vgerbot.orm.influxdb.InfluxDBException; import com.vgerbot.orm.influxdb.ql.InfluxQLStatement.ACTION; } Element root = document.getDocumentElement(); NodeList includeNodeList = root.getElementsByTagName("include"); InfluxQLMapper mapper = new InfluxQLMapper(); for (int i = 0; i < includeNodeList.getLength(); i++) { Node item = includeNodeList.item(i); String location = item.getAttributes().getNamedItem("path").getNodeValue(); Resource includedResource = resourceLoader.getResource(location); InfluxQLMapper includedMapper = parseFrom(includedResource); mapper = mapper.union(includedMapper); } mapper.statementsMap.putAll(parseQLTag(root, "select")); mapper.statementsMap.putAll(parseQLTag(root, "execute")); return mapper; } private static Map<String, InfluxQLStatement> parseQLTag(Element root, String tagName) { NodeList nodeList = root.getElementsByTagName(tagName); Map<String, InfluxQLStatement> map = new HashMap<>(); for (int i = 0; i < nodeList.getLength(); i++) { Node item = nodeList.item(i); String id = item.getAttributes().getNamedItem("id").getNodeValue(); String ql = item.getTextContent().trim(); if (map.containsKey(id)) { throw new InfluxDBException("Duplicate " + tagName + " ql id: " + id); }
map.put(id, new InfluxQLStatement(ql, ACTION.valueOf(tagName.toUpperCase())));
y1j2x34/spring-influxdb-orm
spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/metadata/MeasurementClassMetadata.java
// Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/InfluxDBException.java // public class InfluxDBException extends RuntimeException { // // private static final long serialVersionUID = -4410268653794610252L; // // public InfluxDBException() { // super(); // } // // public InfluxDBException(String message, Throwable cause) { // super(message, cause); // } // // public InfluxDBException(String message) { // super(message); // } // // public InfluxDBException(Throwable cause) { // super(cause); // } // }
import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.io.Serializable; import java.lang.reflect.Field; import java.util.Date; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.springframework.util.ReflectionUtils; import com.vgerbot.orm.influxdb.InfluxDBException; import com.vgerbot.orm.influxdb.annotations.FieldColumn; import com.vgerbot.orm.influxdb.annotations.InfluxDBMeasurement; import com.vgerbot.orm.influxdb.annotations.TagColumn;
package com.vgerbot.orm.influxdb.metadata; public class MeasurementClassMetadata { private final String measurementName; private final String retentionPolicy; private final Class<? extends Serializable> measurementClass; private final PropertyDescriptor shardingFieldDescriptor; private final PropertyDescriptor timeFieldDescriptor; /** * map<数据库名称, java字段名称> */ private final Map<String, String> tagColumnJavaFieldNameMap; /** * map<数据库字段名称, java字段名称> */ private final Map<String, String> fieldColumnJavaFieldNameMap; /** * map<数据库字段名称, PropertyDescriptor> */ private final Map<String, PropertyDescriptor> tagColumnDescriptors; /** * map<数据库字段名称, PropertyDescriptor> */ private final Map<String, PropertyDescriptor> fieldColumnDescriptors; private boolean isJavaUtilDateTimeField; private boolean isNumberTimeField; private boolean isStringTimeField; private String[] datetimePatterns; private final int _hashcode; public MeasurementClassMetadata(Class<? extends Serializable> measurementClass, String defaultRetentionPolicy) { this.measurementClass = measurementClass; tagColumnJavaFieldNameMap = new HashMap<>(); fieldColumnJavaFieldNameMap = new HashMap<>(); tagColumnDescriptors = new HashMap<>(); fieldColumnDescriptors = new HashMap<>(); Map<String, PropertyDescriptor> descriptorsMap = descriptorsMap(measurementClass); timeFieldDescriptor = descriptorsMap.get("time"); assertTimeFieldDescriptorNotNull(); Class<?> timeFieldType = timeFieldDescriptor.getPropertyType(); isJavaUtilDateTimeField = Date.class.isAssignableFrom(timeFieldType); isNumberTimeField = Number.class.isAssignableFrom(timeFieldType); isStringTimeField = CharSequence.class.isAssignableFrom(timeFieldType); if (!isJavaUtilDateTimeField && !isNumberTimeField && !isStringTimeField) {
// Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/InfluxDBException.java // public class InfluxDBException extends RuntimeException { // // private static final long serialVersionUID = -4410268653794610252L; // // public InfluxDBException() { // super(); // } // // public InfluxDBException(String message, Throwable cause) { // super(message, cause); // } // // public InfluxDBException(String message) { // super(message); // } // // public InfluxDBException(Throwable cause) { // super(cause); // } // } // Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/metadata/MeasurementClassMetadata.java import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.io.Serializable; import java.lang.reflect.Field; import java.util.Date; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.springframework.util.ReflectionUtils; import com.vgerbot.orm.influxdb.InfluxDBException; import com.vgerbot.orm.influxdb.annotations.FieldColumn; import com.vgerbot.orm.influxdb.annotations.InfluxDBMeasurement; import com.vgerbot.orm.influxdb.annotations.TagColumn; package com.vgerbot.orm.influxdb.metadata; public class MeasurementClassMetadata { private final String measurementName; private final String retentionPolicy; private final Class<? extends Serializable> measurementClass; private final PropertyDescriptor shardingFieldDescriptor; private final PropertyDescriptor timeFieldDescriptor; /** * map<数据库名称, java字段名称> */ private final Map<String, String> tagColumnJavaFieldNameMap; /** * map<数据库字段名称, java字段名称> */ private final Map<String, String> fieldColumnJavaFieldNameMap; /** * map<数据库字段名称, PropertyDescriptor> */ private final Map<String, PropertyDescriptor> tagColumnDescriptors; /** * map<数据库字段名称, PropertyDescriptor> */ private final Map<String, PropertyDescriptor> fieldColumnDescriptors; private boolean isJavaUtilDateTimeField; private boolean isNumberTimeField; private boolean isStringTimeField; private String[] datetimePatterns; private final int _hashcode; public MeasurementClassMetadata(Class<? extends Serializable> measurementClass, String defaultRetentionPolicy) { this.measurementClass = measurementClass; tagColumnJavaFieldNameMap = new HashMap<>(); fieldColumnJavaFieldNameMap = new HashMap<>(); tagColumnDescriptors = new HashMap<>(); fieldColumnDescriptors = new HashMap<>(); Map<String, PropertyDescriptor> descriptorsMap = descriptorsMap(measurementClass); timeFieldDescriptor = descriptorsMap.get("time"); assertTimeFieldDescriptorNotNull(); Class<?> timeFieldType = timeFieldDescriptor.getPropertyType(); isJavaUtilDateTimeField = Date.class.isAssignableFrom(timeFieldType); isNumberTimeField = Number.class.isAssignableFrom(timeFieldType); isStringTimeField = CharSequence.class.isAssignableFrom(timeFieldType); if (!isJavaUtilDateTimeField && !isNumberTimeField && !isStringTimeField) {
throw new InfluxDBException("Unsupported time field type: " + timeFieldType);
y1j2x34/spring-influxdb-orm
spring-influxdb-orm/src/test/java/com/vgerbot/test/orm/influxdb/utils/CommandUtilsTest.java
// Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/param/ParameterSignature.java // public class ParameterSignature { // private final int index; // private final String name; // private final Class<?> type; // // private ParameterSignature(int index, String name, Class<?> type) { // super(); // this.index = index; // this.name = name; // this.type = type; // } // // public static ParameterSignature signature(int index, Parameter parameter, String aliasName) { // Class<?> type = parameter.getType(); // return new ParameterSignature(index, aliasName, type); // } // // public static ParameterSignature signature(int index, Parameter parameter) { // String name = parameter.getName(); // Class<?> type = parameter.getType(); // return new ParameterSignature(index, name, type); // } // // public static List<ParameterSignature> signatures(Method method) { // Parameter[] parameters = method.getParameters(); // List<ParameterSignature> signatures = new ArrayList<>(parameters.length); // // for (int i = 0; i < parameters.length; i++) { // Parameter parameter = parameters[i]; // signatures.add(signature(i, parameter)); // } // // return signatures; // } // // public int getIndex() { // return index; // } // // public String getName() { // return name; // } // // public Class<?> getType() { // return type; // } // // public ParameterValue value(Object value) { // return new ParameterValue(value, this); // } // } // // Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/param/ParameterValue.java // public class ParameterValue { // private final Object value; // private final ParameterSignature signature; // // public ParameterValue(Object value, ParameterSignature signature) { // super(); // this.value = value; // this.signature = signature; // } // // public Object getValue() { // return value; // } // // public ParameterSignature getSignature() { // return signature; // } // // } // // Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/utils/CommandUtils.java // public class CommandUtils { // public static String parseCommand(String command, final Map<String, ParameterValue> parameters) { // command = StringUtils.replace(command, "\\$\\{([^\\}]+)\\}", 1, new ReplaceCallback() { // @Override // public String replace(String word, int index, String source) { // ParameterValue parameterValue = parameters.get(word); // if (parameterValue == null || parameterValue.getValue() == null) { // return ""; // } // Object value = parameterValue.getValue(); // return value.toString(); // } // }); // command = StringUtils.replace(command, "\\#\\{([^\\}]+)\\}", 1, new ReplaceCallback() { // @Override // public String replace(String word, int index, String source) { // ParameterValue parameterValue = parameters.get(word); // if (parameterValue == null) { // return ""; // } // Object value = parameterValue.getValue(); // if (value == null) { // return "null"; // } // Class<?> type = parameterValue.getSignature().getType(); // if (CharSequence.class.isAssignableFrom(type)) { // return "'" + value + "'"; // } else if (Date.class.isInstance(value)) { // return Long.toString(TimeUnit.MILLISECONDS.toNanos(((Date) value).getTime()), 10); // } // return value.toString(); // } // }); // return command; // } // }
import com.vgerbot.orm.influxdb.param.ParameterSignature; import com.vgerbot.orm.influxdb.param.ParameterValue; import com.vgerbot.orm.influxdb.utils.CommandUtils; import org.junit.Test; import static org.junit.Assert.*; import static org.hamcrest.CoreMatchers.*; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; import java.lang.reflect.Modifier; import java.lang.reflect.Parameter; import java.time.Instant; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import static org.mockito.Mockito.*;
package com.vgerbot.test.orm.influxdb.utils; @RunWith(MockitoJUnitRunner.class) public class CommandUtilsTest { private static final Date CONST_BIRTHDAY = Date.from(Instant.parse("2019-09-14T16:26:41.00Z"));
// Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/param/ParameterSignature.java // public class ParameterSignature { // private final int index; // private final String name; // private final Class<?> type; // // private ParameterSignature(int index, String name, Class<?> type) { // super(); // this.index = index; // this.name = name; // this.type = type; // } // // public static ParameterSignature signature(int index, Parameter parameter, String aliasName) { // Class<?> type = parameter.getType(); // return new ParameterSignature(index, aliasName, type); // } // // public static ParameterSignature signature(int index, Parameter parameter) { // String name = parameter.getName(); // Class<?> type = parameter.getType(); // return new ParameterSignature(index, name, type); // } // // public static List<ParameterSignature> signatures(Method method) { // Parameter[] parameters = method.getParameters(); // List<ParameterSignature> signatures = new ArrayList<>(parameters.length); // // for (int i = 0; i < parameters.length; i++) { // Parameter parameter = parameters[i]; // signatures.add(signature(i, parameter)); // } // // return signatures; // } // // public int getIndex() { // return index; // } // // public String getName() { // return name; // } // // public Class<?> getType() { // return type; // } // // public ParameterValue value(Object value) { // return new ParameterValue(value, this); // } // } // // Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/param/ParameterValue.java // public class ParameterValue { // private final Object value; // private final ParameterSignature signature; // // public ParameterValue(Object value, ParameterSignature signature) { // super(); // this.value = value; // this.signature = signature; // } // // public Object getValue() { // return value; // } // // public ParameterSignature getSignature() { // return signature; // } // // } // // Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/utils/CommandUtils.java // public class CommandUtils { // public static String parseCommand(String command, final Map<String, ParameterValue> parameters) { // command = StringUtils.replace(command, "\\$\\{([^\\}]+)\\}", 1, new ReplaceCallback() { // @Override // public String replace(String word, int index, String source) { // ParameterValue parameterValue = parameters.get(word); // if (parameterValue == null || parameterValue.getValue() == null) { // return ""; // } // Object value = parameterValue.getValue(); // return value.toString(); // } // }); // command = StringUtils.replace(command, "\\#\\{([^\\}]+)\\}", 1, new ReplaceCallback() { // @Override // public String replace(String word, int index, String source) { // ParameterValue parameterValue = parameters.get(word); // if (parameterValue == null) { // return ""; // } // Object value = parameterValue.getValue(); // if (value == null) { // return "null"; // } // Class<?> type = parameterValue.getSignature().getType(); // if (CharSequence.class.isAssignableFrom(type)) { // return "'" + value + "'"; // } else if (Date.class.isInstance(value)) { // return Long.toString(TimeUnit.MILLISECONDS.toNanos(((Date) value).getTime()), 10); // } // return value.toString(); // } // }); // return command; // } // } // Path: spring-influxdb-orm/src/test/java/com/vgerbot/test/orm/influxdb/utils/CommandUtilsTest.java import com.vgerbot.orm.influxdb.param.ParameterSignature; import com.vgerbot.orm.influxdb.param.ParameterValue; import com.vgerbot.orm.influxdb.utils.CommandUtils; import org.junit.Test; import static org.junit.Assert.*; import static org.hamcrest.CoreMatchers.*; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; import java.lang.reflect.Modifier; import java.lang.reflect.Parameter; import java.time.Instant; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import static org.mockito.Mockito.*; package com.vgerbot.test.orm.influxdb.utils; @RunWith(MockitoJUnitRunner.class) public class CommandUtilsTest { private static final Date CONST_BIRTHDAY = Date.from(Instant.parse("2019-09-14T16:26:41.00Z"));
private Map<String, ParameterValue> parameterValues = new HashMap<String, ParameterValue>() {{
y1j2x34/spring-influxdb-orm
spring-influxdb-orm/src/test/java/com/vgerbot/test/orm/influxdb/utils/CommandUtilsTest.java
// Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/param/ParameterSignature.java // public class ParameterSignature { // private final int index; // private final String name; // private final Class<?> type; // // private ParameterSignature(int index, String name, Class<?> type) { // super(); // this.index = index; // this.name = name; // this.type = type; // } // // public static ParameterSignature signature(int index, Parameter parameter, String aliasName) { // Class<?> type = parameter.getType(); // return new ParameterSignature(index, aliasName, type); // } // // public static ParameterSignature signature(int index, Parameter parameter) { // String name = parameter.getName(); // Class<?> type = parameter.getType(); // return new ParameterSignature(index, name, type); // } // // public static List<ParameterSignature> signatures(Method method) { // Parameter[] parameters = method.getParameters(); // List<ParameterSignature> signatures = new ArrayList<>(parameters.length); // // for (int i = 0; i < parameters.length; i++) { // Parameter parameter = parameters[i]; // signatures.add(signature(i, parameter)); // } // // return signatures; // } // // public int getIndex() { // return index; // } // // public String getName() { // return name; // } // // public Class<?> getType() { // return type; // } // // public ParameterValue value(Object value) { // return new ParameterValue(value, this); // } // } // // Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/param/ParameterValue.java // public class ParameterValue { // private final Object value; // private final ParameterSignature signature; // // public ParameterValue(Object value, ParameterSignature signature) { // super(); // this.value = value; // this.signature = signature; // } // // public Object getValue() { // return value; // } // // public ParameterSignature getSignature() { // return signature; // } // // } // // Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/utils/CommandUtils.java // public class CommandUtils { // public static String parseCommand(String command, final Map<String, ParameterValue> parameters) { // command = StringUtils.replace(command, "\\$\\{([^\\}]+)\\}", 1, new ReplaceCallback() { // @Override // public String replace(String word, int index, String source) { // ParameterValue parameterValue = parameters.get(word); // if (parameterValue == null || parameterValue.getValue() == null) { // return ""; // } // Object value = parameterValue.getValue(); // return value.toString(); // } // }); // command = StringUtils.replace(command, "\\#\\{([^\\}]+)\\}", 1, new ReplaceCallback() { // @Override // public String replace(String word, int index, String source) { // ParameterValue parameterValue = parameters.get(word); // if (parameterValue == null) { // return ""; // } // Object value = parameterValue.getValue(); // if (value == null) { // return "null"; // } // Class<?> type = parameterValue.getSignature().getType(); // if (CharSequence.class.isAssignableFrom(type)) { // return "'" + value + "'"; // } else if (Date.class.isInstance(value)) { // return Long.toString(TimeUnit.MILLISECONDS.toNanos(((Date) value).getTime()), 10); // } // return value.toString(); // } // }); // return command; // } // }
import com.vgerbot.orm.influxdb.param.ParameterSignature; import com.vgerbot.orm.influxdb.param.ParameterValue; import com.vgerbot.orm.influxdb.utils.CommandUtils; import org.junit.Test; import static org.junit.Assert.*; import static org.hamcrest.CoreMatchers.*; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; import java.lang.reflect.Modifier; import java.lang.reflect.Parameter; import java.time.Instant; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import static org.mockito.Mockito.*;
package com.vgerbot.test.orm.influxdb.utils; @RunWith(MockitoJUnitRunner.class) public class CommandUtilsTest { private static final Date CONST_BIRTHDAY = Date.from(Instant.parse("2019-09-14T16:26:41.00Z")); private Map<String, ParameterValue> parameterValues = new HashMap<String, ParameterValue>() {{ this.put("nickname", createParameterValue("nickname", String.class, "mario")); this.put("age", createParameterValue("age", Integer.class, 18)); this.put("birthday", createParameterValue("birthday", Date.class, CONST_BIRTHDAY)); this.put("null-value", createParameterValue("null-value", Object.class, null)); }}; @Test public void shouldReplaceToEmptyStringIfPlaceholderNotInParameterValuesMap(){
// Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/param/ParameterSignature.java // public class ParameterSignature { // private final int index; // private final String name; // private final Class<?> type; // // private ParameterSignature(int index, String name, Class<?> type) { // super(); // this.index = index; // this.name = name; // this.type = type; // } // // public static ParameterSignature signature(int index, Parameter parameter, String aliasName) { // Class<?> type = parameter.getType(); // return new ParameterSignature(index, aliasName, type); // } // // public static ParameterSignature signature(int index, Parameter parameter) { // String name = parameter.getName(); // Class<?> type = parameter.getType(); // return new ParameterSignature(index, name, type); // } // // public static List<ParameterSignature> signatures(Method method) { // Parameter[] parameters = method.getParameters(); // List<ParameterSignature> signatures = new ArrayList<>(parameters.length); // // for (int i = 0; i < parameters.length; i++) { // Parameter parameter = parameters[i]; // signatures.add(signature(i, parameter)); // } // // return signatures; // } // // public int getIndex() { // return index; // } // // public String getName() { // return name; // } // // public Class<?> getType() { // return type; // } // // public ParameterValue value(Object value) { // return new ParameterValue(value, this); // } // } // // Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/param/ParameterValue.java // public class ParameterValue { // private final Object value; // private final ParameterSignature signature; // // public ParameterValue(Object value, ParameterSignature signature) { // super(); // this.value = value; // this.signature = signature; // } // // public Object getValue() { // return value; // } // // public ParameterSignature getSignature() { // return signature; // } // // } // // Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/utils/CommandUtils.java // public class CommandUtils { // public static String parseCommand(String command, final Map<String, ParameterValue> parameters) { // command = StringUtils.replace(command, "\\$\\{([^\\}]+)\\}", 1, new ReplaceCallback() { // @Override // public String replace(String word, int index, String source) { // ParameterValue parameterValue = parameters.get(word); // if (parameterValue == null || parameterValue.getValue() == null) { // return ""; // } // Object value = parameterValue.getValue(); // return value.toString(); // } // }); // command = StringUtils.replace(command, "\\#\\{([^\\}]+)\\}", 1, new ReplaceCallback() { // @Override // public String replace(String word, int index, String source) { // ParameterValue parameterValue = parameters.get(word); // if (parameterValue == null) { // return ""; // } // Object value = parameterValue.getValue(); // if (value == null) { // return "null"; // } // Class<?> type = parameterValue.getSignature().getType(); // if (CharSequence.class.isAssignableFrom(type)) { // return "'" + value + "'"; // } else if (Date.class.isInstance(value)) { // return Long.toString(TimeUnit.MILLISECONDS.toNanos(((Date) value).getTime()), 10); // } // return value.toString(); // } // }); // return command; // } // } // Path: spring-influxdb-orm/src/test/java/com/vgerbot/test/orm/influxdb/utils/CommandUtilsTest.java import com.vgerbot.orm.influxdb.param.ParameterSignature; import com.vgerbot.orm.influxdb.param.ParameterValue; import com.vgerbot.orm.influxdb.utils.CommandUtils; import org.junit.Test; import static org.junit.Assert.*; import static org.hamcrest.CoreMatchers.*; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; import java.lang.reflect.Modifier; import java.lang.reflect.Parameter; import java.time.Instant; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import static org.mockito.Mockito.*; package com.vgerbot.test.orm.influxdb.utils; @RunWith(MockitoJUnitRunner.class) public class CommandUtilsTest { private static final Date CONST_BIRTHDAY = Date.from(Instant.parse("2019-09-14T16:26:41.00Z")); private Map<String, ParameterValue> parameterValues = new HashMap<String, ParameterValue>() {{ this.put("nickname", createParameterValue("nickname", String.class, "mario")); this.put("age", createParameterValue("age", Integer.class, 18)); this.put("birthday", createParameterValue("birthday", Date.class, CONST_BIRTHDAY)); this.put("null-value", createParameterValue("null-value", Object.class, null)); }}; @Test public void shouldReplaceToEmptyStringIfPlaceholderNotInParameterValuesMap(){
String parsedCommand = CommandUtils.parseCommand("select * from table_name where nickname=${invalid_field}", parameterValues);
y1j2x34/spring-influxdb-orm
spring-influxdb-orm/src/test/java/com/vgerbot/test/orm/influxdb/utils/CommandUtilsTest.java
// Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/param/ParameterSignature.java // public class ParameterSignature { // private final int index; // private final String name; // private final Class<?> type; // // private ParameterSignature(int index, String name, Class<?> type) { // super(); // this.index = index; // this.name = name; // this.type = type; // } // // public static ParameterSignature signature(int index, Parameter parameter, String aliasName) { // Class<?> type = parameter.getType(); // return new ParameterSignature(index, aliasName, type); // } // // public static ParameterSignature signature(int index, Parameter parameter) { // String name = parameter.getName(); // Class<?> type = parameter.getType(); // return new ParameterSignature(index, name, type); // } // // public static List<ParameterSignature> signatures(Method method) { // Parameter[] parameters = method.getParameters(); // List<ParameterSignature> signatures = new ArrayList<>(parameters.length); // // for (int i = 0; i < parameters.length; i++) { // Parameter parameter = parameters[i]; // signatures.add(signature(i, parameter)); // } // // return signatures; // } // // public int getIndex() { // return index; // } // // public String getName() { // return name; // } // // public Class<?> getType() { // return type; // } // // public ParameterValue value(Object value) { // return new ParameterValue(value, this); // } // } // // Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/param/ParameterValue.java // public class ParameterValue { // private final Object value; // private final ParameterSignature signature; // // public ParameterValue(Object value, ParameterSignature signature) { // super(); // this.value = value; // this.signature = signature; // } // // public Object getValue() { // return value; // } // // public ParameterSignature getSignature() { // return signature; // } // // } // // Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/utils/CommandUtils.java // public class CommandUtils { // public static String parseCommand(String command, final Map<String, ParameterValue> parameters) { // command = StringUtils.replace(command, "\\$\\{([^\\}]+)\\}", 1, new ReplaceCallback() { // @Override // public String replace(String word, int index, String source) { // ParameterValue parameterValue = parameters.get(word); // if (parameterValue == null || parameterValue.getValue() == null) { // return ""; // } // Object value = parameterValue.getValue(); // return value.toString(); // } // }); // command = StringUtils.replace(command, "\\#\\{([^\\}]+)\\}", 1, new ReplaceCallback() { // @Override // public String replace(String word, int index, String source) { // ParameterValue parameterValue = parameters.get(word); // if (parameterValue == null) { // return ""; // } // Object value = parameterValue.getValue(); // if (value == null) { // return "null"; // } // Class<?> type = parameterValue.getSignature().getType(); // if (CharSequence.class.isAssignableFrom(type)) { // return "'" + value + "'"; // } else if (Date.class.isInstance(value)) { // return Long.toString(TimeUnit.MILLISECONDS.toNanos(((Date) value).getTime()), 10); // } // return value.toString(); // } // }); // return command; // } // }
import com.vgerbot.orm.influxdb.param.ParameterSignature; import com.vgerbot.orm.influxdb.param.ParameterValue; import com.vgerbot.orm.influxdb.utils.CommandUtils; import org.junit.Test; import static org.junit.Assert.*; import static org.hamcrest.CoreMatchers.*; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; import java.lang.reflect.Modifier; import java.lang.reflect.Parameter; import java.time.Instant; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import static org.mockito.Mockito.*;
@Test public void shouldReplaceToEmptyStringIfValueOfPlaceholderIsNull() { String parsedCommand = CommandUtils.parseCommand("select * from table_name where nv=${null-value}", parameterValues); assertThat(parsedCommand, equalTo("select * from table_name where nv=")); } @Test public void shouldReplacePlaceholdersCorrect() { String parsedCommand = CommandUtils.parseCommand("select * from table_name where nv=${nickname} and age=${age}", parameterValues); assertThat(parsedCommand, equalTo("select * from table_name where nv=mario and age=18")); } @Test public void shouldReplaceCharSequenceRawValueToStringWithAPairOfQuotes() { String parsedCommand = CommandUtils.parseCommand("select * from table_name where nv=#{nickname}", parameterValues); assertThat(parsedCommand, equalTo("select * from table_name where nv='mario'")); } @Test public void shouldReplaceDateObjectToNanosNumeric() { String parsedCommand = CommandUtils.parseCommand("#{birthday}", parameterValues); assertThat(parsedCommand, equalTo(Long.toString(TimeUnit.MILLISECONDS.toNanos(CONST_BIRTHDAY.getTime()),10))); } private static <T> Parameter createParameter(String name, Class<T> type) { Parameter parameter = mock(Parameter.class); when(parameter.getName()).thenReturn(name); when((Object)parameter.getType()).thenReturn((Object)type); return parameter; } private static <T> ParameterValue createParameterValue(String name, Class<T> type, T value) { Parameter parameter = createParameter(name, type);
// Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/param/ParameterSignature.java // public class ParameterSignature { // private final int index; // private final String name; // private final Class<?> type; // // private ParameterSignature(int index, String name, Class<?> type) { // super(); // this.index = index; // this.name = name; // this.type = type; // } // // public static ParameterSignature signature(int index, Parameter parameter, String aliasName) { // Class<?> type = parameter.getType(); // return new ParameterSignature(index, aliasName, type); // } // // public static ParameterSignature signature(int index, Parameter parameter) { // String name = parameter.getName(); // Class<?> type = parameter.getType(); // return new ParameterSignature(index, name, type); // } // // public static List<ParameterSignature> signatures(Method method) { // Parameter[] parameters = method.getParameters(); // List<ParameterSignature> signatures = new ArrayList<>(parameters.length); // // for (int i = 0; i < parameters.length; i++) { // Parameter parameter = parameters[i]; // signatures.add(signature(i, parameter)); // } // // return signatures; // } // // public int getIndex() { // return index; // } // // public String getName() { // return name; // } // // public Class<?> getType() { // return type; // } // // public ParameterValue value(Object value) { // return new ParameterValue(value, this); // } // } // // Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/param/ParameterValue.java // public class ParameterValue { // private final Object value; // private final ParameterSignature signature; // // public ParameterValue(Object value, ParameterSignature signature) { // super(); // this.value = value; // this.signature = signature; // } // // public Object getValue() { // return value; // } // // public ParameterSignature getSignature() { // return signature; // } // // } // // Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/utils/CommandUtils.java // public class CommandUtils { // public static String parseCommand(String command, final Map<String, ParameterValue> parameters) { // command = StringUtils.replace(command, "\\$\\{([^\\}]+)\\}", 1, new ReplaceCallback() { // @Override // public String replace(String word, int index, String source) { // ParameterValue parameterValue = parameters.get(word); // if (parameterValue == null || parameterValue.getValue() == null) { // return ""; // } // Object value = parameterValue.getValue(); // return value.toString(); // } // }); // command = StringUtils.replace(command, "\\#\\{([^\\}]+)\\}", 1, new ReplaceCallback() { // @Override // public String replace(String word, int index, String source) { // ParameterValue parameterValue = parameters.get(word); // if (parameterValue == null) { // return ""; // } // Object value = parameterValue.getValue(); // if (value == null) { // return "null"; // } // Class<?> type = parameterValue.getSignature().getType(); // if (CharSequence.class.isAssignableFrom(type)) { // return "'" + value + "'"; // } else if (Date.class.isInstance(value)) { // return Long.toString(TimeUnit.MILLISECONDS.toNanos(((Date) value).getTime()), 10); // } // return value.toString(); // } // }); // return command; // } // } // Path: spring-influxdb-orm/src/test/java/com/vgerbot/test/orm/influxdb/utils/CommandUtilsTest.java import com.vgerbot.orm.influxdb.param.ParameterSignature; import com.vgerbot.orm.influxdb.param.ParameterValue; import com.vgerbot.orm.influxdb.utils.CommandUtils; import org.junit.Test; import static org.junit.Assert.*; import static org.hamcrest.CoreMatchers.*; import org.junit.runner.RunWith; import org.mockito.junit.MockitoJUnitRunner; import java.lang.reflect.Modifier; import java.lang.reflect.Parameter; import java.time.Instant; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import static org.mockito.Mockito.*; @Test public void shouldReplaceToEmptyStringIfValueOfPlaceholderIsNull() { String parsedCommand = CommandUtils.parseCommand("select * from table_name where nv=${null-value}", parameterValues); assertThat(parsedCommand, equalTo("select * from table_name where nv=")); } @Test public void shouldReplacePlaceholdersCorrect() { String parsedCommand = CommandUtils.parseCommand("select * from table_name where nv=${nickname} and age=${age}", parameterValues); assertThat(parsedCommand, equalTo("select * from table_name where nv=mario and age=18")); } @Test public void shouldReplaceCharSequenceRawValueToStringWithAPairOfQuotes() { String parsedCommand = CommandUtils.parseCommand("select * from table_name where nv=#{nickname}", parameterValues); assertThat(parsedCommand, equalTo("select * from table_name where nv='mario'")); } @Test public void shouldReplaceDateObjectToNanosNumeric() { String parsedCommand = CommandUtils.parseCommand("#{birthday}", parameterValues); assertThat(parsedCommand, equalTo(Long.toString(TimeUnit.MILLISECONDS.toNanos(CONST_BIRTHDAY.getTime()),10))); } private static <T> Parameter createParameter(String name, Class<T> type) { Parameter parameter = mock(Parameter.class); when(parameter.getName()).thenReturn(name); when((Object)parameter.getType()).thenReturn((Object)type); return parameter; } private static <T> ParameterValue createParameterValue(String name, Class<T> type, T value) { Parameter parameter = createParameter(name, type);
return new ParameterValue(value, ParameterSignature.signature(0, parameter));
y1j2x34/spring-influxdb-orm
spring-influxdb-orm-autoconfigure/src/test/java/com/vgerbot/orm/influxdb/App.java
// Path: spring-influxdb-orm-autoconfigure/src/test/java/com/vgerbot/orm/influxdb/test/dao/CensusDao.java // public interface CensusDao extends InfluxDBDao<CensusMeasurement> { // // @InfluxDBSelect("select * from census where scientist = #{scientist}") // public List<CensusMeasurement> selectByScientist(@InfluxDBParam("scientist") String scientist); // // @InfluxDBExecute("DROP SERIES FROM census where scientist=#{scientist} and location=#{location}") // public void deleteSeries( // // @InfluxDBParam("scientist") String scientist, // // @InfluxDBParam("location") Integer location // // ); // // @InfluxDBSelect("select scientist,location,butterflies from census where scientist = #{scientist}") // public List<Map<String, Integer>> selectButterflies( // // @InfluxDBParam("scientist") String scientist, // // @InfluxDBParam("location") Integer location // // ); // // @SpecifiedExecutor(HelloWorldExecutor.class) // public void hello(); // // @InfluxQL // public List<Map<String, Object>> findByScientist(@InfluxDBParam("scientist") String scientist); // // class HelloWorldExecutor extends Executor { // // public HelloWorldExecutor(InfluxDBRepository repository) { // super(repository); // } // // @Override // public ResultContext execute(MapperMethod method, Map<String, ParameterValue> parameters) { // System.out.println("hello world"); // return ResultContext.VOID; // } // } // } // // Path: spring-influxdb-orm-autoconfigure/src/test/java/com/vgerbot/orm/influxdb/test/entity/CensusMeasurement.java // @InfluxDBMeasurement("census") // public class CensusMeasurement implements Serializable { // private static final long serialVersionUID = 8260424450884444916L; // // private Date time; // // @TagColumn("location") // private String location; // @TagColumn("scientist") // private String scientist; // // @FieldColumn("butterflies") // private Integer butterflies; // @FieldColumn("honeybees") // private Integer honeybees; // // public Date getTime() { // return time; // } // // public void setTime(Date time) { // this.time = time; // } // // public String getLocation() { // return location; // } // // public void setLocation(String location) { // this.location = location; // } // // public String getScientist() { // return scientist; // } // // public void setScientist(String scientist) { // this.scientist = scientist; // } // // public Integer getButterflies() { // return butterflies; // } // // public void setButterflies(Integer butterflies) { // this.butterflies = butterflies; // } // // public Integer getHoneybees() { // return honeybees; // } // // public void setHoneybees(Integer honeybees) { // this.honeybees = honeybees; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((location == null) ? 0 : location.hashCode()); // result = prime * result + ((scientist == null) ? 0 : scientist.hashCode()); // result = prime * result + ((time == null) ? 0 : time.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // CensusMeasurement other = (CensusMeasurement) obj; // if (location == null) { // if (other.location != null) { // return false; // } // } else if (!location.equals(other.location)) { // return false; // } // if (scientist == null) { // if (other.scientist != null) { // return false; // } // } else if (!scientist.equals(other.scientist)) { // return false; // } // if (time == null) { // if (other.time != null) { // return false; // } // } else if (!time.equals(other.time)) { // return false; // } // return true; // } // // public String toString() { // return "[time: " + time.getTime() + ", location: " + location + ", scientist: " + scientist + ", butterflies: " + butterflies // + ", honeybees: " + honeybees + "]"; // } // }
import com.vgerbot.orm.influxdb.annotations.InfluxDBORM; import com.vgerbot.orm.influxdb.test.dao.CensusDao; import com.vgerbot.orm.influxdb.test.entity.CensusMeasurement; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import javax.annotation.Resource; import java.util.List;
package com.vgerbot.orm.influxdb; @SpringBootApplication @InfluxDBORM( daoBasePackage = "com.vgerbot.orm.influxdb.test.dao", entityBasePackage = "com.vgerbot.orm.influxdb.test.entity" ) public class App implements CommandLineRunner { @Resource
// Path: spring-influxdb-orm-autoconfigure/src/test/java/com/vgerbot/orm/influxdb/test/dao/CensusDao.java // public interface CensusDao extends InfluxDBDao<CensusMeasurement> { // // @InfluxDBSelect("select * from census where scientist = #{scientist}") // public List<CensusMeasurement> selectByScientist(@InfluxDBParam("scientist") String scientist); // // @InfluxDBExecute("DROP SERIES FROM census where scientist=#{scientist} and location=#{location}") // public void deleteSeries( // // @InfluxDBParam("scientist") String scientist, // // @InfluxDBParam("location") Integer location // // ); // // @InfluxDBSelect("select scientist,location,butterflies from census where scientist = #{scientist}") // public List<Map<String, Integer>> selectButterflies( // // @InfluxDBParam("scientist") String scientist, // // @InfluxDBParam("location") Integer location // // ); // // @SpecifiedExecutor(HelloWorldExecutor.class) // public void hello(); // // @InfluxQL // public List<Map<String, Object>> findByScientist(@InfluxDBParam("scientist") String scientist); // // class HelloWorldExecutor extends Executor { // // public HelloWorldExecutor(InfluxDBRepository repository) { // super(repository); // } // // @Override // public ResultContext execute(MapperMethod method, Map<String, ParameterValue> parameters) { // System.out.println("hello world"); // return ResultContext.VOID; // } // } // } // // Path: spring-influxdb-orm-autoconfigure/src/test/java/com/vgerbot/orm/influxdb/test/entity/CensusMeasurement.java // @InfluxDBMeasurement("census") // public class CensusMeasurement implements Serializable { // private static final long serialVersionUID = 8260424450884444916L; // // private Date time; // // @TagColumn("location") // private String location; // @TagColumn("scientist") // private String scientist; // // @FieldColumn("butterflies") // private Integer butterflies; // @FieldColumn("honeybees") // private Integer honeybees; // // public Date getTime() { // return time; // } // // public void setTime(Date time) { // this.time = time; // } // // public String getLocation() { // return location; // } // // public void setLocation(String location) { // this.location = location; // } // // public String getScientist() { // return scientist; // } // // public void setScientist(String scientist) { // this.scientist = scientist; // } // // public Integer getButterflies() { // return butterflies; // } // // public void setButterflies(Integer butterflies) { // this.butterflies = butterflies; // } // // public Integer getHoneybees() { // return honeybees; // } // // public void setHoneybees(Integer honeybees) { // this.honeybees = honeybees; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((location == null) ? 0 : location.hashCode()); // result = prime * result + ((scientist == null) ? 0 : scientist.hashCode()); // result = prime * result + ((time == null) ? 0 : time.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // CensusMeasurement other = (CensusMeasurement) obj; // if (location == null) { // if (other.location != null) { // return false; // } // } else if (!location.equals(other.location)) { // return false; // } // if (scientist == null) { // if (other.scientist != null) { // return false; // } // } else if (!scientist.equals(other.scientist)) { // return false; // } // if (time == null) { // if (other.time != null) { // return false; // } // } else if (!time.equals(other.time)) { // return false; // } // return true; // } // // public String toString() { // return "[time: " + time.getTime() + ", location: " + location + ", scientist: " + scientist + ", butterflies: " + butterflies // + ", honeybees: " + honeybees + "]"; // } // } // Path: spring-influxdb-orm-autoconfigure/src/test/java/com/vgerbot/orm/influxdb/App.java import com.vgerbot.orm.influxdb.annotations.InfluxDBORM; import com.vgerbot.orm.influxdb.test.dao.CensusDao; import com.vgerbot.orm.influxdb.test.entity.CensusMeasurement; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import javax.annotation.Resource; import java.util.List; package com.vgerbot.orm.influxdb; @SpringBootApplication @InfluxDBORM( daoBasePackage = "com.vgerbot.orm.influxdb.test.dao", entityBasePackage = "com.vgerbot.orm.influxdb.test.entity" ) public class App implements CommandLineRunner { @Resource
private CensusDao dao;
y1j2x34/spring-influxdb-orm
spring-influxdb-orm-autoconfigure/src/test/java/com/vgerbot/orm/influxdb/App.java
// Path: spring-influxdb-orm-autoconfigure/src/test/java/com/vgerbot/orm/influxdb/test/dao/CensusDao.java // public interface CensusDao extends InfluxDBDao<CensusMeasurement> { // // @InfluxDBSelect("select * from census where scientist = #{scientist}") // public List<CensusMeasurement> selectByScientist(@InfluxDBParam("scientist") String scientist); // // @InfluxDBExecute("DROP SERIES FROM census where scientist=#{scientist} and location=#{location}") // public void deleteSeries( // // @InfluxDBParam("scientist") String scientist, // // @InfluxDBParam("location") Integer location // // ); // // @InfluxDBSelect("select scientist,location,butterflies from census where scientist = #{scientist}") // public List<Map<String, Integer>> selectButterflies( // // @InfluxDBParam("scientist") String scientist, // // @InfluxDBParam("location") Integer location // // ); // // @SpecifiedExecutor(HelloWorldExecutor.class) // public void hello(); // // @InfluxQL // public List<Map<String, Object>> findByScientist(@InfluxDBParam("scientist") String scientist); // // class HelloWorldExecutor extends Executor { // // public HelloWorldExecutor(InfluxDBRepository repository) { // super(repository); // } // // @Override // public ResultContext execute(MapperMethod method, Map<String, ParameterValue> parameters) { // System.out.println("hello world"); // return ResultContext.VOID; // } // } // } // // Path: spring-influxdb-orm-autoconfigure/src/test/java/com/vgerbot/orm/influxdb/test/entity/CensusMeasurement.java // @InfluxDBMeasurement("census") // public class CensusMeasurement implements Serializable { // private static final long serialVersionUID = 8260424450884444916L; // // private Date time; // // @TagColumn("location") // private String location; // @TagColumn("scientist") // private String scientist; // // @FieldColumn("butterflies") // private Integer butterflies; // @FieldColumn("honeybees") // private Integer honeybees; // // public Date getTime() { // return time; // } // // public void setTime(Date time) { // this.time = time; // } // // public String getLocation() { // return location; // } // // public void setLocation(String location) { // this.location = location; // } // // public String getScientist() { // return scientist; // } // // public void setScientist(String scientist) { // this.scientist = scientist; // } // // public Integer getButterflies() { // return butterflies; // } // // public void setButterflies(Integer butterflies) { // this.butterflies = butterflies; // } // // public Integer getHoneybees() { // return honeybees; // } // // public void setHoneybees(Integer honeybees) { // this.honeybees = honeybees; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((location == null) ? 0 : location.hashCode()); // result = prime * result + ((scientist == null) ? 0 : scientist.hashCode()); // result = prime * result + ((time == null) ? 0 : time.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // CensusMeasurement other = (CensusMeasurement) obj; // if (location == null) { // if (other.location != null) { // return false; // } // } else if (!location.equals(other.location)) { // return false; // } // if (scientist == null) { // if (other.scientist != null) { // return false; // } // } else if (!scientist.equals(other.scientist)) { // return false; // } // if (time == null) { // if (other.time != null) { // return false; // } // } else if (!time.equals(other.time)) { // return false; // } // return true; // } // // public String toString() { // return "[time: " + time.getTime() + ", location: " + location + ", scientist: " + scientist + ", butterflies: " + butterflies // + ", honeybees: " + honeybees + "]"; // } // }
import com.vgerbot.orm.influxdb.annotations.InfluxDBORM; import com.vgerbot.orm.influxdb.test.dao.CensusDao; import com.vgerbot.orm.influxdb.test.entity.CensusMeasurement; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import javax.annotation.Resource; import java.util.List;
package com.vgerbot.orm.influxdb; @SpringBootApplication @InfluxDBORM( daoBasePackage = "com.vgerbot.orm.influxdb.test.dao", entityBasePackage = "com.vgerbot.orm.influxdb.test.entity" ) public class App implements CommandLineRunner { @Resource private CensusDao dao; public static void main(String[] args) { SpringApplication.run(App.class, args); } @Override public void run(String... args) throws Exception {
// Path: spring-influxdb-orm-autoconfigure/src/test/java/com/vgerbot/orm/influxdb/test/dao/CensusDao.java // public interface CensusDao extends InfluxDBDao<CensusMeasurement> { // // @InfluxDBSelect("select * from census where scientist = #{scientist}") // public List<CensusMeasurement> selectByScientist(@InfluxDBParam("scientist") String scientist); // // @InfluxDBExecute("DROP SERIES FROM census where scientist=#{scientist} and location=#{location}") // public void deleteSeries( // // @InfluxDBParam("scientist") String scientist, // // @InfluxDBParam("location") Integer location // // ); // // @InfluxDBSelect("select scientist,location,butterflies from census where scientist = #{scientist}") // public List<Map<String, Integer>> selectButterflies( // // @InfluxDBParam("scientist") String scientist, // // @InfluxDBParam("location") Integer location // // ); // // @SpecifiedExecutor(HelloWorldExecutor.class) // public void hello(); // // @InfluxQL // public List<Map<String, Object>> findByScientist(@InfluxDBParam("scientist") String scientist); // // class HelloWorldExecutor extends Executor { // // public HelloWorldExecutor(InfluxDBRepository repository) { // super(repository); // } // // @Override // public ResultContext execute(MapperMethod method, Map<String, ParameterValue> parameters) { // System.out.println("hello world"); // return ResultContext.VOID; // } // } // } // // Path: spring-influxdb-orm-autoconfigure/src/test/java/com/vgerbot/orm/influxdb/test/entity/CensusMeasurement.java // @InfluxDBMeasurement("census") // public class CensusMeasurement implements Serializable { // private static final long serialVersionUID = 8260424450884444916L; // // private Date time; // // @TagColumn("location") // private String location; // @TagColumn("scientist") // private String scientist; // // @FieldColumn("butterflies") // private Integer butterflies; // @FieldColumn("honeybees") // private Integer honeybees; // // public Date getTime() { // return time; // } // // public void setTime(Date time) { // this.time = time; // } // // public String getLocation() { // return location; // } // // public void setLocation(String location) { // this.location = location; // } // // public String getScientist() { // return scientist; // } // // public void setScientist(String scientist) { // this.scientist = scientist; // } // // public Integer getButterflies() { // return butterflies; // } // // public void setButterflies(Integer butterflies) { // this.butterflies = butterflies; // } // // public Integer getHoneybees() { // return honeybees; // } // // public void setHoneybees(Integer honeybees) { // this.honeybees = honeybees; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((location == null) ? 0 : location.hashCode()); // result = prime * result + ((scientist == null) ? 0 : scientist.hashCode()); // result = prime * result + ((time == null) ? 0 : time.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // CensusMeasurement other = (CensusMeasurement) obj; // if (location == null) { // if (other.location != null) { // return false; // } // } else if (!location.equals(other.location)) { // return false; // } // if (scientist == null) { // if (other.scientist != null) { // return false; // } // } else if (!scientist.equals(other.scientist)) { // return false; // } // if (time == null) { // if (other.time != null) { // return false; // } // } else if (!time.equals(other.time)) { // return false; // } // return true; // } // // public String toString() { // return "[time: " + time.getTime() + ", location: " + location + ", scientist: " + scientist + ", butterflies: " + butterflies // + ", honeybees: " + honeybees + "]"; // } // } // Path: spring-influxdb-orm-autoconfigure/src/test/java/com/vgerbot/orm/influxdb/App.java import com.vgerbot.orm.influxdb.annotations.InfluxDBORM; import com.vgerbot.orm.influxdb.test.dao.CensusDao; import com.vgerbot.orm.influxdb.test.entity.CensusMeasurement; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import javax.annotation.Resource; import java.util.List; package com.vgerbot.orm.influxdb; @SpringBootApplication @InfluxDBORM( daoBasePackage = "com.vgerbot.orm.influxdb.test.dao", entityBasePackage = "com.vgerbot.orm.influxdb.test.entity" ) public class App implements CommandLineRunner { @Resource private CensusDao dao; public static void main(String[] args) { SpringApplication.run(App.class, args); } @Override public void run(String... args) throws Exception {
List<CensusMeasurement> measurements = dao.selectByScientist("lanstroth");
y1j2x34/spring-influxdb-orm
spring-influxdb-orm-autoconfigure/src/main/java/com/vgerbot/orm/influxdb/annotations/InfluxDBORM.java
// Path: spring-influxdb-orm-autoconfigure/src/main/java/com/vgerbot/orm/influxdb/configure/MeasurementScannerAutoConfigure.java // public class MeasurementScannerAutoConfigure implements ImportBeanDefinitionRegistrar, BeanFactoryAware { // private BeanFactory beanFactory; // @Override // public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { // AnnotationAttributes attributes = AnnotationAttributes.fromMap( // importingClassMetadata.getAnnotationAttributes(InfluxDBORM.class.getName(), false) // ); // String[] measurementPackages = null; // if (attributes != null) { // measurementPackages = attributes.getStringArray(InfluxDBORM.FIELD_NAME_ENTITY_BASE_PACKAGE); // } // if (ArrayUtils.isEmpty(measurementPackages)) { // if(AutoConfigurationPackages.has(beanFactory)) { // List<String> packages = AutoConfigurationPackages.get(beanFactory); // measurementPackages = packages.toArray(new String[packages.size()]); // } // } // Assert.notEmpty(measurementPackages, "At least one base measurement package must be specified"); // BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(ClassPathMeasurementScannerFactoryBean.class); // builder.addPropertyValue(ClassPathMeasurementScannerFactoryBean.MEASUREMENT_PACKAGE, StringUtils.join(measurementPackages, ",")); // BeanDefinition definition = builder.getBeanDefinition(); // String beanName = BeanDefinitionReaderUtils.generateBeanName(definition, registry); // registry.registerBeanDefinition(beanName, definition); // } // // @Override // public void setBeanFactory(BeanFactory beanFactory) throws BeansException { // this.beanFactory = beanFactory; // } // }
import com.vgerbot.orm.influxdb.configure.MeasurementScannerAutoConfigure; import org.springframework.context.annotation.Import; import java.lang.annotation.*;
package com.vgerbot.orm.influxdb.annotations; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented
// Path: spring-influxdb-orm-autoconfigure/src/main/java/com/vgerbot/orm/influxdb/configure/MeasurementScannerAutoConfigure.java // public class MeasurementScannerAutoConfigure implements ImportBeanDefinitionRegistrar, BeanFactoryAware { // private BeanFactory beanFactory; // @Override // public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { // AnnotationAttributes attributes = AnnotationAttributes.fromMap( // importingClassMetadata.getAnnotationAttributes(InfluxDBORM.class.getName(), false) // ); // String[] measurementPackages = null; // if (attributes != null) { // measurementPackages = attributes.getStringArray(InfluxDBORM.FIELD_NAME_ENTITY_BASE_PACKAGE); // } // if (ArrayUtils.isEmpty(measurementPackages)) { // if(AutoConfigurationPackages.has(beanFactory)) { // List<String> packages = AutoConfigurationPackages.get(beanFactory); // measurementPackages = packages.toArray(new String[packages.size()]); // } // } // Assert.notEmpty(measurementPackages, "At least one base measurement package must be specified"); // BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(ClassPathMeasurementScannerFactoryBean.class); // builder.addPropertyValue(ClassPathMeasurementScannerFactoryBean.MEASUREMENT_PACKAGE, StringUtils.join(measurementPackages, ",")); // BeanDefinition definition = builder.getBeanDefinition(); // String beanName = BeanDefinitionReaderUtils.generateBeanName(definition, registry); // registry.registerBeanDefinition(beanName, definition); // } // // @Override // public void setBeanFactory(BeanFactory beanFactory) throws BeansException { // this.beanFactory = beanFactory; // } // } // Path: spring-influxdb-orm-autoconfigure/src/main/java/com/vgerbot/orm/influxdb/annotations/InfluxDBORM.java import com.vgerbot.orm.influxdb.configure.MeasurementScannerAutoConfigure; import org.springframework.context.annotation.Import; import java.lang.annotation.*; package com.vgerbot.orm.influxdb.annotations; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented
@Import(MeasurementScannerAutoConfigure.class)
y1j2x34/spring-influxdb-orm
spring-influxdb-orm-autoconfigure/src/main/java/com/vgerbot/orm/influxdb/configure/MeasurementScannerAutoConfigure.java
// Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/factory/ClassPathMeasurementScannerFactoryBean.java // public class ClassPathMeasurementScannerFactoryBean implements FactoryBean<ClassPathMeasurementScanner>, InitializingBean, EnvironmentAware { // // public static final String MEASUREMENT_PACKAGE = "entityPackage"; // // private Environment environment; // private String entityPackage; // @Override // public ClassPathMeasurementScanner getObject() { // ClassPathMeasurementScanner scanner = new ClassPathMeasurementScanner(this.environment); // if(!StringUtils.isBlank(entityPackage)) { // scanner.setEntityPackages(entityPackage.trim().split("[,;\\s\\r\\n\\t]+")); // } // return scanner; // } // // @Override // public Class<?> getObjectType() { // return ClassPathMeasurementScanner.class; // } // // public void setEntityPackage(String entityPackage) { // this.entityPackage = entityPackage; // } // // @Override // public void afterPropertiesSet() { // // } // // @Override // public void setEnvironment(Environment environment) { // this.environment = environment; // } // } // // Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/utils/StringUtils.java // public class StringUtils extends org.apache.commons.lang3.StringUtils { // // /** // * 正则匹配替换,类似js中的replace // * // * @param source // * @param regex // * @param func // * @return // */ // public static final String replace(String source, String regex, ReplaceCallback func) { // return replace(source, regex, 0, func); // } // // public static final String replace(String source, String regex, int group, ReplaceCallback func) { // Pattern pattern = Pattern.compile(regex); // Matcher m = pattern.matcher(source); // if (m.find()) { // StringBuffer sb = new StringBuffer(); // int i = 0; // do { // String grp = m.group(group); // int index = source.indexOf(grp, i); // m.appendReplacement(sb, func.replace(grp, index, source)); // i = index + 1; // } while (m.find()); // m.appendTail(sb); // return sb.toString(); // } // return source; // } // // /** // * 替换回调函数接口 // * // * @author y1j2x34 // * @date 2014-7-24 // */ // public static interface ReplaceCallback { // String replace(String word, int index, String source); // } // // }
import com.vgerbot.orm.influxdb.annotations.InfluxDBORM; import com.vgerbot.orm.influxdb.factory.ClassPathMeasurementScannerFactoryBean; import com.vgerbot.orm.influxdb.utils.StringUtils; import org.apache.commons.lang3.ArrayUtils; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.BeanDefinitionReaderUtils; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.boot.autoconfigure.AutoConfigurationPackages; import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; import org.springframework.core.annotation.AnnotationAttributes; import org.springframework.core.type.AnnotationMetadata; import org.springframework.util.Assert; import java.util.List;
package com.vgerbot.orm.influxdb.configure; public class MeasurementScannerAutoConfigure implements ImportBeanDefinitionRegistrar, BeanFactoryAware { private BeanFactory beanFactory; @Override public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { AnnotationAttributes attributes = AnnotationAttributes.fromMap( importingClassMetadata.getAnnotationAttributes(InfluxDBORM.class.getName(), false) ); String[] measurementPackages = null; if (attributes != null) { measurementPackages = attributes.getStringArray(InfluxDBORM.FIELD_NAME_ENTITY_BASE_PACKAGE); } if (ArrayUtils.isEmpty(measurementPackages)) { if(AutoConfigurationPackages.has(beanFactory)) { List<String> packages = AutoConfigurationPackages.get(beanFactory); measurementPackages = packages.toArray(new String[packages.size()]); } } Assert.notEmpty(measurementPackages, "At least one base measurement package must be specified");
// Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/factory/ClassPathMeasurementScannerFactoryBean.java // public class ClassPathMeasurementScannerFactoryBean implements FactoryBean<ClassPathMeasurementScanner>, InitializingBean, EnvironmentAware { // // public static final String MEASUREMENT_PACKAGE = "entityPackage"; // // private Environment environment; // private String entityPackage; // @Override // public ClassPathMeasurementScanner getObject() { // ClassPathMeasurementScanner scanner = new ClassPathMeasurementScanner(this.environment); // if(!StringUtils.isBlank(entityPackage)) { // scanner.setEntityPackages(entityPackage.trim().split("[,;\\s\\r\\n\\t]+")); // } // return scanner; // } // // @Override // public Class<?> getObjectType() { // return ClassPathMeasurementScanner.class; // } // // public void setEntityPackage(String entityPackage) { // this.entityPackage = entityPackage; // } // // @Override // public void afterPropertiesSet() { // // } // // @Override // public void setEnvironment(Environment environment) { // this.environment = environment; // } // } // // Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/utils/StringUtils.java // public class StringUtils extends org.apache.commons.lang3.StringUtils { // // /** // * 正则匹配替换,类似js中的replace // * // * @param source // * @param regex // * @param func // * @return // */ // public static final String replace(String source, String regex, ReplaceCallback func) { // return replace(source, regex, 0, func); // } // // public static final String replace(String source, String regex, int group, ReplaceCallback func) { // Pattern pattern = Pattern.compile(regex); // Matcher m = pattern.matcher(source); // if (m.find()) { // StringBuffer sb = new StringBuffer(); // int i = 0; // do { // String grp = m.group(group); // int index = source.indexOf(grp, i); // m.appendReplacement(sb, func.replace(grp, index, source)); // i = index + 1; // } while (m.find()); // m.appendTail(sb); // return sb.toString(); // } // return source; // } // // /** // * 替换回调函数接口 // * // * @author y1j2x34 // * @date 2014-7-24 // */ // public static interface ReplaceCallback { // String replace(String word, int index, String source); // } // // } // Path: spring-influxdb-orm-autoconfigure/src/main/java/com/vgerbot/orm/influxdb/configure/MeasurementScannerAutoConfigure.java import com.vgerbot.orm.influxdb.annotations.InfluxDBORM; import com.vgerbot.orm.influxdb.factory.ClassPathMeasurementScannerFactoryBean; import com.vgerbot.orm.influxdb.utils.StringUtils; import org.apache.commons.lang3.ArrayUtils; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.BeanDefinitionReaderUtils; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.boot.autoconfigure.AutoConfigurationPackages; import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; import org.springframework.core.annotation.AnnotationAttributes; import org.springframework.core.type.AnnotationMetadata; import org.springframework.util.Assert; import java.util.List; package com.vgerbot.orm.influxdb.configure; public class MeasurementScannerAutoConfigure implements ImportBeanDefinitionRegistrar, BeanFactoryAware { private BeanFactory beanFactory; @Override public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { AnnotationAttributes attributes = AnnotationAttributes.fromMap( importingClassMetadata.getAnnotationAttributes(InfluxDBORM.class.getName(), false) ); String[] measurementPackages = null; if (attributes != null) { measurementPackages = attributes.getStringArray(InfluxDBORM.FIELD_NAME_ENTITY_BASE_PACKAGE); } if (ArrayUtils.isEmpty(measurementPackages)) { if(AutoConfigurationPackages.has(beanFactory)) { List<String> packages = AutoConfigurationPackages.get(beanFactory); measurementPackages = packages.toArray(new String[packages.size()]); } } Assert.notEmpty(measurementPackages, "At least one base measurement package must be specified");
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(ClassPathMeasurementScannerFactoryBean.class);
y1j2x34/spring-influxdb-orm
spring-influxdb-orm-autoconfigure/src/main/java/com/vgerbot/orm/influxdb/configure/MeasurementScannerAutoConfigure.java
// Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/factory/ClassPathMeasurementScannerFactoryBean.java // public class ClassPathMeasurementScannerFactoryBean implements FactoryBean<ClassPathMeasurementScanner>, InitializingBean, EnvironmentAware { // // public static final String MEASUREMENT_PACKAGE = "entityPackage"; // // private Environment environment; // private String entityPackage; // @Override // public ClassPathMeasurementScanner getObject() { // ClassPathMeasurementScanner scanner = new ClassPathMeasurementScanner(this.environment); // if(!StringUtils.isBlank(entityPackage)) { // scanner.setEntityPackages(entityPackage.trim().split("[,;\\s\\r\\n\\t]+")); // } // return scanner; // } // // @Override // public Class<?> getObjectType() { // return ClassPathMeasurementScanner.class; // } // // public void setEntityPackage(String entityPackage) { // this.entityPackage = entityPackage; // } // // @Override // public void afterPropertiesSet() { // // } // // @Override // public void setEnvironment(Environment environment) { // this.environment = environment; // } // } // // Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/utils/StringUtils.java // public class StringUtils extends org.apache.commons.lang3.StringUtils { // // /** // * 正则匹配替换,类似js中的replace // * // * @param source // * @param regex // * @param func // * @return // */ // public static final String replace(String source, String regex, ReplaceCallback func) { // return replace(source, regex, 0, func); // } // // public static final String replace(String source, String regex, int group, ReplaceCallback func) { // Pattern pattern = Pattern.compile(regex); // Matcher m = pattern.matcher(source); // if (m.find()) { // StringBuffer sb = new StringBuffer(); // int i = 0; // do { // String grp = m.group(group); // int index = source.indexOf(grp, i); // m.appendReplacement(sb, func.replace(grp, index, source)); // i = index + 1; // } while (m.find()); // m.appendTail(sb); // return sb.toString(); // } // return source; // } // // /** // * 替换回调函数接口 // * // * @author y1j2x34 // * @date 2014-7-24 // */ // public static interface ReplaceCallback { // String replace(String word, int index, String source); // } // // }
import com.vgerbot.orm.influxdb.annotations.InfluxDBORM; import com.vgerbot.orm.influxdb.factory.ClassPathMeasurementScannerFactoryBean; import com.vgerbot.orm.influxdb.utils.StringUtils; import org.apache.commons.lang3.ArrayUtils; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.BeanDefinitionReaderUtils; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.boot.autoconfigure.AutoConfigurationPackages; import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; import org.springframework.core.annotation.AnnotationAttributes; import org.springframework.core.type.AnnotationMetadata; import org.springframework.util.Assert; import java.util.List;
package com.vgerbot.orm.influxdb.configure; public class MeasurementScannerAutoConfigure implements ImportBeanDefinitionRegistrar, BeanFactoryAware { private BeanFactory beanFactory; @Override public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { AnnotationAttributes attributes = AnnotationAttributes.fromMap( importingClassMetadata.getAnnotationAttributes(InfluxDBORM.class.getName(), false) ); String[] measurementPackages = null; if (attributes != null) { measurementPackages = attributes.getStringArray(InfluxDBORM.FIELD_NAME_ENTITY_BASE_PACKAGE); } if (ArrayUtils.isEmpty(measurementPackages)) { if(AutoConfigurationPackages.has(beanFactory)) { List<String> packages = AutoConfigurationPackages.get(beanFactory); measurementPackages = packages.toArray(new String[packages.size()]); } } Assert.notEmpty(measurementPackages, "At least one base measurement package must be specified"); BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(ClassPathMeasurementScannerFactoryBean.class);
// Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/factory/ClassPathMeasurementScannerFactoryBean.java // public class ClassPathMeasurementScannerFactoryBean implements FactoryBean<ClassPathMeasurementScanner>, InitializingBean, EnvironmentAware { // // public static final String MEASUREMENT_PACKAGE = "entityPackage"; // // private Environment environment; // private String entityPackage; // @Override // public ClassPathMeasurementScanner getObject() { // ClassPathMeasurementScanner scanner = new ClassPathMeasurementScanner(this.environment); // if(!StringUtils.isBlank(entityPackage)) { // scanner.setEntityPackages(entityPackage.trim().split("[,;\\s\\r\\n\\t]+")); // } // return scanner; // } // // @Override // public Class<?> getObjectType() { // return ClassPathMeasurementScanner.class; // } // // public void setEntityPackage(String entityPackage) { // this.entityPackage = entityPackage; // } // // @Override // public void afterPropertiesSet() { // // } // // @Override // public void setEnvironment(Environment environment) { // this.environment = environment; // } // } // // Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/utils/StringUtils.java // public class StringUtils extends org.apache.commons.lang3.StringUtils { // // /** // * 正则匹配替换,类似js中的replace // * // * @param source // * @param regex // * @param func // * @return // */ // public static final String replace(String source, String regex, ReplaceCallback func) { // return replace(source, regex, 0, func); // } // // public static final String replace(String source, String regex, int group, ReplaceCallback func) { // Pattern pattern = Pattern.compile(regex); // Matcher m = pattern.matcher(source); // if (m.find()) { // StringBuffer sb = new StringBuffer(); // int i = 0; // do { // String grp = m.group(group); // int index = source.indexOf(grp, i); // m.appendReplacement(sb, func.replace(grp, index, source)); // i = index + 1; // } while (m.find()); // m.appendTail(sb); // return sb.toString(); // } // return source; // } // // /** // * 替换回调函数接口 // * // * @author y1j2x34 // * @date 2014-7-24 // */ // public static interface ReplaceCallback { // String replace(String word, int index, String source); // } // // } // Path: spring-influxdb-orm-autoconfigure/src/main/java/com/vgerbot/orm/influxdb/configure/MeasurementScannerAutoConfigure.java import com.vgerbot.orm.influxdb.annotations.InfluxDBORM; import com.vgerbot.orm.influxdb.factory.ClassPathMeasurementScannerFactoryBean; import com.vgerbot.orm.influxdb.utils.StringUtils; import org.apache.commons.lang3.ArrayUtils; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.BeanDefinitionReaderUtils; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.boot.autoconfigure.AutoConfigurationPackages; import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; import org.springframework.core.annotation.AnnotationAttributes; import org.springframework.core.type.AnnotationMetadata; import org.springframework.util.Assert; import java.util.List; package com.vgerbot.orm.influxdb.configure; public class MeasurementScannerAutoConfigure implements ImportBeanDefinitionRegistrar, BeanFactoryAware { private BeanFactory beanFactory; @Override public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { AnnotationAttributes attributes = AnnotationAttributes.fromMap( importingClassMetadata.getAnnotationAttributes(InfluxDBORM.class.getName(), false) ); String[] measurementPackages = null; if (attributes != null) { measurementPackages = attributes.getStringArray(InfluxDBORM.FIELD_NAME_ENTITY_BASE_PACKAGE); } if (ArrayUtils.isEmpty(measurementPackages)) { if(AutoConfigurationPackages.has(beanFactory)) { List<String> packages = AutoConfigurationPackages.get(beanFactory); measurementPackages = packages.toArray(new String[packages.size()]); } } Assert.notEmpty(measurementPackages, "At least one base measurement package must be specified"); BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(ClassPathMeasurementScannerFactoryBean.class);
builder.addPropertyValue(ClassPathMeasurementScannerFactoryBean.MEASUREMENT_PACKAGE, StringUtils.join(measurementPackages, ","));
y1j2x34/spring-influxdb-orm
spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/annotations/AnnotateExecutor.java
// Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/exec/AnnotationExecutor.java // public abstract class AnnotationExecutor<Anno extends Annotation> extends Executor { // protected final Anno annotation; // // public AnnotationExecutor(InfluxDBRepository repository, Anno annotation) { // super(repository); // this.annotation = annotation; // } // // public Anno getAnnotation() { // return annotation; // } // }
import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import com.vgerbot.orm.influxdb.exec.AnnotationExecutor;
package com.vgerbot.orm.influxdb.annotations; @Target(ElementType.ANNOTATION_TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface AnnotateExecutor {
// Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/exec/AnnotationExecutor.java // public abstract class AnnotationExecutor<Anno extends Annotation> extends Executor { // protected final Anno annotation; // // public AnnotationExecutor(InfluxDBRepository repository, Anno annotation) { // super(repository); // this.annotation = annotation; // } // // public Anno getAnnotation() { // return annotation; // } // } // Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/annotations/AnnotateExecutor.java import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import com.vgerbot.orm.influxdb.exec.AnnotationExecutor; package com.vgerbot.orm.influxdb.annotations; @Target(ElementType.ANNOTATION_TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface AnnotateExecutor {
Class<? extends AnnotationExecutor<?>> value();
y1j2x34/spring-influxdb-orm
spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/binding/MapperInterface.java
// Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/utils/ReflectionUtils.java // public class ReflectionUtils extends org.springframework.util.ReflectionUtils { // // public static Class<?> getInterfaceGenericType(Class<?> clazz, int typeIndex) { // Assert.notNull(clazz, "class is required"); // Assert.isTrue(typeIndex >= 0, "Negative index"); // // Type[] genericInterfaces = clazz.getGenericInterfaces(); // if (genericInterfaces == null || genericInterfaces.length < 1) { // return null; // } // // ParameterizedType pType = (ParameterizedType) genericInterfaces[0]; // Type[] actualTypeArguments = pType.getActualTypeArguments(); // if (actualTypeArguments == null || actualTypeArguments.length < 1) { // return null; // } // // return (Class<?>) actualTypeArguments[typeIndex]; // } // }
import com.vgerbot.orm.influxdb.utils.ReflectionUtils;
package com.vgerbot.orm.influxdb.binding; public class MapperInterface { private final Class<?> interfaceClass; private final Class<?> measurementClass; public MapperInterface(Class<?> interfaceClass) { super(); this.interfaceClass = interfaceClass;
// Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/utils/ReflectionUtils.java // public class ReflectionUtils extends org.springframework.util.ReflectionUtils { // // public static Class<?> getInterfaceGenericType(Class<?> clazz, int typeIndex) { // Assert.notNull(clazz, "class is required"); // Assert.isTrue(typeIndex >= 0, "Negative index"); // // Type[] genericInterfaces = clazz.getGenericInterfaces(); // if (genericInterfaces == null || genericInterfaces.length < 1) { // return null; // } // // ParameterizedType pType = (ParameterizedType) genericInterfaces[0]; // Type[] actualTypeArguments = pType.getActualTypeArguments(); // if (actualTypeArguments == null || actualTypeArguments.length < 1) { // return null; // } // // return (Class<?>) actualTypeArguments[typeIndex]; // } // } // Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/binding/MapperInterface.java import com.vgerbot.orm.influxdb.utils.ReflectionUtils; package com.vgerbot.orm.influxdb.binding; public class MapperInterface { private final Class<?> interfaceClass; private final Class<?> measurementClass; public MapperInterface(Class<?> interfaceClass) { super(); this.interfaceClass = interfaceClass;
this.measurementClass = (Class<?>) ReflectionUtils.getInterfaceGenericType(interfaceClass, 0);
y1j2x34/spring-influxdb-orm
spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/result/NativeResultContext.java
// Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/InfluxDBException.java // public class InfluxDBException extends RuntimeException { // // private static final long serialVersionUID = -4410268653794610252L; // // public InfluxDBException() { // super(); // } // // public InfluxDBException(String message, Throwable cause) { // super(message, cause); // } // // public InfluxDBException(String message) { // super(message); // } // // public InfluxDBException(Throwable cause) { // super(cause); // } // } // // Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/utils/StringUtils.java // public class StringUtils extends org.apache.commons.lang3.StringUtils { // // /** // * 正则匹配替换,类似js中的replace // * // * @param source // * @param regex // * @param func // * @return // */ // public static final String replace(String source, String regex, ReplaceCallback func) { // return replace(source, regex, 0, func); // } // // public static final String replace(String source, String regex, int group, ReplaceCallback func) { // Pattern pattern = Pattern.compile(regex); // Matcher m = pattern.matcher(source); // if (m.find()) { // StringBuffer sb = new StringBuffer(); // int i = 0; // do { // String grp = m.group(group); // int index = source.indexOf(grp, i); // m.appendReplacement(sb, func.replace(grp, index, source)); // i = index + 1; // } while (m.find()); // m.appendTail(sb); // return sb.toString(); // } // return source; // } // // /** // * 替换回调函数接口 // * // * @author y1j2x34 // * @date 2014-7-24 // */ // public static interface ReplaceCallback { // String replace(String word, int index, String source); // } // // }
import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import org.influxdb.dto.QueryResult; import org.influxdb.dto.QueryResult.Result; import org.influxdb.dto.QueryResult.Series; import com.vgerbot.orm.influxdb.InfluxDBException; import com.vgerbot.orm.influxdb.utils.StringUtils;
package com.vgerbot.orm.influxdb.result; public class NativeResultContext implements ResultContext { private static final Map<String, List<Map<String, Object>>> EMPTY_SERIES_MAP = Collections.unmodifiableMap(new HashMap<>()); private static final Set<String> EMPTY_SET = Collections.emptySet(); private String errorMessage; private boolean hasResult; private Set<String> measurementNames; private Map<String, List<Map<String, Object>>> seriesMap; public NativeResultContext(QueryResult queryResult) { this.errorMessage = queryResult.getError(); List<Result> results = queryResult.getResults(); if (isNotEmpty(results)) { if (results.size() > 1) {
// Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/InfluxDBException.java // public class InfluxDBException extends RuntimeException { // // private static final long serialVersionUID = -4410268653794610252L; // // public InfluxDBException() { // super(); // } // // public InfluxDBException(String message, Throwable cause) { // super(message, cause); // } // // public InfluxDBException(String message) { // super(message); // } // // public InfluxDBException(Throwable cause) { // super(cause); // } // } // // Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/utils/StringUtils.java // public class StringUtils extends org.apache.commons.lang3.StringUtils { // // /** // * 正则匹配替换,类似js中的replace // * // * @param source // * @param regex // * @param func // * @return // */ // public static final String replace(String source, String regex, ReplaceCallback func) { // return replace(source, regex, 0, func); // } // // public static final String replace(String source, String regex, int group, ReplaceCallback func) { // Pattern pattern = Pattern.compile(regex); // Matcher m = pattern.matcher(source); // if (m.find()) { // StringBuffer sb = new StringBuffer(); // int i = 0; // do { // String grp = m.group(group); // int index = source.indexOf(grp, i); // m.appendReplacement(sb, func.replace(grp, index, source)); // i = index + 1; // } while (m.find()); // m.appendTail(sb); // return sb.toString(); // } // return source; // } // // /** // * 替换回调函数接口 // * // * @author y1j2x34 // * @date 2014-7-24 // */ // public static interface ReplaceCallback { // String replace(String word, int index, String source); // } // // } // Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/result/NativeResultContext.java import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import org.influxdb.dto.QueryResult; import org.influxdb.dto.QueryResult.Result; import org.influxdb.dto.QueryResult.Series; import com.vgerbot.orm.influxdb.InfluxDBException; import com.vgerbot.orm.influxdb.utils.StringUtils; package com.vgerbot.orm.influxdb.result; public class NativeResultContext implements ResultContext { private static final Map<String, List<Map<String, Object>>> EMPTY_SERIES_MAP = Collections.unmodifiableMap(new HashMap<>()); private static final Set<String> EMPTY_SET = Collections.emptySet(); private String errorMessage; private boolean hasResult; private Set<String> measurementNames; private Map<String, List<Map<String, Object>>> seriesMap; public NativeResultContext(QueryResult queryResult) { this.errorMessage = queryResult.getError(); List<Result> results = queryResult.getResults(); if (isNotEmpty(results)) { if (results.size() > 1) {
throw new InfluxDBException("Multiple results is not suppported!");
y1j2x34/spring-influxdb-orm
spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/result/NativeResultContext.java
// Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/InfluxDBException.java // public class InfluxDBException extends RuntimeException { // // private static final long serialVersionUID = -4410268653794610252L; // // public InfluxDBException() { // super(); // } // // public InfluxDBException(String message, Throwable cause) { // super(message, cause); // } // // public InfluxDBException(String message) { // super(message); // } // // public InfluxDBException(Throwable cause) { // super(cause); // } // } // // Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/utils/StringUtils.java // public class StringUtils extends org.apache.commons.lang3.StringUtils { // // /** // * 正则匹配替换,类似js中的replace // * // * @param source // * @param regex // * @param func // * @return // */ // public static final String replace(String source, String regex, ReplaceCallback func) { // return replace(source, regex, 0, func); // } // // public static final String replace(String source, String regex, int group, ReplaceCallback func) { // Pattern pattern = Pattern.compile(regex); // Matcher m = pattern.matcher(source); // if (m.find()) { // StringBuffer sb = new StringBuffer(); // int i = 0; // do { // String grp = m.group(group); // int index = source.indexOf(grp, i); // m.appendReplacement(sb, func.replace(grp, index, source)); // i = index + 1; // } while (m.find()); // m.appendTail(sb); // return sb.toString(); // } // return source; // } // // /** // * 替换回调函数接口 // * // * @author y1j2x34 // * @date 2014-7-24 // */ // public static interface ReplaceCallback { // String replace(String word, int index, String source); // } // // }
import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import org.influxdb.dto.QueryResult; import org.influxdb.dto.QueryResult.Result; import org.influxdb.dto.QueryResult.Series; import com.vgerbot.orm.influxdb.InfluxDBException; import com.vgerbot.orm.influxdb.utils.StringUtils;
package com.vgerbot.orm.influxdb.result; public class NativeResultContext implements ResultContext { private static final Map<String, List<Map<String, Object>>> EMPTY_SERIES_MAP = Collections.unmodifiableMap(new HashMap<>()); private static final Set<String> EMPTY_SET = Collections.emptySet(); private String errorMessage; private boolean hasResult; private Set<String> measurementNames; private Map<String, List<Map<String, Object>>> seriesMap; public NativeResultContext(QueryResult queryResult) { this.errorMessage = queryResult.getError(); List<Result> results = queryResult.getResults(); if (isNotEmpty(results)) { if (results.size() > 1) { throw new InfluxDBException("Multiple results is not suppported!"); } Result result = results.get(0);
// Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/InfluxDBException.java // public class InfluxDBException extends RuntimeException { // // private static final long serialVersionUID = -4410268653794610252L; // // public InfluxDBException() { // super(); // } // // public InfluxDBException(String message, Throwable cause) { // super(message, cause); // } // // public InfluxDBException(String message) { // super(message); // } // // public InfluxDBException(Throwable cause) { // super(cause); // } // } // // Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/utils/StringUtils.java // public class StringUtils extends org.apache.commons.lang3.StringUtils { // // /** // * 正则匹配替换,类似js中的replace // * // * @param source // * @param regex // * @param func // * @return // */ // public static final String replace(String source, String regex, ReplaceCallback func) { // return replace(source, regex, 0, func); // } // // public static final String replace(String source, String regex, int group, ReplaceCallback func) { // Pattern pattern = Pattern.compile(regex); // Matcher m = pattern.matcher(source); // if (m.find()) { // StringBuffer sb = new StringBuffer(); // int i = 0; // do { // String grp = m.group(group); // int index = source.indexOf(grp, i); // m.appendReplacement(sb, func.replace(grp, index, source)); // i = index + 1; // } while (m.find()); // m.appendTail(sb); // return sb.toString(); // } // return source; // } // // /** // * 替换回调函数接口 // * // * @author y1j2x34 // * @date 2014-7-24 // */ // public static interface ReplaceCallback { // String replace(String word, int index, String source); // } // // } // Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/result/NativeResultContext.java import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import org.influxdb.dto.QueryResult; import org.influxdb.dto.QueryResult.Result; import org.influxdb.dto.QueryResult.Series; import com.vgerbot.orm.influxdb.InfluxDBException; import com.vgerbot.orm.influxdb.utils.StringUtils; package com.vgerbot.orm.influxdb.result; public class NativeResultContext implements ResultContext { private static final Map<String, List<Map<String, Object>>> EMPTY_SERIES_MAP = Collections.unmodifiableMap(new HashMap<>()); private static final Set<String> EMPTY_SET = Collections.emptySet(); private String errorMessage; private boolean hasResult; private Set<String> measurementNames; private Map<String, List<Map<String, Object>>> seriesMap; public NativeResultContext(QueryResult queryResult) { this.errorMessage = queryResult.getError(); List<Result> results = queryResult.getResults(); if (isNotEmpty(results)) { if (results.size() > 1) { throw new InfluxDBException("Multiple results is not suppported!"); } Result result = results.get(0);
if (StringUtils.isNotBlank(result.getError())) {
y1j2x34/spring-influxdb-orm
spring-influxdb-orm-autoconfigure/src/main/java/com/vgerbot/orm/influxdb/configure/MapperScannerAutoConfigure.java
// Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/mapper/MapperScannerConfigurer.java // public class MapperScannerConfigurer implements BeanDefinitionRegistryPostProcessor, InitializingBean { // // public static final String BASE_DAO_PACKAGE_FIELD = "baseDaoPackage"; // public static final String REPOSITORY_NAME_FIELD = "repositoryName"; // // private String baseDaoPackage; // // private String includeDaoClassNameRegex; // // private String excludeDaoClassNameRegex; // // private String repositoryName; // // @Override // public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { // // } // // @Override // public void afterPropertiesSet() throws Exception { // Assert.notNull(baseDaoPackage, "Property 'baseDaoPackage' is required"); // Assert.notNull(repositoryName, "Property 'repositoryName' is required"); // // } // // @Override // public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { // ClassPathMapperScanner scanner = new ClassPathMapperScanner(registry); // scanner.setIncludeDaoClassNameRegex(includeDaoClassNameRegex); // scanner.setExcludeDaoClassNameRegex(excludeDaoClassNameRegex); // scanner.registerFilters(); // scanner.setRepositoryName(repositoryName); // scanner.scan(StringUtils.tokenizeToStringArray(baseDaoPackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS)); // } // // public void setBaseDaoPackage(String baseDaoPackage) { // this.baseDaoPackage = baseDaoPackage; // } // // public void setRepositoryName(String repositoryName) { // this.repositoryName = repositoryName; // } // // public void setIncludeDaoClassNameRegex(String includeDaoClassNameRegex) { // this.includeDaoClassNameRegex = includeDaoClassNameRegex; // } // // public void setExcludeDaoClassNameRegex(String excludeDaoClassNameRegex) { // this.excludeDaoClassNameRegex = excludeDaoClassNameRegex; // } // }
import com.vgerbot.orm.influxdb.annotations.InfluxDBORM; import com.vgerbot.orm.influxdb.mapper.MapperScannerConfigurer; import org.apache.commons.lang3.ArrayUtils; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.BeanDefinitionReaderUtils; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.boot.autoconfigure.AutoConfigurationPackages; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; import org.springframework.core.annotation.AnnotationAttributes; import org.springframework.core.type.AnnotationMetadata; import org.springframework.util.Assert; import java.util.List;
package com.vgerbot.orm.influxdb.configure; @AutoConfigureAfter({ RepositoryAutoConfigure.class}) public class MapperScannerAutoConfigure implements ImportBeanDefinitionRegistrar, BeanFactoryAware { private BeanFactory beanFactory; @Override public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { AnnotationAttributes attributes = AnnotationAttributes.fromMap( importingClassMetadata.getAnnotationAttributes(InfluxDBORM.class.getName(), false) ); String[] daoBasePackages = null; if (attributes != null) { daoBasePackages = attributes.getStringArray(InfluxDBORM.FIELD_NAME_DAO_BASE_PACKAGE); } if (ArrayUtils.isEmpty(daoBasePackages)) { if(AutoConfigurationPackages.has(beanFactory)) { List<String> packages = AutoConfigurationPackages.get(beanFactory); daoBasePackages = packages.toArray(new String[packages.size()]); } } Assert.notEmpty(daoBasePackages, "At least one base dao package must be specified");
// Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/mapper/MapperScannerConfigurer.java // public class MapperScannerConfigurer implements BeanDefinitionRegistryPostProcessor, InitializingBean { // // public static final String BASE_DAO_PACKAGE_FIELD = "baseDaoPackage"; // public static final String REPOSITORY_NAME_FIELD = "repositoryName"; // // private String baseDaoPackage; // // private String includeDaoClassNameRegex; // // private String excludeDaoClassNameRegex; // // private String repositoryName; // // @Override // public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { // // } // // @Override // public void afterPropertiesSet() throws Exception { // Assert.notNull(baseDaoPackage, "Property 'baseDaoPackage' is required"); // Assert.notNull(repositoryName, "Property 'repositoryName' is required"); // // } // // @Override // public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { // ClassPathMapperScanner scanner = new ClassPathMapperScanner(registry); // scanner.setIncludeDaoClassNameRegex(includeDaoClassNameRegex); // scanner.setExcludeDaoClassNameRegex(excludeDaoClassNameRegex); // scanner.registerFilters(); // scanner.setRepositoryName(repositoryName); // scanner.scan(StringUtils.tokenizeToStringArray(baseDaoPackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS)); // } // // public void setBaseDaoPackage(String baseDaoPackage) { // this.baseDaoPackage = baseDaoPackage; // } // // public void setRepositoryName(String repositoryName) { // this.repositoryName = repositoryName; // } // // public void setIncludeDaoClassNameRegex(String includeDaoClassNameRegex) { // this.includeDaoClassNameRegex = includeDaoClassNameRegex; // } // // public void setExcludeDaoClassNameRegex(String excludeDaoClassNameRegex) { // this.excludeDaoClassNameRegex = excludeDaoClassNameRegex; // } // } // Path: spring-influxdb-orm-autoconfigure/src/main/java/com/vgerbot/orm/influxdb/configure/MapperScannerAutoConfigure.java import com.vgerbot.orm.influxdb.annotations.InfluxDBORM; import com.vgerbot.orm.influxdb.mapper.MapperScannerConfigurer; import org.apache.commons.lang3.ArrayUtils; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.BeanDefinitionReaderUtils; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.boot.autoconfigure.AutoConfigurationPackages; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; import org.springframework.core.annotation.AnnotationAttributes; import org.springframework.core.type.AnnotationMetadata; import org.springframework.util.Assert; import java.util.List; package com.vgerbot.orm.influxdb.configure; @AutoConfigureAfter({ RepositoryAutoConfigure.class}) public class MapperScannerAutoConfigure implements ImportBeanDefinitionRegistrar, BeanFactoryAware { private BeanFactory beanFactory; @Override public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { AnnotationAttributes attributes = AnnotationAttributes.fromMap( importingClassMetadata.getAnnotationAttributes(InfluxDBORM.class.getName(), false) ); String[] daoBasePackages = null; if (attributes != null) { daoBasePackages = attributes.getStringArray(InfluxDBORM.FIELD_NAME_DAO_BASE_PACKAGE); } if (ArrayUtils.isEmpty(daoBasePackages)) { if(AutoConfigurationPackages.has(beanFactory)) { List<String> packages = AutoConfigurationPackages.get(beanFactory); daoBasePackages = packages.toArray(new String[packages.size()]); } } Assert.notEmpty(daoBasePackages, "At least one base dao package must be specified");
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(MapperScannerConfigurer.class);
y1j2x34/spring-influxdb-orm
spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/annotations/SpecifiedExecutor.java
// Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/exec/Executor.java // public abstract class Executor { // protected final InfluxDBRepository repository; // // public Executor(InfluxDBRepository repository) { // this.repository = repository; // } // // public abstract ResultContext execute(MapperMethod method, Map<String, ParameterValue> parameters); // } // // Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/exec/SpecificExecutor.java // public class SpecificExecutor extends AnnotationExecutor<SpecifiedExecutor> { // private final Executor realExecutor; // // public SpecificExecutor(InfluxDBRepository repository, SpecifiedExecutor annotation) { // super(repository, annotation); // realExecutor = instantiateRealExecutor(repository, annotation); // } // // private Executor instantiateRealExecutor(InfluxDBRepository repository, SpecifiedExecutor annotation) { // Class<? extends Executor> executorClass = annotation.value(); // try { // Constructor<? extends Executor> constructor = executorClass.getDeclaredConstructor(InfluxDBRepository.class); // if (!constructor.isAccessible()) { // constructor.setAccessible(true); // } // return constructor.newInstance(repository); // } catch (NoSuchMethodException | SecurityException e) { // throw new InfluxDBException("invalid executor constructor", e); // } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { // throw new InfluxDBException("an error occured while instantiating executor", e); // } // } // // @Override // public ResultContext execute(MapperMethod method, Map<String, ParameterValue> parameters) { // return realExecutor.execute(method, parameters); // } // }
import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import com.vgerbot.orm.influxdb.exec.Executor; import com.vgerbot.orm.influxdb.exec.SpecificExecutor;
package com.vgerbot.orm.influxdb.annotations; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME)
// Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/exec/Executor.java // public abstract class Executor { // protected final InfluxDBRepository repository; // // public Executor(InfluxDBRepository repository) { // this.repository = repository; // } // // public abstract ResultContext execute(MapperMethod method, Map<String, ParameterValue> parameters); // } // // Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/exec/SpecificExecutor.java // public class SpecificExecutor extends AnnotationExecutor<SpecifiedExecutor> { // private final Executor realExecutor; // // public SpecificExecutor(InfluxDBRepository repository, SpecifiedExecutor annotation) { // super(repository, annotation); // realExecutor = instantiateRealExecutor(repository, annotation); // } // // private Executor instantiateRealExecutor(InfluxDBRepository repository, SpecifiedExecutor annotation) { // Class<? extends Executor> executorClass = annotation.value(); // try { // Constructor<? extends Executor> constructor = executorClass.getDeclaredConstructor(InfluxDBRepository.class); // if (!constructor.isAccessible()) { // constructor.setAccessible(true); // } // return constructor.newInstance(repository); // } catch (NoSuchMethodException | SecurityException e) { // throw new InfluxDBException("invalid executor constructor", e); // } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { // throw new InfluxDBException("an error occured while instantiating executor", e); // } // } // // @Override // public ResultContext execute(MapperMethod method, Map<String, ParameterValue> parameters) { // return realExecutor.execute(method, parameters); // } // } // Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/annotations/SpecifiedExecutor.java import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import com.vgerbot.orm.influxdb.exec.Executor; import com.vgerbot.orm.influxdb.exec.SpecificExecutor; package com.vgerbot.orm.influxdb.annotations; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME)
@AnnotateExecutor(SpecificExecutor.class)
y1j2x34/spring-influxdb-orm
spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/annotations/SpecifiedExecutor.java
// Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/exec/Executor.java // public abstract class Executor { // protected final InfluxDBRepository repository; // // public Executor(InfluxDBRepository repository) { // this.repository = repository; // } // // public abstract ResultContext execute(MapperMethod method, Map<String, ParameterValue> parameters); // } // // Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/exec/SpecificExecutor.java // public class SpecificExecutor extends AnnotationExecutor<SpecifiedExecutor> { // private final Executor realExecutor; // // public SpecificExecutor(InfluxDBRepository repository, SpecifiedExecutor annotation) { // super(repository, annotation); // realExecutor = instantiateRealExecutor(repository, annotation); // } // // private Executor instantiateRealExecutor(InfluxDBRepository repository, SpecifiedExecutor annotation) { // Class<? extends Executor> executorClass = annotation.value(); // try { // Constructor<? extends Executor> constructor = executorClass.getDeclaredConstructor(InfluxDBRepository.class); // if (!constructor.isAccessible()) { // constructor.setAccessible(true); // } // return constructor.newInstance(repository); // } catch (NoSuchMethodException | SecurityException e) { // throw new InfluxDBException("invalid executor constructor", e); // } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { // throw new InfluxDBException("an error occured while instantiating executor", e); // } // } // // @Override // public ResultContext execute(MapperMethod method, Map<String, ParameterValue> parameters) { // return realExecutor.execute(method, parameters); // } // }
import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import com.vgerbot.orm.influxdb.exec.Executor; import com.vgerbot.orm.influxdb.exec.SpecificExecutor;
package com.vgerbot.orm.influxdb.annotations; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @AnnotateExecutor(SpecificExecutor.class) public @interface SpecifiedExecutor {
// Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/exec/Executor.java // public abstract class Executor { // protected final InfluxDBRepository repository; // // public Executor(InfluxDBRepository repository) { // this.repository = repository; // } // // public abstract ResultContext execute(MapperMethod method, Map<String, ParameterValue> parameters); // } // // Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/exec/SpecificExecutor.java // public class SpecificExecutor extends AnnotationExecutor<SpecifiedExecutor> { // private final Executor realExecutor; // // public SpecificExecutor(InfluxDBRepository repository, SpecifiedExecutor annotation) { // super(repository, annotation); // realExecutor = instantiateRealExecutor(repository, annotation); // } // // private Executor instantiateRealExecutor(InfluxDBRepository repository, SpecifiedExecutor annotation) { // Class<? extends Executor> executorClass = annotation.value(); // try { // Constructor<? extends Executor> constructor = executorClass.getDeclaredConstructor(InfluxDBRepository.class); // if (!constructor.isAccessible()) { // constructor.setAccessible(true); // } // return constructor.newInstance(repository); // } catch (NoSuchMethodException | SecurityException e) { // throw new InfluxDBException("invalid executor constructor", e); // } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { // throw new InfluxDBException("an error occured while instantiating executor", e); // } // } // // @Override // public ResultContext execute(MapperMethod method, Map<String, ParameterValue> parameters) { // return realExecutor.execute(method, parameters); // } // } // Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/annotations/SpecifiedExecutor.java import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import com.vgerbot.orm.influxdb.exec.Executor; import com.vgerbot.orm.influxdb.exec.SpecificExecutor; package com.vgerbot.orm.influxdb.annotations; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @AnnotateExecutor(SpecificExecutor.class) public @interface SpecifiedExecutor {
Class<? extends Executor> value();
y1j2x34/spring-influxdb-orm
spring-influxdb-orm/src/test/java/com/vgerbot/test/orm/influxdb/common/MockitoMatchers.java
// Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/param/ParameterSignature.java // public class ParameterSignature { // private final int index; // private final String name; // private final Class<?> type; // // private ParameterSignature(int index, String name, Class<?> type) { // super(); // this.index = index; // this.name = name; // this.type = type; // } // // public static ParameterSignature signature(int index, Parameter parameter, String aliasName) { // Class<?> type = parameter.getType(); // return new ParameterSignature(index, aliasName, type); // } // // public static ParameterSignature signature(int index, Parameter parameter) { // String name = parameter.getName(); // Class<?> type = parameter.getType(); // return new ParameterSignature(index, name, type); // } // // public static List<ParameterSignature> signatures(Method method) { // Parameter[] parameters = method.getParameters(); // List<ParameterSignature> signatures = new ArrayList<>(parameters.length); // // for (int i = 0; i < parameters.length; i++) { // Parameter parameter = parameters[i]; // signatures.add(signature(i, parameter)); // } // // return signatures; // } // // public int getIndex() { // return index; // } // // public String getName() { // return name; // } // // public Class<?> getType() { // return type; // } // // public ParameterValue value(Object value) { // return new ParameterValue(value, this); // } // } // // Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/param/ParameterValue.java // public class ParameterValue { // private final Object value; // private final ParameterSignature signature; // // public ParameterValue(Object value, ParameterSignature signature) { // super(); // this.value = value; // this.signature = signature; // } // // public Object getValue() { // return value; // } // // public ParameterSignature getSignature() { // return signature; // } // // }
import com.vgerbot.orm.influxdb.param.ParameterSignature; import com.vgerbot.orm.influxdb.param.ParameterValue; import org.apache.commons.lang3.StringUtils; import org.mockito.ArgumentMatcher; import org.mockito.internal.progress.ThreadSafeMockingProgress; import org.mockito.internal.util.Primitives; import java.util.Map; import java.util.Objects; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
package com.vgerbot.test.orm.influxdb.common; public class MockitoMatchers { private static ParameterSignature createMockParameterSignature(int index, String name, Class<?> type) { ParameterSignature signature = mock(ParameterSignature.class); when(signature.getIndex()).thenReturn(index); when(signature.getName()).thenReturn(name); when((Object)signature.getType()).thenReturn(type); return signature; }
// Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/param/ParameterSignature.java // public class ParameterSignature { // private final int index; // private final String name; // private final Class<?> type; // // private ParameterSignature(int index, String name, Class<?> type) { // super(); // this.index = index; // this.name = name; // this.type = type; // } // // public static ParameterSignature signature(int index, Parameter parameter, String aliasName) { // Class<?> type = parameter.getType(); // return new ParameterSignature(index, aliasName, type); // } // // public static ParameterSignature signature(int index, Parameter parameter) { // String name = parameter.getName(); // Class<?> type = parameter.getType(); // return new ParameterSignature(index, name, type); // } // // public static List<ParameterSignature> signatures(Method method) { // Parameter[] parameters = method.getParameters(); // List<ParameterSignature> signatures = new ArrayList<>(parameters.length); // // for (int i = 0; i < parameters.length; i++) { // Parameter parameter = parameters[i]; // signatures.add(signature(i, parameter)); // } // // return signatures; // } // // public int getIndex() { // return index; // } // // public String getName() { // return name; // } // // public Class<?> getType() { // return type; // } // // public ParameterValue value(Object value) { // return new ParameterValue(value, this); // } // } // // Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/param/ParameterValue.java // public class ParameterValue { // private final Object value; // private final ParameterSignature signature; // // public ParameterValue(Object value, ParameterSignature signature) { // super(); // this.value = value; // this.signature = signature; // } // // public Object getValue() { // return value; // } // // public ParameterSignature getSignature() { // return signature; // } // // } // Path: spring-influxdb-orm/src/test/java/com/vgerbot/test/orm/influxdb/common/MockitoMatchers.java import com.vgerbot.orm.influxdb.param.ParameterSignature; import com.vgerbot.orm.influxdb.param.ParameterValue; import org.apache.commons.lang3.StringUtils; import org.mockito.ArgumentMatcher; import org.mockito.internal.progress.ThreadSafeMockingProgress; import org.mockito.internal.util.Primitives; import java.util.Map; import java.util.Objects; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; package com.vgerbot.test.orm.influxdb.common; public class MockitoMatchers { private static ParameterSignature createMockParameterSignature(int index, String name, Class<?> type) { ParameterSignature signature = mock(ParameterSignature.class); when(signature.getIndex()).thenReturn(index); when(signature.getName()).thenReturn(name); when((Object)signature.getType()).thenReturn(type); return signature; }
public static Map<String, ParameterValue> parameters(Map<String, ParameterValue> value) {
y1j2x34/spring-influxdb-orm
spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/annotations/InfluxQL.java
// Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/exec/InfluxQLAnnotExecutor.java // public class InfluxQLAnnotExecutor extends AnnotationExecutor<InfluxQL> { // // public InfluxQLAnnotExecutor(InfluxDBRepository repository, InfluxQL annotation) { // super(repository, annotation); // } // // @Override // public ResultContext execute(MapperMethod method, Map<String, ParameterValue> parameters) { // String key = super.annotation.value(); // if (StringUtils.isEmpty(key)) { // key = method.getMethodSignature().getMethod().getName(); // } // InfluxQLStatement statement = this.repository.getStatement(key); // if (statement == null) { // throw new InfluxDBException("Statement not found: " + key); // } // // switch (statement.getAction()) { // case SELECT: // return this.repository.query(statement.getTemplate(), parameters); // case EXECUTE: // this.repository.execute(statement.getTemplate(), parameters); // } // return ResultContext.VOID; // } // // }
import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import com.vgerbot.orm.influxdb.exec.InfluxQLAnnotExecutor;
package com.vgerbot.orm.influxdb.annotations; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD)
// Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/exec/InfluxQLAnnotExecutor.java // public class InfluxQLAnnotExecutor extends AnnotationExecutor<InfluxQL> { // // public InfluxQLAnnotExecutor(InfluxDBRepository repository, InfluxQL annotation) { // super(repository, annotation); // } // // @Override // public ResultContext execute(MapperMethod method, Map<String, ParameterValue> parameters) { // String key = super.annotation.value(); // if (StringUtils.isEmpty(key)) { // key = method.getMethodSignature().getMethod().getName(); // } // InfluxQLStatement statement = this.repository.getStatement(key); // if (statement == null) { // throw new InfluxDBException("Statement not found: " + key); // } // // switch (statement.getAction()) { // case SELECT: // return this.repository.query(statement.getTemplate(), parameters); // case EXECUTE: // this.repository.execute(statement.getTemplate(), parameters); // } // return ResultContext.VOID; // } // // } // Path: spring-influxdb-orm/src/main/java/com/vgerbot/orm/influxdb/annotations/InfluxQL.java import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import com.vgerbot.orm.influxdb.exec.InfluxQLAnnotExecutor; package com.vgerbot.orm.influxdb.annotations; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD)
@AnnotateExecutor(InfluxQLAnnotExecutor.class)
y1j2x34/spring-influxdb-orm
spring-influxdb-orm/src/test/java/com/vgerbot/test/orm/influxdb/common/JSON.java
// Path: spring-influxdb-orm/src/test/java/com/vgerbot/test/orm/influxdb/intergration/entity/CensusMeasurement.java // @InfluxDBMeasurement("census") // public class CensusMeasurement implements Serializable { // private static final long serialVersionUID = 8260424450884444916L; // // private Date time; // // @TagColumn("location") // private String location; // @TagColumn("scientist") // private String scientist; // // @FieldColumn("butterflies") // private Integer butterflies; // @FieldColumn("honeybees") // private Integer honeybees; // // public Date getTime() { // return time; // } // // public void setTime(Date time) { // this.time = time; // } // // public String getLocation() { // return location; // } // // public void setLocation(String location) { // this.location = location; // } // // public String getScientist() { // return scientist; // } // // public void setScientist(String scientist) { // this.scientist = scientist; // } // // public Integer getButterflies() { // return butterflies; // } // // public void setButterflies(Integer butterflies) { // this.butterflies = butterflies; // } // // public Integer getHoneybees() { // return honeybees; // } // // public void setHoneybees(Integer honeybees) { // this.honeybees = honeybees; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((location == null) ? 0 : location.hashCode()); // result = prime * result + ((scientist == null) ? 0 : scientist.hashCode()); // result = prime * result + ((time == null) ? 0 : time.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // CensusMeasurement other = (CensusMeasurement) obj; // if (location == null) { // if (other.location != null) { // return false; // } // } else if (!location.equals(other.location)) { // return false; // } // if (scientist == null) { // if (other.scientist != null) { // return false; // } // } else if (!scientist.equals(other.scientist)) { // return false; // } // if (time == null) { // if (other.time != null) { // return false; // } // } else if (!time.equals(other.time)) { // return false; // } // return true; // } // // public String toString() { // return "[time: " + time.getTime() + ", location: " + location + ", scientist: " + scientist + ", butterflies: " + butterflies // + ", honeybees: " + honeybees + "]"; // } // }
import java.io.IOException; import java.io.StringWriter; import com.fasterxml.jackson.databind.ObjectMapper; import com.vgerbot.test.orm.influxdb.intergration.entity.CensusMeasurement;
package com.vgerbot.test.orm.influxdb.common; public class JSON { private static ObjectMapper mapper = new ObjectMapper(); public static String stringify(Object value) { if (value == null) { return "null"; } else { StringWriter sw = new StringWriter(); try { mapper.writerFor(value.getClass()).writeValue(sw, value); } catch (IOException e) { throw new RuntimeException(e); } return sw.toString(); } } public static void main(String[] args) throws Exception { // mapper.configure(Feature.IGNORE_UNKNOWN, true);
// Path: spring-influxdb-orm/src/test/java/com/vgerbot/test/orm/influxdb/intergration/entity/CensusMeasurement.java // @InfluxDBMeasurement("census") // public class CensusMeasurement implements Serializable { // private static final long serialVersionUID = 8260424450884444916L; // // private Date time; // // @TagColumn("location") // private String location; // @TagColumn("scientist") // private String scientist; // // @FieldColumn("butterflies") // private Integer butterflies; // @FieldColumn("honeybees") // private Integer honeybees; // // public Date getTime() { // return time; // } // // public void setTime(Date time) { // this.time = time; // } // // public String getLocation() { // return location; // } // // public void setLocation(String location) { // this.location = location; // } // // public String getScientist() { // return scientist; // } // // public void setScientist(String scientist) { // this.scientist = scientist; // } // // public Integer getButterflies() { // return butterflies; // } // // public void setButterflies(Integer butterflies) { // this.butterflies = butterflies; // } // // public Integer getHoneybees() { // return honeybees; // } // // public void setHoneybees(Integer honeybees) { // this.honeybees = honeybees; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((location == null) ? 0 : location.hashCode()); // result = prime * result + ((scientist == null) ? 0 : scientist.hashCode()); // result = prime * result + ((time == null) ? 0 : time.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // CensusMeasurement other = (CensusMeasurement) obj; // if (location == null) { // if (other.location != null) { // return false; // } // } else if (!location.equals(other.location)) { // return false; // } // if (scientist == null) { // if (other.scientist != null) { // return false; // } // } else if (!scientist.equals(other.scientist)) { // return false; // } // if (time == null) { // if (other.time != null) { // return false; // } // } else if (!time.equals(other.time)) { // return false; // } // return true; // } // // public String toString() { // return "[time: " + time.getTime() + ", location: " + location + ", scientist: " + scientist + ", butterflies: " + butterflies // + ", honeybees: " + honeybees + "]"; // } // } // Path: spring-influxdb-orm/src/test/java/com/vgerbot/test/orm/influxdb/common/JSON.java import java.io.IOException; import java.io.StringWriter; import com.fasterxml.jackson.databind.ObjectMapper; import com.vgerbot.test.orm.influxdb.intergration.entity.CensusMeasurement; package com.vgerbot.test.orm.influxdb.common; public class JSON { private static ObjectMapper mapper = new ObjectMapper(); public static String stringify(Object value) { if (value == null) { return "null"; } else { StringWriter sw = new StringWriter(); try { mapper.writerFor(value.getClass()).writeValue(sw, value); } catch (IOException e) { throw new RuntimeException(e); } return sw.toString(); } } public static void main(String[] args) throws Exception { // mapper.configure(Feature.IGNORE_UNKNOWN, true);
CensusMeasurement m = new CensusMeasurement();
tagbangers/spring-best-practices
spring-best-practice-hibernate-search-multi-tenancy/src/main/java/practice/repository/ItemRepositoryImpl.java
// Path: spring-best-practice-hibernate-search-multi-tenancy/src/main/java/practice/entity/Item.java // @Entity // @Indexed // public class Item implements Serializable { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private long id; // // private String name; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return name; // } // }
import org.apache.lucene.search.Query; import org.hibernate.search.jpa.FullTextEntityManager; import org.hibernate.search.jpa.FullTextQuery; import org.hibernate.search.jpa.Search; import org.hibernate.search.query.dsl.BooleanJunction; import org.hibernate.search.query.dsl.QueryBuilder; import practice.entity.Item; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import java.util.List;
package practice.repository; public class ItemRepositoryImpl implements ItemRepositoryCustom { @PersistenceContext private EntityManager entityManager; @Override
// Path: spring-best-practice-hibernate-search-multi-tenancy/src/main/java/practice/entity/Item.java // @Entity // @Indexed // public class Item implements Serializable { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private long id; // // private String name; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return name; // } // } // Path: spring-best-practice-hibernate-search-multi-tenancy/src/main/java/practice/repository/ItemRepositoryImpl.java import org.apache.lucene.search.Query; import org.hibernate.search.jpa.FullTextEntityManager; import org.hibernate.search.jpa.FullTextQuery; import org.hibernate.search.jpa.Search; import org.hibernate.search.query.dsl.BooleanJunction; import org.hibernate.search.query.dsl.QueryBuilder; import practice.entity.Item; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import java.util.List; package practice.repository; public class ItemRepositoryImpl implements ItemRepositoryCustom { @PersistenceContext private EntityManager entityManager; @Override
public List<Item> search() {
tagbangers/spring-best-practices
spring-best-practice-hibernate-search-multi-tenancy/src/main/java/practice/mvc/CurrentTenantIdentifierChangeInterceptor.java
// Path: spring-best-practice-hibernate-search-multi-tenancy/src/main/java/practice/support/CurrentTenantIdentifierResolverImpl.java // @Component // public class CurrentTenantIdentifierResolverImpl implements CurrentTenantIdentifierResolver { // // public static final String IDENTIFIER_ATTRIBUTE = CurrentTenantIdentifierResolverImpl.class.getName() + ".IDENTIFIER"; // // public static final String TENANT_1_IDENTIFIER = "tenant1"; // public static final String TENANT_2_IDENTIFIER = "tenant2"; // // @Override // public String resolveCurrentTenantIdentifier() { // RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); // if (requestAttributes != null) { // String identifier = (String) requestAttributes.getAttribute(IDENTIFIER_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST); // if (identifier != null) { // return identifier; // } // } // return TENANT_1_IDENTIFIER; // } // // @Override // public boolean validateExistingCurrentSessions() { // return true; // } // }
import org.springframework.web.servlet.HandlerMapping; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import practice.support.CurrentTenantIdentifierResolverImpl; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Map;
package practice.mvc; public class CurrentTenantIdentifierChangeInterceptor extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { Map<String, Object> pathVariables = (Map<String, Object>) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE); if (pathVariables.containsKey("tenant")) {
// Path: spring-best-practice-hibernate-search-multi-tenancy/src/main/java/practice/support/CurrentTenantIdentifierResolverImpl.java // @Component // public class CurrentTenantIdentifierResolverImpl implements CurrentTenantIdentifierResolver { // // public static final String IDENTIFIER_ATTRIBUTE = CurrentTenantIdentifierResolverImpl.class.getName() + ".IDENTIFIER"; // // public static final String TENANT_1_IDENTIFIER = "tenant1"; // public static final String TENANT_2_IDENTIFIER = "tenant2"; // // @Override // public String resolveCurrentTenantIdentifier() { // RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); // if (requestAttributes != null) { // String identifier = (String) requestAttributes.getAttribute(IDENTIFIER_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST); // if (identifier != null) { // return identifier; // } // } // return TENANT_1_IDENTIFIER; // } // // @Override // public boolean validateExistingCurrentSessions() { // return true; // } // } // Path: spring-best-practice-hibernate-search-multi-tenancy/src/main/java/practice/mvc/CurrentTenantIdentifierChangeInterceptor.java import org.springframework.web.servlet.HandlerMapping; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import practice.support.CurrentTenantIdentifierResolverImpl; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Map; package practice.mvc; public class CurrentTenantIdentifierChangeInterceptor extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { Map<String, Object> pathVariables = (Map<String, Object>) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE); if (pathVariables.containsKey("tenant")) {
request.setAttribute(CurrentTenantIdentifierResolverImpl.IDENTIFIER_ATTRIBUTE, pathVariables.get("tenant"));
tagbangers/spring-best-practices
spring-best-practice-hibernate-search-multi-tenancy/src/main/java/practice/configure/WebMvcConfiguration.java
// Path: spring-best-practice-hibernate-search-multi-tenancy/src/main/java/practice/mvc/CurrentTenantIdentifierChangeInterceptor.java // public class CurrentTenantIdentifierChangeInterceptor extends HandlerInterceptorAdapter { // // @Override // public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // Map<String, Object> pathVariables = (Map<String, Object>) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE); // if (pathVariables.containsKey("tenant")) { // request.setAttribute(CurrentTenantIdentifierResolverImpl.IDENTIFIER_ATTRIBUTE, pathVariables.get("tenant")); // } // return true; // } // }
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import practice.mvc.CurrentTenantIdentifierChangeInterceptor;
package practice.configure; @Configuration public class WebMvcConfiguration extends WebMvcConfigurerAdapter { @Override public void addInterceptors(InterceptorRegistry registry) {
// Path: spring-best-practice-hibernate-search-multi-tenancy/src/main/java/practice/mvc/CurrentTenantIdentifierChangeInterceptor.java // public class CurrentTenantIdentifierChangeInterceptor extends HandlerInterceptorAdapter { // // @Override // public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // Map<String, Object> pathVariables = (Map<String, Object>) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE); // if (pathVariables.containsKey("tenant")) { // request.setAttribute(CurrentTenantIdentifierResolverImpl.IDENTIFIER_ATTRIBUTE, pathVariables.get("tenant")); // } // return true; // } // } // Path: spring-best-practice-hibernate-search-multi-tenancy/src/main/java/practice/configure/WebMvcConfiguration.java import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import practice.mvc.CurrentTenantIdentifierChangeInterceptor; package practice.configure; @Configuration public class WebMvcConfiguration extends WebMvcConfigurerAdapter { @Override public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new CurrentTenantIdentifierChangeInterceptor());
tagbangers/spring-best-practices
spring-best-practice-hibernate-search-multi-tenancy/src/main/java/practice/mvc/ItemController.java
// Path: spring-best-practice-hibernate-search-multi-tenancy/src/main/java/practice/entity/Item.java // @Entity // @Indexed // public class Item implements Serializable { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private long id; // // private String name; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return name; // } // } // // Path: spring-best-practice-hibernate-search-multi-tenancy/src/main/java/practice/repository/ItemRepository.java // public interface ItemRepository extends CrudRepository<Item, Long>, ItemRepositoryCustom { // }
import org.hibernate.search.jpa.FullTextEntityManager; import org.hibernate.search.jpa.Search; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import practice.entity.Item; import practice.repository.ItemRepository; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.transaction.Transactional; import java.util.List;
package practice.mvc; @Controller @RequestMapping("/{tenant}") public class ItemController { @Autowired
// Path: spring-best-practice-hibernate-search-multi-tenancy/src/main/java/practice/entity/Item.java // @Entity // @Indexed // public class Item implements Serializable { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private long id; // // private String name; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return name; // } // } // // Path: spring-best-practice-hibernate-search-multi-tenancy/src/main/java/practice/repository/ItemRepository.java // public interface ItemRepository extends CrudRepository<Item, Long>, ItemRepositoryCustom { // } // Path: spring-best-practice-hibernate-search-multi-tenancy/src/main/java/practice/mvc/ItemController.java import org.hibernate.search.jpa.FullTextEntityManager; import org.hibernate.search.jpa.Search; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import practice.entity.Item; import practice.repository.ItemRepository; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.transaction.Transactional; import java.util.List; package practice.mvc; @Controller @RequestMapping("/{tenant}") public class ItemController { @Autowired
private ItemRepository itemRepository;
tagbangers/spring-best-practices
spring-best-practice-hibernate-search-multi-tenancy/src/main/java/practice/mvc/ItemController.java
// Path: spring-best-practice-hibernate-search-multi-tenancy/src/main/java/practice/entity/Item.java // @Entity // @Indexed // public class Item implements Serializable { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private long id; // // private String name; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return name; // } // } // // Path: spring-best-practice-hibernate-search-multi-tenancy/src/main/java/practice/repository/ItemRepository.java // public interface ItemRepository extends CrudRepository<Item, Long>, ItemRepositoryCustom { // }
import org.hibernate.search.jpa.FullTextEntityManager; import org.hibernate.search.jpa.Search; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import practice.entity.Item; import practice.repository.ItemRepository; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.transaction.Transactional; import java.util.List;
package practice.mvc; @Controller @RequestMapping("/{tenant}") public class ItemController { @Autowired private ItemRepository itemRepository; @PersistenceContext private EntityManager entityManager; @RequestMapping public String items(@PathVariable String tenant, Model model) {
// Path: spring-best-practice-hibernate-search-multi-tenancy/src/main/java/practice/entity/Item.java // @Entity // @Indexed // public class Item implements Serializable { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private long id; // // private String name; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return name; // } // } // // Path: spring-best-practice-hibernate-search-multi-tenancy/src/main/java/practice/repository/ItemRepository.java // public interface ItemRepository extends CrudRepository<Item, Long>, ItemRepositoryCustom { // } // Path: spring-best-practice-hibernate-search-multi-tenancy/src/main/java/practice/mvc/ItemController.java import org.hibernate.search.jpa.FullTextEntityManager; import org.hibernate.search.jpa.Search; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import practice.entity.Item; import practice.repository.ItemRepository; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.transaction.Transactional; import java.util.List; package practice.mvc; @Controller @RequestMapping("/{tenant}") public class ItemController { @Autowired private ItemRepository itemRepository; @PersistenceContext private EntityManager entityManager; @RequestMapping public String items(@PathVariable String tenant, Model model) {
List<Item> items = itemRepository.search();
tagbangers/spring-best-practices
spring-best-practice-hibernate-search-multi-tenancy/src/main/java/practice/configure/MultiTenancyJpaConfiguration.java
// Path: spring-best-practice-hibernate-search-multi-tenancy/src/main/java/practice/entity/Item.java // @Entity // @Indexed // public class Item implements Serializable { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private long id; // // private String name; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return name; // } // }
import org.hibernate.MultiTenancyStrategy; import org.hibernate.cfg.Environment; import org.hibernate.context.spi.CurrentTenantIdentifierResolver; import org.hibernate.engine.jdbc.connections.spi.MultiTenantConnectionProvider; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.orm.jpa.EntityManagerFactoryBuilder; import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import practice.entity.Item; import javax.sql.DataSource; import java.util.LinkedHashMap; import java.util.Map;
package practice.configure; @Configuration @EnableConfigurationProperties(JpaProperties.class) public class MultiTenancyJpaConfiguration { @Autowired private DataSource dataSource; @Autowired private JpaProperties jpaProperties; @Autowired private MultiTenantConnectionProvider multiTenantConnectionProvider; @Autowired private CurrentTenantIdentifierResolver currentTenantIdentifierResolver; @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder factoryBuilder) { Map<String, Object> vendorProperties = new LinkedHashMap<>(); vendorProperties.putAll(jpaProperties.getHibernateProperties(dataSource)); vendorProperties.put(Environment.MULTI_TENANT, MultiTenancyStrategy.DATABASE); vendorProperties.put(Environment.MULTI_TENANT_CONNECTION_PROVIDER, multiTenantConnectionProvider); vendorProperties.put(Environment.MULTI_TENANT_IDENTIFIER_RESOLVER, currentTenantIdentifierResolver); return factoryBuilder.dataSource(dataSource)
// Path: spring-best-practice-hibernate-search-multi-tenancy/src/main/java/practice/entity/Item.java // @Entity // @Indexed // public class Item implements Serializable { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private long id; // // private String name; // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return name; // } // } // Path: spring-best-practice-hibernate-search-multi-tenancy/src/main/java/practice/configure/MultiTenancyJpaConfiguration.java import org.hibernate.MultiTenancyStrategy; import org.hibernate.cfg.Environment; import org.hibernate.context.spi.CurrentTenantIdentifierResolver; import org.hibernate.engine.jdbc.connections.spi.MultiTenantConnectionProvider; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.orm.jpa.EntityManagerFactoryBuilder; import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import practice.entity.Item; import javax.sql.DataSource; import java.util.LinkedHashMap; import java.util.Map; package practice.configure; @Configuration @EnableConfigurationProperties(JpaProperties.class) public class MultiTenancyJpaConfiguration { @Autowired private DataSource dataSource; @Autowired private JpaProperties jpaProperties; @Autowired private MultiTenantConnectionProvider multiTenantConnectionProvider; @Autowired private CurrentTenantIdentifierResolver currentTenantIdentifierResolver; @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder factoryBuilder) { Map<String, Object> vendorProperties = new LinkedHashMap<>(); vendorProperties.putAll(jpaProperties.getHibernateProperties(dataSource)); vendorProperties.put(Environment.MULTI_TENANT, MultiTenancyStrategy.DATABASE); vendorProperties.put(Environment.MULTI_TENANT_CONNECTION_PROVIDER, multiTenantConnectionProvider); vendorProperties.put(Environment.MULTI_TENANT_IDENTIFIER_RESOLVER, currentTenantIdentifierResolver); return factoryBuilder.dataSource(dataSource)
.packages(Item.class.getPackage().getName())
tim-savage/SavageDeathChest
src/main/java/com/winterhavenmc/deathchest/commands/HelpCommand.java
// Path: src/main/java/com/winterhavenmc/deathchest/PluginMain.java // public final class PluginMain extends JavaPlugin { // // public MessageBuilder<MessageId, Macro> messageBuilder; // public WorldManager worldManager; // public SoundConfiguration soundConfig; // public ChestManager chestManager; // public CommandManager commandManager; // public ProtectionPluginRegistry protectionPluginRegistry; // // // @Override // public void onEnable() { // // // bStats // new Metrics(this, 13916); // // // copy default config from jar if it doesn't exist // saveDefaultConfig(); // // // initialize message builder // messageBuilder = new MessageBuilder<>(this); // // // instantiate sound configuration // soundConfig = new YamlSoundConfiguration(this); // // // instantiate world manager // worldManager = new WorldManager(this); // // // instantiate chest manager // chestManager = new ChestManager(this); // // // load all chests from datastore // chestManager.loadChests(); // // // instantiate command manager // commandManager = new CommandManager(this); // // // initialize event listeners // new PlayerEventListener(this); // new BlockEventListener(this); // new InventoryEventListener(this); // // // instantiate protection plugin registry // protectionPluginRegistry = new ProtectionPluginRegistry(this); // } // // // @Override // public void onDisable() { // // // close datastore // chestManager.closeDataStore(); // } // // } // // Path: src/main/java/com/winterhavenmc/deathchest/messages/MessageId.java // public enum MessageId { // // CHEST_SUCCESS, // DOUBLECHEST_PARTIAL_SUCCESS, // CHEST_DENIED_DEPLOYMENT_BY_PLUGIN, // CHEST_DENIED_ACCESS_BY_PLUGIN, // CHEST_DENIED_BLOCK, // CHEST_DENIED_PERMISSION, // CHEST_DENIED_ADJACENT, // CHEST_DENIED_SPAWN_RADIUS, // CHEST_DENIED_WORLD_DISABLED, // CHEST_DENIED_VOID, // CHEST_DEPLOYED_PROTECTION_TIME, // CHEST_ACCESSED_PROTECTION_TIME, // INVENTORY_EMPTY, // INVENTORY_FULL, // NO_CHEST_IN_INVENTORY, // NOT_OWNER, // CHEST_EXPIRED, // CREATIVE_MODE, // NO_CREATIVE_ACCESS, // CHEST_CURRENTLY_OPEN, // // COMMAND_FAIL_INVALID_COMMAND, // COMMAND_FAIL_ARGS_COUNT_OVER, // COMMAND_FAIL_HELP_PERMISSION, // COMMAND_FAIL_LIST_PERMISSION, // COMMAND_FAIL_LIST_OTHER_PERMISSION, // COMMAND_FAIL_RELOAD_PERMISSION, // COMMAND_FAIL_STATUS_PERMISSION, // COMMAND_SUCCESS_RELOAD, // // COMMAND_HELP_INVALID, // COMMAND_HELP_HELP, // COMMAND_HELP_LIST, // COMMAND_HELP_RELOAD, // COMMAND_HELP_STATUS, // COMMAND_HELP_USAGE, // // LIST_HEADER, // LIST_FOOTER, // LIST_EMPTY, // LIST_ITEM, // LIST_ITEM_ALL, // LIST_PLAYER_NOT_FOUND, // // } // // Path: src/main/java/com/winterhavenmc/deathchest/sounds/SoundId.java // public enum SoundId { // // CHEST_BREAK, // CHEST_DENIED_ACCESS, // COMMAND_FAIL, // INVENTORY_ADD_ITEM, // COMMAND_INVALID, // COMMAND_RELOAD_SUCCESS, // // }
import com.winterhavenmc.deathchest.PluginMain; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import com.winterhavenmc.deathchest.messages.MessageId; import com.winterhavenmc.deathchest.sounds.SoundId; import javax.annotation.Nonnull; import java.util.LinkedList; import java.util.List; import java.util.Objects;
/* * Copyright (c) 2022 Tim Savage. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.winterhavenmc.deathchest.commands; /** * Class that implements the help subcommand. Displays help and usage for plugin subcommands. */ final class HelpCommand extends SubcommandAbstract { private final PluginMain plugin; private final SubcommandRegistry subcommandRegistry; /** * Class constructor * @param plugin reference to the plugin main class * @param subcommandRegistry reference to the subcommand registry */ HelpCommand(final PluginMain plugin, final SubcommandRegistry subcommandRegistry) { this.plugin = Objects.requireNonNull(plugin); this.subcommandRegistry = Objects.requireNonNull(subcommandRegistry); this.name = "help"; this.usageString = "/deathchest help [command]";
// Path: src/main/java/com/winterhavenmc/deathchest/PluginMain.java // public final class PluginMain extends JavaPlugin { // // public MessageBuilder<MessageId, Macro> messageBuilder; // public WorldManager worldManager; // public SoundConfiguration soundConfig; // public ChestManager chestManager; // public CommandManager commandManager; // public ProtectionPluginRegistry protectionPluginRegistry; // // // @Override // public void onEnable() { // // // bStats // new Metrics(this, 13916); // // // copy default config from jar if it doesn't exist // saveDefaultConfig(); // // // initialize message builder // messageBuilder = new MessageBuilder<>(this); // // // instantiate sound configuration // soundConfig = new YamlSoundConfiguration(this); // // // instantiate world manager // worldManager = new WorldManager(this); // // // instantiate chest manager // chestManager = new ChestManager(this); // // // load all chests from datastore // chestManager.loadChests(); // // // instantiate command manager // commandManager = new CommandManager(this); // // // initialize event listeners // new PlayerEventListener(this); // new BlockEventListener(this); // new InventoryEventListener(this); // // // instantiate protection plugin registry // protectionPluginRegistry = new ProtectionPluginRegistry(this); // } // // // @Override // public void onDisable() { // // // close datastore // chestManager.closeDataStore(); // } // // } // // Path: src/main/java/com/winterhavenmc/deathchest/messages/MessageId.java // public enum MessageId { // // CHEST_SUCCESS, // DOUBLECHEST_PARTIAL_SUCCESS, // CHEST_DENIED_DEPLOYMENT_BY_PLUGIN, // CHEST_DENIED_ACCESS_BY_PLUGIN, // CHEST_DENIED_BLOCK, // CHEST_DENIED_PERMISSION, // CHEST_DENIED_ADJACENT, // CHEST_DENIED_SPAWN_RADIUS, // CHEST_DENIED_WORLD_DISABLED, // CHEST_DENIED_VOID, // CHEST_DEPLOYED_PROTECTION_TIME, // CHEST_ACCESSED_PROTECTION_TIME, // INVENTORY_EMPTY, // INVENTORY_FULL, // NO_CHEST_IN_INVENTORY, // NOT_OWNER, // CHEST_EXPIRED, // CREATIVE_MODE, // NO_CREATIVE_ACCESS, // CHEST_CURRENTLY_OPEN, // // COMMAND_FAIL_INVALID_COMMAND, // COMMAND_FAIL_ARGS_COUNT_OVER, // COMMAND_FAIL_HELP_PERMISSION, // COMMAND_FAIL_LIST_PERMISSION, // COMMAND_FAIL_LIST_OTHER_PERMISSION, // COMMAND_FAIL_RELOAD_PERMISSION, // COMMAND_FAIL_STATUS_PERMISSION, // COMMAND_SUCCESS_RELOAD, // // COMMAND_HELP_INVALID, // COMMAND_HELP_HELP, // COMMAND_HELP_LIST, // COMMAND_HELP_RELOAD, // COMMAND_HELP_STATUS, // COMMAND_HELP_USAGE, // // LIST_HEADER, // LIST_FOOTER, // LIST_EMPTY, // LIST_ITEM, // LIST_ITEM_ALL, // LIST_PLAYER_NOT_FOUND, // // } // // Path: src/main/java/com/winterhavenmc/deathchest/sounds/SoundId.java // public enum SoundId { // // CHEST_BREAK, // CHEST_DENIED_ACCESS, // COMMAND_FAIL, // INVENTORY_ADD_ITEM, // COMMAND_INVALID, // COMMAND_RELOAD_SUCCESS, // // } // Path: src/main/java/com/winterhavenmc/deathchest/commands/HelpCommand.java import com.winterhavenmc.deathchest.PluginMain; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import com.winterhavenmc.deathchest.messages.MessageId; import com.winterhavenmc.deathchest.sounds.SoundId; import javax.annotation.Nonnull; import java.util.LinkedList; import java.util.List; import java.util.Objects; /* * Copyright (c) 2022 Tim Savage. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.winterhavenmc.deathchest.commands; /** * Class that implements the help subcommand. Displays help and usage for plugin subcommands. */ final class HelpCommand extends SubcommandAbstract { private final PluginMain plugin; private final SubcommandRegistry subcommandRegistry; /** * Class constructor * @param plugin reference to the plugin main class * @param subcommandRegistry reference to the subcommand registry */ HelpCommand(final PluginMain plugin, final SubcommandRegistry subcommandRegistry) { this.plugin = Objects.requireNonNull(plugin); this.subcommandRegistry = Objects.requireNonNull(subcommandRegistry); this.name = "help"; this.usageString = "/deathchest help [command]";
this.description = MessageId.COMMAND_HELP_HELP;
tim-savage/SavageDeathChest
src/main/java/com/winterhavenmc/deathchest/commands/HelpCommand.java
// Path: src/main/java/com/winterhavenmc/deathchest/PluginMain.java // public final class PluginMain extends JavaPlugin { // // public MessageBuilder<MessageId, Macro> messageBuilder; // public WorldManager worldManager; // public SoundConfiguration soundConfig; // public ChestManager chestManager; // public CommandManager commandManager; // public ProtectionPluginRegistry protectionPluginRegistry; // // // @Override // public void onEnable() { // // // bStats // new Metrics(this, 13916); // // // copy default config from jar if it doesn't exist // saveDefaultConfig(); // // // initialize message builder // messageBuilder = new MessageBuilder<>(this); // // // instantiate sound configuration // soundConfig = new YamlSoundConfiguration(this); // // // instantiate world manager // worldManager = new WorldManager(this); // // // instantiate chest manager // chestManager = new ChestManager(this); // // // load all chests from datastore // chestManager.loadChests(); // // // instantiate command manager // commandManager = new CommandManager(this); // // // initialize event listeners // new PlayerEventListener(this); // new BlockEventListener(this); // new InventoryEventListener(this); // // // instantiate protection plugin registry // protectionPluginRegistry = new ProtectionPluginRegistry(this); // } // // // @Override // public void onDisable() { // // // close datastore // chestManager.closeDataStore(); // } // // } // // Path: src/main/java/com/winterhavenmc/deathchest/messages/MessageId.java // public enum MessageId { // // CHEST_SUCCESS, // DOUBLECHEST_PARTIAL_SUCCESS, // CHEST_DENIED_DEPLOYMENT_BY_PLUGIN, // CHEST_DENIED_ACCESS_BY_PLUGIN, // CHEST_DENIED_BLOCK, // CHEST_DENIED_PERMISSION, // CHEST_DENIED_ADJACENT, // CHEST_DENIED_SPAWN_RADIUS, // CHEST_DENIED_WORLD_DISABLED, // CHEST_DENIED_VOID, // CHEST_DEPLOYED_PROTECTION_TIME, // CHEST_ACCESSED_PROTECTION_TIME, // INVENTORY_EMPTY, // INVENTORY_FULL, // NO_CHEST_IN_INVENTORY, // NOT_OWNER, // CHEST_EXPIRED, // CREATIVE_MODE, // NO_CREATIVE_ACCESS, // CHEST_CURRENTLY_OPEN, // // COMMAND_FAIL_INVALID_COMMAND, // COMMAND_FAIL_ARGS_COUNT_OVER, // COMMAND_FAIL_HELP_PERMISSION, // COMMAND_FAIL_LIST_PERMISSION, // COMMAND_FAIL_LIST_OTHER_PERMISSION, // COMMAND_FAIL_RELOAD_PERMISSION, // COMMAND_FAIL_STATUS_PERMISSION, // COMMAND_SUCCESS_RELOAD, // // COMMAND_HELP_INVALID, // COMMAND_HELP_HELP, // COMMAND_HELP_LIST, // COMMAND_HELP_RELOAD, // COMMAND_HELP_STATUS, // COMMAND_HELP_USAGE, // // LIST_HEADER, // LIST_FOOTER, // LIST_EMPTY, // LIST_ITEM, // LIST_ITEM_ALL, // LIST_PLAYER_NOT_FOUND, // // } // // Path: src/main/java/com/winterhavenmc/deathchest/sounds/SoundId.java // public enum SoundId { // // CHEST_BREAK, // CHEST_DENIED_ACCESS, // COMMAND_FAIL, // INVENTORY_ADD_ITEM, // COMMAND_INVALID, // COMMAND_RELOAD_SUCCESS, // // }
import com.winterhavenmc.deathchest.PluginMain; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import com.winterhavenmc.deathchest.messages.MessageId; import com.winterhavenmc.deathchest.sounds.SoundId; import javax.annotation.Nonnull; import java.util.LinkedList; import java.util.List; import java.util.Objects;
@Override public List<String> onTabComplete(final @Nonnull CommandSender sender, final @Nonnull Command command, final @Nonnull String alias, final String[] args) { List<String> returnList = new LinkedList<>(); if (args.length == 2) { for (String subcommand : subcommandRegistry.getNames()) { if (sender.hasPermission("deathchest." + subcommand) && subcommand.startsWith(args[1].toLowerCase()) && !subcommand.equalsIgnoreCase("help")) { returnList.add(subcommand); } } } return returnList; } @Override public boolean onCommand(final CommandSender sender, final List<String> args) { // if command sender does not have permission to display help, output error message and return true if (!sender.hasPermission("deathchest.help")) { plugin.messageBuilder.build(sender, MessageId.COMMAND_FAIL_HELP_PERMISSION).send();
// Path: src/main/java/com/winterhavenmc/deathchest/PluginMain.java // public final class PluginMain extends JavaPlugin { // // public MessageBuilder<MessageId, Macro> messageBuilder; // public WorldManager worldManager; // public SoundConfiguration soundConfig; // public ChestManager chestManager; // public CommandManager commandManager; // public ProtectionPluginRegistry protectionPluginRegistry; // // // @Override // public void onEnable() { // // // bStats // new Metrics(this, 13916); // // // copy default config from jar if it doesn't exist // saveDefaultConfig(); // // // initialize message builder // messageBuilder = new MessageBuilder<>(this); // // // instantiate sound configuration // soundConfig = new YamlSoundConfiguration(this); // // // instantiate world manager // worldManager = new WorldManager(this); // // // instantiate chest manager // chestManager = new ChestManager(this); // // // load all chests from datastore // chestManager.loadChests(); // // // instantiate command manager // commandManager = new CommandManager(this); // // // initialize event listeners // new PlayerEventListener(this); // new BlockEventListener(this); // new InventoryEventListener(this); // // // instantiate protection plugin registry // protectionPluginRegistry = new ProtectionPluginRegistry(this); // } // // // @Override // public void onDisable() { // // // close datastore // chestManager.closeDataStore(); // } // // } // // Path: src/main/java/com/winterhavenmc/deathchest/messages/MessageId.java // public enum MessageId { // // CHEST_SUCCESS, // DOUBLECHEST_PARTIAL_SUCCESS, // CHEST_DENIED_DEPLOYMENT_BY_PLUGIN, // CHEST_DENIED_ACCESS_BY_PLUGIN, // CHEST_DENIED_BLOCK, // CHEST_DENIED_PERMISSION, // CHEST_DENIED_ADJACENT, // CHEST_DENIED_SPAWN_RADIUS, // CHEST_DENIED_WORLD_DISABLED, // CHEST_DENIED_VOID, // CHEST_DEPLOYED_PROTECTION_TIME, // CHEST_ACCESSED_PROTECTION_TIME, // INVENTORY_EMPTY, // INVENTORY_FULL, // NO_CHEST_IN_INVENTORY, // NOT_OWNER, // CHEST_EXPIRED, // CREATIVE_MODE, // NO_CREATIVE_ACCESS, // CHEST_CURRENTLY_OPEN, // // COMMAND_FAIL_INVALID_COMMAND, // COMMAND_FAIL_ARGS_COUNT_OVER, // COMMAND_FAIL_HELP_PERMISSION, // COMMAND_FAIL_LIST_PERMISSION, // COMMAND_FAIL_LIST_OTHER_PERMISSION, // COMMAND_FAIL_RELOAD_PERMISSION, // COMMAND_FAIL_STATUS_PERMISSION, // COMMAND_SUCCESS_RELOAD, // // COMMAND_HELP_INVALID, // COMMAND_HELP_HELP, // COMMAND_HELP_LIST, // COMMAND_HELP_RELOAD, // COMMAND_HELP_STATUS, // COMMAND_HELP_USAGE, // // LIST_HEADER, // LIST_FOOTER, // LIST_EMPTY, // LIST_ITEM, // LIST_ITEM_ALL, // LIST_PLAYER_NOT_FOUND, // // } // // Path: src/main/java/com/winterhavenmc/deathchest/sounds/SoundId.java // public enum SoundId { // // CHEST_BREAK, // CHEST_DENIED_ACCESS, // COMMAND_FAIL, // INVENTORY_ADD_ITEM, // COMMAND_INVALID, // COMMAND_RELOAD_SUCCESS, // // } // Path: src/main/java/com/winterhavenmc/deathchest/commands/HelpCommand.java import com.winterhavenmc.deathchest.PluginMain; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import com.winterhavenmc.deathchest.messages.MessageId; import com.winterhavenmc.deathchest.sounds.SoundId; import javax.annotation.Nonnull; import java.util.LinkedList; import java.util.List; import java.util.Objects; @Override public List<String> onTabComplete(final @Nonnull CommandSender sender, final @Nonnull Command command, final @Nonnull String alias, final String[] args) { List<String> returnList = new LinkedList<>(); if (args.length == 2) { for (String subcommand : subcommandRegistry.getNames()) { if (sender.hasPermission("deathchest." + subcommand) && subcommand.startsWith(args[1].toLowerCase()) && !subcommand.equalsIgnoreCase("help")) { returnList.add(subcommand); } } } return returnList; } @Override public boolean onCommand(final CommandSender sender, final List<String> args) { // if command sender does not have permission to display help, output error message and return true if (!sender.hasPermission("deathchest.help")) { plugin.messageBuilder.build(sender, MessageId.COMMAND_FAIL_HELP_PERMISSION).send();
plugin.soundConfig.playSound(sender, SoundId.COMMAND_FAIL);
tim-savage/SavageDeathChest
src/main/java/com/winterhavenmc/deathchest/commands/Subcommand.java
// Path: src/main/java/com/winterhavenmc/deathchest/messages/MessageId.java // public enum MessageId { // // CHEST_SUCCESS, // DOUBLECHEST_PARTIAL_SUCCESS, // CHEST_DENIED_DEPLOYMENT_BY_PLUGIN, // CHEST_DENIED_ACCESS_BY_PLUGIN, // CHEST_DENIED_BLOCK, // CHEST_DENIED_PERMISSION, // CHEST_DENIED_ADJACENT, // CHEST_DENIED_SPAWN_RADIUS, // CHEST_DENIED_WORLD_DISABLED, // CHEST_DENIED_VOID, // CHEST_DEPLOYED_PROTECTION_TIME, // CHEST_ACCESSED_PROTECTION_TIME, // INVENTORY_EMPTY, // INVENTORY_FULL, // NO_CHEST_IN_INVENTORY, // NOT_OWNER, // CHEST_EXPIRED, // CREATIVE_MODE, // NO_CREATIVE_ACCESS, // CHEST_CURRENTLY_OPEN, // // COMMAND_FAIL_INVALID_COMMAND, // COMMAND_FAIL_ARGS_COUNT_OVER, // COMMAND_FAIL_HELP_PERMISSION, // COMMAND_FAIL_LIST_PERMISSION, // COMMAND_FAIL_LIST_OTHER_PERMISSION, // COMMAND_FAIL_RELOAD_PERMISSION, // COMMAND_FAIL_STATUS_PERMISSION, // COMMAND_SUCCESS_RELOAD, // // COMMAND_HELP_INVALID, // COMMAND_HELP_HELP, // COMMAND_HELP_LIST, // COMMAND_HELP_RELOAD, // COMMAND_HELP_STATUS, // COMMAND_HELP_USAGE, // // LIST_HEADER, // LIST_FOOTER, // LIST_EMPTY, // LIST_ITEM, // LIST_ITEM_ALL, // LIST_PLAYER_NOT_FOUND, // // }
import com.winterhavenmc.deathchest.messages.MessageId; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import java.util.List;
/* * Copyright (c) 2022 Tim Savage. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.winterhavenmc.deathchest.commands; interface Subcommand { boolean onCommand(final CommandSender sender, final List<String> argsList); List<String> onTabComplete(final CommandSender sender, final Command command, final String alias, final String[] args); String getName(); String getUsage(); void displayUsage(final CommandSender sender);
// Path: src/main/java/com/winterhavenmc/deathchest/messages/MessageId.java // public enum MessageId { // // CHEST_SUCCESS, // DOUBLECHEST_PARTIAL_SUCCESS, // CHEST_DENIED_DEPLOYMENT_BY_PLUGIN, // CHEST_DENIED_ACCESS_BY_PLUGIN, // CHEST_DENIED_BLOCK, // CHEST_DENIED_PERMISSION, // CHEST_DENIED_ADJACENT, // CHEST_DENIED_SPAWN_RADIUS, // CHEST_DENIED_WORLD_DISABLED, // CHEST_DENIED_VOID, // CHEST_DEPLOYED_PROTECTION_TIME, // CHEST_ACCESSED_PROTECTION_TIME, // INVENTORY_EMPTY, // INVENTORY_FULL, // NO_CHEST_IN_INVENTORY, // NOT_OWNER, // CHEST_EXPIRED, // CREATIVE_MODE, // NO_CREATIVE_ACCESS, // CHEST_CURRENTLY_OPEN, // // COMMAND_FAIL_INVALID_COMMAND, // COMMAND_FAIL_ARGS_COUNT_OVER, // COMMAND_FAIL_HELP_PERMISSION, // COMMAND_FAIL_LIST_PERMISSION, // COMMAND_FAIL_LIST_OTHER_PERMISSION, // COMMAND_FAIL_RELOAD_PERMISSION, // COMMAND_FAIL_STATUS_PERMISSION, // COMMAND_SUCCESS_RELOAD, // // COMMAND_HELP_INVALID, // COMMAND_HELP_HELP, // COMMAND_HELP_LIST, // COMMAND_HELP_RELOAD, // COMMAND_HELP_STATUS, // COMMAND_HELP_USAGE, // // LIST_HEADER, // LIST_FOOTER, // LIST_EMPTY, // LIST_ITEM, // LIST_ITEM_ALL, // LIST_PLAYER_NOT_FOUND, // // } // Path: src/main/java/com/winterhavenmc/deathchest/commands/Subcommand.java import com.winterhavenmc.deathchest.messages.MessageId; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import java.util.List; /* * Copyright (c) 2022 Tim Savage. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.winterhavenmc.deathchest.commands; interface Subcommand { boolean onCommand(final CommandSender sender, final List<String> argsList); List<String> onTabComplete(final CommandSender sender, final Command command, final String alias, final String[] args); String getName(); String getUsage(); void displayUsage(final CommandSender sender);
MessageId getDescription();
tim-savage/SavageDeathChest
src/main/java/com/winterhavenmc/deathchest/commands/CommandManager.java
// Path: src/main/java/com/winterhavenmc/deathchest/PluginMain.java // public final class PluginMain extends JavaPlugin { // // public MessageBuilder<MessageId, Macro> messageBuilder; // public WorldManager worldManager; // public SoundConfiguration soundConfig; // public ChestManager chestManager; // public CommandManager commandManager; // public ProtectionPluginRegistry protectionPluginRegistry; // // // @Override // public void onEnable() { // // // bStats // new Metrics(this, 13916); // // // copy default config from jar if it doesn't exist // saveDefaultConfig(); // // // initialize message builder // messageBuilder = new MessageBuilder<>(this); // // // instantiate sound configuration // soundConfig = new YamlSoundConfiguration(this); // // // instantiate world manager // worldManager = new WorldManager(this); // // // instantiate chest manager // chestManager = new ChestManager(this); // // // load all chests from datastore // chestManager.loadChests(); // // // instantiate command manager // commandManager = new CommandManager(this); // // // initialize event listeners // new PlayerEventListener(this); // new BlockEventListener(this); // new InventoryEventListener(this); // // // instantiate protection plugin registry // protectionPluginRegistry = new ProtectionPluginRegistry(this); // } // // // @Override // public void onDisable() { // // // close datastore // chestManager.closeDataStore(); // } // // } // // Path: src/main/java/com/winterhavenmc/deathchest/messages/MessageId.java // public enum MessageId { // // CHEST_SUCCESS, // DOUBLECHEST_PARTIAL_SUCCESS, // CHEST_DENIED_DEPLOYMENT_BY_PLUGIN, // CHEST_DENIED_ACCESS_BY_PLUGIN, // CHEST_DENIED_BLOCK, // CHEST_DENIED_PERMISSION, // CHEST_DENIED_ADJACENT, // CHEST_DENIED_SPAWN_RADIUS, // CHEST_DENIED_WORLD_DISABLED, // CHEST_DENIED_VOID, // CHEST_DEPLOYED_PROTECTION_TIME, // CHEST_ACCESSED_PROTECTION_TIME, // INVENTORY_EMPTY, // INVENTORY_FULL, // NO_CHEST_IN_INVENTORY, // NOT_OWNER, // CHEST_EXPIRED, // CREATIVE_MODE, // NO_CREATIVE_ACCESS, // CHEST_CURRENTLY_OPEN, // // COMMAND_FAIL_INVALID_COMMAND, // COMMAND_FAIL_ARGS_COUNT_OVER, // COMMAND_FAIL_HELP_PERMISSION, // COMMAND_FAIL_LIST_PERMISSION, // COMMAND_FAIL_LIST_OTHER_PERMISSION, // COMMAND_FAIL_RELOAD_PERMISSION, // COMMAND_FAIL_STATUS_PERMISSION, // COMMAND_SUCCESS_RELOAD, // // COMMAND_HELP_INVALID, // COMMAND_HELP_HELP, // COMMAND_HELP_LIST, // COMMAND_HELP_RELOAD, // COMMAND_HELP_STATUS, // COMMAND_HELP_USAGE, // // LIST_HEADER, // LIST_FOOTER, // LIST_EMPTY, // LIST_ITEM, // LIST_ITEM_ALL, // LIST_PLAYER_NOT_FOUND, // // } // // Path: src/main/java/com/winterhavenmc/deathchest/sounds/SoundId.java // public enum SoundId { // // CHEST_BREAK, // CHEST_DENIED_ACCESS, // COMMAND_FAIL, // INVENTORY_ADD_ITEM, // COMMAND_INVALID, // COMMAND_RELOAD_SUCCESS, // // }
import com.winterhavenmc.deathchest.PluginMain; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.command.TabCompleter; import com.winterhavenmc.deathchest.messages.MessageId; import com.winterhavenmc.deathchest.sounds.SoundId; import javax.annotation.Nonnull; import java.util.*;
* @param args Array of String - command arguments * @return boolean - always returns {@code true}, to suppress bukkit builtin help message */ @Override public boolean onCommand(final @Nonnull CommandSender sender, final @Nonnull Command command, final @Nonnull String label, final String[] args) { // convert args array to list List<String> argsList = new LinkedList<>(Arrays.asList(args)); String subcommandName; // get subcommand, remove from front of list if (argsList.size() > 0) { subcommandName = argsList.remove(0); } // if no arguments, set command to help else { subcommandName = "help"; } // get subcommand from map by name Subcommand subcommand = subcommandRegistry.getCommand(subcommandName); // if subcommand is null, get help command from map if (subcommand == null) { subcommand = subcommandRegistry.getCommand("help");
// Path: src/main/java/com/winterhavenmc/deathchest/PluginMain.java // public final class PluginMain extends JavaPlugin { // // public MessageBuilder<MessageId, Macro> messageBuilder; // public WorldManager worldManager; // public SoundConfiguration soundConfig; // public ChestManager chestManager; // public CommandManager commandManager; // public ProtectionPluginRegistry protectionPluginRegistry; // // // @Override // public void onEnable() { // // // bStats // new Metrics(this, 13916); // // // copy default config from jar if it doesn't exist // saveDefaultConfig(); // // // initialize message builder // messageBuilder = new MessageBuilder<>(this); // // // instantiate sound configuration // soundConfig = new YamlSoundConfiguration(this); // // // instantiate world manager // worldManager = new WorldManager(this); // // // instantiate chest manager // chestManager = new ChestManager(this); // // // load all chests from datastore // chestManager.loadChests(); // // // instantiate command manager // commandManager = new CommandManager(this); // // // initialize event listeners // new PlayerEventListener(this); // new BlockEventListener(this); // new InventoryEventListener(this); // // // instantiate protection plugin registry // protectionPluginRegistry = new ProtectionPluginRegistry(this); // } // // // @Override // public void onDisable() { // // // close datastore // chestManager.closeDataStore(); // } // // } // // Path: src/main/java/com/winterhavenmc/deathchest/messages/MessageId.java // public enum MessageId { // // CHEST_SUCCESS, // DOUBLECHEST_PARTIAL_SUCCESS, // CHEST_DENIED_DEPLOYMENT_BY_PLUGIN, // CHEST_DENIED_ACCESS_BY_PLUGIN, // CHEST_DENIED_BLOCK, // CHEST_DENIED_PERMISSION, // CHEST_DENIED_ADJACENT, // CHEST_DENIED_SPAWN_RADIUS, // CHEST_DENIED_WORLD_DISABLED, // CHEST_DENIED_VOID, // CHEST_DEPLOYED_PROTECTION_TIME, // CHEST_ACCESSED_PROTECTION_TIME, // INVENTORY_EMPTY, // INVENTORY_FULL, // NO_CHEST_IN_INVENTORY, // NOT_OWNER, // CHEST_EXPIRED, // CREATIVE_MODE, // NO_CREATIVE_ACCESS, // CHEST_CURRENTLY_OPEN, // // COMMAND_FAIL_INVALID_COMMAND, // COMMAND_FAIL_ARGS_COUNT_OVER, // COMMAND_FAIL_HELP_PERMISSION, // COMMAND_FAIL_LIST_PERMISSION, // COMMAND_FAIL_LIST_OTHER_PERMISSION, // COMMAND_FAIL_RELOAD_PERMISSION, // COMMAND_FAIL_STATUS_PERMISSION, // COMMAND_SUCCESS_RELOAD, // // COMMAND_HELP_INVALID, // COMMAND_HELP_HELP, // COMMAND_HELP_LIST, // COMMAND_HELP_RELOAD, // COMMAND_HELP_STATUS, // COMMAND_HELP_USAGE, // // LIST_HEADER, // LIST_FOOTER, // LIST_EMPTY, // LIST_ITEM, // LIST_ITEM_ALL, // LIST_PLAYER_NOT_FOUND, // // } // // Path: src/main/java/com/winterhavenmc/deathchest/sounds/SoundId.java // public enum SoundId { // // CHEST_BREAK, // CHEST_DENIED_ACCESS, // COMMAND_FAIL, // INVENTORY_ADD_ITEM, // COMMAND_INVALID, // COMMAND_RELOAD_SUCCESS, // // } // Path: src/main/java/com/winterhavenmc/deathchest/commands/CommandManager.java import com.winterhavenmc.deathchest.PluginMain; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.command.TabCompleter; import com.winterhavenmc.deathchest.messages.MessageId; import com.winterhavenmc.deathchest.sounds.SoundId; import javax.annotation.Nonnull; import java.util.*; * @param args Array of String - command arguments * @return boolean - always returns {@code true}, to suppress bukkit builtin help message */ @Override public boolean onCommand(final @Nonnull CommandSender sender, final @Nonnull Command command, final @Nonnull String label, final String[] args) { // convert args array to list List<String> argsList = new LinkedList<>(Arrays.asList(args)); String subcommandName; // get subcommand, remove from front of list if (argsList.size() > 0) { subcommandName = argsList.remove(0); } // if no arguments, set command to help else { subcommandName = "help"; } // get subcommand from map by name Subcommand subcommand = subcommandRegistry.getCommand(subcommandName); // if subcommand is null, get help command from map if (subcommand == null) { subcommand = subcommandRegistry.getCommand("help");
plugin.messageBuilder.build(sender, MessageId.COMMAND_FAIL_INVALID_COMMAND).send();
tim-savage/SavageDeathChest
src/main/java/com/winterhavenmc/deathchest/commands/CommandManager.java
// Path: src/main/java/com/winterhavenmc/deathchest/PluginMain.java // public final class PluginMain extends JavaPlugin { // // public MessageBuilder<MessageId, Macro> messageBuilder; // public WorldManager worldManager; // public SoundConfiguration soundConfig; // public ChestManager chestManager; // public CommandManager commandManager; // public ProtectionPluginRegistry protectionPluginRegistry; // // // @Override // public void onEnable() { // // // bStats // new Metrics(this, 13916); // // // copy default config from jar if it doesn't exist // saveDefaultConfig(); // // // initialize message builder // messageBuilder = new MessageBuilder<>(this); // // // instantiate sound configuration // soundConfig = new YamlSoundConfiguration(this); // // // instantiate world manager // worldManager = new WorldManager(this); // // // instantiate chest manager // chestManager = new ChestManager(this); // // // load all chests from datastore // chestManager.loadChests(); // // // instantiate command manager // commandManager = new CommandManager(this); // // // initialize event listeners // new PlayerEventListener(this); // new BlockEventListener(this); // new InventoryEventListener(this); // // // instantiate protection plugin registry // protectionPluginRegistry = new ProtectionPluginRegistry(this); // } // // // @Override // public void onDisable() { // // // close datastore // chestManager.closeDataStore(); // } // // } // // Path: src/main/java/com/winterhavenmc/deathchest/messages/MessageId.java // public enum MessageId { // // CHEST_SUCCESS, // DOUBLECHEST_PARTIAL_SUCCESS, // CHEST_DENIED_DEPLOYMENT_BY_PLUGIN, // CHEST_DENIED_ACCESS_BY_PLUGIN, // CHEST_DENIED_BLOCK, // CHEST_DENIED_PERMISSION, // CHEST_DENIED_ADJACENT, // CHEST_DENIED_SPAWN_RADIUS, // CHEST_DENIED_WORLD_DISABLED, // CHEST_DENIED_VOID, // CHEST_DEPLOYED_PROTECTION_TIME, // CHEST_ACCESSED_PROTECTION_TIME, // INVENTORY_EMPTY, // INVENTORY_FULL, // NO_CHEST_IN_INVENTORY, // NOT_OWNER, // CHEST_EXPIRED, // CREATIVE_MODE, // NO_CREATIVE_ACCESS, // CHEST_CURRENTLY_OPEN, // // COMMAND_FAIL_INVALID_COMMAND, // COMMAND_FAIL_ARGS_COUNT_OVER, // COMMAND_FAIL_HELP_PERMISSION, // COMMAND_FAIL_LIST_PERMISSION, // COMMAND_FAIL_LIST_OTHER_PERMISSION, // COMMAND_FAIL_RELOAD_PERMISSION, // COMMAND_FAIL_STATUS_PERMISSION, // COMMAND_SUCCESS_RELOAD, // // COMMAND_HELP_INVALID, // COMMAND_HELP_HELP, // COMMAND_HELP_LIST, // COMMAND_HELP_RELOAD, // COMMAND_HELP_STATUS, // COMMAND_HELP_USAGE, // // LIST_HEADER, // LIST_FOOTER, // LIST_EMPTY, // LIST_ITEM, // LIST_ITEM_ALL, // LIST_PLAYER_NOT_FOUND, // // } // // Path: src/main/java/com/winterhavenmc/deathchest/sounds/SoundId.java // public enum SoundId { // // CHEST_BREAK, // CHEST_DENIED_ACCESS, // COMMAND_FAIL, // INVENTORY_ADD_ITEM, // COMMAND_INVALID, // COMMAND_RELOAD_SUCCESS, // // }
import com.winterhavenmc.deathchest.PluginMain; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.command.TabCompleter; import com.winterhavenmc.deathchest.messages.MessageId; import com.winterhavenmc.deathchest.sounds.SoundId; import javax.annotation.Nonnull; import java.util.*;
* @return boolean - always returns {@code true}, to suppress bukkit builtin help message */ @Override public boolean onCommand(final @Nonnull CommandSender sender, final @Nonnull Command command, final @Nonnull String label, final String[] args) { // convert args array to list List<String> argsList = new LinkedList<>(Arrays.asList(args)); String subcommandName; // get subcommand, remove from front of list if (argsList.size() > 0) { subcommandName = argsList.remove(0); } // if no arguments, set command to help else { subcommandName = "help"; } // get subcommand from map by name Subcommand subcommand = subcommandRegistry.getCommand(subcommandName); // if subcommand is null, get help command from map if (subcommand == null) { subcommand = subcommandRegistry.getCommand("help"); plugin.messageBuilder.build(sender, MessageId.COMMAND_FAIL_INVALID_COMMAND).send();
// Path: src/main/java/com/winterhavenmc/deathchest/PluginMain.java // public final class PluginMain extends JavaPlugin { // // public MessageBuilder<MessageId, Macro> messageBuilder; // public WorldManager worldManager; // public SoundConfiguration soundConfig; // public ChestManager chestManager; // public CommandManager commandManager; // public ProtectionPluginRegistry protectionPluginRegistry; // // // @Override // public void onEnable() { // // // bStats // new Metrics(this, 13916); // // // copy default config from jar if it doesn't exist // saveDefaultConfig(); // // // initialize message builder // messageBuilder = new MessageBuilder<>(this); // // // instantiate sound configuration // soundConfig = new YamlSoundConfiguration(this); // // // instantiate world manager // worldManager = new WorldManager(this); // // // instantiate chest manager // chestManager = new ChestManager(this); // // // load all chests from datastore // chestManager.loadChests(); // // // instantiate command manager // commandManager = new CommandManager(this); // // // initialize event listeners // new PlayerEventListener(this); // new BlockEventListener(this); // new InventoryEventListener(this); // // // instantiate protection plugin registry // protectionPluginRegistry = new ProtectionPluginRegistry(this); // } // // // @Override // public void onDisable() { // // // close datastore // chestManager.closeDataStore(); // } // // } // // Path: src/main/java/com/winterhavenmc/deathchest/messages/MessageId.java // public enum MessageId { // // CHEST_SUCCESS, // DOUBLECHEST_PARTIAL_SUCCESS, // CHEST_DENIED_DEPLOYMENT_BY_PLUGIN, // CHEST_DENIED_ACCESS_BY_PLUGIN, // CHEST_DENIED_BLOCK, // CHEST_DENIED_PERMISSION, // CHEST_DENIED_ADJACENT, // CHEST_DENIED_SPAWN_RADIUS, // CHEST_DENIED_WORLD_DISABLED, // CHEST_DENIED_VOID, // CHEST_DEPLOYED_PROTECTION_TIME, // CHEST_ACCESSED_PROTECTION_TIME, // INVENTORY_EMPTY, // INVENTORY_FULL, // NO_CHEST_IN_INVENTORY, // NOT_OWNER, // CHEST_EXPIRED, // CREATIVE_MODE, // NO_CREATIVE_ACCESS, // CHEST_CURRENTLY_OPEN, // // COMMAND_FAIL_INVALID_COMMAND, // COMMAND_FAIL_ARGS_COUNT_OVER, // COMMAND_FAIL_HELP_PERMISSION, // COMMAND_FAIL_LIST_PERMISSION, // COMMAND_FAIL_LIST_OTHER_PERMISSION, // COMMAND_FAIL_RELOAD_PERMISSION, // COMMAND_FAIL_STATUS_PERMISSION, // COMMAND_SUCCESS_RELOAD, // // COMMAND_HELP_INVALID, // COMMAND_HELP_HELP, // COMMAND_HELP_LIST, // COMMAND_HELP_RELOAD, // COMMAND_HELP_STATUS, // COMMAND_HELP_USAGE, // // LIST_HEADER, // LIST_FOOTER, // LIST_EMPTY, // LIST_ITEM, // LIST_ITEM_ALL, // LIST_PLAYER_NOT_FOUND, // // } // // Path: src/main/java/com/winterhavenmc/deathchest/sounds/SoundId.java // public enum SoundId { // // CHEST_BREAK, // CHEST_DENIED_ACCESS, // COMMAND_FAIL, // INVENTORY_ADD_ITEM, // COMMAND_INVALID, // COMMAND_RELOAD_SUCCESS, // // } // Path: src/main/java/com/winterhavenmc/deathchest/commands/CommandManager.java import com.winterhavenmc.deathchest.PluginMain; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.command.TabCompleter; import com.winterhavenmc.deathchest.messages.MessageId; import com.winterhavenmc.deathchest.sounds.SoundId; import javax.annotation.Nonnull; import java.util.*; * @return boolean - always returns {@code true}, to suppress bukkit builtin help message */ @Override public boolean onCommand(final @Nonnull CommandSender sender, final @Nonnull Command command, final @Nonnull String label, final String[] args) { // convert args array to list List<String> argsList = new LinkedList<>(Arrays.asList(args)); String subcommandName; // get subcommand, remove from front of list if (argsList.size() > 0) { subcommandName = argsList.remove(0); } // if no arguments, set command to help else { subcommandName = "help"; } // get subcommand from map by name Subcommand subcommand = subcommandRegistry.getCommand(subcommandName); // if subcommand is null, get help command from map if (subcommand == null) { subcommand = subcommandRegistry.getCommand("help"); plugin.messageBuilder.build(sender, MessageId.COMMAND_FAIL_INVALID_COMMAND).send();
plugin.soundConfig.playSound(sender, SoundId.COMMAND_INVALID);
tim-savage/SavageDeathChest
src/main/java/com/winterhavenmc/deathchest/chests/search/QuadrantSearch.java
// Path: src/main/java/com/winterhavenmc/deathchest/PluginMain.java // public final class PluginMain extends JavaPlugin { // // public MessageBuilder<MessageId, Macro> messageBuilder; // public WorldManager worldManager; // public SoundConfiguration soundConfig; // public ChestManager chestManager; // public CommandManager commandManager; // public ProtectionPluginRegistry protectionPluginRegistry; // // // @Override // public void onEnable() { // // // bStats // new Metrics(this, 13916); // // // copy default config from jar if it doesn't exist // saveDefaultConfig(); // // // initialize message builder // messageBuilder = new MessageBuilder<>(this); // // // instantiate sound configuration // soundConfig = new YamlSoundConfiguration(this); // // // instantiate world manager // worldManager = new WorldManager(this); // // // instantiate chest manager // chestManager = new ChestManager(this); // // // load all chests from datastore // chestManager.loadChests(); // // // instantiate command manager // commandManager = new CommandManager(this); // // // initialize event listeners // new PlayerEventListener(this); // new BlockEventListener(this); // new InventoryEventListener(this); // // // instantiate protection plugin registry // protectionPluginRegistry = new ProtectionPluginRegistry(this); // } // // // @Override // public void onDisable() { // // // close datastore // chestManager.closeDataStore(); // } // // } // // Path: src/main/java/com/winterhavenmc/deathchest/chests/ChestSize.java // public enum ChestSize { // // SINGLE(27), // DOUBLE(54); // // private final int size; // // // /** // * Constructor // * // * @param size the chest inventory size // */ // ChestSize(final int size) { // this.size = size; // } // // // /** // * Determine chest size required for a given inventory size // * // * @param itemCount the number of ItemStacks to be considered for chest size // * @return ChestSize enum value, SINGLE or DOUBLE // */ // public static ChestSize selectFor(final int itemCount) { // // if (itemCount > SINGLE.size) { // return DOUBLE; // } // return SINGLE; // } // // }
import com.winterhavenmc.deathchest.PluginMain; import com.winterhavenmc.deathchest.chests.ChestSize; import org.bukkit.Location; import org.bukkit.entity.Player;
/* * Copyright (c) 2022 Tim Savage. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.winterhavenmc.deathchest.chests.search; /** * A class that implements a search strategy for a valid chest location */ public final class QuadrantSearch extends AbstractSearch { /** * An enum that implements a cartesian quadrant system, where each member defines the sign of the x and z coordinates */ private enum Quadrant { I(1,1), II(-1,1), III(-1,-1), IV(1,-1); final int xFactor; final int zFactor; /** * Constructor for the Quadrant enum * @param xFactor the x multiplier to achieve negative or positive sign for the quadrant member * @param zFactor the z multiplier to achieve negative or positive sign for the quadrant member */ Quadrant(final int xFactor, final int zFactor) { this.xFactor = xFactor; this.zFactor = zFactor; } } /** * Class constructor * @param plugin reference to plugin main class * @param player the player whose death triggered a death chest deployment * @param chestSize the size of chest required to accommodate the players inventory */
// Path: src/main/java/com/winterhavenmc/deathchest/PluginMain.java // public final class PluginMain extends JavaPlugin { // // public MessageBuilder<MessageId, Macro> messageBuilder; // public WorldManager worldManager; // public SoundConfiguration soundConfig; // public ChestManager chestManager; // public CommandManager commandManager; // public ProtectionPluginRegistry protectionPluginRegistry; // // // @Override // public void onEnable() { // // // bStats // new Metrics(this, 13916); // // // copy default config from jar if it doesn't exist // saveDefaultConfig(); // // // initialize message builder // messageBuilder = new MessageBuilder<>(this); // // // instantiate sound configuration // soundConfig = new YamlSoundConfiguration(this); // // // instantiate world manager // worldManager = new WorldManager(this); // // // instantiate chest manager // chestManager = new ChestManager(this); // // // load all chests from datastore // chestManager.loadChests(); // // // instantiate command manager // commandManager = new CommandManager(this); // // // initialize event listeners // new PlayerEventListener(this); // new BlockEventListener(this); // new InventoryEventListener(this); // // // instantiate protection plugin registry // protectionPluginRegistry = new ProtectionPluginRegistry(this); // } // // // @Override // public void onDisable() { // // // close datastore // chestManager.closeDataStore(); // } // // } // // Path: src/main/java/com/winterhavenmc/deathchest/chests/ChestSize.java // public enum ChestSize { // // SINGLE(27), // DOUBLE(54); // // private final int size; // // // /** // * Constructor // * // * @param size the chest inventory size // */ // ChestSize(final int size) { // this.size = size; // } // // // /** // * Determine chest size required for a given inventory size // * // * @param itemCount the number of ItemStacks to be considered for chest size // * @return ChestSize enum value, SINGLE or DOUBLE // */ // public static ChestSize selectFor(final int itemCount) { // // if (itemCount > SINGLE.size) { // return DOUBLE; // } // return SINGLE; // } // // } // Path: src/main/java/com/winterhavenmc/deathchest/chests/search/QuadrantSearch.java import com.winterhavenmc.deathchest.PluginMain; import com.winterhavenmc.deathchest.chests.ChestSize; import org.bukkit.Location; import org.bukkit.entity.Player; /* * Copyright (c) 2022 Tim Savage. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.winterhavenmc.deathchest.chests.search; /** * A class that implements a search strategy for a valid chest location */ public final class QuadrantSearch extends AbstractSearch { /** * An enum that implements a cartesian quadrant system, where each member defines the sign of the x and z coordinates */ private enum Quadrant { I(1,1), II(-1,1), III(-1,-1), IV(1,-1); final int xFactor; final int zFactor; /** * Constructor for the Quadrant enum * @param xFactor the x multiplier to achieve negative or positive sign for the quadrant member * @param zFactor the z multiplier to achieve negative or positive sign for the quadrant member */ Quadrant(final int xFactor, final int zFactor) { this.xFactor = xFactor; this.zFactor = zFactor; } } /** * Class constructor * @param plugin reference to plugin main class * @param player the player whose death triggered a death chest deployment * @param chestSize the size of chest required to accommodate the players inventory */
public QuadrantSearch(final PluginMain plugin,
tim-savage/SavageDeathChest
src/main/java/com/winterhavenmc/deathchest/chests/search/QuadrantSearch.java
// Path: src/main/java/com/winterhavenmc/deathchest/PluginMain.java // public final class PluginMain extends JavaPlugin { // // public MessageBuilder<MessageId, Macro> messageBuilder; // public WorldManager worldManager; // public SoundConfiguration soundConfig; // public ChestManager chestManager; // public CommandManager commandManager; // public ProtectionPluginRegistry protectionPluginRegistry; // // // @Override // public void onEnable() { // // // bStats // new Metrics(this, 13916); // // // copy default config from jar if it doesn't exist // saveDefaultConfig(); // // // initialize message builder // messageBuilder = new MessageBuilder<>(this); // // // instantiate sound configuration // soundConfig = new YamlSoundConfiguration(this); // // // instantiate world manager // worldManager = new WorldManager(this); // // // instantiate chest manager // chestManager = new ChestManager(this); // // // load all chests from datastore // chestManager.loadChests(); // // // instantiate command manager // commandManager = new CommandManager(this); // // // initialize event listeners // new PlayerEventListener(this); // new BlockEventListener(this); // new InventoryEventListener(this); // // // instantiate protection plugin registry // protectionPluginRegistry = new ProtectionPluginRegistry(this); // } // // // @Override // public void onDisable() { // // // close datastore // chestManager.closeDataStore(); // } // // } // // Path: src/main/java/com/winterhavenmc/deathchest/chests/ChestSize.java // public enum ChestSize { // // SINGLE(27), // DOUBLE(54); // // private final int size; // // // /** // * Constructor // * // * @param size the chest inventory size // */ // ChestSize(final int size) { // this.size = size; // } // // // /** // * Determine chest size required for a given inventory size // * // * @param itemCount the number of ItemStacks to be considered for chest size // * @return ChestSize enum value, SINGLE or DOUBLE // */ // public static ChestSize selectFor(final int itemCount) { // // if (itemCount > SINGLE.size) { // return DOUBLE; // } // return SINGLE; // } // // }
import com.winterhavenmc.deathchest.PluginMain; import com.winterhavenmc.deathchest.chests.ChestSize; import org.bukkit.Location; import org.bukkit.entity.Player;
/* * Copyright (c) 2022 Tim Savage. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.winterhavenmc.deathchest.chests.search; /** * A class that implements a search strategy for a valid chest location */ public final class QuadrantSearch extends AbstractSearch { /** * An enum that implements a cartesian quadrant system, where each member defines the sign of the x and z coordinates */ private enum Quadrant { I(1,1), II(-1,1), III(-1,-1), IV(1,-1); final int xFactor; final int zFactor; /** * Constructor for the Quadrant enum * @param xFactor the x multiplier to achieve negative or positive sign for the quadrant member * @param zFactor the z multiplier to achieve negative or positive sign for the quadrant member */ Quadrant(final int xFactor, final int zFactor) { this.xFactor = xFactor; this.zFactor = zFactor; } } /** * Class constructor * @param plugin reference to plugin main class * @param player the player whose death triggered a death chest deployment * @param chestSize the size of chest required to accommodate the players inventory */ public QuadrantSearch(final PluginMain plugin, final Player player,
// Path: src/main/java/com/winterhavenmc/deathchest/PluginMain.java // public final class PluginMain extends JavaPlugin { // // public MessageBuilder<MessageId, Macro> messageBuilder; // public WorldManager worldManager; // public SoundConfiguration soundConfig; // public ChestManager chestManager; // public CommandManager commandManager; // public ProtectionPluginRegistry protectionPluginRegistry; // // // @Override // public void onEnable() { // // // bStats // new Metrics(this, 13916); // // // copy default config from jar if it doesn't exist // saveDefaultConfig(); // // // initialize message builder // messageBuilder = new MessageBuilder<>(this); // // // instantiate sound configuration // soundConfig = new YamlSoundConfiguration(this); // // // instantiate world manager // worldManager = new WorldManager(this); // // // instantiate chest manager // chestManager = new ChestManager(this); // // // load all chests from datastore // chestManager.loadChests(); // // // instantiate command manager // commandManager = new CommandManager(this); // // // initialize event listeners // new PlayerEventListener(this); // new BlockEventListener(this); // new InventoryEventListener(this); // // // instantiate protection plugin registry // protectionPluginRegistry = new ProtectionPluginRegistry(this); // } // // // @Override // public void onDisable() { // // // close datastore // chestManager.closeDataStore(); // } // // } // // Path: src/main/java/com/winterhavenmc/deathchest/chests/ChestSize.java // public enum ChestSize { // // SINGLE(27), // DOUBLE(54); // // private final int size; // // // /** // * Constructor // * // * @param size the chest inventory size // */ // ChestSize(final int size) { // this.size = size; // } // // // /** // * Determine chest size required for a given inventory size // * // * @param itemCount the number of ItemStacks to be considered for chest size // * @return ChestSize enum value, SINGLE or DOUBLE // */ // public static ChestSize selectFor(final int itemCount) { // // if (itemCount > SINGLE.size) { // return DOUBLE; // } // return SINGLE; // } // // } // Path: src/main/java/com/winterhavenmc/deathchest/chests/search/QuadrantSearch.java import com.winterhavenmc.deathchest.PluginMain; import com.winterhavenmc.deathchest.chests.ChestSize; import org.bukkit.Location; import org.bukkit.entity.Player; /* * Copyright (c) 2022 Tim Savage. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.winterhavenmc.deathchest.chests.search; /** * A class that implements a search strategy for a valid chest location */ public final class QuadrantSearch extends AbstractSearch { /** * An enum that implements a cartesian quadrant system, where each member defines the sign of the x and z coordinates */ private enum Quadrant { I(1,1), II(-1,1), III(-1,-1), IV(1,-1); final int xFactor; final int zFactor; /** * Constructor for the Quadrant enum * @param xFactor the x multiplier to achieve negative or positive sign for the quadrant member * @param zFactor the z multiplier to achieve negative or positive sign for the quadrant member */ Quadrant(final int xFactor, final int zFactor) { this.xFactor = xFactor; this.zFactor = zFactor; } } /** * Class constructor * @param plugin reference to plugin main class * @param player the player whose death triggered a death chest deployment * @param chestSize the size of chest required to accommodate the players inventory */ public QuadrantSearch(final PluginMain plugin, final Player player,
final ChestSize chestSize) {
tim-savage/SavageDeathChest
src/main/java/com/winterhavenmc/deathchest/commands/SubcommandType.java
// Path: src/main/java/com/winterhavenmc/deathchest/PluginMain.java // public final class PluginMain extends JavaPlugin { // // public MessageBuilder<MessageId, Macro> messageBuilder; // public WorldManager worldManager; // public SoundConfiguration soundConfig; // public ChestManager chestManager; // public CommandManager commandManager; // public ProtectionPluginRegistry protectionPluginRegistry; // // // @Override // public void onEnable() { // // // bStats // new Metrics(this, 13916); // // // copy default config from jar if it doesn't exist // saveDefaultConfig(); // // // initialize message builder // messageBuilder = new MessageBuilder<>(this); // // // instantiate sound configuration // soundConfig = new YamlSoundConfiguration(this); // // // instantiate world manager // worldManager = new WorldManager(this); // // // instantiate chest manager // chestManager = new ChestManager(this); // // // load all chests from datastore // chestManager.loadChests(); // // // instantiate command manager // commandManager = new CommandManager(this); // // // initialize event listeners // new PlayerEventListener(this); // new BlockEventListener(this); // new InventoryEventListener(this); // // // instantiate protection plugin registry // protectionPluginRegistry = new ProtectionPluginRegistry(this); // } // // // @Override // public void onDisable() { // // // close datastore // chestManager.closeDataStore(); // } // // }
import com.winterhavenmc.deathchest.PluginMain;
/* * Copyright (c) 2022 Tim Savage. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.winterhavenmc.deathchest.commands; enum SubcommandType { LIST() { @Override
// Path: src/main/java/com/winterhavenmc/deathchest/PluginMain.java // public final class PluginMain extends JavaPlugin { // // public MessageBuilder<MessageId, Macro> messageBuilder; // public WorldManager worldManager; // public SoundConfiguration soundConfig; // public ChestManager chestManager; // public CommandManager commandManager; // public ProtectionPluginRegistry protectionPluginRegistry; // // // @Override // public void onEnable() { // // // bStats // new Metrics(this, 13916); // // // copy default config from jar if it doesn't exist // saveDefaultConfig(); // // // initialize message builder // messageBuilder = new MessageBuilder<>(this); // // // instantiate sound configuration // soundConfig = new YamlSoundConfiguration(this); // // // instantiate world manager // worldManager = new WorldManager(this); // // // instantiate chest manager // chestManager = new ChestManager(this); // // // load all chests from datastore // chestManager.loadChests(); // // // instantiate command manager // commandManager = new CommandManager(this); // // // initialize event listeners // new PlayerEventListener(this); // new BlockEventListener(this); // new InventoryEventListener(this); // // // instantiate protection plugin registry // protectionPluginRegistry = new ProtectionPluginRegistry(this); // } // // // @Override // public void onDisable() { // // // close datastore // chestManager.closeDataStore(); // } // // } // Path: src/main/java/com/winterhavenmc/deathchest/commands/SubcommandType.java import com.winterhavenmc.deathchest.PluginMain; /* * Copyright (c) 2022 Tim Savage. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.winterhavenmc.deathchest.commands; enum SubcommandType { LIST() { @Override
Subcommand create(final PluginMain plugin) {
tim-savage/SavageDeathChest
src/main/java/com/winterhavenmc/deathchest/chests/search/SearchResult.java
// Path: src/main/java/com/winterhavenmc/deathchest/permissions/protectionplugins/ProtectionPlugin.java // public interface ProtectionPlugin { // // // /** // * Check if plugin will allow chest placement at location by player // * // * @param player the player whose death chest will be placed // * @param location the location where the death chest will be placed // * @return boolean - true if placement is allowed by plugin, false if not // */ // boolean allowChestPlacement(final Player player, final Location location); // // // /** // * Check if plugin will allow chest access at location by player // * // * @param player the player who is trying to access a death chest // * @param location the location where the death chest is being accessed // * @return boolean - true if access is allowed by plugin, false if not // */ // boolean allowChestAccess(final Player player, final Location location); // // // /** // * Log error if chest placement failed // */ // void logPlaceError(); // // // /** // * Log error if chest placement failed // */ // void logPlaceError(final String message); // // // /** // * Log error if chest access failed // */ // @SuppressWarnings("unused") // void logAccessError(); // // // /** // * Log error if chest access failed // */ // void logAccessError(final String message); // // // /** // * Get the name of the protection plugin // * // * @return String - the name of the protection plugin // */ // @SuppressWarnings("unused") // String getPluginName(); // // // /** // * Get the version of the protection plugin // * // * @return String - the version of the protection plugin // */ // @SuppressWarnings("unused") // String getPluginVersion(); // // // /** // * Check if the protection plugin is configured to be ignored on chest placement // * // * @return boolean - true if plugin is configured ignore on place, otherwise false // */ // boolean isIgnoredOnPlace(); // // // /** // * Check if the protection plugin is configured to be ignored on chest access // * // * @return boolean - true if plugin is configured ignore on access, otherwise false // */ // boolean isIgnoredOnAccess(); // // }
import com.winterhavenmc.deathchest.permissions.protectionplugins.ProtectionPlugin; import org.bukkit.Location; import org.bukkit.inventory.ItemStack; import java.util.Collection; import java.util.LinkedList;
/* * Copyright (c) 2022 Tim Savage. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.winterhavenmc.deathchest.chests.search; /** * A class that encapsulates fields to be returned * as the result of a search for a valid chest location */ public final class SearchResult { private SearchResultCode searchResultCode; private Location location;
// Path: src/main/java/com/winterhavenmc/deathchest/permissions/protectionplugins/ProtectionPlugin.java // public interface ProtectionPlugin { // // // /** // * Check if plugin will allow chest placement at location by player // * // * @param player the player whose death chest will be placed // * @param location the location where the death chest will be placed // * @return boolean - true if placement is allowed by plugin, false if not // */ // boolean allowChestPlacement(final Player player, final Location location); // // // /** // * Check if plugin will allow chest access at location by player // * // * @param player the player who is trying to access a death chest // * @param location the location where the death chest is being accessed // * @return boolean - true if access is allowed by plugin, false if not // */ // boolean allowChestAccess(final Player player, final Location location); // // // /** // * Log error if chest placement failed // */ // void logPlaceError(); // // // /** // * Log error if chest placement failed // */ // void logPlaceError(final String message); // // // /** // * Log error if chest access failed // */ // @SuppressWarnings("unused") // void logAccessError(); // // // /** // * Log error if chest access failed // */ // void logAccessError(final String message); // // // /** // * Get the name of the protection plugin // * // * @return String - the name of the protection plugin // */ // @SuppressWarnings("unused") // String getPluginName(); // // // /** // * Get the version of the protection plugin // * // * @return String - the version of the protection plugin // */ // @SuppressWarnings("unused") // String getPluginVersion(); // // // /** // * Check if the protection plugin is configured to be ignored on chest placement // * // * @return boolean - true if plugin is configured ignore on place, otherwise false // */ // boolean isIgnoredOnPlace(); // // // /** // * Check if the protection plugin is configured to be ignored on chest access // * // * @return boolean - true if plugin is configured ignore on access, otherwise false // */ // boolean isIgnoredOnAccess(); // // } // Path: src/main/java/com/winterhavenmc/deathchest/chests/search/SearchResult.java import com.winterhavenmc.deathchest.permissions.protectionplugins.ProtectionPlugin; import org.bukkit.Location; import org.bukkit.inventory.ItemStack; import java.util.Collection; import java.util.LinkedList; /* * Copyright (c) 2022 Tim Savage. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.winterhavenmc.deathchest.chests.search; /** * A class that encapsulates fields to be returned * as the result of a search for a valid chest location */ public final class SearchResult { private SearchResultCode searchResultCode; private Location location;
private ProtectionPlugin protectionPlugin;
tim-savage/SavageDeathChest
src/main/java/com/winterhavenmc/deathchest/commands/SubcommandAbstract.java
// Path: src/main/java/com/winterhavenmc/deathchest/messages/MessageId.java // public enum MessageId { // // CHEST_SUCCESS, // DOUBLECHEST_PARTIAL_SUCCESS, // CHEST_DENIED_DEPLOYMENT_BY_PLUGIN, // CHEST_DENIED_ACCESS_BY_PLUGIN, // CHEST_DENIED_BLOCK, // CHEST_DENIED_PERMISSION, // CHEST_DENIED_ADJACENT, // CHEST_DENIED_SPAWN_RADIUS, // CHEST_DENIED_WORLD_DISABLED, // CHEST_DENIED_VOID, // CHEST_DEPLOYED_PROTECTION_TIME, // CHEST_ACCESSED_PROTECTION_TIME, // INVENTORY_EMPTY, // INVENTORY_FULL, // NO_CHEST_IN_INVENTORY, // NOT_OWNER, // CHEST_EXPIRED, // CREATIVE_MODE, // NO_CREATIVE_ACCESS, // CHEST_CURRENTLY_OPEN, // // COMMAND_FAIL_INVALID_COMMAND, // COMMAND_FAIL_ARGS_COUNT_OVER, // COMMAND_FAIL_HELP_PERMISSION, // COMMAND_FAIL_LIST_PERMISSION, // COMMAND_FAIL_LIST_OTHER_PERMISSION, // COMMAND_FAIL_RELOAD_PERMISSION, // COMMAND_FAIL_STATUS_PERMISSION, // COMMAND_SUCCESS_RELOAD, // // COMMAND_HELP_INVALID, // COMMAND_HELP_HELP, // COMMAND_HELP_LIST, // COMMAND_HELP_RELOAD, // COMMAND_HELP_STATUS, // COMMAND_HELP_USAGE, // // LIST_HEADER, // LIST_FOOTER, // LIST_EMPTY, // LIST_ITEM, // LIST_ITEM_ALL, // LIST_PLAYER_NOT_FOUND, // // }
import com.winterhavenmc.deathchest.messages.MessageId; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import javax.annotation.Nonnull; import java.util.*;
/* * Copyright (c) 2022 Tim Savage. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.winterhavenmc.deathchest.commands; abstract class SubcommandAbstract implements Subcommand { protected String name; protected String usageString;
// Path: src/main/java/com/winterhavenmc/deathchest/messages/MessageId.java // public enum MessageId { // // CHEST_SUCCESS, // DOUBLECHEST_PARTIAL_SUCCESS, // CHEST_DENIED_DEPLOYMENT_BY_PLUGIN, // CHEST_DENIED_ACCESS_BY_PLUGIN, // CHEST_DENIED_BLOCK, // CHEST_DENIED_PERMISSION, // CHEST_DENIED_ADJACENT, // CHEST_DENIED_SPAWN_RADIUS, // CHEST_DENIED_WORLD_DISABLED, // CHEST_DENIED_VOID, // CHEST_DEPLOYED_PROTECTION_TIME, // CHEST_ACCESSED_PROTECTION_TIME, // INVENTORY_EMPTY, // INVENTORY_FULL, // NO_CHEST_IN_INVENTORY, // NOT_OWNER, // CHEST_EXPIRED, // CREATIVE_MODE, // NO_CREATIVE_ACCESS, // CHEST_CURRENTLY_OPEN, // // COMMAND_FAIL_INVALID_COMMAND, // COMMAND_FAIL_ARGS_COUNT_OVER, // COMMAND_FAIL_HELP_PERMISSION, // COMMAND_FAIL_LIST_PERMISSION, // COMMAND_FAIL_LIST_OTHER_PERMISSION, // COMMAND_FAIL_RELOAD_PERMISSION, // COMMAND_FAIL_STATUS_PERMISSION, // COMMAND_SUCCESS_RELOAD, // // COMMAND_HELP_INVALID, // COMMAND_HELP_HELP, // COMMAND_HELP_LIST, // COMMAND_HELP_RELOAD, // COMMAND_HELP_STATUS, // COMMAND_HELP_USAGE, // // LIST_HEADER, // LIST_FOOTER, // LIST_EMPTY, // LIST_ITEM, // LIST_ITEM_ALL, // LIST_PLAYER_NOT_FOUND, // // } // Path: src/main/java/com/winterhavenmc/deathchest/commands/SubcommandAbstract.java import com.winterhavenmc.deathchest.messages.MessageId; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import javax.annotation.Nonnull; import java.util.*; /* * Copyright (c) 2022 Tim Savage. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.winterhavenmc.deathchest.commands; abstract class SubcommandAbstract implements Subcommand { protected String name; protected String usageString;
protected MessageId description;
tim-savage/SavageDeathChest
src/main/java/com/winterhavenmc/deathchest/storage/DataStoreType.java
// Path: src/main/java/com/winterhavenmc/deathchest/PluginMain.java // public final class PluginMain extends JavaPlugin { // // public MessageBuilder<MessageId, Macro> messageBuilder; // public WorldManager worldManager; // public SoundConfiguration soundConfig; // public ChestManager chestManager; // public CommandManager commandManager; // public ProtectionPluginRegistry protectionPluginRegistry; // // // @Override // public void onEnable() { // // // bStats // new Metrics(this, 13916); // // // copy default config from jar if it doesn't exist // saveDefaultConfig(); // // // initialize message builder // messageBuilder = new MessageBuilder<>(this); // // // instantiate sound configuration // soundConfig = new YamlSoundConfiguration(this); // // // instantiate world manager // worldManager = new WorldManager(this); // // // instantiate chest manager // chestManager = new ChestManager(this); // // // load all chests from datastore // chestManager.loadChests(); // // // instantiate command manager // commandManager = new CommandManager(this); // // // initialize event listeners // new PlayerEventListener(this); // new BlockEventListener(this); // new InventoryEventListener(this); // // // instantiate protection plugin registry // protectionPluginRegistry = new ProtectionPluginRegistry(this); // } // // // @Override // public void onDisable() { // // // close datastore // chestManager.closeDataStore(); // } // // }
import com.winterhavenmc.deathchest.PluginMain; import org.bukkit.plugin.java.JavaPlugin; import java.io.File; import java.util.*;
/* * Copyright (c) 2022 Tim Savage. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.winterhavenmc.deathchest.storage; /** * An enum whose values represent the types of data store available.<br> * Note: Only SQLite data store is implemented at this time. */ public enum DataStoreType { SQLITE("SQLite", "deathchests.db") { @Override
// Path: src/main/java/com/winterhavenmc/deathchest/PluginMain.java // public final class PluginMain extends JavaPlugin { // // public MessageBuilder<MessageId, Macro> messageBuilder; // public WorldManager worldManager; // public SoundConfiguration soundConfig; // public ChestManager chestManager; // public CommandManager commandManager; // public ProtectionPluginRegistry protectionPluginRegistry; // // // @Override // public void onEnable() { // // // bStats // new Metrics(this, 13916); // // // copy default config from jar if it doesn't exist // saveDefaultConfig(); // // // initialize message builder // messageBuilder = new MessageBuilder<>(this); // // // instantiate sound configuration // soundConfig = new YamlSoundConfiguration(this); // // // instantiate world manager // worldManager = new WorldManager(this); // // // instantiate chest manager // chestManager = new ChestManager(this); // // // load all chests from datastore // chestManager.loadChests(); // // // instantiate command manager // commandManager = new CommandManager(this); // // // initialize event listeners // new PlayerEventListener(this); // new BlockEventListener(this); // new InventoryEventListener(this); // // // instantiate protection plugin registry // protectionPluginRegistry = new ProtectionPluginRegistry(this); // } // // // @Override // public void onDisable() { // // // close datastore // chestManager.closeDataStore(); // } // // } // Path: src/main/java/com/winterhavenmc/deathchest/storage/DataStoreType.java import com.winterhavenmc.deathchest.PluginMain; import org.bukkit.plugin.java.JavaPlugin; import java.io.File; import java.util.*; /* * Copyright (c) 2022 Tim Savage. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.winterhavenmc.deathchest.storage; /** * An enum whose values represent the types of data store available.<br> * Note: Only SQLite data store is implemented at this time. */ public enum DataStoreType { SQLITE("SQLite", "deathchests.db") { @Override
public DataStore connect(final PluginMain plugin) {
tim-savage/SavageDeathChest
src/main/java/com/winterhavenmc/deathchest/commands/ReloadCommand.java
// Path: src/main/java/com/winterhavenmc/deathchest/PluginMain.java // public final class PluginMain extends JavaPlugin { // // public MessageBuilder<MessageId, Macro> messageBuilder; // public WorldManager worldManager; // public SoundConfiguration soundConfig; // public ChestManager chestManager; // public CommandManager commandManager; // public ProtectionPluginRegistry protectionPluginRegistry; // // // @Override // public void onEnable() { // // // bStats // new Metrics(this, 13916); // // // copy default config from jar if it doesn't exist // saveDefaultConfig(); // // // initialize message builder // messageBuilder = new MessageBuilder<>(this); // // // instantiate sound configuration // soundConfig = new YamlSoundConfiguration(this); // // // instantiate world manager // worldManager = new WorldManager(this); // // // instantiate chest manager // chestManager = new ChestManager(this); // // // load all chests from datastore // chestManager.loadChests(); // // // instantiate command manager // commandManager = new CommandManager(this); // // // initialize event listeners // new PlayerEventListener(this); // new BlockEventListener(this); // new InventoryEventListener(this); // // // instantiate protection plugin registry // protectionPluginRegistry = new ProtectionPluginRegistry(this); // } // // // @Override // public void onDisable() { // // // close datastore // chestManager.closeDataStore(); // } // // } // // Path: src/main/java/com/winterhavenmc/deathchest/messages/MessageId.java // public enum MessageId { // // CHEST_SUCCESS, // DOUBLECHEST_PARTIAL_SUCCESS, // CHEST_DENIED_DEPLOYMENT_BY_PLUGIN, // CHEST_DENIED_ACCESS_BY_PLUGIN, // CHEST_DENIED_BLOCK, // CHEST_DENIED_PERMISSION, // CHEST_DENIED_ADJACENT, // CHEST_DENIED_SPAWN_RADIUS, // CHEST_DENIED_WORLD_DISABLED, // CHEST_DENIED_VOID, // CHEST_DEPLOYED_PROTECTION_TIME, // CHEST_ACCESSED_PROTECTION_TIME, // INVENTORY_EMPTY, // INVENTORY_FULL, // NO_CHEST_IN_INVENTORY, // NOT_OWNER, // CHEST_EXPIRED, // CREATIVE_MODE, // NO_CREATIVE_ACCESS, // CHEST_CURRENTLY_OPEN, // // COMMAND_FAIL_INVALID_COMMAND, // COMMAND_FAIL_ARGS_COUNT_OVER, // COMMAND_FAIL_HELP_PERMISSION, // COMMAND_FAIL_LIST_PERMISSION, // COMMAND_FAIL_LIST_OTHER_PERMISSION, // COMMAND_FAIL_RELOAD_PERMISSION, // COMMAND_FAIL_STATUS_PERMISSION, // COMMAND_SUCCESS_RELOAD, // // COMMAND_HELP_INVALID, // COMMAND_HELP_HELP, // COMMAND_HELP_LIST, // COMMAND_HELP_RELOAD, // COMMAND_HELP_STATUS, // COMMAND_HELP_USAGE, // // LIST_HEADER, // LIST_FOOTER, // LIST_EMPTY, // LIST_ITEM, // LIST_ITEM_ALL, // LIST_PLAYER_NOT_FOUND, // // } // // Path: src/main/java/com/winterhavenmc/deathchest/sounds/SoundId.java // public enum SoundId { // // CHEST_BREAK, // CHEST_DENIED_ACCESS, // COMMAND_FAIL, // INVENTORY_ADD_ITEM, // COMMAND_INVALID, // COMMAND_RELOAD_SUCCESS, // // }
import com.winterhavenmc.deathchest.PluginMain; import com.winterhavenmc.deathchest.messages.MessageId; import com.winterhavenmc.deathchest.sounds.SoundId; import org.bukkit.command.CommandSender; import java.util.List; import java.util.Objects;
/* * Copyright (c) 2022 Tim Savage. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.winterhavenmc.deathchest.commands; /** * Class that implements the reload subcommand. Reloads the plugin configuration settings. */ final class ReloadCommand extends SubcommandAbstract { private final PluginMain plugin; /** * Class constructor * * @param plugin reference to plugin main class */ ReloadCommand(final PluginMain plugin) { this.plugin = Objects.requireNonNull(plugin); this.name = "reload"; this.usageString = "/deathchest reload";
// Path: src/main/java/com/winterhavenmc/deathchest/PluginMain.java // public final class PluginMain extends JavaPlugin { // // public MessageBuilder<MessageId, Macro> messageBuilder; // public WorldManager worldManager; // public SoundConfiguration soundConfig; // public ChestManager chestManager; // public CommandManager commandManager; // public ProtectionPluginRegistry protectionPluginRegistry; // // // @Override // public void onEnable() { // // // bStats // new Metrics(this, 13916); // // // copy default config from jar if it doesn't exist // saveDefaultConfig(); // // // initialize message builder // messageBuilder = new MessageBuilder<>(this); // // // instantiate sound configuration // soundConfig = new YamlSoundConfiguration(this); // // // instantiate world manager // worldManager = new WorldManager(this); // // // instantiate chest manager // chestManager = new ChestManager(this); // // // load all chests from datastore // chestManager.loadChests(); // // // instantiate command manager // commandManager = new CommandManager(this); // // // initialize event listeners // new PlayerEventListener(this); // new BlockEventListener(this); // new InventoryEventListener(this); // // // instantiate protection plugin registry // protectionPluginRegistry = new ProtectionPluginRegistry(this); // } // // // @Override // public void onDisable() { // // // close datastore // chestManager.closeDataStore(); // } // // } // // Path: src/main/java/com/winterhavenmc/deathchest/messages/MessageId.java // public enum MessageId { // // CHEST_SUCCESS, // DOUBLECHEST_PARTIAL_SUCCESS, // CHEST_DENIED_DEPLOYMENT_BY_PLUGIN, // CHEST_DENIED_ACCESS_BY_PLUGIN, // CHEST_DENIED_BLOCK, // CHEST_DENIED_PERMISSION, // CHEST_DENIED_ADJACENT, // CHEST_DENIED_SPAWN_RADIUS, // CHEST_DENIED_WORLD_DISABLED, // CHEST_DENIED_VOID, // CHEST_DEPLOYED_PROTECTION_TIME, // CHEST_ACCESSED_PROTECTION_TIME, // INVENTORY_EMPTY, // INVENTORY_FULL, // NO_CHEST_IN_INVENTORY, // NOT_OWNER, // CHEST_EXPIRED, // CREATIVE_MODE, // NO_CREATIVE_ACCESS, // CHEST_CURRENTLY_OPEN, // // COMMAND_FAIL_INVALID_COMMAND, // COMMAND_FAIL_ARGS_COUNT_OVER, // COMMAND_FAIL_HELP_PERMISSION, // COMMAND_FAIL_LIST_PERMISSION, // COMMAND_FAIL_LIST_OTHER_PERMISSION, // COMMAND_FAIL_RELOAD_PERMISSION, // COMMAND_FAIL_STATUS_PERMISSION, // COMMAND_SUCCESS_RELOAD, // // COMMAND_HELP_INVALID, // COMMAND_HELP_HELP, // COMMAND_HELP_LIST, // COMMAND_HELP_RELOAD, // COMMAND_HELP_STATUS, // COMMAND_HELP_USAGE, // // LIST_HEADER, // LIST_FOOTER, // LIST_EMPTY, // LIST_ITEM, // LIST_ITEM_ALL, // LIST_PLAYER_NOT_FOUND, // // } // // Path: src/main/java/com/winterhavenmc/deathchest/sounds/SoundId.java // public enum SoundId { // // CHEST_BREAK, // CHEST_DENIED_ACCESS, // COMMAND_FAIL, // INVENTORY_ADD_ITEM, // COMMAND_INVALID, // COMMAND_RELOAD_SUCCESS, // // } // Path: src/main/java/com/winterhavenmc/deathchest/commands/ReloadCommand.java import com.winterhavenmc.deathchest.PluginMain; import com.winterhavenmc.deathchest.messages.MessageId; import com.winterhavenmc.deathchest.sounds.SoundId; import org.bukkit.command.CommandSender; import java.util.List; import java.util.Objects; /* * Copyright (c) 2022 Tim Savage. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.winterhavenmc.deathchest.commands; /** * Class that implements the reload subcommand. Reloads the plugin configuration settings. */ final class ReloadCommand extends SubcommandAbstract { private final PluginMain plugin; /** * Class constructor * * @param plugin reference to plugin main class */ ReloadCommand(final PluginMain plugin) { this.plugin = Objects.requireNonNull(plugin); this.name = "reload"; this.usageString = "/deathchest reload";
this.description = MessageId.COMMAND_HELP_RELOAD;
tim-savage/SavageDeathChest
src/main/java/com/winterhavenmc/deathchest/commands/ReloadCommand.java
// Path: src/main/java/com/winterhavenmc/deathchest/PluginMain.java // public final class PluginMain extends JavaPlugin { // // public MessageBuilder<MessageId, Macro> messageBuilder; // public WorldManager worldManager; // public SoundConfiguration soundConfig; // public ChestManager chestManager; // public CommandManager commandManager; // public ProtectionPluginRegistry protectionPluginRegistry; // // // @Override // public void onEnable() { // // // bStats // new Metrics(this, 13916); // // // copy default config from jar if it doesn't exist // saveDefaultConfig(); // // // initialize message builder // messageBuilder = new MessageBuilder<>(this); // // // instantiate sound configuration // soundConfig = new YamlSoundConfiguration(this); // // // instantiate world manager // worldManager = new WorldManager(this); // // // instantiate chest manager // chestManager = new ChestManager(this); // // // load all chests from datastore // chestManager.loadChests(); // // // instantiate command manager // commandManager = new CommandManager(this); // // // initialize event listeners // new PlayerEventListener(this); // new BlockEventListener(this); // new InventoryEventListener(this); // // // instantiate protection plugin registry // protectionPluginRegistry = new ProtectionPluginRegistry(this); // } // // // @Override // public void onDisable() { // // // close datastore // chestManager.closeDataStore(); // } // // } // // Path: src/main/java/com/winterhavenmc/deathchest/messages/MessageId.java // public enum MessageId { // // CHEST_SUCCESS, // DOUBLECHEST_PARTIAL_SUCCESS, // CHEST_DENIED_DEPLOYMENT_BY_PLUGIN, // CHEST_DENIED_ACCESS_BY_PLUGIN, // CHEST_DENIED_BLOCK, // CHEST_DENIED_PERMISSION, // CHEST_DENIED_ADJACENT, // CHEST_DENIED_SPAWN_RADIUS, // CHEST_DENIED_WORLD_DISABLED, // CHEST_DENIED_VOID, // CHEST_DEPLOYED_PROTECTION_TIME, // CHEST_ACCESSED_PROTECTION_TIME, // INVENTORY_EMPTY, // INVENTORY_FULL, // NO_CHEST_IN_INVENTORY, // NOT_OWNER, // CHEST_EXPIRED, // CREATIVE_MODE, // NO_CREATIVE_ACCESS, // CHEST_CURRENTLY_OPEN, // // COMMAND_FAIL_INVALID_COMMAND, // COMMAND_FAIL_ARGS_COUNT_OVER, // COMMAND_FAIL_HELP_PERMISSION, // COMMAND_FAIL_LIST_PERMISSION, // COMMAND_FAIL_LIST_OTHER_PERMISSION, // COMMAND_FAIL_RELOAD_PERMISSION, // COMMAND_FAIL_STATUS_PERMISSION, // COMMAND_SUCCESS_RELOAD, // // COMMAND_HELP_INVALID, // COMMAND_HELP_HELP, // COMMAND_HELP_LIST, // COMMAND_HELP_RELOAD, // COMMAND_HELP_STATUS, // COMMAND_HELP_USAGE, // // LIST_HEADER, // LIST_FOOTER, // LIST_EMPTY, // LIST_ITEM, // LIST_ITEM_ALL, // LIST_PLAYER_NOT_FOUND, // // } // // Path: src/main/java/com/winterhavenmc/deathchest/sounds/SoundId.java // public enum SoundId { // // CHEST_BREAK, // CHEST_DENIED_ACCESS, // COMMAND_FAIL, // INVENTORY_ADD_ITEM, // COMMAND_INVALID, // COMMAND_RELOAD_SUCCESS, // // }
import com.winterhavenmc.deathchest.PluginMain; import com.winterhavenmc.deathchest.messages.MessageId; import com.winterhavenmc.deathchest.sounds.SoundId; import org.bukkit.command.CommandSender; import java.util.List; import java.util.Objects;
/* * Copyright (c) 2022 Tim Savage. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.winterhavenmc.deathchest.commands; /** * Class that implements the reload subcommand. Reloads the plugin configuration settings. */ final class ReloadCommand extends SubcommandAbstract { private final PluginMain plugin; /** * Class constructor * * @param plugin reference to plugin main class */ ReloadCommand(final PluginMain plugin) { this.plugin = Objects.requireNonNull(plugin); this.name = "reload"; this.usageString = "/deathchest reload"; this.description = MessageId.COMMAND_HELP_RELOAD; } public boolean onCommand(final CommandSender sender, final List<String> args) { // check for null parameter Objects.requireNonNull(sender); if (!sender.hasPermission("deathchest.reload")) { plugin.messageBuilder.build(sender, MessageId.COMMAND_FAIL_RELOAD_PERMISSION).send();
// Path: src/main/java/com/winterhavenmc/deathchest/PluginMain.java // public final class PluginMain extends JavaPlugin { // // public MessageBuilder<MessageId, Macro> messageBuilder; // public WorldManager worldManager; // public SoundConfiguration soundConfig; // public ChestManager chestManager; // public CommandManager commandManager; // public ProtectionPluginRegistry protectionPluginRegistry; // // // @Override // public void onEnable() { // // // bStats // new Metrics(this, 13916); // // // copy default config from jar if it doesn't exist // saveDefaultConfig(); // // // initialize message builder // messageBuilder = new MessageBuilder<>(this); // // // instantiate sound configuration // soundConfig = new YamlSoundConfiguration(this); // // // instantiate world manager // worldManager = new WorldManager(this); // // // instantiate chest manager // chestManager = new ChestManager(this); // // // load all chests from datastore // chestManager.loadChests(); // // // instantiate command manager // commandManager = new CommandManager(this); // // // initialize event listeners // new PlayerEventListener(this); // new BlockEventListener(this); // new InventoryEventListener(this); // // // instantiate protection plugin registry // protectionPluginRegistry = new ProtectionPluginRegistry(this); // } // // // @Override // public void onDisable() { // // // close datastore // chestManager.closeDataStore(); // } // // } // // Path: src/main/java/com/winterhavenmc/deathchest/messages/MessageId.java // public enum MessageId { // // CHEST_SUCCESS, // DOUBLECHEST_PARTIAL_SUCCESS, // CHEST_DENIED_DEPLOYMENT_BY_PLUGIN, // CHEST_DENIED_ACCESS_BY_PLUGIN, // CHEST_DENIED_BLOCK, // CHEST_DENIED_PERMISSION, // CHEST_DENIED_ADJACENT, // CHEST_DENIED_SPAWN_RADIUS, // CHEST_DENIED_WORLD_DISABLED, // CHEST_DENIED_VOID, // CHEST_DEPLOYED_PROTECTION_TIME, // CHEST_ACCESSED_PROTECTION_TIME, // INVENTORY_EMPTY, // INVENTORY_FULL, // NO_CHEST_IN_INVENTORY, // NOT_OWNER, // CHEST_EXPIRED, // CREATIVE_MODE, // NO_CREATIVE_ACCESS, // CHEST_CURRENTLY_OPEN, // // COMMAND_FAIL_INVALID_COMMAND, // COMMAND_FAIL_ARGS_COUNT_OVER, // COMMAND_FAIL_HELP_PERMISSION, // COMMAND_FAIL_LIST_PERMISSION, // COMMAND_FAIL_LIST_OTHER_PERMISSION, // COMMAND_FAIL_RELOAD_PERMISSION, // COMMAND_FAIL_STATUS_PERMISSION, // COMMAND_SUCCESS_RELOAD, // // COMMAND_HELP_INVALID, // COMMAND_HELP_HELP, // COMMAND_HELP_LIST, // COMMAND_HELP_RELOAD, // COMMAND_HELP_STATUS, // COMMAND_HELP_USAGE, // // LIST_HEADER, // LIST_FOOTER, // LIST_EMPTY, // LIST_ITEM, // LIST_ITEM_ALL, // LIST_PLAYER_NOT_FOUND, // // } // // Path: src/main/java/com/winterhavenmc/deathchest/sounds/SoundId.java // public enum SoundId { // // CHEST_BREAK, // CHEST_DENIED_ACCESS, // COMMAND_FAIL, // INVENTORY_ADD_ITEM, // COMMAND_INVALID, // COMMAND_RELOAD_SUCCESS, // // } // Path: src/main/java/com/winterhavenmc/deathchest/commands/ReloadCommand.java import com.winterhavenmc.deathchest.PluginMain; import com.winterhavenmc.deathchest.messages.MessageId; import com.winterhavenmc.deathchest.sounds.SoundId; import org.bukkit.command.CommandSender; import java.util.List; import java.util.Objects; /* * Copyright (c) 2022 Tim Savage. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.winterhavenmc.deathchest.commands; /** * Class that implements the reload subcommand. Reloads the plugin configuration settings. */ final class ReloadCommand extends SubcommandAbstract { private final PluginMain plugin; /** * Class constructor * * @param plugin reference to plugin main class */ ReloadCommand(final PluginMain plugin) { this.plugin = Objects.requireNonNull(plugin); this.name = "reload"; this.usageString = "/deathchest reload"; this.description = MessageId.COMMAND_HELP_RELOAD; } public boolean onCommand(final CommandSender sender, final List<String> args) { // check for null parameter Objects.requireNonNull(sender); if (!sender.hasPermission("deathchest.reload")) { plugin.messageBuilder.build(sender, MessageId.COMMAND_FAIL_RELOAD_PERMISSION).send();
plugin.soundConfig.playSound(sender, SoundId.COMMAND_FAIL);