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
xebialabs/overcast
src/main/java/com/xebialabs/overcast/support/libvirt/Metadata.java
// Path: src/main/java/com/xebialabs/overcast/Preconditions.java // public final class Preconditions { // private Preconditions() {} // // public static void checkState( // boolean expression, // String errorMessageTemplate, // Object... errorMessageArgs) { // if (!expression) { // throw new IllegalStateException(String.format(errorMessageTemplate, errorMessageArgs)); // } // } // // public static void checkArgument( // boolean expression, // String errorMessageTemplate, // Object... errorMessageArgs) { // if (!expression) { // throw new IllegalArgumentException(String.format(errorMessageTemplate, errorMessageArgs)); // } // } // // public static void checkNotNull(Object reference) { // if (reference == null) { // throw new NullPointerException(); // } // } // // public static void checkNotNull( // Object reference, String errorMessageTemplate, Object... errorMessageArgs) { // if (reference == null) { // throw new NullPointerException(String.format(errorMessageTemplate, errorMessageArgs)); // } // } // // public static void checkNotNullOrEmpty(String s) { // if (isNullOrEmpty(s)) { // throw new NullPointerException(); // } // } // // } // // Path: src/main/java/com/xebialabs/overcast/support/libvirt/JDomUtil.java // public static String getElementText(Element parent, String localName, Namespace ns) { // if (parent == null) { // throw new IllegalArgumentException("parent element not found"); // } // Element child = parent.getChild(localName, ns); // if (child == null) { // throw new IllegalArgumentException(String.format("child element '%s' not found", localName)); // } // return child.getText(); // }
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; import com.xebialabs.overcast.Preconditions; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.Namespace; import static com.xebialabs.overcast.support.libvirt.JDomUtil.getElementText;
public String getProvisionedChecksum() { return provisionedChecksum; } public Date getCreationTime() { return creationTime; } public boolean isProvisioned() { return provisionedWith != null; } /** * Extract {@link Metadata} from the domain XML. Throws {@link IllegalArgumentException} if the metadata is * malformed. * * @return the metadata or <code>null</code> if there's no metadata */ public static Metadata fromXml(Document domainXml) { try { SimpleDateFormat sdf = new SimpleDateFormat(XML_DATE_FORMAT); Element metadata = getMetadataElement(domainXml); if (metadata == null) { return null; } Namespace ns = Namespace.getNamespace(METADATA_NS_V1); Element ocMetadata = metadata.getChild(OVERCAST_METADATA, ns); if (ocMetadata == null) { return null; }
// Path: src/main/java/com/xebialabs/overcast/Preconditions.java // public final class Preconditions { // private Preconditions() {} // // public static void checkState( // boolean expression, // String errorMessageTemplate, // Object... errorMessageArgs) { // if (!expression) { // throw new IllegalStateException(String.format(errorMessageTemplate, errorMessageArgs)); // } // } // // public static void checkArgument( // boolean expression, // String errorMessageTemplate, // Object... errorMessageArgs) { // if (!expression) { // throw new IllegalArgumentException(String.format(errorMessageTemplate, errorMessageArgs)); // } // } // // public static void checkNotNull(Object reference) { // if (reference == null) { // throw new NullPointerException(); // } // } // // public static void checkNotNull( // Object reference, String errorMessageTemplate, Object... errorMessageArgs) { // if (reference == null) { // throw new NullPointerException(String.format(errorMessageTemplate, errorMessageArgs)); // } // } // // public static void checkNotNullOrEmpty(String s) { // if (isNullOrEmpty(s)) { // throw new NullPointerException(); // } // } // // } // // Path: src/main/java/com/xebialabs/overcast/support/libvirt/JDomUtil.java // public static String getElementText(Element parent, String localName, Namespace ns) { // if (parent == null) { // throw new IllegalArgumentException("parent element not found"); // } // Element child = parent.getChild(localName, ns); // if (child == null) { // throw new IllegalArgumentException(String.format("child element '%s' not found", localName)); // } // return child.getText(); // } // Path: src/main/java/com/xebialabs/overcast/support/libvirt/Metadata.java import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; import com.xebialabs.overcast.Preconditions; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.Namespace; import static com.xebialabs.overcast.support.libvirt.JDomUtil.getElementText; public String getProvisionedChecksum() { return provisionedChecksum; } public Date getCreationTime() { return creationTime; } public boolean isProvisioned() { return provisionedWith != null; } /** * Extract {@link Metadata} from the domain XML. Throws {@link IllegalArgumentException} if the metadata is * malformed. * * @return the metadata or <code>null</code> if there's no metadata */ public static Metadata fromXml(Document domainXml) { try { SimpleDateFormat sdf = new SimpleDateFormat(XML_DATE_FORMAT); Element metadata = getMetadataElement(domainXml); if (metadata == null) { return null; } Namespace ns = Namespace.getNamespace(METADATA_NS_V1); Element ocMetadata = metadata.getChild(OVERCAST_METADATA, ns); if (ocMetadata == null) { return null; }
String parentDomain = getElementText(ocMetadata, PARENT_DOMAIN, ns);
xebialabs/overcast
src/main/java/com/xebialabs/overcast/Preconditions.java
// Path: src/main/java/com/xebialabs/overcast/Strings.java // public static boolean isNullOrEmpty(String s) { // return s == null || s.isEmpty(); // }
import static com.xebialabs.overcast.Strings.isNullOrEmpty;
String errorMessageTemplate, Object... errorMessageArgs) { if (!expression) { throw new IllegalStateException(String.format(errorMessageTemplate, errorMessageArgs)); } } public static void checkArgument( boolean expression, String errorMessageTemplate, Object... errorMessageArgs) { if (!expression) { throw new IllegalArgumentException(String.format(errorMessageTemplate, errorMessageArgs)); } } public static void checkNotNull(Object reference) { if (reference == null) { throw new NullPointerException(); } } public static void checkNotNull( Object reference, String errorMessageTemplate, Object... errorMessageArgs) { if (reference == null) { throw new NullPointerException(String.format(errorMessageTemplate, errorMessageArgs)); } } public static void checkNotNullOrEmpty(String s) {
// Path: src/main/java/com/xebialabs/overcast/Strings.java // public static boolean isNullOrEmpty(String s) { // return s == null || s.isEmpty(); // } // Path: src/main/java/com/xebialabs/overcast/Preconditions.java import static com.xebialabs.overcast.Strings.isNullOrEmpty; String errorMessageTemplate, Object... errorMessageArgs) { if (!expression) { throw new IllegalStateException(String.format(errorMessageTemplate, errorMessageArgs)); } } public static void checkArgument( boolean expression, String errorMessageTemplate, Object... errorMessageArgs) { if (!expression) { throw new IllegalArgumentException(String.format(errorMessageTemplate, errorMessageArgs)); } } public static void checkNotNull(Object reference) { if (reference == null) { throw new NullPointerException(); } } public static void checkNotNull( Object reference, String errorMessageTemplate, Object... errorMessageArgs) { if (reference == null) { throw new NullPointerException(String.format(errorMessageTemplate, errorMessageArgs)); } } public static void checkNotNullOrEmpty(String s) {
if (isNullOrEmpty(s)) {
xebialabs/overcast
src/main/java/com/xebialabs/overcast/host/TunneledCloudHost.java
// Path: src/main/java/com/xebialabs/overcast/Preconditions.java // public static void checkArgument( // boolean expression, // String errorMessageTemplate, // Object... errorMessageArgs) { // if (!expression) { // throw new IllegalArgumentException(String.format(errorMessageTemplate, errorMessageArgs)); // } // }
import static com.xebialabs.overcast.Preconditions.checkArgument; import java.io.IOException; import java.net.ConnectException; import java.net.InetSocketAddress; import java.net.NoRouteToHostException; import java.net.ServerSocket; import java.util.ArrayList; import java.util.List; import java.util.Map; import net.schmizz.sshj.SSHClient; import net.schmizz.sshj.connection.channel.direct.LocalPortForwarder; import net.schmizz.sshj.transport.verification.PromiscuousVerifier; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
ServerSocket ss = new ServerSocket(); ss.setReuseAddress(true); ss.bind(new InetSocketAddress(localHost, localPort)); final LocalPortForwarder forwarder = client.newLocalPortForwarder(params, ss); Thread forwarderThread = new Thread(() -> { try { forwarder.listen(); } catch (IOException ignore) { } }, "SSH port forwarder thread from local port " + localPort + " to " + remoteHostName + ":" + remotePort); forwarderThread.setDaemon(true); logger.info("Starting {}", forwarderThread.getName()); forwarderThread.start(); return new PortForwarder(forwarderThread, ss); } public void close() { try { thread.interrupt(); socket.close(); } catch (IOException e) { logger.debug("Ignoring exception while closing forwarding socket.", e); } } } TunneledCloudHost(CloudHost actualHost, String username, String password, Map<Integer, Integer> portForwardMap, int setupTimeout) {
// Path: src/main/java/com/xebialabs/overcast/Preconditions.java // public static void checkArgument( // boolean expression, // String errorMessageTemplate, // Object... errorMessageArgs) { // if (!expression) { // throw new IllegalArgumentException(String.format(errorMessageTemplate, errorMessageArgs)); // } // } // Path: src/main/java/com/xebialabs/overcast/host/TunneledCloudHost.java import static com.xebialabs.overcast.Preconditions.checkArgument; import java.io.IOException; import java.net.ConnectException; import java.net.InetSocketAddress; import java.net.NoRouteToHostException; import java.net.ServerSocket; import java.util.ArrayList; import java.util.List; import java.util.Map; import net.schmizz.sshj.SSHClient; import net.schmizz.sshj.connection.channel.direct.LocalPortForwarder; import net.schmizz.sshj.transport.verification.PromiscuousVerifier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; ServerSocket ss = new ServerSocket(); ss.setReuseAddress(true); ss.bind(new InetSocketAddress(localHost, localPort)); final LocalPortForwarder forwarder = client.newLocalPortForwarder(params, ss); Thread forwarderThread = new Thread(() -> { try { forwarder.listen(); } catch (IOException ignore) { } }, "SSH port forwarder thread from local port " + localPort + " to " + remoteHostName + ":" + remotePort); forwarderThread.setDaemon(true); logger.info("Starting {}", forwarderThread.getName()); forwarderThread.start(); return new PortForwarder(forwarderThread, ss); } public void close() { try { thread.interrupt(); socket.close(); } catch (IOException e) { logger.debug("Ignoring exception while closing forwarding socket.", e); } } } TunneledCloudHost(CloudHost actualHost, String username, String password, Map<Integer, Integer> portForwardMap, int setupTimeout) {
checkArgument(setupTimeout >= 0, "setupTimeout must be >= 0");
xebialabs/overcast
src/main/java/com/xebialabs/overcast/support/libvirt/StaticIpLookupStrategy.java
// Path: src/main/java/com/xebialabs/overcast/OvercastProperties.java // public static String getRequiredOvercastProperty(String key) { // String value = getOvercastProperty(key); // checkState(value != null, "Required property %s is not specified as a system property or in " + PropertiesLoader.OVERCAST_CONF_FILE // + " which can be placed in the current working directory, in ~/.overcast or on the classpath", key); // return value; // }
import static com.xebialabs.overcast.OvercastProperties.getRequiredOvercastProperty;
/** * Copyright 2012-2021 Digital.ai * * 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.xebialabs.overcast.support.libvirt; /** * Simple {@link IpLookupStrategy} that returns a pre-configured static IP. */ public class StaticIpLookupStrategy implements IpLookupStrategy { private static final String STATIC_IP_SUFFIX = ".static.ip"; private final String ip; public StaticIpLookupStrategy(String ip) { this.ip = ip; } public static StaticIpLookupStrategy create(String prefix) {
// Path: src/main/java/com/xebialabs/overcast/OvercastProperties.java // public static String getRequiredOvercastProperty(String key) { // String value = getOvercastProperty(key); // checkState(value != null, "Required property %s is not specified as a system property or in " + PropertiesLoader.OVERCAST_CONF_FILE // + " which can be placed in the current working directory, in ~/.overcast or on the classpath", key); // return value; // } // Path: src/main/java/com/xebialabs/overcast/support/libvirt/StaticIpLookupStrategy.java import static com.xebialabs.overcast.OvercastProperties.getRequiredOvercastProperty; /** * Copyright 2012-2021 Digital.ai * * 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.xebialabs.overcast.support.libvirt; /** * Simple {@link IpLookupStrategy} that returns a pre-configured static IP. */ public class StaticIpLookupStrategy implements IpLookupStrategy { private static final String STATIC_IP_SUFFIX = ".static.ip"; private final String ip; public StaticIpLookupStrategy(String ip) { this.ip = ip; } public static StaticIpLookupStrategy create(String prefix) {
String ip = getRequiredOvercastProperty(prefix + STATIC_IP_SUFFIX);
xebialabs/overcast
src/main/java/com/xebialabs/overcast/host/VagrantCloudHost.java
// Path: src/main/java/com/xebialabs/overcast/support/vagrant/VagrantDriver.java // public class VagrantDriver { // // private final String hostLabel; // private final CommandProcessor commandProcessor; // // public VagrantDriver(String hostLabel, CommandProcessor commandProcessor) { // this.hostLabel = hostLabel; // this.commandProcessor = commandProcessor; // } // // /** // * Executes vagrant command which means that arguments passed here will be prepended with "vagrant" // * @param vagrantCommand arguments for <i>vagrant</i> command // * @return vagrant response object // */ // public CommandResponse doVagrant(String vagrantVm, final String... vagrantCommand) { // CommandResponse response = commandProcessor.run( // aCommand("vagrant").withArguments(vagrantCommand).withOptions(vagrantVm) // ); // // if(!response.isSuccessful()) { // throw new RuntimeException("Errors during vagrant execution: \n" + response.getErrors()); // } // // // Check for puppet errors. Not vagrant still returns 0 when puppet fails // // May not be needed after this PR released: https://github.com/mitchellh/vagrant/pull/1175 // for (String line : response.getOutput().split("\n\u001B")) { // if (line.startsWith("[1;35merr:")) { // throw new RuntimeException("Error in puppet output: " + line); // } // } // // return response; // } // // public CommandResponse status(String vm) { // return doVagrant(vm, "status"); // } // // public VagrantState state(String vm) { // return VagrantState.fromStatusString(status(vm).getOutput()); // } // // @Override // public String toString() { // return hostLabel; // } // // } // // Path: src/main/java/com/xebialabs/overcast/support/vagrant/VagrantState.java // public enum VagrantState { // NOT_CREATED, POWEROFF, ABORTED, SAVED, RUNNING; // // public static VagrantState fromStatusString(String s) { // if (s.contains("not created")) return NOT_CREATED; // if (s.contains("poweroff")) return POWEROFF; // if (s.contains("aborted")) return ABORTED; // if (s.contains("saved")) return SAVED; // if (s.contains("running")) return RUNNING; // // throw new RuntimeException("Unknown status: " + s); // } // // public static String[] getTransitionCommand(VagrantState newState, Map<String, String> vagrantParameters) { // // switch (newState) { // case NOT_CREATED: // return new String[]{"destroy", "-f"}; // case POWEROFF: // return new String[]{"halt"}; // case SAVED: // return new String[]{"suspend"}; // case RUNNING: // if(isNullOrEmpty(vagrantParameters)) { // return new String[]{"up", "--provision"}; // } else { // ArrayList<String> arr = new ArrayList<>(); // for (var entry : vagrantParameters.entrySet()) { // arr.add("--" + entry.getKey() + "=" + entry.getValue()); // } // arr.add("up"); // arr.add("--provision"); // return arr.toArray(new String[0]); // } // case ABORTED: // break; // ignore // default: // throw new IllegalArgumentException(String.format("The state %s is not known", newState)); // } // throw new RuntimeException("Unexpected state in getTransitionCommand "+newState.name()); // } // private static boolean isNullOrEmpty(final Map< ?, ? > m) { // return m == null || m.isEmpty(); // } // }
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.xebialabs.overcast.support.vagrant.VagrantDriver; import com.xebialabs.overcast.support.vagrant.VagrantState; import java.util.Map; import static com.xebialabs.overcast.support.vagrant.VagrantState.NOT_CREATED; import static com.xebialabs.overcast.support.vagrant.VagrantState.getTransitionCommand;
/** * Copyright 2012-2021 Digital.ai * * 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.xebialabs.overcast.host; public class VagrantCloudHost implements CloudHost { protected String vagrantIp; protected String vagrantVm;
// Path: src/main/java/com/xebialabs/overcast/support/vagrant/VagrantDriver.java // public class VagrantDriver { // // private final String hostLabel; // private final CommandProcessor commandProcessor; // // public VagrantDriver(String hostLabel, CommandProcessor commandProcessor) { // this.hostLabel = hostLabel; // this.commandProcessor = commandProcessor; // } // // /** // * Executes vagrant command which means that arguments passed here will be prepended with "vagrant" // * @param vagrantCommand arguments for <i>vagrant</i> command // * @return vagrant response object // */ // public CommandResponse doVagrant(String vagrantVm, final String... vagrantCommand) { // CommandResponse response = commandProcessor.run( // aCommand("vagrant").withArguments(vagrantCommand).withOptions(vagrantVm) // ); // // if(!response.isSuccessful()) { // throw new RuntimeException("Errors during vagrant execution: \n" + response.getErrors()); // } // // // Check for puppet errors. Not vagrant still returns 0 when puppet fails // // May not be needed after this PR released: https://github.com/mitchellh/vagrant/pull/1175 // for (String line : response.getOutput().split("\n\u001B")) { // if (line.startsWith("[1;35merr:")) { // throw new RuntimeException("Error in puppet output: " + line); // } // } // // return response; // } // // public CommandResponse status(String vm) { // return doVagrant(vm, "status"); // } // // public VagrantState state(String vm) { // return VagrantState.fromStatusString(status(vm).getOutput()); // } // // @Override // public String toString() { // return hostLabel; // } // // } // // Path: src/main/java/com/xebialabs/overcast/support/vagrant/VagrantState.java // public enum VagrantState { // NOT_CREATED, POWEROFF, ABORTED, SAVED, RUNNING; // // public static VagrantState fromStatusString(String s) { // if (s.contains("not created")) return NOT_CREATED; // if (s.contains("poweroff")) return POWEROFF; // if (s.contains("aborted")) return ABORTED; // if (s.contains("saved")) return SAVED; // if (s.contains("running")) return RUNNING; // // throw new RuntimeException("Unknown status: " + s); // } // // public static String[] getTransitionCommand(VagrantState newState, Map<String, String> vagrantParameters) { // // switch (newState) { // case NOT_CREATED: // return new String[]{"destroy", "-f"}; // case POWEROFF: // return new String[]{"halt"}; // case SAVED: // return new String[]{"suspend"}; // case RUNNING: // if(isNullOrEmpty(vagrantParameters)) { // return new String[]{"up", "--provision"}; // } else { // ArrayList<String> arr = new ArrayList<>(); // for (var entry : vagrantParameters.entrySet()) { // arr.add("--" + entry.getKey() + "=" + entry.getValue()); // } // arr.add("up"); // arr.add("--provision"); // return arr.toArray(new String[0]); // } // case ABORTED: // break; // ignore // default: // throw new IllegalArgumentException(String.format("The state %s is not known", newState)); // } // throw new RuntimeException("Unexpected state in getTransitionCommand "+newState.name()); // } // private static boolean isNullOrEmpty(final Map< ?, ? > m) { // return m == null || m.isEmpty(); // } // } // Path: src/main/java/com/xebialabs/overcast/host/VagrantCloudHost.java import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.xebialabs.overcast.support.vagrant.VagrantDriver; import com.xebialabs.overcast.support.vagrant.VagrantState; import java.util.Map; import static com.xebialabs.overcast.support.vagrant.VagrantState.NOT_CREATED; import static com.xebialabs.overcast.support.vagrant.VagrantState.getTransitionCommand; /** * Copyright 2012-2021 Digital.ai * * 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.xebialabs.overcast.host; public class VagrantCloudHost implements CloudHost { protected String vagrantIp; protected String vagrantVm;
protected VagrantDriver vagrantDriver;
xebialabs/overcast
src/main/java/com/xebialabs/overcast/host/VagrantCloudHost.java
// Path: src/main/java/com/xebialabs/overcast/support/vagrant/VagrantDriver.java // public class VagrantDriver { // // private final String hostLabel; // private final CommandProcessor commandProcessor; // // public VagrantDriver(String hostLabel, CommandProcessor commandProcessor) { // this.hostLabel = hostLabel; // this.commandProcessor = commandProcessor; // } // // /** // * Executes vagrant command which means that arguments passed here will be prepended with "vagrant" // * @param vagrantCommand arguments for <i>vagrant</i> command // * @return vagrant response object // */ // public CommandResponse doVagrant(String vagrantVm, final String... vagrantCommand) { // CommandResponse response = commandProcessor.run( // aCommand("vagrant").withArguments(vagrantCommand).withOptions(vagrantVm) // ); // // if(!response.isSuccessful()) { // throw new RuntimeException("Errors during vagrant execution: \n" + response.getErrors()); // } // // // Check for puppet errors. Not vagrant still returns 0 when puppet fails // // May not be needed after this PR released: https://github.com/mitchellh/vagrant/pull/1175 // for (String line : response.getOutput().split("\n\u001B")) { // if (line.startsWith("[1;35merr:")) { // throw new RuntimeException("Error in puppet output: " + line); // } // } // // return response; // } // // public CommandResponse status(String vm) { // return doVagrant(vm, "status"); // } // // public VagrantState state(String vm) { // return VagrantState.fromStatusString(status(vm).getOutput()); // } // // @Override // public String toString() { // return hostLabel; // } // // } // // Path: src/main/java/com/xebialabs/overcast/support/vagrant/VagrantState.java // public enum VagrantState { // NOT_CREATED, POWEROFF, ABORTED, SAVED, RUNNING; // // public static VagrantState fromStatusString(String s) { // if (s.contains("not created")) return NOT_CREATED; // if (s.contains("poweroff")) return POWEROFF; // if (s.contains("aborted")) return ABORTED; // if (s.contains("saved")) return SAVED; // if (s.contains("running")) return RUNNING; // // throw new RuntimeException("Unknown status: " + s); // } // // public static String[] getTransitionCommand(VagrantState newState, Map<String, String> vagrantParameters) { // // switch (newState) { // case NOT_CREATED: // return new String[]{"destroy", "-f"}; // case POWEROFF: // return new String[]{"halt"}; // case SAVED: // return new String[]{"suspend"}; // case RUNNING: // if(isNullOrEmpty(vagrantParameters)) { // return new String[]{"up", "--provision"}; // } else { // ArrayList<String> arr = new ArrayList<>(); // for (var entry : vagrantParameters.entrySet()) { // arr.add("--" + entry.getKey() + "=" + entry.getValue()); // } // arr.add("up"); // arr.add("--provision"); // return arr.toArray(new String[0]); // } // case ABORTED: // break; // ignore // default: // throw new IllegalArgumentException(String.format("The state %s is not known", newState)); // } // throw new RuntimeException("Unexpected state in getTransitionCommand "+newState.name()); // } // private static boolean isNullOrEmpty(final Map< ?, ? > m) { // return m == null || m.isEmpty(); // } // }
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.xebialabs.overcast.support.vagrant.VagrantDriver; import com.xebialabs.overcast.support.vagrant.VagrantState; import java.util.Map; import static com.xebialabs.overcast.support.vagrant.VagrantState.NOT_CREATED; import static com.xebialabs.overcast.support.vagrant.VagrantState.getTransitionCommand;
/** * Copyright 2012-2021 Digital.ai * * 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.xebialabs.overcast.host; public class VagrantCloudHost implements CloudHost { protected String vagrantIp; protected String vagrantVm; protected VagrantDriver vagrantDriver;
// Path: src/main/java/com/xebialabs/overcast/support/vagrant/VagrantDriver.java // public class VagrantDriver { // // private final String hostLabel; // private final CommandProcessor commandProcessor; // // public VagrantDriver(String hostLabel, CommandProcessor commandProcessor) { // this.hostLabel = hostLabel; // this.commandProcessor = commandProcessor; // } // // /** // * Executes vagrant command which means that arguments passed here will be prepended with "vagrant" // * @param vagrantCommand arguments for <i>vagrant</i> command // * @return vagrant response object // */ // public CommandResponse doVagrant(String vagrantVm, final String... vagrantCommand) { // CommandResponse response = commandProcessor.run( // aCommand("vagrant").withArguments(vagrantCommand).withOptions(vagrantVm) // ); // // if(!response.isSuccessful()) { // throw new RuntimeException("Errors during vagrant execution: \n" + response.getErrors()); // } // // // Check for puppet errors. Not vagrant still returns 0 when puppet fails // // May not be needed after this PR released: https://github.com/mitchellh/vagrant/pull/1175 // for (String line : response.getOutput().split("\n\u001B")) { // if (line.startsWith("[1;35merr:")) { // throw new RuntimeException("Error in puppet output: " + line); // } // } // // return response; // } // // public CommandResponse status(String vm) { // return doVagrant(vm, "status"); // } // // public VagrantState state(String vm) { // return VagrantState.fromStatusString(status(vm).getOutput()); // } // // @Override // public String toString() { // return hostLabel; // } // // } // // Path: src/main/java/com/xebialabs/overcast/support/vagrant/VagrantState.java // public enum VagrantState { // NOT_CREATED, POWEROFF, ABORTED, SAVED, RUNNING; // // public static VagrantState fromStatusString(String s) { // if (s.contains("not created")) return NOT_CREATED; // if (s.contains("poweroff")) return POWEROFF; // if (s.contains("aborted")) return ABORTED; // if (s.contains("saved")) return SAVED; // if (s.contains("running")) return RUNNING; // // throw new RuntimeException("Unknown status: " + s); // } // // public static String[] getTransitionCommand(VagrantState newState, Map<String, String> vagrantParameters) { // // switch (newState) { // case NOT_CREATED: // return new String[]{"destroy", "-f"}; // case POWEROFF: // return new String[]{"halt"}; // case SAVED: // return new String[]{"suspend"}; // case RUNNING: // if(isNullOrEmpty(vagrantParameters)) { // return new String[]{"up", "--provision"}; // } else { // ArrayList<String> arr = new ArrayList<>(); // for (var entry : vagrantParameters.entrySet()) { // arr.add("--" + entry.getKey() + "=" + entry.getValue()); // } // arr.add("up"); // arr.add("--provision"); // return arr.toArray(new String[0]); // } // case ABORTED: // break; // ignore // default: // throw new IllegalArgumentException(String.format("The state %s is not known", newState)); // } // throw new RuntimeException("Unexpected state in getTransitionCommand "+newState.name()); // } // private static boolean isNullOrEmpty(final Map< ?, ? > m) { // return m == null || m.isEmpty(); // } // } // Path: src/main/java/com/xebialabs/overcast/host/VagrantCloudHost.java import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.xebialabs.overcast.support.vagrant.VagrantDriver; import com.xebialabs.overcast.support.vagrant.VagrantState; import java.util.Map; import static com.xebialabs.overcast.support.vagrant.VagrantState.NOT_CREATED; import static com.xebialabs.overcast.support.vagrant.VagrantState.getTransitionCommand; /** * Copyright 2012-2021 Digital.ai * * 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.xebialabs.overcast.host; public class VagrantCloudHost implements CloudHost { protected String vagrantIp; protected String vagrantVm; protected VagrantDriver vagrantDriver;
private VagrantState initialState;
xebialabs/overcast
src/main/java/com/xebialabs/overcast/support/libvirt/Disk.java
// Path: src/main/java/com/xebialabs/overcast/support/libvirt/jdom/DiskXml.java // public final class DiskXml { // private static final String XPATH_DISK_DEV = "//target/@dev"; // private static final String XPATH_DISK_FILE = "//source/@file"; // private static final String XPATH_DISK_TYPE = "//driver[@name='qemu']/@type"; // private static final String XPATH_DISK = "/domain/devices/disk[@device='disk']"; // // private DiskXml() { // } // // /** // * update the disks in the domain XML. It is assumed that the the size of the volumes is the same as the number of // * disk elements and that the order is the same. // */ // public static void updateDisks(Document domainXml, List<StorageVol> volumes) throws LibvirtException { // XPathFactory xpf = XPathFactory.instance(); // XPathExpression<Element> diskExpr = xpf.compile(XPATH_DISK, Filters.element()); // XPathExpression<Attribute> fileExpr = xpf.compile(XPATH_DISK_FILE, Filters.attribute()); // List<Element> disks = diskExpr.evaluate(domainXml); // Iterator<StorageVol> cloneDiskIter = volumes.iterator(); // for (Element disk : disks) { // Attribute file = fileExpr.evaluateFirst(disk); // StorageVol cloneDisk = cloneDiskIter.next(); // file.setValue(cloneDisk.getPath()); // } // } // // /** Get the disks connected to the domain. */ // public static List<Disk> getDisks(Connect connect, Document domainXml) { // try { // List<Disk> ret = new ArrayList<>(); // XPathFactory xpf = XPathFactory.instance(); // XPathExpression<Element> diskExpr = xpf.compile(XPATH_DISK, Filters.element()); // XPathExpression<Attribute> typeExpr = xpf.compile(XPATH_DISK_TYPE, Filters.attribute()); // XPathExpression<Attribute> fileExpr = xpf.compile(XPATH_DISK_FILE, Filters.attribute()); // XPathExpression<Attribute> devExpr = xpf.compile(XPATH_DISK_DEV, Filters.attribute()); // List<Element> disks = diskExpr.evaluate(domainXml); // for (Element disk : disks) { // Attribute type = typeExpr.evaluateFirst(disk); // Attribute file = fileExpr.evaluateFirst(disk); // Attribute dev = devExpr.evaluateFirst(disk); // // StorageVol volume = LibvirtUtil.findVolume(connect, file.getValue()); // // ret.add(new Disk(dev.getValue(), file.getValue(), volume, type.getValue())); // } // return ret; // } catch (LibvirtException e) { // throw new LibvirtRuntimeException(e); // } // } // // public static String cloneVolumeXml(Disk backingDisk, String clonedDiskName) throws IOException { // Element volume = new Element("volume"); // volume.addContent(new Element("name").setText(clonedDiskName)); // volume.addContent(new Element("allocation").setText("0")); // volume.addContent(new Element("capacity").setText("" + backingDisk.getInfo().capacity)); // Element target = new Element("target"); // volume.addContent(target); // target.addContent(new Element("format").setAttribute("type", backingDisk.format)); // target.addContent(new Element("compat").setText("1.1")); // Element backingStore = new Element("backingStore"); // volume.addContent(backingStore); // backingStore.addContent(new Element("path").setText(backingDisk.file)); // backingStore.addContent(new Element("format").setAttribute("type", backingDisk.format)); // // return JDomUtil.elementToString(volume); // } // } // // Path: src/main/java/com/xebialabs/overcast/Preconditions.java // public static void checkNotNull(Object reference) { // if (reference == null) { // throw new NullPointerException(); // } // } // // Path: src/main/java/com/xebialabs/overcast/Preconditions.java // public static void checkNotNullOrEmpty(String s) { // if (isNullOrEmpty(s)) { // throw new NullPointerException(); // } // }
import java.io.IOException; import org.libvirt.LibvirtException; import org.libvirt.StoragePool; import org.libvirt.StorageVol; import org.libvirt.StorageVolInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.xebialabs.overcast.support.libvirt.jdom.DiskXml; import static com.xebialabs.overcast.Preconditions.checkNotNull; import static com.xebialabs.overcast.Preconditions.checkNotNullOrEmpty;
/** * Copyright 2012-2021 Digital.ai * * 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.xebialabs.overcast.support.libvirt; public class Disk { private static final Logger log = LoggerFactory.getLogger(Disk.class); public String device; public String file; public String format; private final StorageVol volume; public Disk(String device, String file, StorageVol volume, String format) {
// Path: src/main/java/com/xebialabs/overcast/support/libvirt/jdom/DiskXml.java // public final class DiskXml { // private static final String XPATH_DISK_DEV = "//target/@dev"; // private static final String XPATH_DISK_FILE = "//source/@file"; // private static final String XPATH_DISK_TYPE = "//driver[@name='qemu']/@type"; // private static final String XPATH_DISK = "/domain/devices/disk[@device='disk']"; // // private DiskXml() { // } // // /** // * update the disks in the domain XML. It is assumed that the the size of the volumes is the same as the number of // * disk elements and that the order is the same. // */ // public static void updateDisks(Document domainXml, List<StorageVol> volumes) throws LibvirtException { // XPathFactory xpf = XPathFactory.instance(); // XPathExpression<Element> diskExpr = xpf.compile(XPATH_DISK, Filters.element()); // XPathExpression<Attribute> fileExpr = xpf.compile(XPATH_DISK_FILE, Filters.attribute()); // List<Element> disks = diskExpr.evaluate(domainXml); // Iterator<StorageVol> cloneDiskIter = volumes.iterator(); // for (Element disk : disks) { // Attribute file = fileExpr.evaluateFirst(disk); // StorageVol cloneDisk = cloneDiskIter.next(); // file.setValue(cloneDisk.getPath()); // } // } // // /** Get the disks connected to the domain. */ // public static List<Disk> getDisks(Connect connect, Document domainXml) { // try { // List<Disk> ret = new ArrayList<>(); // XPathFactory xpf = XPathFactory.instance(); // XPathExpression<Element> diskExpr = xpf.compile(XPATH_DISK, Filters.element()); // XPathExpression<Attribute> typeExpr = xpf.compile(XPATH_DISK_TYPE, Filters.attribute()); // XPathExpression<Attribute> fileExpr = xpf.compile(XPATH_DISK_FILE, Filters.attribute()); // XPathExpression<Attribute> devExpr = xpf.compile(XPATH_DISK_DEV, Filters.attribute()); // List<Element> disks = diskExpr.evaluate(domainXml); // for (Element disk : disks) { // Attribute type = typeExpr.evaluateFirst(disk); // Attribute file = fileExpr.evaluateFirst(disk); // Attribute dev = devExpr.evaluateFirst(disk); // // StorageVol volume = LibvirtUtil.findVolume(connect, file.getValue()); // // ret.add(new Disk(dev.getValue(), file.getValue(), volume, type.getValue())); // } // return ret; // } catch (LibvirtException e) { // throw new LibvirtRuntimeException(e); // } // } // // public static String cloneVolumeXml(Disk backingDisk, String clonedDiskName) throws IOException { // Element volume = new Element("volume"); // volume.addContent(new Element("name").setText(clonedDiskName)); // volume.addContent(new Element("allocation").setText("0")); // volume.addContent(new Element("capacity").setText("" + backingDisk.getInfo().capacity)); // Element target = new Element("target"); // volume.addContent(target); // target.addContent(new Element("format").setAttribute("type", backingDisk.format)); // target.addContent(new Element("compat").setText("1.1")); // Element backingStore = new Element("backingStore"); // volume.addContent(backingStore); // backingStore.addContent(new Element("path").setText(backingDisk.file)); // backingStore.addContent(new Element("format").setAttribute("type", backingDisk.format)); // // return JDomUtil.elementToString(volume); // } // } // // Path: src/main/java/com/xebialabs/overcast/Preconditions.java // public static void checkNotNull(Object reference) { // if (reference == null) { // throw new NullPointerException(); // } // } // // Path: src/main/java/com/xebialabs/overcast/Preconditions.java // public static void checkNotNullOrEmpty(String s) { // if (isNullOrEmpty(s)) { // throw new NullPointerException(); // } // } // Path: src/main/java/com/xebialabs/overcast/support/libvirt/Disk.java import java.io.IOException; import org.libvirt.LibvirtException; import org.libvirt.StoragePool; import org.libvirt.StorageVol; import org.libvirt.StorageVolInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.xebialabs.overcast.support.libvirt.jdom.DiskXml; import static com.xebialabs.overcast.Preconditions.checkNotNull; import static com.xebialabs.overcast.Preconditions.checkNotNullOrEmpty; /** * Copyright 2012-2021 Digital.ai * * 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.xebialabs.overcast.support.libvirt; public class Disk { private static final Logger log = LoggerFactory.getLogger(Disk.class); public String device; public String file; public String format; private final StorageVol volume; public Disk(String device, String file, StorageVol volume, String format) {
checkNotNullOrEmpty(device);
xebialabs/overcast
src/main/java/com/xebialabs/overcast/support/libvirt/Disk.java
// Path: src/main/java/com/xebialabs/overcast/support/libvirt/jdom/DiskXml.java // public final class DiskXml { // private static final String XPATH_DISK_DEV = "//target/@dev"; // private static final String XPATH_DISK_FILE = "//source/@file"; // private static final String XPATH_DISK_TYPE = "//driver[@name='qemu']/@type"; // private static final String XPATH_DISK = "/domain/devices/disk[@device='disk']"; // // private DiskXml() { // } // // /** // * update the disks in the domain XML. It is assumed that the the size of the volumes is the same as the number of // * disk elements and that the order is the same. // */ // public static void updateDisks(Document domainXml, List<StorageVol> volumes) throws LibvirtException { // XPathFactory xpf = XPathFactory.instance(); // XPathExpression<Element> diskExpr = xpf.compile(XPATH_DISK, Filters.element()); // XPathExpression<Attribute> fileExpr = xpf.compile(XPATH_DISK_FILE, Filters.attribute()); // List<Element> disks = diskExpr.evaluate(domainXml); // Iterator<StorageVol> cloneDiskIter = volumes.iterator(); // for (Element disk : disks) { // Attribute file = fileExpr.evaluateFirst(disk); // StorageVol cloneDisk = cloneDiskIter.next(); // file.setValue(cloneDisk.getPath()); // } // } // // /** Get the disks connected to the domain. */ // public static List<Disk> getDisks(Connect connect, Document domainXml) { // try { // List<Disk> ret = new ArrayList<>(); // XPathFactory xpf = XPathFactory.instance(); // XPathExpression<Element> diskExpr = xpf.compile(XPATH_DISK, Filters.element()); // XPathExpression<Attribute> typeExpr = xpf.compile(XPATH_DISK_TYPE, Filters.attribute()); // XPathExpression<Attribute> fileExpr = xpf.compile(XPATH_DISK_FILE, Filters.attribute()); // XPathExpression<Attribute> devExpr = xpf.compile(XPATH_DISK_DEV, Filters.attribute()); // List<Element> disks = diskExpr.evaluate(domainXml); // for (Element disk : disks) { // Attribute type = typeExpr.evaluateFirst(disk); // Attribute file = fileExpr.evaluateFirst(disk); // Attribute dev = devExpr.evaluateFirst(disk); // // StorageVol volume = LibvirtUtil.findVolume(connect, file.getValue()); // // ret.add(new Disk(dev.getValue(), file.getValue(), volume, type.getValue())); // } // return ret; // } catch (LibvirtException e) { // throw new LibvirtRuntimeException(e); // } // } // // public static String cloneVolumeXml(Disk backingDisk, String clonedDiskName) throws IOException { // Element volume = new Element("volume"); // volume.addContent(new Element("name").setText(clonedDiskName)); // volume.addContent(new Element("allocation").setText("0")); // volume.addContent(new Element("capacity").setText("" + backingDisk.getInfo().capacity)); // Element target = new Element("target"); // volume.addContent(target); // target.addContent(new Element("format").setAttribute("type", backingDisk.format)); // target.addContent(new Element("compat").setText("1.1")); // Element backingStore = new Element("backingStore"); // volume.addContent(backingStore); // backingStore.addContent(new Element("path").setText(backingDisk.file)); // backingStore.addContent(new Element("format").setAttribute("type", backingDisk.format)); // // return JDomUtil.elementToString(volume); // } // } // // Path: src/main/java/com/xebialabs/overcast/Preconditions.java // public static void checkNotNull(Object reference) { // if (reference == null) { // throw new NullPointerException(); // } // } // // Path: src/main/java/com/xebialabs/overcast/Preconditions.java // public static void checkNotNullOrEmpty(String s) { // if (isNullOrEmpty(s)) { // throw new NullPointerException(); // } // }
import java.io.IOException; import org.libvirt.LibvirtException; import org.libvirt.StoragePool; import org.libvirt.StorageVol; import org.libvirt.StorageVolInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.xebialabs.overcast.support.libvirt.jdom.DiskXml; import static com.xebialabs.overcast.Preconditions.checkNotNull; import static com.xebialabs.overcast.Preconditions.checkNotNullOrEmpty;
/** * Copyright 2012-2021 Digital.ai * * 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.xebialabs.overcast.support.libvirt; public class Disk { private static final Logger log = LoggerFactory.getLogger(Disk.class); public String device; public String file; public String format; private final StorageVol volume; public Disk(String device, String file, StorageVol volume, String format) { checkNotNullOrEmpty(device); checkNotNullOrEmpty(file);
// Path: src/main/java/com/xebialabs/overcast/support/libvirt/jdom/DiskXml.java // public final class DiskXml { // private static final String XPATH_DISK_DEV = "//target/@dev"; // private static final String XPATH_DISK_FILE = "//source/@file"; // private static final String XPATH_DISK_TYPE = "//driver[@name='qemu']/@type"; // private static final String XPATH_DISK = "/domain/devices/disk[@device='disk']"; // // private DiskXml() { // } // // /** // * update the disks in the domain XML. It is assumed that the the size of the volumes is the same as the number of // * disk elements and that the order is the same. // */ // public static void updateDisks(Document domainXml, List<StorageVol> volumes) throws LibvirtException { // XPathFactory xpf = XPathFactory.instance(); // XPathExpression<Element> diskExpr = xpf.compile(XPATH_DISK, Filters.element()); // XPathExpression<Attribute> fileExpr = xpf.compile(XPATH_DISK_FILE, Filters.attribute()); // List<Element> disks = diskExpr.evaluate(domainXml); // Iterator<StorageVol> cloneDiskIter = volumes.iterator(); // for (Element disk : disks) { // Attribute file = fileExpr.evaluateFirst(disk); // StorageVol cloneDisk = cloneDiskIter.next(); // file.setValue(cloneDisk.getPath()); // } // } // // /** Get the disks connected to the domain. */ // public static List<Disk> getDisks(Connect connect, Document domainXml) { // try { // List<Disk> ret = new ArrayList<>(); // XPathFactory xpf = XPathFactory.instance(); // XPathExpression<Element> diskExpr = xpf.compile(XPATH_DISK, Filters.element()); // XPathExpression<Attribute> typeExpr = xpf.compile(XPATH_DISK_TYPE, Filters.attribute()); // XPathExpression<Attribute> fileExpr = xpf.compile(XPATH_DISK_FILE, Filters.attribute()); // XPathExpression<Attribute> devExpr = xpf.compile(XPATH_DISK_DEV, Filters.attribute()); // List<Element> disks = diskExpr.evaluate(domainXml); // for (Element disk : disks) { // Attribute type = typeExpr.evaluateFirst(disk); // Attribute file = fileExpr.evaluateFirst(disk); // Attribute dev = devExpr.evaluateFirst(disk); // // StorageVol volume = LibvirtUtil.findVolume(connect, file.getValue()); // // ret.add(new Disk(dev.getValue(), file.getValue(), volume, type.getValue())); // } // return ret; // } catch (LibvirtException e) { // throw new LibvirtRuntimeException(e); // } // } // // public static String cloneVolumeXml(Disk backingDisk, String clonedDiskName) throws IOException { // Element volume = new Element("volume"); // volume.addContent(new Element("name").setText(clonedDiskName)); // volume.addContent(new Element("allocation").setText("0")); // volume.addContent(new Element("capacity").setText("" + backingDisk.getInfo().capacity)); // Element target = new Element("target"); // volume.addContent(target); // target.addContent(new Element("format").setAttribute("type", backingDisk.format)); // target.addContent(new Element("compat").setText("1.1")); // Element backingStore = new Element("backingStore"); // volume.addContent(backingStore); // backingStore.addContent(new Element("path").setText(backingDisk.file)); // backingStore.addContent(new Element("format").setAttribute("type", backingDisk.format)); // // return JDomUtil.elementToString(volume); // } // } // // Path: src/main/java/com/xebialabs/overcast/Preconditions.java // public static void checkNotNull(Object reference) { // if (reference == null) { // throw new NullPointerException(); // } // } // // Path: src/main/java/com/xebialabs/overcast/Preconditions.java // public static void checkNotNullOrEmpty(String s) { // if (isNullOrEmpty(s)) { // throw new NullPointerException(); // } // } // Path: src/main/java/com/xebialabs/overcast/support/libvirt/Disk.java import java.io.IOException; import org.libvirt.LibvirtException; import org.libvirt.StoragePool; import org.libvirt.StorageVol; import org.libvirt.StorageVolInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.xebialabs.overcast.support.libvirt.jdom.DiskXml; import static com.xebialabs.overcast.Preconditions.checkNotNull; import static com.xebialabs.overcast.Preconditions.checkNotNullOrEmpty; /** * Copyright 2012-2021 Digital.ai * * 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.xebialabs.overcast.support.libvirt; public class Disk { private static final Logger log = LoggerFactory.getLogger(Disk.class); public String device; public String file; public String format; private final StorageVol volume; public Disk(String device, String file, StorageVol volume, String format) { checkNotNullOrEmpty(device); checkNotNullOrEmpty(file);
checkNotNull(volume);
xebialabs/overcast
src/main/java/com/xebialabs/overcast/support/libvirt/Disk.java
// Path: src/main/java/com/xebialabs/overcast/support/libvirt/jdom/DiskXml.java // public final class DiskXml { // private static final String XPATH_DISK_DEV = "//target/@dev"; // private static final String XPATH_DISK_FILE = "//source/@file"; // private static final String XPATH_DISK_TYPE = "//driver[@name='qemu']/@type"; // private static final String XPATH_DISK = "/domain/devices/disk[@device='disk']"; // // private DiskXml() { // } // // /** // * update the disks in the domain XML. It is assumed that the the size of the volumes is the same as the number of // * disk elements and that the order is the same. // */ // public static void updateDisks(Document domainXml, List<StorageVol> volumes) throws LibvirtException { // XPathFactory xpf = XPathFactory.instance(); // XPathExpression<Element> diskExpr = xpf.compile(XPATH_DISK, Filters.element()); // XPathExpression<Attribute> fileExpr = xpf.compile(XPATH_DISK_FILE, Filters.attribute()); // List<Element> disks = diskExpr.evaluate(domainXml); // Iterator<StorageVol> cloneDiskIter = volumes.iterator(); // for (Element disk : disks) { // Attribute file = fileExpr.evaluateFirst(disk); // StorageVol cloneDisk = cloneDiskIter.next(); // file.setValue(cloneDisk.getPath()); // } // } // // /** Get the disks connected to the domain. */ // public static List<Disk> getDisks(Connect connect, Document domainXml) { // try { // List<Disk> ret = new ArrayList<>(); // XPathFactory xpf = XPathFactory.instance(); // XPathExpression<Element> diskExpr = xpf.compile(XPATH_DISK, Filters.element()); // XPathExpression<Attribute> typeExpr = xpf.compile(XPATH_DISK_TYPE, Filters.attribute()); // XPathExpression<Attribute> fileExpr = xpf.compile(XPATH_DISK_FILE, Filters.attribute()); // XPathExpression<Attribute> devExpr = xpf.compile(XPATH_DISK_DEV, Filters.attribute()); // List<Element> disks = diskExpr.evaluate(domainXml); // for (Element disk : disks) { // Attribute type = typeExpr.evaluateFirst(disk); // Attribute file = fileExpr.evaluateFirst(disk); // Attribute dev = devExpr.evaluateFirst(disk); // // StorageVol volume = LibvirtUtil.findVolume(connect, file.getValue()); // // ret.add(new Disk(dev.getValue(), file.getValue(), volume, type.getValue())); // } // return ret; // } catch (LibvirtException e) { // throw new LibvirtRuntimeException(e); // } // } // // public static String cloneVolumeXml(Disk backingDisk, String clonedDiskName) throws IOException { // Element volume = new Element("volume"); // volume.addContent(new Element("name").setText(clonedDiskName)); // volume.addContent(new Element("allocation").setText("0")); // volume.addContent(new Element("capacity").setText("" + backingDisk.getInfo().capacity)); // Element target = new Element("target"); // volume.addContent(target); // target.addContent(new Element("format").setAttribute("type", backingDisk.format)); // target.addContent(new Element("compat").setText("1.1")); // Element backingStore = new Element("backingStore"); // volume.addContent(backingStore); // backingStore.addContent(new Element("path").setText(backingDisk.file)); // backingStore.addContent(new Element("format").setAttribute("type", backingDisk.format)); // // return JDomUtil.elementToString(volume); // } // } // // Path: src/main/java/com/xebialabs/overcast/Preconditions.java // public static void checkNotNull(Object reference) { // if (reference == null) { // throw new NullPointerException(); // } // } // // Path: src/main/java/com/xebialabs/overcast/Preconditions.java // public static void checkNotNullOrEmpty(String s) { // if (isNullOrEmpty(s)) { // throw new NullPointerException(); // } // }
import java.io.IOException; import org.libvirt.LibvirtException; import org.libvirt.StoragePool; import org.libvirt.StorageVol; import org.libvirt.StorageVolInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.xebialabs.overcast.support.libvirt.jdom.DiskXml; import static com.xebialabs.overcast.Preconditions.checkNotNull; import static com.xebialabs.overcast.Preconditions.checkNotNullOrEmpty;
try { return volume.getName(); } catch (LibvirtException e) { throw new LibvirtRuntimeException(e); } } public String getBaseName() { String name = getName(); int idx = name.lastIndexOf('.'); if (idx == -1) { return name; } return name.substring(0, idx); } public StorageVol getVolume() { return volume; } public StoragePool getStoragePool() { try { return volume.storagePoolLookupByVolume(); } catch (LibvirtException e) { throw new LibvirtRuntimeException(e); } } public StorageVol createCloneWithBackingStore(String name) { try {
// Path: src/main/java/com/xebialabs/overcast/support/libvirt/jdom/DiskXml.java // public final class DiskXml { // private static final String XPATH_DISK_DEV = "//target/@dev"; // private static final String XPATH_DISK_FILE = "//source/@file"; // private static final String XPATH_DISK_TYPE = "//driver[@name='qemu']/@type"; // private static final String XPATH_DISK = "/domain/devices/disk[@device='disk']"; // // private DiskXml() { // } // // /** // * update the disks in the domain XML. It is assumed that the the size of the volumes is the same as the number of // * disk elements and that the order is the same. // */ // public static void updateDisks(Document domainXml, List<StorageVol> volumes) throws LibvirtException { // XPathFactory xpf = XPathFactory.instance(); // XPathExpression<Element> diskExpr = xpf.compile(XPATH_DISK, Filters.element()); // XPathExpression<Attribute> fileExpr = xpf.compile(XPATH_DISK_FILE, Filters.attribute()); // List<Element> disks = diskExpr.evaluate(domainXml); // Iterator<StorageVol> cloneDiskIter = volumes.iterator(); // for (Element disk : disks) { // Attribute file = fileExpr.evaluateFirst(disk); // StorageVol cloneDisk = cloneDiskIter.next(); // file.setValue(cloneDisk.getPath()); // } // } // // /** Get the disks connected to the domain. */ // public static List<Disk> getDisks(Connect connect, Document domainXml) { // try { // List<Disk> ret = new ArrayList<>(); // XPathFactory xpf = XPathFactory.instance(); // XPathExpression<Element> diskExpr = xpf.compile(XPATH_DISK, Filters.element()); // XPathExpression<Attribute> typeExpr = xpf.compile(XPATH_DISK_TYPE, Filters.attribute()); // XPathExpression<Attribute> fileExpr = xpf.compile(XPATH_DISK_FILE, Filters.attribute()); // XPathExpression<Attribute> devExpr = xpf.compile(XPATH_DISK_DEV, Filters.attribute()); // List<Element> disks = diskExpr.evaluate(domainXml); // for (Element disk : disks) { // Attribute type = typeExpr.evaluateFirst(disk); // Attribute file = fileExpr.evaluateFirst(disk); // Attribute dev = devExpr.evaluateFirst(disk); // // StorageVol volume = LibvirtUtil.findVolume(connect, file.getValue()); // // ret.add(new Disk(dev.getValue(), file.getValue(), volume, type.getValue())); // } // return ret; // } catch (LibvirtException e) { // throw new LibvirtRuntimeException(e); // } // } // // public static String cloneVolumeXml(Disk backingDisk, String clonedDiskName) throws IOException { // Element volume = new Element("volume"); // volume.addContent(new Element("name").setText(clonedDiskName)); // volume.addContent(new Element("allocation").setText("0")); // volume.addContent(new Element("capacity").setText("" + backingDisk.getInfo().capacity)); // Element target = new Element("target"); // volume.addContent(target); // target.addContent(new Element("format").setAttribute("type", backingDisk.format)); // target.addContent(new Element("compat").setText("1.1")); // Element backingStore = new Element("backingStore"); // volume.addContent(backingStore); // backingStore.addContent(new Element("path").setText(backingDisk.file)); // backingStore.addContent(new Element("format").setAttribute("type", backingDisk.format)); // // return JDomUtil.elementToString(volume); // } // } // // Path: src/main/java/com/xebialabs/overcast/Preconditions.java // public static void checkNotNull(Object reference) { // if (reference == null) { // throw new NullPointerException(); // } // } // // Path: src/main/java/com/xebialabs/overcast/Preconditions.java // public static void checkNotNullOrEmpty(String s) { // if (isNullOrEmpty(s)) { // throw new NullPointerException(); // } // } // Path: src/main/java/com/xebialabs/overcast/support/libvirt/Disk.java import java.io.IOException; import org.libvirt.LibvirtException; import org.libvirt.StoragePool; import org.libvirt.StorageVol; import org.libvirt.StorageVolInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.xebialabs.overcast.support.libvirt.jdom.DiskXml; import static com.xebialabs.overcast.Preconditions.checkNotNull; import static com.xebialabs.overcast.Preconditions.checkNotNullOrEmpty; try { return volume.getName(); } catch (LibvirtException e) { throw new LibvirtRuntimeException(e); } } public String getBaseName() { String name = getName(); int idx = name.lastIndexOf('.'); if (idx == -1) { return name; } return name.substring(0, idx); } public StorageVol getVolume() { return volume; } public StoragePool getStoragePool() { try { return volume.storagePoolLookupByVolume(); } catch (LibvirtException e) { throw new LibvirtRuntimeException(e); } } public StorageVol createCloneWithBackingStore(String name) { try {
String volumeXml = DiskXml.cloneVolumeXml(this, name);
xebialabs/overcast
src/main/java/com/xebialabs/overcast/OvercastProperties.java
// Path: src/main/java/com/xebialabs/overcast/Preconditions.java // public static void checkArgument( // boolean expression, // String errorMessageTemplate, // Object... errorMessageArgs) { // if (!expression) { // throw new IllegalArgumentException(String.format(errorMessageTemplate, errorMessageArgs)); // } // } // // Path: src/main/java/com/xebialabs/overcast/Preconditions.java // public static void checkState( // boolean expression, // String errorMessageTemplate, // Object... errorMessageArgs) { // if (!expression) { // throw new IllegalStateException(String.format(errorMessageTemplate, errorMessageArgs)); // } // }
import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import com.typesafe.config.ConfigUtil; import com.typesafe.config.ConfigValue; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import static com.xebialabs.overcast.Preconditions.checkArgument; import static com.xebialabs.overcast.Preconditions.checkState;
/** * Copyright 2012-2021 Digital.ai * * 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.xebialabs.overcast; /** * Methods to load and access the {@code overcast.conf} file. */ public class OvercastProperties { public static final String PASSWORD_PROPERTY_SUFFIX = ".password"; private static final Logger logger = LoggerFactory.getLogger(OvercastProperties.class); private static Config overcastProperties; private static Config getOvercastConfig() { if (overcastProperties == null) { overcastProperties = PropertiesLoader.loadOvercastConfig(); } return overcastProperties; } public static void reloadOvercastProperties() { ConfigFactory.invalidateCaches(); overcastProperties = null; } /** Get set of property names directly below path. */ public static Set<String> getOvercastPropertyNames(final String path) { Config overcastConfig = getOvercastConfig(); if (!overcastConfig.hasPath(path)) { return new HashSet<>(); } Config cfg = overcastConfig.getConfig(path); Set<String> result = new HashSet<>(); for (Map.Entry<String, ConfigValue> e : cfg.entrySet()) { result.add(ConfigUtil.splitPath(e.getKey()).get(0)); } return result; } public static String getOvercastProperty(String key) { return getOvercastProperty(key, null); } public static String getOvercastProperty(String key, String defaultValue) { String value; Config overcastConfig = getOvercastConfig(); if (overcastConfig.hasPath(key)) { value = overcastConfig.getString(key); } else { value = defaultValue; } if (logger.isTraceEnabled()) { if (value == null) { logger.trace("Overcast property {} is null", key); } else { logger.trace("Overcast property {}={}", key, key.endsWith(PASSWORD_PROPERTY_SUFFIX) ? "********" : value); } } return value; } public static boolean getOvercastBooleanProperty(String key) { return getOvercastBooleanProperty(key, false); } public static boolean getOvercastBooleanProperty(String key, boolean defaultValue) { boolean value; Config overcastConfig = getOvercastConfig(); if (overcastConfig.hasPath(key)) { value = overcastConfig.getBoolean(key); } else { value = defaultValue; } if (logger.isTraceEnabled()) { logger.trace("Overcast property {}={}", key, key.endsWith(PASSWORD_PROPERTY_SUFFIX) ? "********" : value); } return value; } public static List<String> getOvercastListProperty(String key) { return getOvercastListProperty(key, new ArrayList<String>()); } public static List<String> getOvercastListProperty(String key, List<String> defaultValue) { List<String> value; Config overcastConfig = getOvercastConfig(); if (overcastConfig.hasPath(key)) { value = overcastConfig.getStringList(key); } else { value = defaultValue; } if (logger.isTraceEnabled()) { if (value == null) { logger.trace("Overcast property {} is null", key); } else { logger.trace("Overcast property {}={}", key, key.endsWith(PASSWORD_PROPERTY_SUFFIX) ? "********" : value); } } return value; } public static Map<String, String> getOvercastMapProperty(String key) { return getOvercastMapProperty(key, new LinkedHashMap<>()); } public static Map<String, String> getOvercastMapProperty(String key, Map<String, String> defaultValue) { Map<String, String> value; Config overcastConfig = getOvercastConfig(); if (overcastConfig.hasPath(key)) { value = new LinkedHashMap<>(); for( Map.Entry<String, ConfigValue> element : overcastConfig.getConfig(key).entrySet()) { value.put(element.getKey(), element.getValue().unwrapped().toString()); } } else { value = defaultValue; } if (logger.isTraceEnabled()) { if (value == null) { logger.trace("Overcast property {} is null", key); } else { logger.trace("Overcast property {}={}", key, key.endsWith(PASSWORD_PROPERTY_SUFFIX) ? "********" : value); } } return value; } public static String getRequiredOvercastProperty(String key) { String value = getOvercastProperty(key);
// Path: src/main/java/com/xebialabs/overcast/Preconditions.java // public static void checkArgument( // boolean expression, // String errorMessageTemplate, // Object... errorMessageArgs) { // if (!expression) { // throw new IllegalArgumentException(String.format(errorMessageTemplate, errorMessageArgs)); // } // } // // Path: src/main/java/com/xebialabs/overcast/Preconditions.java // public static void checkState( // boolean expression, // String errorMessageTemplate, // Object... errorMessageArgs) { // if (!expression) { // throw new IllegalStateException(String.format(errorMessageTemplate, errorMessageArgs)); // } // } // Path: src/main/java/com/xebialabs/overcast/OvercastProperties.java import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import com.typesafe.config.ConfigUtil; import com.typesafe.config.ConfigValue; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import static com.xebialabs.overcast.Preconditions.checkArgument; import static com.xebialabs.overcast.Preconditions.checkState; /** * Copyright 2012-2021 Digital.ai * * 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.xebialabs.overcast; /** * Methods to load and access the {@code overcast.conf} file. */ public class OvercastProperties { public static final String PASSWORD_PROPERTY_SUFFIX = ".password"; private static final Logger logger = LoggerFactory.getLogger(OvercastProperties.class); private static Config overcastProperties; private static Config getOvercastConfig() { if (overcastProperties == null) { overcastProperties = PropertiesLoader.loadOvercastConfig(); } return overcastProperties; } public static void reloadOvercastProperties() { ConfigFactory.invalidateCaches(); overcastProperties = null; } /** Get set of property names directly below path. */ public static Set<String> getOvercastPropertyNames(final String path) { Config overcastConfig = getOvercastConfig(); if (!overcastConfig.hasPath(path)) { return new HashSet<>(); } Config cfg = overcastConfig.getConfig(path); Set<String> result = new HashSet<>(); for (Map.Entry<String, ConfigValue> e : cfg.entrySet()) { result.add(ConfigUtil.splitPath(e.getKey()).get(0)); } return result; } public static String getOvercastProperty(String key) { return getOvercastProperty(key, null); } public static String getOvercastProperty(String key, String defaultValue) { String value; Config overcastConfig = getOvercastConfig(); if (overcastConfig.hasPath(key)) { value = overcastConfig.getString(key); } else { value = defaultValue; } if (logger.isTraceEnabled()) { if (value == null) { logger.trace("Overcast property {} is null", key); } else { logger.trace("Overcast property {}={}", key, key.endsWith(PASSWORD_PROPERTY_SUFFIX) ? "********" : value); } } return value; } public static boolean getOvercastBooleanProperty(String key) { return getOvercastBooleanProperty(key, false); } public static boolean getOvercastBooleanProperty(String key, boolean defaultValue) { boolean value; Config overcastConfig = getOvercastConfig(); if (overcastConfig.hasPath(key)) { value = overcastConfig.getBoolean(key); } else { value = defaultValue; } if (logger.isTraceEnabled()) { logger.trace("Overcast property {}={}", key, key.endsWith(PASSWORD_PROPERTY_SUFFIX) ? "********" : value); } return value; } public static List<String> getOvercastListProperty(String key) { return getOvercastListProperty(key, new ArrayList<String>()); } public static List<String> getOvercastListProperty(String key, List<String> defaultValue) { List<String> value; Config overcastConfig = getOvercastConfig(); if (overcastConfig.hasPath(key)) { value = overcastConfig.getStringList(key); } else { value = defaultValue; } if (logger.isTraceEnabled()) { if (value == null) { logger.trace("Overcast property {} is null", key); } else { logger.trace("Overcast property {}={}", key, key.endsWith(PASSWORD_PROPERTY_SUFFIX) ? "********" : value); } } return value; } public static Map<String, String> getOvercastMapProperty(String key) { return getOvercastMapProperty(key, new LinkedHashMap<>()); } public static Map<String, String> getOvercastMapProperty(String key, Map<String, String> defaultValue) { Map<String, String> value; Config overcastConfig = getOvercastConfig(); if (overcastConfig.hasPath(key)) { value = new LinkedHashMap<>(); for( Map.Entry<String, ConfigValue> element : overcastConfig.getConfig(key).entrySet()) { value.put(element.getKey(), element.getValue().unwrapped().toString()); } } else { value = defaultValue; } if (logger.isTraceEnabled()) { if (value == null) { logger.trace("Overcast property {} is null", key); } else { logger.trace("Overcast property {}={}", key, key.endsWith(PASSWORD_PROPERTY_SUFFIX) ? "********" : value); } } return value; } public static String getRequiredOvercastProperty(String key) { String value = getOvercastProperty(key);
checkState(value != null, "Required property %s is not specified as a system property or in " + PropertiesLoader.OVERCAST_CONF_FILE
xebialabs/overcast
src/main/java/com/xebialabs/overcast/support/virtualbox/VirtualboxDriver.java
// Path: src/main/java/com/xebialabs/overcast/command/CommandProcessor.java // public class CommandProcessor { // // public static Logger logger = LoggerFactory.getLogger(CommandProcessor.class); // // private String execDir = "."; // // private CommandProcessor(final String execDir) { // this.execDir = execDir; // } // // private CommandProcessor() {} // // public static CommandProcessor atLocation(String l) { // return new CommandProcessor(l); // } // // public static CommandProcessor atCurrentDir() { // return new CommandProcessor(); // } // // public CommandResponse run(final Command command) { // // logger.debug("Executing command {}", command); // // try { // Process p = new ProcessBuilder(command.asList()).directory(new File(execDir)).start(); // // // We do this small trick to have stdout and stderr of the process on the console and // // at the same time capture them to strings. // ByteArrayOutputStream errors = new ByteArrayOutputStream(); // ByteArrayOutputStream messages = new ByteArrayOutputStream(); // // Thread t1 = showProcessOutput(new TeeInputStream(p.getErrorStream(), errors), System.err); // Thread t2 = showProcessOutput(new TeeInputStream(p.getInputStream(), messages), System.out); // // int code = p.waitFor(); // // t1.join(); // t2.join(); // // CommandResponse response = new CommandResponse(code, errors.toString(), messages.toString()); // // if (!response.isSuccessful()) { // throw new NonZeroCodeException(command, response); // } // // return response; // // } catch (InterruptedException e) { // Thread.currentThread().interrupt(); // throw new RuntimeException("Cannot execute " + command.toString(), e); // } catch (IOException e) { // throw new RuntimeException("Cannot execute " + command.toString(), e); // } // } // // private Thread showProcessOutput(final InputStream from, final PrintStream to) { // Thread t = new Thread(() -> { // try { // for (; ; ) { // int c = from.read(); // if (c == -1) // break; // to.write((char) c); // } // } catch (IOException ignore) { // } // }); // t.start(); // return t; // } // // } // // Path: src/main/java/com/xebialabs/overcast/command/Command.java // public static Command aCommand(String executable) { // if (executable == null) { // throw new IllegalArgumentException("Executable can not be null"); // } // Command c = new Command(); // c.withPart(executable); // return c; // }
import com.xebialabs.overcast.command.CommandProcessor; import java.util.EnumSet; import static com.xebialabs.overcast.command.Command.aCommand; import static com.xebialabs.overcast.support.virtualbox.VirtualboxState.POWEROFF; import static com.xebialabs.overcast.support.virtualbox.VirtualboxState.SAVED;
String[] lines = execute("snapshot", vm, "list", "--machinereadable").split("\n"); for (String line : lines) { if (!line.isEmpty()) { String[] parts = line.split("="); if (parts[0].equals("CurrentSnapshotUUID")) { quotedId = parts[1]; } } } if (quotedId != null) { loadSnapshot(vm, quotedId.substring(1, quotedId.length() - 1)); } } /** * Shuts down VM. */ public void powerOff(final String vm) { execute("controlvm", vm, "poweroff"); } public void start(String vm) { execute("startvm", vm, "--type", "headless"); } /** * Executes custom VBoxManage command */ public String execute(String... command) {
// Path: src/main/java/com/xebialabs/overcast/command/CommandProcessor.java // public class CommandProcessor { // // public static Logger logger = LoggerFactory.getLogger(CommandProcessor.class); // // private String execDir = "."; // // private CommandProcessor(final String execDir) { // this.execDir = execDir; // } // // private CommandProcessor() {} // // public static CommandProcessor atLocation(String l) { // return new CommandProcessor(l); // } // // public static CommandProcessor atCurrentDir() { // return new CommandProcessor(); // } // // public CommandResponse run(final Command command) { // // logger.debug("Executing command {}", command); // // try { // Process p = new ProcessBuilder(command.asList()).directory(new File(execDir)).start(); // // // We do this small trick to have stdout and stderr of the process on the console and // // at the same time capture them to strings. // ByteArrayOutputStream errors = new ByteArrayOutputStream(); // ByteArrayOutputStream messages = new ByteArrayOutputStream(); // // Thread t1 = showProcessOutput(new TeeInputStream(p.getErrorStream(), errors), System.err); // Thread t2 = showProcessOutput(new TeeInputStream(p.getInputStream(), messages), System.out); // // int code = p.waitFor(); // // t1.join(); // t2.join(); // // CommandResponse response = new CommandResponse(code, errors.toString(), messages.toString()); // // if (!response.isSuccessful()) { // throw new NonZeroCodeException(command, response); // } // // return response; // // } catch (InterruptedException e) { // Thread.currentThread().interrupt(); // throw new RuntimeException("Cannot execute " + command.toString(), e); // } catch (IOException e) { // throw new RuntimeException("Cannot execute " + command.toString(), e); // } // } // // private Thread showProcessOutput(final InputStream from, final PrintStream to) { // Thread t = new Thread(() -> { // try { // for (; ; ) { // int c = from.read(); // if (c == -1) // break; // to.write((char) c); // } // } catch (IOException ignore) { // } // }); // t.start(); // return t; // } // // } // // Path: src/main/java/com/xebialabs/overcast/command/Command.java // public static Command aCommand(String executable) { // if (executable == null) { // throw new IllegalArgumentException("Executable can not be null"); // } // Command c = new Command(); // c.withPart(executable); // return c; // } // Path: src/main/java/com/xebialabs/overcast/support/virtualbox/VirtualboxDriver.java import com.xebialabs.overcast.command.CommandProcessor; import java.util.EnumSet; import static com.xebialabs.overcast.command.Command.aCommand; import static com.xebialabs.overcast.support.virtualbox.VirtualboxState.POWEROFF; import static com.xebialabs.overcast.support.virtualbox.VirtualboxState.SAVED; String[] lines = execute("snapshot", vm, "list", "--machinereadable").split("\n"); for (String line : lines) { if (!line.isEmpty()) { String[] parts = line.split("="); if (parts[0].equals("CurrentSnapshotUUID")) { quotedId = parts[1]; } } } if (quotedId != null) { loadSnapshot(vm, quotedId.substring(1, quotedId.length() - 1)); } } /** * Shuts down VM. */ public void powerOff(final String vm) { execute("controlvm", vm, "poweroff"); } public void start(String vm) { execute("startvm", vm, "--type", "headless"); } /** * Executes custom VBoxManage command */ public String execute(String... command) {
return commandProcessor.run(aCommand("VBoxManage").withArguments(command)).getOutput();
idega/is.idega.idegaweb.egov.cases
src/java/is/idega/idegaweb/egov/cases/business/CaseHandlerCollectionHandler.java
// Path: src/java/is/idega/idegaweb/egov/cases/data/CaseCategory.java // public interface CaseCategory extends IDOEntity { // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#getName // */ // public String getName(); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#getDescription // */ // public String getDescription(); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#getHandlerGroup // */ // public Group getHandlerGroup(); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#getOrder // */ // public int getOrder(); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#getParent // */ // public CaseCategory getParent(); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#setName // */ // public void setName(String name); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#setDescription // */ // public void setDescription(String description); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#setHandlerGroup // */ // public void setHandlerGroup(Group group); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#setHandlerGroup // */ // public void setHandlerGroup(Object groupPK); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#setOrder // */ // public void setOrder(int order); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#setParent // */ // public void setParent(CaseCategory category); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#getLocalizedCategoryName // */ // public String getLocalizedCategoryName(Locale locale); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#getLocalizedCategoryDescription // */ // public String getLocalizedCategoryDescription(Locale locale); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#addLocalization // */ // public void addLocalization(LocalizedText localizedText) throws SQLException; // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#getLocalizedText // */ // public LocalizedText getLocalizedText(int icLocaleId); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#getLocalizedText // */ // public LocalizedText getLocalizedText(Locale locale); // }
import is.idega.idegaweb.egov.cases.data.CaseCategory; import java.rmi.RemoteException; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import javax.ejb.FinderException; import com.idega.business.IBOLookup; import com.idega.business.IBOLookupException; import com.idega.business.IBORuntimeException; import com.idega.idegaweb.IWApplicationContext; import com.idega.presentation.IWContext; import com.idega.presentation.remotescripting.RemoteScriptCollection; import com.idega.presentation.remotescripting.RemoteScriptHandler; import com.idega.presentation.remotescripting.RemoteScriptingResults; import com.idega.user.business.UserBusiness; import com.idega.user.data.Group; import com.idega.user.data.User;
/* * $Id$ * Created on Oct 18, 2006 * * Copyright (C) 2006 Idega Software hf. All Rights Reserved. * * This software is the proprietary information of Idega hf. * Use is subject to license terms. */ package is.idega.idegaweb.egov.cases.business; public class CaseHandlerCollectionHandler implements RemoteScriptCollection { public RemoteScriptingResults getResults(IWContext iwc) { String sourceName = iwc.getParameter(RemoteScriptHandler.PARAMETER_SOURCE_PARAMETER_NAME); String sourceID = iwc.getParameter(sourceName); Collection ids = new ArrayList(); Collection names = new ArrayList(); try {
// Path: src/java/is/idega/idegaweb/egov/cases/data/CaseCategory.java // public interface CaseCategory extends IDOEntity { // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#getName // */ // public String getName(); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#getDescription // */ // public String getDescription(); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#getHandlerGroup // */ // public Group getHandlerGroup(); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#getOrder // */ // public int getOrder(); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#getParent // */ // public CaseCategory getParent(); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#setName // */ // public void setName(String name); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#setDescription // */ // public void setDescription(String description); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#setHandlerGroup // */ // public void setHandlerGroup(Group group); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#setHandlerGroup // */ // public void setHandlerGroup(Object groupPK); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#setOrder // */ // public void setOrder(int order); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#setParent // */ // public void setParent(CaseCategory category); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#getLocalizedCategoryName // */ // public String getLocalizedCategoryName(Locale locale); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#getLocalizedCategoryDescription // */ // public String getLocalizedCategoryDescription(Locale locale); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#addLocalization // */ // public void addLocalization(LocalizedText localizedText) throws SQLException; // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#getLocalizedText // */ // public LocalizedText getLocalizedText(int icLocaleId); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#getLocalizedText // */ // public LocalizedText getLocalizedText(Locale locale); // } // Path: src/java/is/idega/idegaweb/egov/cases/business/CaseHandlerCollectionHandler.java import is.idega.idegaweb.egov.cases.data.CaseCategory; import java.rmi.RemoteException; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import javax.ejb.FinderException; import com.idega.business.IBOLookup; import com.idega.business.IBOLookupException; import com.idega.business.IBORuntimeException; import com.idega.idegaweb.IWApplicationContext; import com.idega.presentation.IWContext; import com.idega.presentation.remotescripting.RemoteScriptCollection; import com.idega.presentation.remotescripting.RemoteScriptHandler; import com.idega.presentation.remotescripting.RemoteScriptingResults; import com.idega.user.business.UserBusiness; import com.idega.user.data.Group; import com.idega.user.data.User; /* * $Id$ * Created on Oct 18, 2006 * * Copyright (C) 2006 Idega Software hf. All Rights Reserved. * * This software is the proprietary information of Idega hf. * Use is subject to license terms. */ package is.idega.idegaweb.egov.cases.business; public class CaseHandlerCollectionHandler implements RemoteScriptCollection { public RemoteScriptingResults getResults(IWContext iwc) { String sourceName = iwc.getParameter(RemoteScriptHandler.PARAMETER_SOURCE_PARAMETER_NAME); String sourceID = iwc.getParameter(sourceName); Collection ids = new ArrayList(); Collection names = new ArrayList(); try {
CaseCategory category = getBusiness(iwc).getCaseCategory(sourceID);
idega/is.idega.idegaweb.egov.cases
src/java/is/idega/idegaweb/egov/cases/presentation/CaseCategoryEditor.java
// Path: src/java/is/idega/idegaweb/egov/cases/data/CaseCategory.java // public interface CaseCategory extends IDOEntity { // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#getName // */ // public String getName(); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#getDescription // */ // public String getDescription(); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#getHandlerGroup // */ // public Group getHandlerGroup(); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#getOrder // */ // public int getOrder(); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#getParent // */ // public CaseCategory getParent(); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#setName // */ // public void setName(String name); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#setDescription // */ // public void setDescription(String description); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#setHandlerGroup // */ // public void setHandlerGroup(Group group); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#setHandlerGroup // */ // public void setHandlerGroup(Object groupPK); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#setOrder // */ // public void setOrder(int order); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#setParent // */ // public void setParent(CaseCategory category); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#getLocalizedCategoryName // */ // public String getLocalizedCategoryName(Locale locale); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#getLocalizedCategoryDescription // */ // public String getLocalizedCategoryDescription(Locale locale); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#addLocalization // */ // public void addLocalization(LocalizedText localizedText) throws SQLException; // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#getLocalizedText // */ // public LocalizedText getLocalizedText(int icLocaleId); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#getLocalizedText // */ // public LocalizedText getLocalizedText(Locale locale); // }
import is.idega.idegaweb.egov.cases.data.CaseCategory; import java.rmi.RemoteException; import java.util.Collection; import java.util.Iterator; import java.util.Locale; import java.util.Map; import javax.ejb.CreateException; import javax.ejb.FinderException; import javax.ejb.RemoveException; import com.idega.block.text.business.TextFinder; import com.idega.core.localisation.business.ICLocaleBusiness; import com.idega.core.localisation.presentation.ICLocalePresentation; import com.idega.presentation.IWContext; import com.idega.presentation.Layer; import com.idega.presentation.Table2; import com.idega.presentation.TableCell2; import com.idega.presentation.TableColumn; import com.idega.presentation.TableColumnGroup; import com.idega.presentation.TableRow; import com.idega.presentation.TableRowGroup; import com.idega.presentation.text.Link; import com.idega.presentation.text.Text; import com.idega.presentation.ui.DropdownMenu; import com.idega.presentation.ui.Form; import com.idega.presentation.ui.HiddenInput; import com.idega.presentation.ui.Label; import com.idega.presentation.ui.SelectOption; import com.idega.presentation.ui.SubmitButton; import com.idega.presentation.ui.TextArea; import com.idega.presentation.ui.TextInput; import com.idega.user.data.Group; import com.idega.user.presentation.GroupChooser; import com.idega.util.PresentationUtil;
cell.setStyleClass("name"); cell.add(new Text(getResourceBundle().getLocalizedString("name", "Name"))); cell = row.createHeaderCell(); cell.setStyleClass("description"); cell.add(new Text(getResourceBundle().getLocalizedString("description", "Description"))); cell = row.createHeaderCell(); cell.setStyleClass("handlerGroup"); cell.add(new Text(getResourceBundle().getLocalizedString("handler_group", "Handler group"))); cell = row.createHeaderCell(); cell.setStyleClass("order"); cell.add(new Text(getResourceBundle().getLocalizedString("order", "Order"))); cell = row.createHeaderCell(); cell.setStyleClass("edit"); cell.add(new Text(getResourceBundle().getLocalizedString("edit", "Edit"))); cell = row.createHeaderCell(); cell.setStyleClass("lastColumn"); cell.setStyleClass("delete"); cell.add(new Text(getResourceBundle().getLocalizedString("delete", "Delete"))); group = table.createBodyRowGroup(); int iRow = 1; Iterator iter = categories.iterator(); while (iter.hasNext()) {
// Path: src/java/is/idega/idegaweb/egov/cases/data/CaseCategory.java // public interface CaseCategory extends IDOEntity { // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#getName // */ // public String getName(); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#getDescription // */ // public String getDescription(); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#getHandlerGroup // */ // public Group getHandlerGroup(); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#getOrder // */ // public int getOrder(); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#getParent // */ // public CaseCategory getParent(); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#setName // */ // public void setName(String name); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#setDescription // */ // public void setDescription(String description); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#setHandlerGroup // */ // public void setHandlerGroup(Group group); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#setHandlerGroup // */ // public void setHandlerGroup(Object groupPK); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#setOrder // */ // public void setOrder(int order); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#setParent // */ // public void setParent(CaseCategory category); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#getLocalizedCategoryName // */ // public String getLocalizedCategoryName(Locale locale); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#getLocalizedCategoryDescription // */ // public String getLocalizedCategoryDescription(Locale locale); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#addLocalization // */ // public void addLocalization(LocalizedText localizedText) throws SQLException; // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#getLocalizedText // */ // public LocalizedText getLocalizedText(int icLocaleId); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseCategoryBMPBean#getLocalizedText // */ // public LocalizedText getLocalizedText(Locale locale); // } // Path: src/java/is/idega/idegaweb/egov/cases/presentation/CaseCategoryEditor.java import is.idega.idegaweb.egov.cases.data.CaseCategory; import java.rmi.RemoteException; import java.util.Collection; import java.util.Iterator; import java.util.Locale; import java.util.Map; import javax.ejb.CreateException; import javax.ejb.FinderException; import javax.ejb.RemoveException; import com.idega.block.text.business.TextFinder; import com.idega.core.localisation.business.ICLocaleBusiness; import com.idega.core.localisation.presentation.ICLocalePresentation; import com.idega.presentation.IWContext; import com.idega.presentation.Layer; import com.idega.presentation.Table2; import com.idega.presentation.TableCell2; import com.idega.presentation.TableColumn; import com.idega.presentation.TableColumnGroup; import com.idega.presentation.TableRow; import com.idega.presentation.TableRowGroup; import com.idega.presentation.text.Link; import com.idega.presentation.text.Text; import com.idega.presentation.ui.DropdownMenu; import com.idega.presentation.ui.Form; import com.idega.presentation.ui.HiddenInput; import com.idega.presentation.ui.Label; import com.idega.presentation.ui.SelectOption; import com.idega.presentation.ui.SubmitButton; import com.idega.presentation.ui.TextArea; import com.idega.presentation.ui.TextInput; import com.idega.user.data.Group; import com.idega.user.presentation.GroupChooser; import com.idega.util.PresentationUtil; cell.setStyleClass("name"); cell.add(new Text(getResourceBundle().getLocalizedString("name", "Name"))); cell = row.createHeaderCell(); cell.setStyleClass("description"); cell.add(new Text(getResourceBundle().getLocalizedString("description", "Description"))); cell = row.createHeaderCell(); cell.setStyleClass("handlerGroup"); cell.add(new Text(getResourceBundle().getLocalizedString("handler_group", "Handler group"))); cell = row.createHeaderCell(); cell.setStyleClass("order"); cell.add(new Text(getResourceBundle().getLocalizedString("order", "Order"))); cell = row.createHeaderCell(); cell.setStyleClass("edit"); cell.add(new Text(getResourceBundle().getLocalizedString("edit", "Edit"))); cell = row.createHeaderCell(); cell.setStyleClass("lastColumn"); cell.setStyleClass("delete"); cell.add(new Text(getResourceBundle().getLocalizedString("delete", "Delete"))); group = table.createBodyRowGroup(); int iRow = 1; Iterator iter = categories.iterator(); while (iter.hasNext()) {
CaseCategory category = (CaseCategory) iter.next();
idega/is.idega.idegaweb.egov.cases
src/java/is/idega/idegaweb/egov/cases/presentation/CaseTypeEditor.java
// Path: src/java/is/idega/idegaweb/egov/cases/data/CaseType.java // public interface CaseType extends IDOEntity { // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseTypeBMPBean#getName // */ // public String getName(); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseTypeBMPBean#getDescription // */ // public String getDescription(); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseTypeBMPBean#getOrder // */ // public int getOrder(); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseTypeBMPBean#setName // */ // public void setName(String name); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseTypeBMPBean#setDescription // */ // public void setDescription(String description); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseTypeBMPBean#setOrder // */ // public void setOrder(int order); // }
import is.idega.idegaweb.egov.cases.data.CaseType; import java.rmi.RemoteException; import java.util.Collection; import java.util.Iterator; import java.util.Map; import javax.ejb.CreateException; import javax.ejb.FinderException; import javax.ejb.RemoveException; import com.idega.presentation.IWContext; import com.idega.presentation.Layer; import com.idega.presentation.Table2; import com.idega.presentation.TableCell2; import com.idega.presentation.TableColumn; import com.idega.presentation.TableColumnGroup; import com.idega.presentation.TableRow; import com.idega.presentation.TableRowGroup; import com.idega.presentation.text.Link; import com.idega.presentation.text.Text; import com.idega.presentation.ui.Form; import com.idega.presentation.ui.HiddenInput; import com.idega.presentation.ui.Label; import com.idega.presentation.ui.SubmitButton; import com.idega.presentation.ui.TextArea; import com.idega.presentation.ui.TextInput; import com.idega.util.PresentationUtil;
TableColumn column = columnGroup.createColumn(); column.setSpan(2); column = columnGroup.createColumn(); column.setSpan(2); Collection types = getCasesBusiness().getCaseTypes(); TableRowGroup group = table.createHeaderRowGroup(); TableRow row = group.createRow(); TableCell2 cell = row.createHeaderCell(); cell.setStyleClass("firstColumn"); cell.add(new Text(getResourceBundle().getLocalizedString("name", "Name"))); row.createHeaderCell().add(new Text(getResourceBundle().getLocalizedString("description", "Description"))); row.createHeaderCell().add(new Text(getResourceBundle().getLocalizedString("order", "Order"))); cell = row.createHeaderCell(); cell.setStyleClass("edit"); cell.add(new Text(getResourceBundle().getLocalizedString("edit", "Edit"))); cell = row.createHeaderCell(); cell.setStyleClass("lastColumn"); cell.setStyleClass("delete"); cell.add(new Text(getResourceBundle().getLocalizedString("delete", "Delete"))); group = table.createBodyRowGroup(); int iRow = 1; Iterator iter = types.iterator(); while (iter.hasNext()) {
// Path: src/java/is/idega/idegaweb/egov/cases/data/CaseType.java // public interface CaseType extends IDOEntity { // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseTypeBMPBean#getName // */ // public String getName(); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseTypeBMPBean#getDescription // */ // public String getDescription(); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseTypeBMPBean#getOrder // */ // public int getOrder(); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseTypeBMPBean#setName // */ // public void setName(String name); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseTypeBMPBean#setDescription // */ // public void setDescription(String description); // // /** // * @see is.idega.idegaweb.egov.cases.data.CaseTypeBMPBean#setOrder // */ // public void setOrder(int order); // } // Path: src/java/is/idega/idegaweb/egov/cases/presentation/CaseTypeEditor.java import is.idega.idegaweb.egov.cases.data.CaseType; import java.rmi.RemoteException; import java.util.Collection; import java.util.Iterator; import java.util.Map; import javax.ejb.CreateException; import javax.ejb.FinderException; import javax.ejb.RemoveException; import com.idega.presentation.IWContext; import com.idega.presentation.Layer; import com.idega.presentation.Table2; import com.idega.presentation.TableCell2; import com.idega.presentation.TableColumn; import com.idega.presentation.TableColumnGroup; import com.idega.presentation.TableRow; import com.idega.presentation.TableRowGroup; import com.idega.presentation.text.Link; import com.idega.presentation.text.Text; import com.idega.presentation.ui.Form; import com.idega.presentation.ui.HiddenInput; import com.idega.presentation.ui.Label; import com.idega.presentation.ui.SubmitButton; import com.idega.presentation.ui.TextArea; import com.idega.presentation.ui.TextInput; import com.idega.util.PresentationUtil; TableColumn column = columnGroup.createColumn(); column.setSpan(2); column = columnGroup.createColumn(); column.setSpan(2); Collection types = getCasesBusiness().getCaseTypes(); TableRowGroup group = table.createHeaderRowGroup(); TableRow row = group.createRow(); TableCell2 cell = row.createHeaderCell(); cell.setStyleClass("firstColumn"); cell.add(new Text(getResourceBundle().getLocalizedString("name", "Name"))); row.createHeaderCell().add(new Text(getResourceBundle().getLocalizedString("description", "Description"))); row.createHeaderCell().add(new Text(getResourceBundle().getLocalizedString("order", "Order"))); cell = row.createHeaderCell(); cell.setStyleClass("edit"); cell.add(new Text(getResourceBundle().getLocalizedString("edit", "Edit"))); cell = row.createHeaderCell(); cell.setStyleClass("lastColumn"); cell.setStyleClass("delete"); cell.add(new Text(getResourceBundle().getLocalizedString("delete", "Delete"))); group = table.createBodyRowGroup(); int iRow = 1; Iterator iter = types.iterator(); while (iter.hasNext()) {
CaseType type = (CaseType) iter.next();
idega/is.idega.idegaweb.egov.cases
src/java/is/idega/idegaweb/egov/cases/presentation/handlers/CasesListTypePropertyHandler.java
// Path: src/java/is/idega/idegaweb/egov/cases/util/CasesConstants.java // public class CasesConstants { // // public static final String IW_BUNDLE_IDENTIFIER = "is.idega.idegaweb.egov.cases"; // // public static final String CASE_CODE_KEY = "GENCASE"; // // public static final String ROLE_CASES_SUPER_ADMIN = "cases_super_admin"; // // public static final String PROPERTY_USE_SUB_CATEGORIES = "egov.cases.use.sub.categories"; // public static final String PROPERTY_USE_TYPES = "egov.cases.use.types"; // public static final String PROPERTY_ALLOW_PRIVATE_CASES = "egov.cases.allow.private.cases"; // public static final String PROPERTY_ALLOW_ANONYMOUS_CASES = "egov.cases.allow.anonymous.cases"; // public static final String PROPERTY_ALLOW_ATTACHMENTS = "egov.cases.allow.attachments"; // public static final String PROPERTY_WAIT_FOR_ALL_CASE_PARTS_LOADED = "wait_for_all_case_parts_loaded"; // // public static final String CASES_LIST_HELPER_JAVA_SCRIPT_FILE = "javascript/CasesListHelper.js"; // // public static final String GENERAL_CASES_TYPE = "generalCases"; // // public static final String CASES_LIST_GRID_EXPANDER_STYLE_CLASS = "casesListGridExpanderStyleClass", // // // APPLIED_GRANT_AMOUNT_VARIABLE = "string_ownerGrantAmount"; // }
import is.idega.idegaweb.egov.cases.util.CasesConstants; import java.util.List; import com.idega.block.process.business.CasesRetrievalManager; import com.idega.core.builder.presentation.ICPropertyHandler; import com.idega.idegaweb.IWResourceBundle; import com.idega.presentation.IWContext; import com.idega.presentation.PresentationObject; import com.idega.presentation.ui.DropdownMenu; import com.idega.presentation.ui.SelectOption;
package is.idega.idegaweb.egov.cases.presentation.handlers; public class CasesListTypePropertyHandler implements ICPropertyHandler { public List<?> getDefaultHandlerTypes() { return null; } public PresentationObject getHandlerObject(String name, String stringValue, IWContext iwc, boolean oldGenerationHandler, String instanceId, String method) { DropdownMenu caseListTypes = new DropdownMenu();
// Path: src/java/is/idega/idegaweb/egov/cases/util/CasesConstants.java // public class CasesConstants { // // public static final String IW_BUNDLE_IDENTIFIER = "is.idega.idegaweb.egov.cases"; // // public static final String CASE_CODE_KEY = "GENCASE"; // // public static final String ROLE_CASES_SUPER_ADMIN = "cases_super_admin"; // // public static final String PROPERTY_USE_SUB_CATEGORIES = "egov.cases.use.sub.categories"; // public static final String PROPERTY_USE_TYPES = "egov.cases.use.types"; // public static final String PROPERTY_ALLOW_PRIVATE_CASES = "egov.cases.allow.private.cases"; // public static final String PROPERTY_ALLOW_ANONYMOUS_CASES = "egov.cases.allow.anonymous.cases"; // public static final String PROPERTY_ALLOW_ATTACHMENTS = "egov.cases.allow.attachments"; // public static final String PROPERTY_WAIT_FOR_ALL_CASE_PARTS_LOADED = "wait_for_all_case_parts_loaded"; // // public static final String CASES_LIST_HELPER_JAVA_SCRIPT_FILE = "javascript/CasesListHelper.js"; // // public static final String GENERAL_CASES_TYPE = "generalCases"; // // public static final String CASES_LIST_GRID_EXPANDER_STYLE_CLASS = "casesListGridExpanderStyleClass", // // // APPLIED_GRANT_AMOUNT_VARIABLE = "string_ownerGrantAmount"; // } // Path: src/java/is/idega/idegaweb/egov/cases/presentation/handlers/CasesListTypePropertyHandler.java import is.idega.idegaweb.egov.cases.util.CasesConstants; import java.util.List; import com.idega.block.process.business.CasesRetrievalManager; import com.idega.core.builder.presentation.ICPropertyHandler; import com.idega.idegaweb.IWResourceBundle; import com.idega.presentation.IWContext; import com.idega.presentation.PresentationObject; import com.idega.presentation.ui.DropdownMenu; import com.idega.presentation.ui.SelectOption; package is.idega.idegaweb.egov.cases.presentation.handlers; public class CasesListTypePropertyHandler implements ICPropertyHandler { public List<?> getDefaultHandlerTypes() { return null; } public PresentationObject getHandlerObject(String name, String stringValue, IWContext iwc, boolean oldGenerationHandler, String instanceId, String method) { DropdownMenu caseListTypes = new DropdownMenu();
IWResourceBundle iwrb = iwc.getIWMainApplication().getBundle(CasesConstants.IW_BUNDLE_IDENTIFIER).getResourceBundle(iwc);
idega/is.idega.idegaweb.egov.cases
src/java/is/idega/idegaweb/egov/cases/data/GeneralCaseBMPBean.java
// Path: src/java/is/idega/idegaweb/egov/cases/util/CasesConstants.java // public class CasesConstants { // // public static final String IW_BUNDLE_IDENTIFIER = "is.idega.idegaweb.egov.cases"; // // public static final String CASE_CODE_KEY = "GENCASE"; // // public static final String ROLE_CASES_SUPER_ADMIN = "cases_super_admin"; // // public static final String PROPERTY_USE_SUB_CATEGORIES = "egov.cases.use.sub.categories"; // public static final String PROPERTY_USE_TYPES = "egov.cases.use.types"; // public static final String PROPERTY_ALLOW_PRIVATE_CASES = "egov.cases.allow.private.cases"; // public static final String PROPERTY_ALLOW_ANONYMOUS_CASES = "egov.cases.allow.anonymous.cases"; // public static final String PROPERTY_ALLOW_ATTACHMENTS = "egov.cases.allow.attachments"; // public static final String PROPERTY_WAIT_FOR_ALL_CASE_PARTS_LOADED = "wait_for_all_case_parts_loaded"; // // public static final String CASES_LIST_HELPER_JAVA_SCRIPT_FILE = "javascript/CasesListHelper.js"; // // public static final String GENERAL_CASES_TYPE = "generalCases"; // // public static final String CASES_LIST_GRID_EXPANDER_STYLE_CLASS = "casesListGridExpanderStyleClass", // // // APPLIED_GRANT_AMOUNT_VARIABLE = "string_ownerGrantAmount"; // }
import is.idega.idegaweb.egov.cases.util.CasesConstants; import java.sql.Date; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.logging.Level; import javax.ejb.FinderException; import com.idega.block.process.data.AbstractCaseBMPBean; import com.idega.block.process.data.Case; import com.idega.block.process.data.CaseBMPBean; import com.idega.block.process.data.CaseStatus; import com.idega.core.file.data.ICFile; import com.idega.data.IDOException; import com.idega.data.IDORelationshipException; import com.idega.data.query.BetweenCriteria; import com.idega.data.query.Column; import com.idega.data.query.CountColumn; import com.idega.data.query.InCriteria; import com.idega.data.query.MatchCriteria; import com.idega.data.query.Order; import com.idega.data.query.SelectQuery; import com.idega.data.query.Table; import com.idega.data.query.range.DateRange; import com.idega.user.data.Group; import com.idega.user.data.User; import com.idega.util.CoreUtil; import com.idega.util.IWTimestamp; import com.idega.util.ListUtil;
/* * $Id$ Created on Oct 30, 2005 * * Copyright (C) 2005 Idega Software hf. All Rights Reserved. * * This software is the proprietary information of Idega hf. Use is subject to license terms. */ package is.idega.idegaweb.egov.cases.data; public class GeneralCaseBMPBean extends AbstractCaseBMPBean implements Case, GeneralCase { private static final long serialVersionUID = 1213681239602561355L; private static final String ENTITY_NAME = "comm_case"; private static final String COLUMN_MESSAGE = "message"; private static final String COLUMN_REPLY = "reply"; private static final String COLUMN_CASE_CATEGORY = "case_category"; private static final String COLUMN_CASE_TYPE = "case_type"; private static final String COLUMN_FILE = "ic_file_id"; private static final String COLUMN_TYPE = "type"; private static final String COLUMN_HANDLER = "handler"; private static final String COLUMN_IS_PRIVATE = "is_private"; private static final String COLUMN_IS_ANONYMOUS = "is_anonymous"; private static final String COLUMN_PRIORITY = "priority"; private static final String COLUMN_TITLE = "title"; private static final String COLUMN_WANT_REPLY = "want_reply"; private static final String COLUMN_WANT_REPLY_EMAIL = "want_reply_email"; private static final String COLUMN_WANT_REPLY_PHONE = "want_reply_phone"; private static final String COLUMN_CASE_SUBSCRIBERS = ENTITY_NAME + "_subscribers"; private static final String COLUMN_REFERENCE = "reference"; /* * (non-Javadoc) * * @see com.idega.block.process.data.AbstractCaseBMPBean#getCaseCodeKey() */ @Override public String getCaseCodeKey() {
// Path: src/java/is/idega/idegaweb/egov/cases/util/CasesConstants.java // public class CasesConstants { // // public static final String IW_BUNDLE_IDENTIFIER = "is.idega.idegaweb.egov.cases"; // // public static final String CASE_CODE_KEY = "GENCASE"; // // public static final String ROLE_CASES_SUPER_ADMIN = "cases_super_admin"; // // public static final String PROPERTY_USE_SUB_CATEGORIES = "egov.cases.use.sub.categories"; // public static final String PROPERTY_USE_TYPES = "egov.cases.use.types"; // public static final String PROPERTY_ALLOW_PRIVATE_CASES = "egov.cases.allow.private.cases"; // public static final String PROPERTY_ALLOW_ANONYMOUS_CASES = "egov.cases.allow.anonymous.cases"; // public static final String PROPERTY_ALLOW_ATTACHMENTS = "egov.cases.allow.attachments"; // public static final String PROPERTY_WAIT_FOR_ALL_CASE_PARTS_LOADED = "wait_for_all_case_parts_loaded"; // // public static final String CASES_LIST_HELPER_JAVA_SCRIPT_FILE = "javascript/CasesListHelper.js"; // // public static final String GENERAL_CASES_TYPE = "generalCases"; // // public static final String CASES_LIST_GRID_EXPANDER_STYLE_CLASS = "casesListGridExpanderStyleClass", // // // APPLIED_GRANT_AMOUNT_VARIABLE = "string_ownerGrantAmount"; // } // Path: src/java/is/idega/idegaweb/egov/cases/data/GeneralCaseBMPBean.java import is.idega.idegaweb.egov.cases.util.CasesConstants; import java.sql.Date; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.logging.Level; import javax.ejb.FinderException; import com.idega.block.process.data.AbstractCaseBMPBean; import com.idega.block.process.data.Case; import com.idega.block.process.data.CaseBMPBean; import com.idega.block.process.data.CaseStatus; import com.idega.core.file.data.ICFile; import com.idega.data.IDOException; import com.idega.data.IDORelationshipException; import com.idega.data.query.BetweenCriteria; import com.idega.data.query.Column; import com.idega.data.query.CountColumn; import com.idega.data.query.InCriteria; import com.idega.data.query.MatchCriteria; import com.idega.data.query.Order; import com.idega.data.query.SelectQuery; import com.idega.data.query.Table; import com.idega.data.query.range.DateRange; import com.idega.user.data.Group; import com.idega.user.data.User; import com.idega.util.CoreUtil; import com.idega.util.IWTimestamp; import com.idega.util.ListUtil; /* * $Id$ Created on Oct 30, 2005 * * Copyright (C) 2005 Idega Software hf. All Rights Reserved. * * This software is the proprietary information of Idega hf. Use is subject to license terms. */ package is.idega.idegaweb.egov.cases.data; public class GeneralCaseBMPBean extends AbstractCaseBMPBean implements Case, GeneralCase { private static final long serialVersionUID = 1213681239602561355L; private static final String ENTITY_NAME = "comm_case"; private static final String COLUMN_MESSAGE = "message"; private static final String COLUMN_REPLY = "reply"; private static final String COLUMN_CASE_CATEGORY = "case_category"; private static final String COLUMN_CASE_TYPE = "case_type"; private static final String COLUMN_FILE = "ic_file_id"; private static final String COLUMN_TYPE = "type"; private static final String COLUMN_HANDLER = "handler"; private static final String COLUMN_IS_PRIVATE = "is_private"; private static final String COLUMN_IS_ANONYMOUS = "is_anonymous"; private static final String COLUMN_PRIORITY = "priority"; private static final String COLUMN_TITLE = "title"; private static final String COLUMN_WANT_REPLY = "want_reply"; private static final String COLUMN_WANT_REPLY_EMAIL = "want_reply_email"; private static final String COLUMN_WANT_REPLY_PHONE = "want_reply_phone"; private static final String COLUMN_CASE_SUBSCRIBERS = ENTITY_NAME + "_subscribers"; private static final String COLUMN_REFERENCE = "reference"; /* * (non-Javadoc) * * @see com.idega.block.process.data.AbstractCaseBMPBean#getCaseCodeKey() */ @Override public String getCaseCodeKey() {
return CasesConstants.CASE_CODE_KEY;
idega/is.idega.idegaweb.egov.cases
src/java/is/idega/idegaweb/egov/cases/business/CasesEngine.java
// Path: src/java/is/idega/idegaweb/egov/cases/bean/CasesExportParams.java // public class CasesExportParams implements Serializable { // // private static final long serialVersionUID = -4099540752887950292L; // // private Long processDefinitionId; // // private String id, status, dateFrom, dateTo; // // public Long getProcessDefinitionId() { // return processDefinitionId; // } // // public void setProcessDefinitionId(Long processDefinitionId) { // this.processDefinitionId = processDefinitionId; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getStatus() { // return status; // } // // public void setStatus(String status) { // this.status = status; // } // // public String getDateFrom() { // return dateFrom; // } // // public void setDateFrom(String dateFrom) { // this.dateFrom = dateFrom; // } // // public String getDateTo() { // return dateTo; // } // // public void setDateTo(String dateTo) { // this.dateTo = dateTo; // } // // @Override // public String toString() { // return "Proc. def. ID: " + getProcessDefinitionId() + ", ID: " + getId() + ", status: " + getStatus() + ", from: " + getDateFrom() + ", to: " + // getDateTo(); // } // // }
import is.idega.idegaweb.egov.cases.bean.CasesExportParams; import java.util.List; import org.jdom.Document; import com.idega.block.process.business.CasesRetrievalManager; import com.idega.block.process.presentation.beans.CasePresentation; import com.idega.block.process.presentation.beans.CasesSearchCriteriaBean; import com.idega.builder.bean.AdvancedProperty; import com.idega.core.business.DefaultSpringBean; import com.idega.presentation.IWContext; import com.idega.presentation.paging.PagedDataCollection; import com.idega.user.data.User;
package is.idega.idegaweb.egov.cases.business; public interface CasesEngine { public abstract boolean clearSearchResults(String id); public abstract AdvancedProperty getExportedSearchResults(String id); public abstract boolean setCaseSubject(String caseId, String subject); public abstract List<AdvancedProperty> getDefaultSortingOptions(IWContext iwc); public PagedDataCollection<CasePresentation> getCasesByQuery(CasesSearchCriteriaBean criteriaBean); public Document getRenderedCasesByQuery(CasesSearchCriteriaBean criteriaBean); public String getCaseStatus(Long processInstanceId); public boolean setCasesPagerAttributes(int page, int pageSize); /** * <p>Method for getting available processes in simplified form.</p> * @param iwc {@link IWContext}. * @return {@link List} of {@link AdvancedProperty}( * {@link CasesRetrievalManager#getLatestProcessDefinitionIdByProcessName(String)}, * {@link CasesRetrievalManager#getProcessName(String, java.util.Locale)} * ). */ public List<AdvancedProperty> getAvailableProcesses(IWContext iwc); /** * <p>Check if there is Spring bean registered in cache with such name, * which has value <code>true</code>. If not registered in cache, it checks * if exist and registers answer to cache. Cache is found in * {@link DefaultSpringBean#getCache(String)} method.</p> * @param beanName {@link String} representation of bean name to check. * @return UI class name if there is Spring bean with given name, null otherwise. */ public String isResolverExist(String beanName); public AdvancedProperty getExportedCases(String instanceId, String uri, Boolean isExportContacts, Boolean isShowCompany); public boolean showCaseAssets(); public void doLoadCases(User user);
// Path: src/java/is/idega/idegaweb/egov/cases/bean/CasesExportParams.java // public class CasesExportParams implements Serializable { // // private static final long serialVersionUID = -4099540752887950292L; // // private Long processDefinitionId; // // private String id, status, dateFrom, dateTo; // // public Long getProcessDefinitionId() { // return processDefinitionId; // } // // public void setProcessDefinitionId(Long processDefinitionId) { // this.processDefinitionId = processDefinitionId; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getStatus() { // return status; // } // // public void setStatus(String status) { // this.status = status; // } // // public String getDateFrom() { // return dateFrom; // } // // public void setDateFrom(String dateFrom) { // this.dateFrom = dateFrom; // } // // public String getDateTo() { // return dateTo; // } // // public void setDateTo(String dateTo) { // this.dateTo = dateTo; // } // // @Override // public String toString() { // return "Proc. def. ID: " + getProcessDefinitionId() + ", ID: " + getId() + ", status: " + getStatus() + ", from: " + getDateFrom() + ", to: " + // getDateTo(); // } // // } // Path: src/java/is/idega/idegaweb/egov/cases/business/CasesEngine.java import is.idega.idegaweb.egov.cases.bean.CasesExportParams; import java.util.List; import org.jdom.Document; import com.idega.block.process.business.CasesRetrievalManager; import com.idega.block.process.presentation.beans.CasePresentation; import com.idega.block.process.presentation.beans.CasesSearchCriteriaBean; import com.idega.builder.bean.AdvancedProperty; import com.idega.core.business.DefaultSpringBean; import com.idega.presentation.IWContext; import com.idega.presentation.paging.PagedDataCollection; import com.idega.user.data.User; package is.idega.idegaweb.egov.cases.business; public interface CasesEngine { public abstract boolean clearSearchResults(String id); public abstract AdvancedProperty getExportedSearchResults(String id); public abstract boolean setCaseSubject(String caseId, String subject); public abstract List<AdvancedProperty> getDefaultSortingOptions(IWContext iwc); public PagedDataCollection<CasePresentation> getCasesByQuery(CasesSearchCriteriaBean criteriaBean); public Document getRenderedCasesByQuery(CasesSearchCriteriaBean criteriaBean); public String getCaseStatus(Long processInstanceId); public boolean setCasesPagerAttributes(int page, int pageSize); /** * <p>Method for getting available processes in simplified form.</p> * @param iwc {@link IWContext}. * @return {@link List} of {@link AdvancedProperty}( * {@link CasesRetrievalManager#getLatestProcessDefinitionIdByProcessName(String)}, * {@link CasesRetrievalManager#getProcessName(String, java.util.Locale)} * ). */ public List<AdvancedProperty> getAvailableProcesses(IWContext iwc); /** * <p>Check if there is Spring bean registered in cache with such name, * which has value <code>true</code>. If not registered in cache, it checks * if exist and registers answer to cache. Cache is found in * {@link DefaultSpringBean#getCache(String)} method.</p> * @param beanName {@link String} representation of bean name to check. * @return UI class name if there is Spring bean with given name, null otherwise. */ public String isResolverExist(String beanName); public AdvancedProperty getExportedCases(String instanceId, String uri, Boolean isExportContacts, Boolean isShowCompany); public boolean showCaseAssets(); public void doLoadCases(User user);
public AdvancedProperty getExportedCasesToPDF(CasesExportParams params);
idega/is.idega.idegaweb.egov.cases
src/java/is/idega/idegaweb/egov/cases/presentation/CasesBoardViewCustomizer.java
// Path: src/java/is/idega/idegaweb/egov/cases/business/BoardCasesManager.java // public interface BoardCasesManager { // // public static final String BEAN_NAME = "boardCasesManager"; // // /** // * // * @author <a href="mailto:martynas@idega.is">Martynas Stakė</a> // * @param dateFrom is floor of {@link Case#getCreated()}, // * skipped if <code>null</code>; // * @param dateTo is ceiling of {@link Case#getCreated()}, // * skipped if <code>null</code>; // */ // public List<CaseBoardBean> getAllSortedCases( // Collection<String> caseStatus, // String processName, // String uuid, // boolean isSubscribedOnly, // boolean backPage, // String taskName, Date dateFrom, Date dateTo); // // /** // * // * <p>Construcs data for table to be shown.</p> // * @param iwc - application context; // * @param caseStatus of cases to add to table, for example: // * "BVJD, INPR, FINI, ..."; // * @param processName is name of ProcessDefinition object; // * @param customColumns - variable names, which should be shown as columns, // * for example: "string_caseIdentifier,string_caseDescription,..." // * @param uuid of {@link CasesBoardViewer} component; // * @return data for table to represent or <code>null</code> on failure. // * @author <a href="mailto:martynas@idega.com">Martynas Stakė</a> // */ // public CaseBoardTableBean getTableData( // Collection<String> caseStatus, // String processName, // String uuid, // boolean isSubscribedOnly, // boolean useBasePage, // String taskName); // // /** // * @param dateFrom is floor of {@link Case#getCreated()}, // * skipped if <code>null</code>; // * @param dateTo is ceiling of {@link Case#getCreated()}, // * skipped if <code>null</code>; // */ // public CaseBoardTableBean getTableData( // Date dateFrom, // Date dateTo, // Collection<String> caseStatus, // String processName, // String uuid, // boolean isSubscribedOnly, // boolean useBasePage, // String taskName); // // public AdvancedProperty getHandlerInfo(IWContext iwc, User handler); // // public String getLinkToTheTaskRedirector(IWContext iwc, String basePage, String caseId, Long processInstanceId, String backPage, String taskName); // // public List<AdvancedProperty> getAvailableVariables(String processName); // // public Map<Integer, List<AdvancedProperty>> getColumns(String uuid); // // public List<String> getCustomColumns(String uuid); // // public boolean isEqual(String currentColumn, String columnOfDomain); // // public int getIndexOfColumn(String column, String uuid); // // public Long getNumberValue(String value); // // } // // Path: src/java/is/idega/idegaweb/egov/cases/util/CasesConstants.java // public class CasesConstants { // // public static final String IW_BUNDLE_IDENTIFIER = "is.idega.idegaweb.egov.cases"; // // public static final String CASE_CODE_KEY = "GENCASE"; // // public static final String ROLE_CASES_SUPER_ADMIN = "cases_super_admin"; // // public static final String PROPERTY_USE_SUB_CATEGORIES = "egov.cases.use.sub.categories"; // public static final String PROPERTY_USE_TYPES = "egov.cases.use.types"; // public static final String PROPERTY_ALLOW_PRIVATE_CASES = "egov.cases.allow.private.cases"; // public static final String PROPERTY_ALLOW_ANONYMOUS_CASES = "egov.cases.allow.anonymous.cases"; // public static final String PROPERTY_ALLOW_ATTACHMENTS = "egov.cases.allow.attachments"; // public static final String PROPERTY_WAIT_FOR_ALL_CASE_PARTS_LOADED = "wait_for_all_case_parts_loaded"; // // public static final String CASES_LIST_HELPER_JAVA_SCRIPT_FILE = "javascript/CasesListHelper.js"; // // public static final String GENERAL_CASES_TYPE = "generalCases"; // // public static final String CASES_LIST_GRID_EXPANDER_STYLE_CLASS = "casesListGridExpanderStyleClass", // // // APPLIED_GRANT_AMOUNT_VARIABLE = "string_ownerGrantAmount"; // }
import is.idega.idegaweb.egov.cases.business.BoardCasesManager; import is.idega.idegaweb.egov.cases.util.CasesConstants; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import com.idega.builder.bean.AdvancedProperty; import com.idega.idegaweb.IWBundle; import com.idega.idegaweb.IWResourceBundle; import com.idega.presentation.Block; import com.idega.presentation.IWContext; import com.idega.presentation.Layer; import com.idega.presentation.text.Heading4; import com.idega.presentation.ui.Form; import com.idega.presentation.ui.GenericButton; import com.idega.presentation.ui.SelectionBox; import com.idega.presentation.ui.SelectionDoubleBox; import com.idega.util.ListUtil; import com.idega.util.expression.ELUtil;
package is.idega.idegaweb.egov.cases.presentation; public class CasesBoardViewCustomizer extends Block { public static final String FINANCING_TABLE_COLUMN = "financing_table_column"; @Autowired
// Path: src/java/is/idega/idegaweb/egov/cases/business/BoardCasesManager.java // public interface BoardCasesManager { // // public static final String BEAN_NAME = "boardCasesManager"; // // /** // * // * @author <a href="mailto:martynas@idega.is">Martynas Stakė</a> // * @param dateFrom is floor of {@link Case#getCreated()}, // * skipped if <code>null</code>; // * @param dateTo is ceiling of {@link Case#getCreated()}, // * skipped if <code>null</code>; // */ // public List<CaseBoardBean> getAllSortedCases( // Collection<String> caseStatus, // String processName, // String uuid, // boolean isSubscribedOnly, // boolean backPage, // String taskName, Date dateFrom, Date dateTo); // // /** // * // * <p>Construcs data for table to be shown.</p> // * @param iwc - application context; // * @param caseStatus of cases to add to table, for example: // * "BVJD, INPR, FINI, ..."; // * @param processName is name of ProcessDefinition object; // * @param customColumns - variable names, which should be shown as columns, // * for example: "string_caseIdentifier,string_caseDescription,..." // * @param uuid of {@link CasesBoardViewer} component; // * @return data for table to represent or <code>null</code> on failure. // * @author <a href="mailto:martynas@idega.com">Martynas Stakė</a> // */ // public CaseBoardTableBean getTableData( // Collection<String> caseStatus, // String processName, // String uuid, // boolean isSubscribedOnly, // boolean useBasePage, // String taskName); // // /** // * @param dateFrom is floor of {@link Case#getCreated()}, // * skipped if <code>null</code>; // * @param dateTo is ceiling of {@link Case#getCreated()}, // * skipped if <code>null</code>; // */ // public CaseBoardTableBean getTableData( // Date dateFrom, // Date dateTo, // Collection<String> caseStatus, // String processName, // String uuid, // boolean isSubscribedOnly, // boolean useBasePage, // String taskName); // // public AdvancedProperty getHandlerInfo(IWContext iwc, User handler); // // public String getLinkToTheTaskRedirector(IWContext iwc, String basePage, String caseId, Long processInstanceId, String backPage, String taskName); // // public List<AdvancedProperty> getAvailableVariables(String processName); // // public Map<Integer, List<AdvancedProperty>> getColumns(String uuid); // // public List<String> getCustomColumns(String uuid); // // public boolean isEqual(String currentColumn, String columnOfDomain); // // public int getIndexOfColumn(String column, String uuid); // // public Long getNumberValue(String value); // // } // // Path: src/java/is/idega/idegaweb/egov/cases/util/CasesConstants.java // public class CasesConstants { // // public static final String IW_BUNDLE_IDENTIFIER = "is.idega.idegaweb.egov.cases"; // // public static final String CASE_CODE_KEY = "GENCASE"; // // public static final String ROLE_CASES_SUPER_ADMIN = "cases_super_admin"; // // public static final String PROPERTY_USE_SUB_CATEGORIES = "egov.cases.use.sub.categories"; // public static final String PROPERTY_USE_TYPES = "egov.cases.use.types"; // public static final String PROPERTY_ALLOW_PRIVATE_CASES = "egov.cases.allow.private.cases"; // public static final String PROPERTY_ALLOW_ANONYMOUS_CASES = "egov.cases.allow.anonymous.cases"; // public static final String PROPERTY_ALLOW_ATTACHMENTS = "egov.cases.allow.attachments"; // public static final String PROPERTY_WAIT_FOR_ALL_CASE_PARTS_LOADED = "wait_for_all_case_parts_loaded"; // // public static final String CASES_LIST_HELPER_JAVA_SCRIPT_FILE = "javascript/CasesListHelper.js"; // // public static final String GENERAL_CASES_TYPE = "generalCases"; // // public static final String CASES_LIST_GRID_EXPANDER_STYLE_CLASS = "casesListGridExpanderStyleClass", // // // APPLIED_GRANT_AMOUNT_VARIABLE = "string_ownerGrantAmount"; // } // Path: src/java/is/idega/idegaweb/egov/cases/presentation/CasesBoardViewCustomizer.java import is.idega.idegaweb.egov.cases.business.BoardCasesManager; import is.idega.idegaweb.egov.cases.util.CasesConstants; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import com.idega.builder.bean.AdvancedProperty; import com.idega.idegaweb.IWBundle; import com.idega.idegaweb.IWResourceBundle; import com.idega.presentation.Block; import com.idega.presentation.IWContext; import com.idega.presentation.Layer; import com.idega.presentation.text.Heading4; import com.idega.presentation.ui.Form; import com.idega.presentation.ui.GenericButton; import com.idega.presentation.ui.SelectionBox; import com.idega.presentation.ui.SelectionDoubleBox; import com.idega.util.ListUtil; import com.idega.util.expression.ELUtil; package is.idega.idegaweb.egov.cases.presentation; public class CasesBoardViewCustomizer extends Block { public static final String FINANCING_TABLE_COLUMN = "financing_table_column"; @Autowired
@Qualifier(BoardCasesManager.BEAN_NAME)
manuel-freire/iw
plantilla/src/main/java/es/ucm/fdi/iw/IwUserDetailsService.java
// Path: plantilla/src/main/java/es/ucm/fdi/iw/model/User.java // @Entity // @Data // @NoArgsConstructor // @NamedQueries({ // @NamedQuery(name="User.byUsername", // query="SELECT u FROM User u " // + "WHERE u.username = :username AND u.enabled = TRUE"), // @NamedQuery(name="User.hasUsername", // query="SELECT COUNT(u) " // + "FROM User u " // + "WHERE u.username = :username") // }) // @Table(name="IWUser") // public class User implements Transferable<User.Transfer> { // // public enum Role { // USER, // normal users // ADMIN, // admin users // } // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "gen") // @SequenceGenerator(name = "gen", sequenceName = "gen") // private long id; // // @Column(nullable = false, unique = true) // private String username; // @Column(nullable = false) // private String password; // // private String firstName; // private String lastName; // // private boolean enabled; // private String roles; // split by ',' to separate roles // // @OneToMany // @JoinColumn(name = "sender_id") // private List<Message> sent = new ArrayList<>(); // @OneToMany // @JoinColumn(name = "recipient_id") // private List<Message> received = new ArrayList<>(); // // /** // * Checks whether this user has a given role. // * @param role to check // * @return true iff this user has that role. // */ // public boolean hasRole(Role role) { // String roleName = role.name(); // return Arrays.asList(roles.split(",")).contains(roleName); // } // // @Getter // @AllArgsConstructor // public static class Transfer { // private long id; // private String username; // private int totalReceived; // private int totalSent; // } // // @Override // public Transfer toTransfer() { // return new Transfer(id, username, received.size(), sent.size()); // } // // @Override // public String toString() { // return toTransfer().toString(); // } // }
import java.util.ArrayList; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import es.ucm.fdi.iw.model.User;
package es.ucm.fdi.iw; /** * Authenticates login attempts against a JPA database */ public class IwUserDetailsService implements UserDetailsService { private static Logger log = LogManager.getLogger(IwUserDetailsService.class); private EntityManager entityManager; @PersistenceContext public void setEntityManager(EntityManager em){ this.entityManager = em; } public UserDetails loadUserByUsername(String username){ try {
// Path: plantilla/src/main/java/es/ucm/fdi/iw/model/User.java // @Entity // @Data // @NoArgsConstructor // @NamedQueries({ // @NamedQuery(name="User.byUsername", // query="SELECT u FROM User u " // + "WHERE u.username = :username AND u.enabled = TRUE"), // @NamedQuery(name="User.hasUsername", // query="SELECT COUNT(u) " // + "FROM User u " // + "WHERE u.username = :username") // }) // @Table(name="IWUser") // public class User implements Transferable<User.Transfer> { // // public enum Role { // USER, // normal users // ADMIN, // admin users // } // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "gen") // @SequenceGenerator(name = "gen", sequenceName = "gen") // private long id; // // @Column(nullable = false, unique = true) // private String username; // @Column(nullable = false) // private String password; // // private String firstName; // private String lastName; // // private boolean enabled; // private String roles; // split by ',' to separate roles // // @OneToMany // @JoinColumn(name = "sender_id") // private List<Message> sent = new ArrayList<>(); // @OneToMany // @JoinColumn(name = "recipient_id") // private List<Message> received = new ArrayList<>(); // // /** // * Checks whether this user has a given role. // * @param role to check // * @return true iff this user has that role. // */ // public boolean hasRole(Role role) { // String roleName = role.name(); // return Arrays.asList(roles.split(",")).contains(roleName); // } // // @Getter // @AllArgsConstructor // public static class Transfer { // private long id; // private String username; // private int totalReceived; // private int totalSent; // } // // @Override // public Transfer toTransfer() { // return new Transfer(id, username, received.size(), sent.size()); // } // // @Override // public String toString() { // return toTransfer().toString(); // } // } // Path: plantilla/src/main/java/es/ucm/fdi/iw/IwUserDetailsService.java import java.util.ArrayList; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import es.ucm.fdi.iw.model.User; package es.ucm.fdi.iw; /** * Authenticates login attempts against a JPA database */ public class IwUserDetailsService implements UserDetailsService { private static Logger log = LogManager.getLogger(IwUserDetailsService.class); private EntityManager entityManager; @PersistenceContext public void setEntityManager(EntityManager em){ this.entityManager = em; } public UserDetails loadUserByUsername(String username){ try {
User u = entityManager.createNamedQuery("User.byUsername", User.class)
manuel-freire/iw
plantilla/src/main/java/es/ucm/fdi/iw/WebSocketSecurityConfig.java
// Path: plantilla/src/main/java/es/ucm/fdi/iw/model/User.java // @Entity // @Data // @NoArgsConstructor // @NamedQueries({ // @NamedQuery(name="User.byUsername", // query="SELECT u FROM User u " // + "WHERE u.username = :username AND u.enabled = TRUE"), // @NamedQuery(name="User.hasUsername", // query="SELECT COUNT(u) " // + "FROM User u " // + "WHERE u.username = :username") // }) // @Table(name="IWUser") // public class User implements Transferable<User.Transfer> { // // public enum Role { // USER, // normal users // ADMIN, // admin users // } // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "gen") // @SequenceGenerator(name = "gen", sequenceName = "gen") // private long id; // // @Column(nullable = false, unique = true) // private String username; // @Column(nullable = false) // private String password; // // private String firstName; // private String lastName; // // private boolean enabled; // private String roles; // split by ',' to separate roles // // @OneToMany // @JoinColumn(name = "sender_id") // private List<Message> sent = new ArrayList<>(); // @OneToMany // @JoinColumn(name = "recipient_id") // private List<Message> received = new ArrayList<>(); // // /** // * Checks whether this user has a given role. // * @param role to check // * @return true iff this user has that role. // */ // public boolean hasRole(Role role) { // String roleName = role.name(); // return Arrays.asList(roles.split(",")).contains(roleName); // } // // @Getter // @AllArgsConstructor // public static class Transfer { // private long id; // private String username; // private int totalReceived; // private int totalSent; // } // // @Override // public Transfer toTransfer() { // return new Transfer(id, username, received.size(), sent.size()); // } // // @Override // public String toString() { // return toTransfer().toString(); // } // }
import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.messaging.MessageSecurityMetadataSourceRegistry; import org.springframework.security.config.annotation.web.socket.AbstractSecurityWebSocketMessageBrokerConfigurer; import es.ucm.fdi.iw.model.User;
package es.ucm.fdi.iw; /** * Similar to SecurityConfig, but for websockets that use STOMP. * * @see https://docs.spring.io/spring-security/reference/servlet/integrations/websocket.html */ @Configuration public class WebSocketSecurityConfig extends AbstractSecurityWebSocketMessageBrokerConfigurer { protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) { messages .simpSubscribeDestMatchers("/topic/admin") // only admins can subscribe
// Path: plantilla/src/main/java/es/ucm/fdi/iw/model/User.java // @Entity // @Data // @NoArgsConstructor // @NamedQueries({ // @NamedQuery(name="User.byUsername", // query="SELECT u FROM User u " // + "WHERE u.username = :username AND u.enabled = TRUE"), // @NamedQuery(name="User.hasUsername", // query="SELECT COUNT(u) " // + "FROM User u " // + "WHERE u.username = :username") // }) // @Table(name="IWUser") // public class User implements Transferable<User.Transfer> { // // public enum Role { // USER, // normal users // ADMIN, // admin users // } // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "gen") // @SequenceGenerator(name = "gen", sequenceName = "gen") // private long id; // // @Column(nullable = false, unique = true) // private String username; // @Column(nullable = false) // private String password; // // private String firstName; // private String lastName; // // private boolean enabled; // private String roles; // split by ',' to separate roles // // @OneToMany // @JoinColumn(name = "sender_id") // private List<Message> sent = new ArrayList<>(); // @OneToMany // @JoinColumn(name = "recipient_id") // private List<Message> received = new ArrayList<>(); // // /** // * Checks whether this user has a given role. // * @param role to check // * @return true iff this user has that role. // */ // public boolean hasRole(Role role) { // String roleName = role.name(); // return Arrays.asList(roles.split(",")).contains(roleName); // } // // @Getter // @AllArgsConstructor // public static class Transfer { // private long id; // private String username; // private int totalReceived; // private int totalSent; // } // // @Override // public Transfer toTransfer() { // return new Transfer(id, username, received.size(), sent.size()); // } // // @Override // public String toString() { // return toTransfer().toString(); // } // } // Path: plantilla/src/main/java/es/ucm/fdi/iw/WebSocketSecurityConfig.java import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.messaging.MessageSecurityMetadataSourceRegistry; import org.springframework.security.config.annotation.web.socket.AbstractSecurityWebSocketMessageBrokerConfigurer; import es.ucm.fdi.iw.model.User; package es.ucm.fdi.iw; /** * Similar to SecurityConfig, but for websockets that use STOMP. * * @see https://docs.spring.io/spring-security/reference/servlet/integrations/websocket.html */ @Configuration public class WebSocketSecurityConfig extends AbstractSecurityWebSocketMessageBrokerConfigurer { protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) { messages .simpSubscribeDestMatchers("/topic/admin") // only admins can subscribe
.hasRole(User.Role.ADMIN.toString())
manuel-freire/iw
plantilla/src/main/java/es/ucm/fdi/iw/LoginSuccessHandler.java
// Path: plantilla/src/main/java/es/ucm/fdi/iw/model/User.java // @Entity // @Data // @NoArgsConstructor // @NamedQueries({ // @NamedQuery(name="User.byUsername", // query="SELECT u FROM User u " // + "WHERE u.username = :username AND u.enabled = TRUE"), // @NamedQuery(name="User.hasUsername", // query="SELECT COUNT(u) " // + "FROM User u " // + "WHERE u.username = :username") // }) // @Table(name="IWUser") // public class User implements Transferable<User.Transfer> { // // public enum Role { // USER, // normal users // ADMIN, // admin users // } // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "gen") // @SequenceGenerator(name = "gen", sequenceName = "gen") // private long id; // // @Column(nullable = false, unique = true) // private String username; // @Column(nullable = false) // private String password; // // private String firstName; // private String lastName; // // private boolean enabled; // private String roles; // split by ',' to separate roles // // @OneToMany // @JoinColumn(name = "sender_id") // private List<Message> sent = new ArrayList<>(); // @OneToMany // @JoinColumn(name = "recipient_id") // private List<Message> received = new ArrayList<>(); // // /** // * Checks whether this user has a given role. // * @param role to check // * @return true iff this user has that role. // */ // public boolean hasRole(Role role) { // String roleName = role.name(); // return Arrays.asList(roles.split(",")).contains(roleName); // } // // @Getter // @AllArgsConstructor // public static class Transfer { // private long id; // private String username; // private int totalReceived; // private int totalSent; // } // // @Override // public Transfer toTransfer() { // return new Transfer(id, username, received.size(), sent.size()); // } // // @Override // public String toString() { // return toTransfer().toString(); // } // } // // Path: plantilla/src/main/java/es/ucm/fdi/iw/model/User.java // public enum Role { // USER, // normal users // ADMIN, // admin users // }
import java.io.IOException; import java.util.Collection; import javax.persistence.EntityManager; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.stereotype.Component; import es.ucm.fdi.iw.model.User; import es.ucm.fdi.iw.model.User.Role;
package es.ucm.fdi.iw; /** * Called when a user is first authenticated (via login). * Called from SecurityConfig; see https://stackoverflow.com/a/53353324 * * Adds a "u" variable to the session when a user is first authenticated. * Important: the user is retrieved from the database, but is not refreshed at each request. * You should refresh the user's information if anything important changes; for example, after * updating the user's profile. */ @Component public class LoginSuccessHandler implements AuthenticationSuccessHandler { @Autowired private HttpSession session; @Autowired private EntityManager entityManager; private static Logger log = LogManager.getLogger(LoginSuccessHandler.class); /** * Called whenever a user authenticates correctly. */ @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { /* Avoids following warning: Cookie “JSESSIONID” will be soon rejected because it has the “SameSite” attribute set to “None” or an invalid value, without the “secure” attribute. To know more about the “SameSite“ attribute, read https://developer.mozilla.org/docs/Web/HTTP/Headers/Set-Cookie/SameSite */ addSameSiteCookieAttribute(response);
// Path: plantilla/src/main/java/es/ucm/fdi/iw/model/User.java // @Entity // @Data // @NoArgsConstructor // @NamedQueries({ // @NamedQuery(name="User.byUsername", // query="SELECT u FROM User u " // + "WHERE u.username = :username AND u.enabled = TRUE"), // @NamedQuery(name="User.hasUsername", // query="SELECT COUNT(u) " // + "FROM User u " // + "WHERE u.username = :username") // }) // @Table(name="IWUser") // public class User implements Transferable<User.Transfer> { // // public enum Role { // USER, // normal users // ADMIN, // admin users // } // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "gen") // @SequenceGenerator(name = "gen", sequenceName = "gen") // private long id; // // @Column(nullable = false, unique = true) // private String username; // @Column(nullable = false) // private String password; // // private String firstName; // private String lastName; // // private boolean enabled; // private String roles; // split by ',' to separate roles // // @OneToMany // @JoinColumn(name = "sender_id") // private List<Message> sent = new ArrayList<>(); // @OneToMany // @JoinColumn(name = "recipient_id") // private List<Message> received = new ArrayList<>(); // // /** // * Checks whether this user has a given role. // * @param role to check // * @return true iff this user has that role. // */ // public boolean hasRole(Role role) { // String roleName = role.name(); // return Arrays.asList(roles.split(",")).contains(roleName); // } // // @Getter // @AllArgsConstructor // public static class Transfer { // private long id; // private String username; // private int totalReceived; // private int totalSent; // } // // @Override // public Transfer toTransfer() { // return new Transfer(id, username, received.size(), sent.size()); // } // // @Override // public String toString() { // return toTransfer().toString(); // } // } // // Path: plantilla/src/main/java/es/ucm/fdi/iw/model/User.java // public enum Role { // USER, // normal users // ADMIN, // admin users // } // Path: plantilla/src/main/java/es/ucm/fdi/iw/LoginSuccessHandler.java import java.io.IOException; import java.util.Collection; import javax.persistence.EntityManager; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.stereotype.Component; import es.ucm.fdi.iw.model.User; import es.ucm.fdi.iw.model.User.Role; package es.ucm.fdi.iw; /** * Called when a user is first authenticated (via login). * Called from SecurityConfig; see https://stackoverflow.com/a/53353324 * * Adds a "u" variable to the session when a user is first authenticated. * Important: the user is retrieved from the database, but is not refreshed at each request. * You should refresh the user's information if anything important changes; for example, after * updating the user's profile. */ @Component public class LoginSuccessHandler implements AuthenticationSuccessHandler { @Autowired private HttpSession session; @Autowired private EntityManager entityManager; private static Logger log = LogManager.getLogger(LoginSuccessHandler.class); /** * Called whenever a user authenticates correctly. */ @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { /* Avoids following warning: Cookie “JSESSIONID” will be soon rejected because it has the “SameSite” attribute set to “None” or an invalid value, without the “secure” attribute. To know more about the “SameSite“ attribute, read https://developer.mozilla.org/docs/Web/HTTP/Headers/Set-Cookie/SameSite */ addSameSiteCookieAttribute(response);
String username = ((org.springframework.security.core.userdetails.User)
manuel-freire/iw
plantilla/src/main/java/es/ucm/fdi/iw/LoginSuccessHandler.java
// Path: plantilla/src/main/java/es/ucm/fdi/iw/model/User.java // @Entity // @Data // @NoArgsConstructor // @NamedQueries({ // @NamedQuery(name="User.byUsername", // query="SELECT u FROM User u " // + "WHERE u.username = :username AND u.enabled = TRUE"), // @NamedQuery(name="User.hasUsername", // query="SELECT COUNT(u) " // + "FROM User u " // + "WHERE u.username = :username") // }) // @Table(name="IWUser") // public class User implements Transferable<User.Transfer> { // // public enum Role { // USER, // normal users // ADMIN, // admin users // } // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "gen") // @SequenceGenerator(name = "gen", sequenceName = "gen") // private long id; // // @Column(nullable = false, unique = true) // private String username; // @Column(nullable = false) // private String password; // // private String firstName; // private String lastName; // // private boolean enabled; // private String roles; // split by ',' to separate roles // // @OneToMany // @JoinColumn(name = "sender_id") // private List<Message> sent = new ArrayList<>(); // @OneToMany // @JoinColumn(name = "recipient_id") // private List<Message> received = new ArrayList<>(); // // /** // * Checks whether this user has a given role. // * @param role to check // * @return true iff this user has that role. // */ // public boolean hasRole(Role role) { // String roleName = role.name(); // return Arrays.asList(roles.split(",")).contains(roleName); // } // // @Getter // @AllArgsConstructor // public static class Transfer { // private long id; // private String username; // private int totalReceived; // private int totalSent; // } // // @Override // public Transfer toTransfer() { // return new Transfer(id, username, received.size(), sent.size()); // } // // @Override // public String toString() { // return toTransfer().toString(); // } // } // // Path: plantilla/src/main/java/es/ucm/fdi/iw/model/User.java // public enum Role { // USER, // normal users // ADMIN, // admin users // }
import java.io.IOException; import java.util.Collection; import javax.persistence.EntityManager; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.stereotype.Component; import es.ucm.fdi.iw.model.User; import es.ucm.fdi.iw.model.User.Role;
package es.ucm.fdi.iw; /** * Called when a user is first authenticated (via login). * Called from SecurityConfig; see https://stackoverflow.com/a/53353324 * * Adds a "u" variable to the session when a user is first authenticated. * Important: the user is retrieved from the database, but is not refreshed at each request. * You should refresh the user's information if anything important changes; for example, after * updating the user's profile. */ @Component public class LoginSuccessHandler implements AuthenticationSuccessHandler { @Autowired private HttpSession session; @Autowired private EntityManager entityManager; private static Logger log = LogManager.getLogger(LoginSuccessHandler.class); /** * Called whenever a user authenticates correctly. */ @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { /* Avoids following warning: Cookie “JSESSIONID” will be soon rejected because it has the “SameSite” attribute set to “None” or an invalid value, without the “secure” attribute. To know more about the “SameSite“ attribute, read https://developer.mozilla.org/docs/Web/HTTP/Headers/Set-Cookie/SameSite */ addSameSiteCookieAttribute(response); String username = ((org.springframework.security.core.userdetails.User) authentication.getPrincipal()).getUsername(); // add a 'u' session variable, accessible from thymeleaf via ${session.u} log.info("Storing user info for {} in session {}", username, session.getId()); User u = entityManager.createNamedQuery("User.byUsername", User.class) .setParameter("username", username) .getSingleResult(); session.setAttribute("u", u); // add 'url' and 'ws' session variables String url = request.getRequestURL().toString() .replaceFirst("/[^/]*$", ""); // .../foo => ... session.setAttribute("url", url); String ws = url .replaceFirst("[^:]*", "ws"); // http[s]://... => ws://... session.setAttribute("ws", ws + "/ws"); // redirects to 'admin' or 'user/{id}', depending on the user
// Path: plantilla/src/main/java/es/ucm/fdi/iw/model/User.java // @Entity // @Data // @NoArgsConstructor // @NamedQueries({ // @NamedQuery(name="User.byUsername", // query="SELECT u FROM User u " // + "WHERE u.username = :username AND u.enabled = TRUE"), // @NamedQuery(name="User.hasUsername", // query="SELECT COUNT(u) " // + "FROM User u " // + "WHERE u.username = :username") // }) // @Table(name="IWUser") // public class User implements Transferable<User.Transfer> { // // public enum Role { // USER, // normal users // ADMIN, // admin users // } // // @Id // @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "gen") // @SequenceGenerator(name = "gen", sequenceName = "gen") // private long id; // // @Column(nullable = false, unique = true) // private String username; // @Column(nullable = false) // private String password; // // private String firstName; // private String lastName; // // private boolean enabled; // private String roles; // split by ',' to separate roles // // @OneToMany // @JoinColumn(name = "sender_id") // private List<Message> sent = new ArrayList<>(); // @OneToMany // @JoinColumn(name = "recipient_id") // private List<Message> received = new ArrayList<>(); // // /** // * Checks whether this user has a given role. // * @param role to check // * @return true iff this user has that role. // */ // public boolean hasRole(Role role) { // String roleName = role.name(); // return Arrays.asList(roles.split(",")).contains(roleName); // } // // @Getter // @AllArgsConstructor // public static class Transfer { // private long id; // private String username; // private int totalReceived; // private int totalSent; // } // // @Override // public Transfer toTransfer() { // return new Transfer(id, username, received.size(), sent.size()); // } // // @Override // public String toString() { // return toTransfer().toString(); // } // } // // Path: plantilla/src/main/java/es/ucm/fdi/iw/model/User.java // public enum Role { // USER, // normal users // ADMIN, // admin users // } // Path: plantilla/src/main/java/es/ucm/fdi/iw/LoginSuccessHandler.java import java.io.IOException; import java.util.Collection; import javax.persistence.EntityManager; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.stereotype.Component; import es.ucm.fdi.iw.model.User; import es.ucm.fdi.iw.model.User.Role; package es.ucm.fdi.iw; /** * Called when a user is first authenticated (via login). * Called from SecurityConfig; see https://stackoverflow.com/a/53353324 * * Adds a "u" variable to the session when a user is first authenticated. * Important: the user is retrieved from the database, but is not refreshed at each request. * You should refresh the user's information if anything important changes; for example, after * updating the user's profile. */ @Component public class LoginSuccessHandler implements AuthenticationSuccessHandler { @Autowired private HttpSession session; @Autowired private EntityManager entityManager; private static Logger log = LogManager.getLogger(LoginSuccessHandler.class); /** * Called whenever a user authenticates correctly. */ @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { /* Avoids following warning: Cookie “JSESSIONID” will be soon rejected because it has the “SameSite” attribute set to “None” or an invalid value, without the “secure” attribute. To know more about the “SameSite“ attribute, read https://developer.mozilla.org/docs/Web/HTTP/Headers/Set-Cookie/SameSite */ addSameSiteCookieAttribute(response); String username = ((org.springframework.security.core.userdetails.User) authentication.getPrincipal()).getUsername(); // add a 'u' session variable, accessible from thymeleaf via ${session.u} log.info("Storing user info for {} in session {}", username, session.getId()); User u = entityManager.createNamedQuery("User.byUsername", User.class) .setParameter("username", username) .getSingleResult(); session.setAttribute("u", u); // add 'url' and 'ws' session variables String url = request.getRequestURL().toString() .replaceFirst("/[^/]*$", ""); // .../foo => ... session.setAttribute("url", url); String ws = url .replaceFirst("[^:]*", "ws"); // http[s]://... => ws://... session.setAttribute("ws", ws + "/ws"); // redirects to 'admin' or 'user/{id}', depending on the user
String nextUrl = u.hasRole(User.Role.ADMIN) ?
manuel-freire/iw
jpademo/src/main/java/com/example/demo/control/TestController.java
// Path: jpademo/src/main/java/com/example/demo/model/Car.java // @Entity // @Data // public class Car { // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private long id; // private String company; // // @NotNull // @Size(max=10) // private String model; // // @ManyToMany(mappedBy="rides") // private List<Driver> drivers = new ArrayList<>(); // @OneToMany // @JoinColumn(name="car_id") // private List<Wheel> wheels = new ArrayList<>(); // // @Override // public String toString() { // return "Car #" + id; // } // } // // Path: jpademo/src/main/java/com/example/demo/model/Wheel.java // @Entity // @Data // public class Wheel { // // public enum Position { FrontRight, FrontLeft, RearRight, RearLeft }; // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private long id; // // @ManyToOne // private Car car; // private Position position; // // @Override // public String toString() { // return "Wheel #" + id; // } // }
import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.persistence.EntityManager; import javax.persistence.ManyToMany; import javax.persistence.OneToMany; import javax.servlet.http.HttpServletRequest; import javax.transaction.Transactional; import javax.validation.Valid; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.PropertyAccessor; import org.springframework.beans.PropertyAccessorFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import com.example.demo.model.Car; import com.example.demo.model.Wheel;
package com.example.demo.control; /** * Controlador para probar cosas con la BD. * * OJO: Sólo para probar cosas. En una aplicación real, debería haber * - Control de accesos. No todo el mundo debe poder tocar todo. * - Validación de campos. No nos podemos fiar de que los usuarios no intenten * introducir valores "malignos" en la aplicación, y hay que revisarlos tanto * en el cliente (=js en su navegador), por si lo hacen sin querer, como en el * servidor (=aquí), por si los meten queriendo (y entonces pueden pasar * fácilmente de las validaciones del navegador) * - Paginación. Mostrar toda la BD a la vez es caro, lento, e innecesario: * mejor mostrar sólo lo que se necesita en cada momento. * * @author mfreire */ @Controller public class TestController { @Autowired private EntityManager entityManager; private static final Logger log = LogManager.getLogger(TestController.class); @PostMapping("/addCar1") @Transactional public String addCar1( @RequestParam String company, @RequestParam String model, Model m) {
// Path: jpademo/src/main/java/com/example/demo/model/Car.java // @Entity // @Data // public class Car { // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private long id; // private String company; // // @NotNull // @Size(max=10) // private String model; // // @ManyToMany(mappedBy="rides") // private List<Driver> drivers = new ArrayList<>(); // @OneToMany // @JoinColumn(name="car_id") // private List<Wheel> wheels = new ArrayList<>(); // // @Override // public String toString() { // return "Car #" + id; // } // } // // Path: jpademo/src/main/java/com/example/demo/model/Wheel.java // @Entity // @Data // public class Wheel { // // public enum Position { FrontRight, FrontLeft, RearRight, RearLeft }; // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private long id; // // @ManyToOne // private Car car; // private Position position; // // @Override // public String toString() { // return "Wheel #" + id; // } // } // Path: jpademo/src/main/java/com/example/demo/control/TestController.java import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.persistence.EntityManager; import javax.persistence.ManyToMany; import javax.persistence.OneToMany; import javax.servlet.http.HttpServletRequest; import javax.transaction.Transactional; import javax.validation.Valid; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.PropertyAccessor; import org.springframework.beans.PropertyAccessorFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import com.example.demo.model.Car; import com.example.demo.model.Wheel; package com.example.demo.control; /** * Controlador para probar cosas con la BD. * * OJO: Sólo para probar cosas. En una aplicación real, debería haber * - Control de accesos. No todo el mundo debe poder tocar todo. * - Validación de campos. No nos podemos fiar de que los usuarios no intenten * introducir valores "malignos" en la aplicación, y hay que revisarlos tanto * en el cliente (=js en su navegador), por si lo hacen sin querer, como en el * servidor (=aquí), por si los meten queriendo (y entonces pueden pasar * fácilmente de las validaciones del navegador) * - Paginación. Mostrar toda la BD a la vez es caro, lento, e innecesario: * mejor mostrar sólo lo que se necesita en cada momento. * * @author mfreire */ @Controller public class TestController { @Autowired private EntityManager entityManager; private static final Logger log = LogManager.getLogger(TestController.class); @PostMapping("/addCar1") @Transactional public String addCar1( @RequestParam String company, @RequestParam String model, Model m) {
Car car = new Car();
manuel-freire/iw
jpademo/src/main/java/com/example/demo/control/TestController.java
// Path: jpademo/src/main/java/com/example/demo/model/Car.java // @Entity // @Data // public class Car { // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private long id; // private String company; // // @NotNull // @Size(max=10) // private String model; // // @ManyToMany(mappedBy="rides") // private List<Driver> drivers = new ArrayList<>(); // @OneToMany // @JoinColumn(name="car_id") // private List<Wheel> wheels = new ArrayList<>(); // // @Override // public String toString() { // return "Car #" + id; // } // } // // Path: jpademo/src/main/java/com/example/demo/model/Wheel.java // @Entity // @Data // public class Wheel { // // public enum Position { FrontRight, FrontLeft, RearRight, RearLeft }; // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private long id; // // @ManyToOne // private Car car; // private Position position; // // @Override // public String toString() { // return "Wheel #" + id; // } // }
import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.persistence.EntityManager; import javax.persistence.ManyToMany; import javax.persistence.OneToMany; import javax.servlet.http.HttpServletRequest; import javax.transaction.Transactional; import javax.validation.Valid; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.PropertyAccessor; import org.springframework.beans.PropertyAccessorFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import com.example.demo.model.Car; import com.example.demo.model.Wheel;
Field f = o.getClass().getDeclaredField(propertyName); if (List.class.isAssignableFrom(f.getType())) { // add a list of references Method getter = getAccessor(clazz, true, propertyName); Class<?> inner = getter.getAnnotation(OneToMany.class) != null ? getter.getAnnotation(OneToMany.class).targetEntity() : getter.getAnnotation(ManyToMany.class).targetEntity(); List list = (List)getter.invoke(o); list.clear(); // remove previous values for (String id : propertyValue.split(",")) { list.add(entityManager.find(inner, Long.parseLong(id))); } } else { // set one reference Method setter = getAccessor(clazz, false, propertyName); setter.invoke(o, entityManager.find(f.getType(), Long.parseLong(propertyValue))); } } else { // set a literal value Method setter = getAccessor(clazz, false, propertyName); Class<?> type = setter.getParameters()[0].getType(); if (type.equals(String.class)) { setter.invoke(o, propertyValue); } else if (type.isPrimitive()) { // rely on Spring - as per https://stackoverflow.com/a/15973019/15472 PropertyAccessor accessor = PropertyAccessorFactory.forBeanPropertyAccess(o); accessor.setPropertyValue(propertyName, propertyValue); } else if (type.isEnum()) {
// Path: jpademo/src/main/java/com/example/demo/model/Car.java // @Entity // @Data // public class Car { // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private long id; // private String company; // // @NotNull // @Size(max=10) // private String model; // // @ManyToMany(mappedBy="rides") // private List<Driver> drivers = new ArrayList<>(); // @OneToMany // @JoinColumn(name="car_id") // private List<Wheel> wheels = new ArrayList<>(); // // @Override // public String toString() { // return "Car #" + id; // } // } // // Path: jpademo/src/main/java/com/example/demo/model/Wheel.java // @Entity // @Data // public class Wheel { // // public enum Position { FrontRight, FrontLeft, RearRight, RearLeft }; // // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) // private long id; // // @ManyToOne // private Car car; // private Position position; // // @Override // public String toString() { // return "Wheel #" + id; // } // } // Path: jpademo/src/main/java/com/example/demo/control/TestController.java import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.persistence.EntityManager; import javax.persistence.ManyToMany; import javax.persistence.OneToMany; import javax.servlet.http.HttpServletRequest; import javax.transaction.Transactional; import javax.validation.Valid; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.PropertyAccessor; import org.springframework.beans.PropertyAccessorFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import com.example.demo.model.Car; import com.example.demo.model.Wheel; Field f = o.getClass().getDeclaredField(propertyName); if (List.class.isAssignableFrom(f.getType())) { // add a list of references Method getter = getAccessor(clazz, true, propertyName); Class<?> inner = getter.getAnnotation(OneToMany.class) != null ? getter.getAnnotation(OneToMany.class).targetEntity() : getter.getAnnotation(ManyToMany.class).targetEntity(); List list = (List)getter.invoke(o); list.clear(); // remove previous values for (String id : propertyValue.split(",")) { list.add(entityManager.find(inner, Long.parseLong(id))); } } else { // set one reference Method setter = getAccessor(clazz, false, propertyName); setter.invoke(o, entityManager.find(f.getType(), Long.parseLong(propertyValue))); } } else { // set a literal value Method setter = getAccessor(clazz, false, propertyName); Class<?> type = setter.getParameters()[0].getType(); if (type.equals(String.class)) { setter.invoke(o, propertyValue); } else if (type.isPrimitive()) { // rely on Spring - as per https://stackoverflow.com/a/15973019/15472 PropertyAccessor accessor = PropertyAccessorFactory.forBeanPropertyAccess(o); accessor.setPropertyValue(propertyName, propertyValue); } else if (type.isEnum()) {
setter.invoke(o, Wheel.Position.valueOf(propertyValue));
lesstif/jira-rest-client
src/test/java/com/lesstif/jira/services/ProjectTest.java
// Path: src/main/java/com/lesstif/jira/issue/IssueType.java // @Data // @EqualsAndHashCode(callSuper = false) // public class IssueType extends JsonPrettyString { // // Default issue type // public static final String ISSUE_TYPE_BUG = "Bug"; // public static final String ISSUE_TYPE_TASK = "Task"; // public static final String ISSUE_TYPE_IMPROVEMENT = "Improvement"; // public static final String ISSUE_TYPE_SUBTASK = "SubTask"; // public static final String ISSUE_TYPE_NEW_FEATURE = "New Feature"; // // private String self; // private String id; // private String description; // private String iconUrl; // private String name; // private Boolean subtask; // private Integer avatarId; // } // // Path: src/main/java/com/lesstif/jira/project/Project.java // @Data // @EqualsAndHashCode(callSuper=false) // @JsonIgnoreProperties({"assigneeType", "roles" // }) // public class Project extends JsonPrettyString{ // private String expand; // private String self; // // private String id; // private String key; // // private String description; // private String name; // private String url; // // @JsonSerialize(using = LocalDateSerializer.class) // @JsonDeserialize(using = LocalDateDeserializer.class) // private LocalDateTime startDate; // // private Lead lead; // // private AvatarUrl avatarUrls; // private ProjectCategory projectCategory; // // private List<Component> components; // private List<IssueType> issueTypes; // private List<Version> versions; // // private String projectTypeKey; // // private boolean archived; // }
import java.io.IOException; import java.util.List; import java.util.Optional; import com.lesstif.jira.issue.IssueType; import org.apache.commons.configuration.ConfigurationException; import org.hamcrest.Matchers; import org.hamcrest.text.IsEmptyString; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.lesstif.jira.project.Project; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*;
package com.lesstif.jira.services; public class ProjectTest { private Logger logger = LoggerFactory.getLogger(getClass()); @Test public void listProject() throws IOException, ConfigurationException { ProjectService prjService = new ProjectService();
// Path: src/main/java/com/lesstif/jira/issue/IssueType.java // @Data // @EqualsAndHashCode(callSuper = false) // public class IssueType extends JsonPrettyString { // // Default issue type // public static final String ISSUE_TYPE_BUG = "Bug"; // public static final String ISSUE_TYPE_TASK = "Task"; // public static final String ISSUE_TYPE_IMPROVEMENT = "Improvement"; // public static final String ISSUE_TYPE_SUBTASK = "SubTask"; // public static final String ISSUE_TYPE_NEW_FEATURE = "New Feature"; // // private String self; // private String id; // private String description; // private String iconUrl; // private String name; // private Boolean subtask; // private Integer avatarId; // } // // Path: src/main/java/com/lesstif/jira/project/Project.java // @Data // @EqualsAndHashCode(callSuper=false) // @JsonIgnoreProperties({"assigneeType", "roles" // }) // public class Project extends JsonPrettyString{ // private String expand; // private String self; // // private String id; // private String key; // // private String description; // private String name; // private String url; // // @JsonSerialize(using = LocalDateSerializer.class) // @JsonDeserialize(using = LocalDateDeserializer.class) // private LocalDateTime startDate; // // private Lead lead; // // private AvatarUrl avatarUrls; // private ProjectCategory projectCategory; // // private List<Component> components; // private List<IssueType> issueTypes; // private List<Version> versions; // // private String projectTypeKey; // // private boolean archived; // } // Path: src/test/java/com/lesstif/jira/services/ProjectTest.java import java.io.IOException; import java.util.List; import java.util.Optional; import com.lesstif.jira.issue.IssueType; import org.apache.commons.configuration.ConfigurationException; import org.hamcrest.Matchers; import org.hamcrest.text.IsEmptyString; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.lesstif.jira.project.Project; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; package com.lesstif.jira.services; public class ProjectTest { private Logger logger = LoggerFactory.getLogger(getClass()); @Test public void listProject() throws IOException, ConfigurationException { ProjectService prjService = new ProjectService();
List<Project> projects = prjService.getProjectList();
lesstif/jira-rest-client
src/test/java/com/lesstif/jira/services/ProjectTest.java
// Path: src/main/java/com/lesstif/jira/issue/IssueType.java // @Data // @EqualsAndHashCode(callSuper = false) // public class IssueType extends JsonPrettyString { // // Default issue type // public static final String ISSUE_TYPE_BUG = "Bug"; // public static final String ISSUE_TYPE_TASK = "Task"; // public static final String ISSUE_TYPE_IMPROVEMENT = "Improvement"; // public static final String ISSUE_TYPE_SUBTASK = "SubTask"; // public static final String ISSUE_TYPE_NEW_FEATURE = "New Feature"; // // private String self; // private String id; // private String description; // private String iconUrl; // private String name; // private Boolean subtask; // private Integer avatarId; // } // // Path: src/main/java/com/lesstif/jira/project/Project.java // @Data // @EqualsAndHashCode(callSuper=false) // @JsonIgnoreProperties({"assigneeType", "roles" // }) // public class Project extends JsonPrettyString{ // private String expand; // private String self; // // private String id; // private String key; // // private String description; // private String name; // private String url; // // @JsonSerialize(using = LocalDateSerializer.class) // @JsonDeserialize(using = LocalDateDeserializer.class) // private LocalDateTime startDate; // // private Lead lead; // // private AvatarUrl avatarUrls; // private ProjectCategory projectCategory; // // private List<Component> components; // private List<IssueType> issueTypes; // private List<Version> versions; // // private String projectTypeKey; // // private boolean archived; // }
import java.io.IOException; import java.util.List; import java.util.Optional; import com.lesstif.jira.issue.IssueType; import org.apache.commons.configuration.ConfigurationException; import org.hamcrest.Matchers; import org.hamcrest.text.IsEmptyString; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.lesstif.jira.project.Project; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*;
package com.lesstif.jira.services; public class ProjectTest { private Logger logger = LoggerFactory.getLogger(getClass()); @Test public void listProject() throws IOException, ConfigurationException { ProjectService prjService = new ProjectService(); List<Project> projects = prjService.getProjectList(); int i = 0; for (Project prj : projects) { logger.info(i++ + "th " + prj.toPrettyJsonString() ); assertThat(prj.getId(), notNullValue()); assertThat(prj.getName(), notNullValue()); //assertThat(prj.getDescription(), not(emptyOrNullString()));
// Path: src/main/java/com/lesstif/jira/issue/IssueType.java // @Data // @EqualsAndHashCode(callSuper = false) // public class IssueType extends JsonPrettyString { // // Default issue type // public static final String ISSUE_TYPE_BUG = "Bug"; // public static final String ISSUE_TYPE_TASK = "Task"; // public static final String ISSUE_TYPE_IMPROVEMENT = "Improvement"; // public static final String ISSUE_TYPE_SUBTASK = "SubTask"; // public static final String ISSUE_TYPE_NEW_FEATURE = "New Feature"; // // private String self; // private String id; // private String description; // private String iconUrl; // private String name; // private Boolean subtask; // private Integer avatarId; // } // // Path: src/main/java/com/lesstif/jira/project/Project.java // @Data // @EqualsAndHashCode(callSuper=false) // @JsonIgnoreProperties({"assigneeType", "roles" // }) // public class Project extends JsonPrettyString{ // private String expand; // private String self; // // private String id; // private String key; // // private String description; // private String name; // private String url; // // @JsonSerialize(using = LocalDateSerializer.class) // @JsonDeserialize(using = LocalDateDeserializer.class) // private LocalDateTime startDate; // // private Lead lead; // // private AvatarUrl avatarUrls; // private ProjectCategory projectCategory; // // private List<Component> components; // private List<IssueType> issueTypes; // private List<Version> versions; // // private String projectTypeKey; // // private boolean archived; // } // Path: src/test/java/com/lesstif/jira/services/ProjectTest.java import java.io.IOException; import java.util.List; import java.util.Optional; import com.lesstif.jira.issue.IssueType; import org.apache.commons.configuration.ConfigurationException; import org.hamcrest.Matchers; import org.hamcrest.text.IsEmptyString; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.lesstif.jira.project.Project; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; package com.lesstif.jira.services; public class ProjectTest { private Logger logger = LoggerFactory.getLogger(getClass()); @Test public void listProject() throws IOException, ConfigurationException { ProjectService prjService = new ProjectService(); List<Project> projects = prjService.getProjectList(); int i = 0; for (Project prj : projects) { logger.info(i++ + "th " + prj.toPrettyJsonString() ); assertThat(prj.getId(), notNullValue()); assertThat(prj.getName(), notNullValue()); //assertThat(prj.getDescription(), not(emptyOrNullString()));
List<IssueType> issueTypes = prj.getIssueTypes();
lesstif/jira-rest-client
src/main/java/com/lesstif/jira/issue/Attachment.java
// Path: src/main/java/com/lesstif/jira/MyZonedDateTimeDeserializer.java // public class MyZonedDateTimeDeserializer extends JsonDeserializer<ZonedDateTime> { // // @SneakyThrows // @Override // public ZonedDateTime deserialize(JsonParser jsonParser, // DeserializationContext deserializationContext) throws IOException { // // SimpleDateFormat dtf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX"); // Date parsedDate = dtf.parse(jsonParser.getText()); // // return ZonedDateTime.ofInstant(parsedDate.toInstant(), // ZoneId.systemDefault()); // } // } // // Path: src/main/java/com/lesstif/jira/JsonPrettyString.java // public class JsonPrettyString { // // final public String toPrettyJsonString() { // ObjectMapper mapper = new ObjectMapper(); // // mapper.configure(SerializationFeature.INDENT_OUTPUT, true); // // StringWriter sw = new StringWriter(); // try { // mapper.writeValue(sw, this); // } catch (IOException e) { // return toString(); // } // // return sw.toString(); // } // // /** // * Map to Pretty Json String // * // * @param map map data // * @return Json String // */ // public static String mapToPrettyJsonString(Map<String, Object> map) { // ObjectMapper mapper = new ObjectMapper(); // // mapper.configure(SerializationFeature.INDENT_OUTPUT, true); // // String jsonStr = ""; // try { // jsonStr = mapper.writeValueAsString(map); // } catch (IOException e) { // e.printStackTrace(); // } // // return jsonStr; // } // // }
import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer; import com.fasterxml.jackson.datatype.jsr310.ser.ZonedDateTimeSerializer; import com.lesstif.jira.MyZonedDateTimeDeserializer; import lombok.Data; import lombok.EqualsAndHashCode; import com.lesstif.jira.JsonPrettyString; import java.time.LocalDateTime; import java.time.ZonedDateTime;
package com.lesstif.jira.issue; /** * @see https://docs.atlassian.com/jira/REST/latest/#d2e4213 * * @author lesstif * */ @EqualsAndHashCode(callSuper=false) @Data @JsonIgnoreProperties({"properties"})
// Path: src/main/java/com/lesstif/jira/MyZonedDateTimeDeserializer.java // public class MyZonedDateTimeDeserializer extends JsonDeserializer<ZonedDateTime> { // // @SneakyThrows // @Override // public ZonedDateTime deserialize(JsonParser jsonParser, // DeserializationContext deserializationContext) throws IOException { // // SimpleDateFormat dtf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX"); // Date parsedDate = dtf.parse(jsonParser.getText()); // // return ZonedDateTime.ofInstant(parsedDate.toInstant(), // ZoneId.systemDefault()); // } // } // // Path: src/main/java/com/lesstif/jira/JsonPrettyString.java // public class JsonPrettyString { // // final public String toPrettyJsonString() { // ObjectMapper mapper = new ObjectMapper(); // // mapper.configure(SerializationFeature.INDENT_OUTPUT, true); // // StringWriter sw = new StringWriter(); // try { // mapper.writeValue(sw, this); // } catch (IOException e) { // return toString(); // } // // return sw.toString(); // } // // /** // * Map to Pretty Json String // * // * @param map map data // * @return Json String // */ // public static String mapToPrettyJsonString(Map<String, Object> map) { // ObjectMapper mapper = new ObjectMapper(); // // mapper.configure(SerializationFeature.INDENT_OUTPUT, true); // // String jsonStr = ""; // try { // jsonStr = mapper.writeValueAsString(map); // } catch (IOException e) { // e.printStackTrace(); // } // // return jsonStr; // } // // } // Path: src/main/java/com/lesstif/jira/issue/Attachment.java import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer; import com.fasterxml.jackson.datatype.jsr310.ser.ZonedDateTimeSerializer; import com.lesstif.jira.MyZonedDateTimeDeserializer; import lombok.Data; import lombok.EqualsAndHashCode; import com.lesstif.jira.JsonPrettyString; import java.time.LocalDateTime; import java.time.ZonedDateTime; package com.lesstif.jira.issue; /** * @see https://docs.atlassian.com/jira/REST/latest/#d2e4213 * * @author lesstif * */ @EqualsAndHashCode(callSuper=false) @Data @JsonIgnoreProperties({"properties"})
public class Attachment extends JsonPrettyString{
lesstif/jira-rest-client
src/main/java/com/lesstif/jira/issue/Attachment.java
// Path: src/main/java/com/lesstif/jira/MyZonedDateTimeDeserializer.java // public class MyZonedDateTimeDeserializer extends JsonDeserializer<ZonedDateTime> { // // @SneakyThrows // @Override // public ZonedDateTime deserialize(JsonParser jsonParser, // DeserializationContext deserializationContext) throws IOException { // // SimpleDateFormat dtf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX"); // Date parsedDate = dtf.parse(jsonParser.getText()); // // return ZonedDateTime.ofInstant(parsedDate.toInstant(), // ZoneId.systemDefault()); // } // } // // Path: src/main/java/com/lesstif/jira/JsonPrettyString.java // public class JsonPrettyString { // // final public String toPrettyJsonString() { // ObjectMapper mapper = new ObjectMapper(); // // mapper.configure(SerializationFeature.INDENT_OUTPUT, true); // // StringWriter sw = new StringWriter(); // try { // mapper.writeValue(sw, this); // } catch (IOException e) { // return toString(); // } // // return sw.toString(); // } // // /** // * Map to Pretty Json String // * // * @param map map data // * @return Json String // */ // public static String mapToPrettyJsonString(Map<String, Object> map) { // ObjectMapper mapper = new ObjectMapper(); // // mapper.configure(SerializationFeature.INDENT_OUTPUT, true); // // String jsonStr = ""; // try { // jsonStr = mapper.writeValueAsString(map); // } catch (IOException e) { // e.printStackTrace(); // } // // return jsonStr; // } // // }
import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer; import com.fasterxml.jackson.datatype.jsr310.ser.ZonedDateTimeSerializer; import com.lesstif.jira.MyZonedDateTimeDeserializer; import lombok.Data; import lombok.EqualsAndHashCode; import com.lesstif.jira.JsonPrettyString; import java.time.LocalDateTime; import java.time.ZonedDateTime;
package com.lesstif.jira.issue; /** * @see https://docs.atlassian.com/jira/REST/latest/#d2e4213 * * @author lesstif * */ @EqualsAndHashCode(callSuper=false) @Data @JsonIgnoreProperties({"properties"}) public class Attachment extends JsonPrettyString{ private String id; private String self; private String filename; private Reporter author; @JsonSerialize(using = ZonedDateTimeSerializer.class)
// Path: src/main/java/com/lesstif/jira/MyZonedDateTimeDeserializer.java // public class MyZonedDateTimeDeserializer extends JsonDeserializer<ZonedDateTime> { // // @SneakyThrows // @Override // public ZonedDateTime deserialize(JsonParser jsonParser, // DeserializationContext deserializationContext) throws IOException { // // SimpleDateFormat dtf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX"); // Date parsedDate = dtf.parse(jsonParser.getText()); // // return ZonedDateTime.ofInstant(parsedDate.toInstant(), // ZoneId.systemDefault()); // } // } // // Path: src/main/java/com/lesstif/jira/JsonPrettyString.java // public class JsonPrettyString { // // final public String toPrettyJsonString() { // ObjectMapper mapper = new ObjectMapper(); // // mapper.configure(SerializationFeature.INDENT_OUTPUT, true); // // StringWriter sw = new StringWriter(); // try { // mapper.writeValue(sw, this); // } catch (IOException e) { // return toString(); // } // // return sw.toString(); // } // // /** // * Map to Pretty Json String // * // * @param map map data // * @return Json String // */ // public static String mapToPrettyJsonString(Map<String, Object> map) { // ObjectMapper mapper = new ObjectMapper(); // // mapper.configure(SerializationFeature.INDENT_OUTPUT, true); // // String jsonStr = ""; // try { // jsonStr = mapper.writeValueAsString(map); // } catch (IOException e) { // e.printStackTrace(); // } // // return jsonStr; // } // // } // Path: src/main/java/com/lesstif/jira/issue/Attachment.java import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer; import com.fasterxml.jackson.datatype.jsr310.ser.ZonedDateTimeSerializer; import com.lesstif.jira.MyZonedDateTimeDeserializer; import lombok.Data; import lombok.EqualsAndHashCode; import com.lesstif.jira.JsonPrettyString; import java.time.LocalDateTime; import java.time.ZonedDateTime; package com.lesstif.jira.issue; /** * @see https://docs.atlassian.com/jira/REST/latest/#d2e4213 * * @author lesstif * */ @EqualsAndHashCode(callSuper=false) @Data @JsonIgnoreProperties({"properties"}) public class Attachment extends JsonPrettyString{ private String id; private String self; private String filename; private Reporter author; @JsonSerialize(using = ZonedDateTimeSerializer.class)
@JsonDeserialize(using = MyZonedDateTimeDeserializer.class)
lesstif/jira-rest-client
src/main/java/com/lesstif/jira/issue/IssueType.java
// Path: src/main/java/com/lesstif/jira/JsonPrettyString.java // public class JsonPrettyString { // // final public String toPrettyJsonString() { // ObjectMapper mapper = new ObjectMapper(); // // mapper.configure(SerializationFeature.INDENT_OUTPUT, true); // // StringWriter sw = new StringWriter(); // try { // mapper.writeValue(sw, this); // } catch (IOException e) { // return toString(); // } // // return sw.toString(); // } // // /** // * Map to Pretty Json String // * // * @param map map data // * @return Json String // */ // public static String mapToPrettyJsonString(Map<String, Object> map) { // ObjectMapper mapper = new ObjectMapper(); // // mapper.configure(SerializationFeature.INDENT_OUTPUT, true); // // String jsonStr = ""; // try { // jsonStr = mapper.writeValueAsString(map); // } catch (IOException e) { // e.printStackTrace(); // } // // return jsonStr; // } // // }
import com.lesstif.jira.JsonPrettyString; import lombok.Data; import lombok.EqualsAndHashCode;
package com.lesstif.jira.issue; @Data @EqualsAndHashCode(callSuper = false)
// Path: src/main/java/com/lesstif/jira/JsonPrettyString.java // public class JsonPrettyString { // // final public String toPrettyJsonString() { // ObjectMapper mapper = new ObjectMapper(); // // mapper.configure(SerializationFeature.INDENT_OUTPUT, true); // // StringWriter sw = new StringWriter(); // try { // mapper.writeValue(sw, this); // } catch (IOException e) { // return toString(); // } // // return sw.toString(); // } // // /** // * Map to Pretty Json String // * // * @param map map data // * @return Json String // */ // public static String mapToPrettyJsonString(Map<String, Object> map) { // ObjectMapper mapper = new ObjectMapper(); // // mapper.configure(SerializationFeature.INDENT_OUTPUT, true); // // String jsonStr = ""; // try { // jsonStr = mapper.writeValueAsString(map); // } catch (IOException e) { // e.printStackTrace(); // } // // return jsonStr; // } // // } // Path: src/main/java/com/lesstif/jira/issue/IssueType.java import com.lesstif.jira.JsonPrettyString; import lombok.Data; import lombok.EqualsAndHashCode; package com.lesstif.jira.issue; @Data @EqualsAndHashCode(callSuper = false)
public class IssueType extends JsonPrettyString {
lesstif/jira-rest-client
src/main/java/com/lesstif/jira/issue/Author.java
// Path: src/main/java/com/lesstif/jira/JsonPrettyString.java // public class JsonPrettyString { // // final public String toPrettyJsonString() { // ObjectMapper mapper = new ObjectMapper(); // // mapper.configure(SerializationFeature.INDENT_OUTPUT, true); // // StringWriter sw = new StringWriter(); // try { // mapper.writeValue(sw, this); // } catch (IOException e) { // return toString(); // } // // return sw.toString(); // } // // /** // * Map to Pretty Json String // * // * @param map map data // * @return Json String // */ // public static String mapToPrettyJsonString(Map<String, Object> map) { // ObjectMapper mapper = new ObjectMapper(); // // mapper.configure(SerializationFeature.INDENT_OUTPUT, true); // // String jsonStr = ""; // try { // jsonStr = mapper.writeValueAsString(map); // } catch (IOException e) { // e.printStackTrace(); // } // // return jsonStr; // } // // }
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.lesstif.jira.JsonPrettyString; import lombok.Data; import lombok.EqualsAndHashCode;
package com.lesstif.jira.issue; @EqualsAndHashCode(callSuper=false) @JsonIgnoreProperties({"avatarUrls" })
// Path: src/main/java/com/lesstif/jira/JsonPrettyString.java // public class JsonPrettyString { // // final public String toPrettyJsonString() { // ObjectMapper mapper = new ObjectMapper(); // // mapper.configure(SerializationFeature.INDENT_OUTPUT, true); // // StringWriter sw = new StringWriter(); // try { // mapper.writeValue(sw, this); // } catch (IOException e) { // return toString(); // } // // return sw.toString(); // } // // /** // * Map to Pretty Json String // * // * @param map map data // * @return Json String // */ // public static String mapToPrettyJsonString(Map<String, Object> map) { // ObjectMapper mapper = new ObjectMapper(); // // mapper.configure(SerializationFeature.INDENT_OUTPUT, true); // // String jsonStr = ""; // try { // jsonStr = mapper.writeValueAsString(map); // } catch (IOException e) { // e.printStackTrace(); // } // // return jsonStr; // } // // } // Path: src/main/java/com/lesstif/jira/issue/Author.java import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.lesstif.jira.JsonPrettyString; import lombok.Data; import lombok.EqualsAndHashCode; package com.lesstif.jira.issue; @EqualsAndHashCode(callSuper=false) @JsonIgnoreProperties({"avatarUrls" })
public class Author extends JsonPrettyString {
lesstif/jira-rest-client
src/main/java/com/lesstif/jira/project/Project.java
// Path: src/main/java/com/lesstif/jira/JsonPrettyString.java // public class JsonPrettyString { // // final public String toPrettyJsonString() { // ObjectMapper mapper = new ObjectMapper(); // // mapper.configure(SerializationFeature.INDENT_OUTPUT, true); // // StringWriter sw = new StringWriter(); // try { // mapper.writeValue(sw, this); // } catch (IOException e) { // return toString(); // } // // return sw.toString(); // } // // /** // * Map to Pretty Json String // * // * @param map map data // * @return Json String // */ // public static String mapToPrettyJsonString(Map<String, Object> map) { // ObjectMapper mapper = new ObjectMapper(); // // mapper.configure(SerializationFeature.INDENT_OUTPUT, true); // // String jsonStr = ""; // try { // jsonStr = mapper.writeValueAsString(map); // } catch (IOException e) { // e.printStackTrace(); // } // // return jsonStr; // } // // } // // Path: src/main/java/com/lesstif/jira/issue/Component.java // @Data // public class Component { // public Component() { // // } // // public Component(String name) { // this.name = name; // } // // public Component(String id, String name) { // this.id = id; // this.name = name; // } // // private String self; // private String id; // private String name; // private String description; // // private Map<String, String> lead; // private String displayName; // private Boolean active; // // private Boolean isAssigneeTypeValid; // } // // Path: src/main/java/com/lesstif/jira/issue/IssueType.java // @Data // @EqualsAndHashCode(callSuper = false) // public class IssueType extends JsonPrettyString { // // Default issue type // public static final String ISSUE_TYPE_BUG = "Bug"; // public static final String ISSUE_TYPE_TASK = "Task"; // public static final String ISSUE_TYPE_IMPROVEMENT = "Improvement"; // public static final String ISSUE_TYPE_SUBTASK = "SubTask"; // public static final String ISSUE_TYPE_NEW_FEATURE = "New Feature"; // // private String self; // private String id; // private String description; // private String iconUrl; // private String name; // private Boolean subtask; // private Integer avatarId; // } // // Path: src/main/java/com/lesstif/jira/issue/Lead.java // @Data // public class Lead { // private String self; // private String name; // private AvatarUrl avatarUrls; // private String displayName; // private Boolean active; // private String key; // } // // Path: src/main/java/com/lesstif/jira/issue/Version.java // @Data // public class Version { // private String self; // private String id; // private String description; // private String name; // private Boolean archived; // private Boolean released; // // @JsonSerialize(using = LocalDateSerializer.class) // @JsonDeserialize(using = LocalDateDeserializer.class) // private LocalDate releaseDate; // // private Boolean overdue; // private String userReleaseDate; // private String projectId; // // @JsonSerialize(using = LocalDateSerializer.class) // @JsonDeserialize(using = LocalDateDeserializer.class) // private LocalDate startDate; // // private String userStartDate; // }
import java.time.LocalDateTime; import java.util.List; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer; import lombok.EqualsAndHashCode; import lombok.Data; import com.lesstif.jira.JsonPrettyString; import com.lesstif.jira.issue.Component; import com.lesstif.jira.issue.IssueType; import com.lesstif.jira.issue.Lead; import com.lesstif.jira.issue.Version;
package com.lesstif.jira.project; /** * @see <a href="https://docs.atlassian.com/software/jira/docs/api/REST/latest/#d2e86">/rest/api/2/project</a> * * @author lesstif * */ @Data @EqualsAndHashCode(callSuper=false) @JsonIgnoreProperties({"assigneeType", "roles" })
// Path: src/main/java/com/lesstif/jira/JsonPrettyString.java // public class JsonPrettyString { // // final public String toPrettyJsonString() { // ObjectMapper mapper = new ObjectMapper(); // // mapper.configure(SerializationFeature.INDENT_OUTPUT, true); // // StringWriter sw = new StringWriter(); // try { // mapper.writeValue(sw, this); // } catch (IOException e) { // return toString(); // } // // return sw.toString(); // } // // /** // * Map to Pretty Json String // * // * @param map map data // * @return Json String // */ // public static String mapToPrettyJsonString(Map<String, Object> map) { // ObjectMapper mapper = new ObjectMapper(); // // mapper.configure(SerializationFeature.INDENT_OUTPUT, true); // // String jsonStr = ""; // try { // jsonStr = mapper.writeValueAsString(map); // } catch (IOException e) { // e.printStackTrace(); // } // // return jsonStr; // } // // } // // Path: src/main/java/com/lesstif/jira/issue/Component.java // @Data // public class Component { // public Component() { // // } // // public Component(String name) { // this.name = name; // } // // public Component(String id, String name) { // this.id = id; // this.name = name; // } // // private String self; // private String id; // private String name; // private String description; // // private Map<String, String> lead; // private String displayName; // private Boolean active; // // private Boolean isAssigneeTypeValid; // } // // Path: src/main/java/com/lesstif/jira/issue/IssueType.java // @Data // @EqualsAndHashCode(callSuper = false) // public class IssueType extends JsonPrettyString { // // Default issue type // public static final String ISSUE_TYPE_BUG = "Bug"; // public static final String ISSUE_TYPE_TASK = "Task"; // public static final String ISSUE_TYPE_IMPROVEMENT = "Improvement"; // public static final String ISSUE_TYPE_SUBTASK = "SubTask"; // public static final String ISSUE_TYPE_NEW_FEATURE = "New Feature"; // // private String self; // private String id; // private String description; // private String iconUrl; // private String name; // private Boolean subtask; // private Integer avatarId; // } // // Path: src/main/java/com/lesstif/jira/issue/Lead.java // @Data // public class Lead { // private String self; // private String name; // private AvatarUrl avatarUrls; // private String displayName; // private Boolean active; // private String key; // } // // Path: src/main/java/com/lesstif/jira/issue/Version.java // @Data // public class Version { // private String self; // private String id; // private String description; // private String name; // private Boolean archived; // private Boolean released; // // @JsonSerialize(using = LocalDateSerializer.class) // @JsonDeserialize(using = LocalDateDeserializer.class) // private LocalDate releaseDate; // // private Boolean overdue; // private String userReleaseDate; // private String projectId; // // @JsonSerialize(using = LocalDateSerializer.class) // @JsonDeserialize(using = LocalDateDeserializer.class) // private LocalDate startDate; // // private String userStartDate; // } // Path: src/main/java/com/lesstif/jira/project/Project.java import java.time.LocalDateTime; import java.util.List; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer; import lombok.EqualsAndHashCode; import lombok.Data; import com.lesstif.jira.JsonPrettyString; import com.lesstif.jira.issue.Component; import com.lesstif.jira.issue.IssueType; import com.lesstif.jira.issue.Lead; import com.lesstif.jira.issue.Version; package com.lesstif.jira.project; /** * @see <a href="https://docs.atlassian.com/software/jira/docs/api/REST/latest/#d2e86">/rest/api/2/project</a> * * @author lesstif * */ @Data @EqualsAndHashCode(callSuper=false) @JsonIgnoreProperties({"assigneeType", "roles" })
public class Project extends JsonPrettyString{
lesstif/jira-rest-client
src/main/java/com/lesstif/jira/project/Project.java
// Path: src/main/java/com/lesstif/jira/JsonPrettyString.java // public class JsonPrettyString { // // final public String toPrettyJsonString() { // ObjectMapper mapper = new ObjectMapper(); // // mapper.configure(SerializationFeature.INDENT_OUTPUT, true); // // StringWriter sw = new StringWriter(); // try { // mapper.writeValue(sw, this); // } catch (IOException e) { // return toString(); // } // // return sw.toString(); // } // // /** // * Map to Pretty Json String // * // * @param map map data // * @return Json String // */ // public static String mapToPrettyJsonString(Map<String, Object> map) { // ObjectMapper mapper = new ObjectMapper(); // // mapper.configure(SerializationFeature.INDENT_OUTPUT, true); // // String jsonStr = ""; // try { // jsonStr = mapper.writeValueAsString(map); // } catch (IOException e) { // e.printStackTrace(); // } // // return jsonStr; // } // // } // // Path: src/main/java/com/lesstif/jira/issue/Component.java // @Data // public class Component { // public Component() { // // } // // public Component(String name) { // this.name = name; // } // // public Component(String id, String name) { // this.id = id; // this.name = name; // } // // private String self; // private String id; // private String name; // private String description; // // private Map<String, String> lead; // private String displayName; // private Boolean active; // // private Boolean isAssigneeTypeValid; // } // // Path: src/main/java/com/lesstif/jira/issue/IssueType.java // @Data // @EqualsAndHashCode(callSuper = false) // public class IssueType extends JsonPrettyString { // // Default issue type // public static final String ISSUE_TYPE_BUG = "Bug"; // public static final String ISSUE_TYPE_TASK = "Task"; // public static final String ISSUE_TYPE_IMPROVEMENT = "Improvement"; // public static final String ISSUE_TYPE_SUBTASK = "SubTask"; // public static final String ISSUE_TYPE_NEW_FEATURE = "New Feature"; // // private String self; // private String id; // private String description; // private String iconUrl; // private String name; // private Boolean subtask; // private Integer avatarId; // } // // Path: src/main/java/com/lesstif/jira/issue/Lead.java // @Data // public class Lead { // private String self; // private String name; // private AvatarUrl avatarUrls; // private String displayName; // private Boolean active; // private String key; // } // // Path: src/main/java/com/lesstif/jira/issue/Version.java // @Data // public class Version { // private String self; // private String id; // private String description; // private String name; // private Boolean archived; // private Boolean released; // // @JsonSerialize(using = LocalDateSerializer.class) // @JsonDeserialize(using = LocalDateDeserializer.class) // private LocalDate releaseDate; // // private Boolean overdue; // private String userReleaseDate; // private String projectId; // // @JsonSerialize(using = LocalDateSerializer.class) // @JsonDeserialize(using = LocalDateDeserializer.class) // private LocalDate startDate; // // private String userStartDate; // }
import java.time.LocalDateTime; import java.util.List; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer; import lombok.EqualsAndHashCode; import lombok.Data; import com.lesstif.jira.JsonPrettyString; import com.lesstif.jira.issue.Component; import com.lesstif.jira.issue.IssueType; import com.lesstif.jira.issue.Lead; import com.lesstif.jira.issue.Version;
package com.lesstif.jira.project; /** * @see <a href="https://docs.atlassian.com/software/jira/docs/api/REST/latest/#d2e86">/rest/api/2/project</a> * * @author lesstif * */ @Data @EqualsAndHashCode(callSuper=false) @JsonIgnoreProperties({"assigneeType", "roles" }) public class Project extends JsonPrettyString{ private String expand; private String self; private String id; private String key; private String description; private String name; private String url; @JsonSerialize(using = LocalDateSerializer.class) @JsonDeserialize(using = LocalDateDeserializer.class) private LocalDateTime startDate;
// Path: src/main/java/com/lesstif/jira/JsonPrettyString.java // public class JsonPrettyString { // // final public String toPrettyJsonString() { // ObjectMapper mapper = new ObjectMapper(); // // mapper.configure(SerializationFeature.INDENT_OUTPUT, true); // // StringWriter sw = new StringWriter(); // try { // mapper.writeValue(sw, this); // } catch (IOException e) { // return toString(); // } // // return sw.toString(); // } // // /** // * Map to Pretty Json String // * // * @param map map data // * @return Json String // */ // public static String mapToPrettyJsonString(Map<String, Object> map) { // ObjectMapper mapper = new ObjectMapper(); // // mapper.configure(SerializationFeature.INDENT_OUTPUT, true); // // String jsonStr = ""; // try { // jsonStr = mapper.writeValueAsString(map); // } catch (IOException e) { // e.printStackTrace(); // } // // return jsonStr; // } // // } // // Path: src/main/java/com/lesstif/jira/issue/Component.java // @Data // public class Component { // public Component() { // // } // // public Component(String name) { // this.name = name; // } // // public Component(String id, String name) { // this.id = id; // this.name = name; // } // // private String self; // private String id; // private String name; // private String description; // // private Map<String, String> lead; // private String displayName; // private Boolean active; // // private Boolean isAssigneeTypeValid; // } // // Path: src/main/java/com/lesstif/jira/issue/IssueType.java // @Data // @EqualsAndHashCode(callSuper = false) // public class IssueType extends JsonPrettyString { // // Default issue type // public static final String ISSUE_TYPE_BUG = "Bug"; // public static final String ISSUE_TYPE_TASK = "Task"; // public static final String ISSUE_TYPE_IMPROVEMENT = "Improvement"; // public static final String ISSUE_TYPE_SUBTASK = "SubTask"; // public static final String ISSUE_TYPE_NEW_FEATURE = "New Feature"; // // private String self; // private String id; // private String description; // private String iconUrl; // private String name; // private Boolean subtask; // private Integer avatarId; // } // // Path: src/main/java/com/lesstif/jira/issue/Lead.java // @Data // public class Lead { // private String self; // private String name; // private AvatarUrl avatarUrls; // private String displayName; // private Boolean active; // private String key; // } // // Path: src/main/java/com/lesstif/jira/issue/Version.java // @Data // public class Version { // private String self; // private String id; // private String description; // private String name; // private Boolean archived; // private Boolean released; // // @JsonSerialize(using = LocalDateSerializer.class) // @JsonDeserialize(using = LocalDateDeserializer.class) // private LocalDate releaseDate; // // private Boolean overdue; // private String userReleaseDate; // private String projectId; // // @JsonSerialize(using = LocalDateSerializer.class) // @JsonDeserialize(using = LocalDateDeserializer.class) // private LocalDate startDate; // // private String userStartDate; // } // Path: src/main/java/com/lesstif/jira/project/Project.java import java.time.LocalDateTime; import java.util.List; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer; import lombok.EqualsAndHashCode; import lombok.Data; import com.lesstif.jira.JsonPrettyString; import com.lesstif.jira.issue.Component; import com.lesstif.jira.issue.IssueType; import com.lesstif.jira.issue.Lead; import com.lesstif.jira.issue.Version; package com.lesstif.jira.project; /** * @see <a href="https://docs.atlassian.com/software/jira/docs/api/REST/latest/#d2e86">/rest/api/2/project</a> * * @author lesstif * */ @Data @EqualsAndHashCode(callSuper=false) @JsonIgnoreProperties({"assigneeType", "roles" }) public class Project extends JsonPrettyString{ private String expand; private String self; private String id; private String key; private String description; private String name; private String url; @JsonSerialize(using = LocalDateSerializer.class) @JsonDeserialize(using = LocalDateDeserializer.class) private LocalDateTime startDate;
private Lead lead;
lesstif/jira-rest-client
src/main/java/com/lesstif/jira/project/Project.java
// Path: src/main/java/com/lesstif/jira/JsonPrettyString.java // public class JsonPrettyString { // // final public String toPrettyJsonString() { // ObjectMapper mapper = new ObjectMapper(); // // mapper.configure(SerializationFeature.INDENT_OUTPUT, true); // // StringWriter sw = new StringWriter(); // try { // mapper.writeValue(sw, this); // } catch (IOException e) { // return toString(); // } // // return sw.toString(); // } // // /** // * Map to Pretty Json String // * // * @param map map data // * @return Json String // */ // public static String mapToPrettyJsonString(Map<String, Object> map) { // ObjectMapper mapper = new ObjectMapper(); // // mapper.configure(SerializationFeature.INDENT_OUTPUT, true); // // String jsonStr = ""; // try { // jsonStr = mapper.writeValueAsString(map); // } catch (IOException e) { // e.printStackTrace(); // } // // return jsonStr; // } // // } // // Path: src/main/java/com/lesstif/jira/issue/Component.java // @Data // public class Component { // public Component() { // // } // // public Component(String name) { // this.name = name; // } // // public Component(String id, String name) { // this.id = id; // this.name = name; // } // // private String self; // private String id; // private String name; // private String description; // // private Map<String, String> lead; // private String displayName; // private Boolean active; // // private Boolean isAssigneeTypeValid; // } // // Path: src/main/java/com/lesstif/jira/issue/IssueType.java // @Data // @EqualsAndHashCode(callSuper = false) // public class IssueType extends JsonPrettyString { // // Default issue type // public static final String ISSUE_TYPE_BUG = "Bug"; // public static final String ISSUE_TYPE_TASK = "Task"; // public static final String ISSUE_TYPE_IMPROVEMENT = "Improvement"; // public static final String ISSUE_TYPE_SUBTASK = "SubTask"; // public static final String ISSUE_TYPE_NEW_FEATURE = "New Feature"; // // private String self; // private String id; // private String description; // private String iconUrl; // private String name; // private Boolean subtask; // private Integer avatarId; // } // // Path: src/main/java/com/lesstif/jira/issue/Lead.java // @Data // public class Lead { // private String self; // private String name; // private AvatarUrl avatarUrls; // private String displayName; // private Boolean active; // private String key; // } // // Path: src/main/java/com/lesstif/jira/issue/Version.java // @Data // public class Version { // private String self; // private String id; // private String description; // private String name; // private Boolean archived; // private Boolean released; // // @JsonSerialize(using = LocalDateSerializer.class) // @JsonDeserialize(using = LocalDateDeserializer.class) // private LocalDate releaseDate; // // private Boolean overdue; // private String userReleaseDate; // private String projectId; // // @JsonSerialize(using = LocalDateSerializer.class) // @JsonDeserialize(using = LocalDateDeserializer.class) // private LocalDate startDate; // // private String userStartDate; // }
import java.time.LocalDateTime; import java.util.List; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer; import lombok.EqualsAndHashCode; import lombok.Data; import com.lesstif.jira.JsonPrettyString; import com.lesstif.jira.issue.Component; import com.lesstif.jira.issue.IssueType; import com.lesstif.jira.issue.Lead; import com.lesstif.jira.issue.Version;
package com.lesstif.jira.project; /** * @see <a href="https://docs.atlassian.com/software/jira/docs/api/REST/latest/#d2e86">/rest/api/2/project</a> * * @author lesstif * */ @Data @EqualsAndHashCode(callSuper=false) @JsonIgnoreProperties({"assigneeType", "roles" }) public class Project extends JsonPrettyString{ private String expand; private String self; private String id; private String key; private String description; private String name; private String url; @JsonSerialize(using = LocalDateSerializer.class) @JsonDeserialize(using = LocalDateDeserializer.class) private LocalDateTime startDate; private Lead lead; private AvatarUrl avatarUrls; private ProjectCategory projectCategory;
// Path: src/main/java/com/lesstif/jira/JsonPrettyString.java // public class JsonPrettyString { // // final public String toPrettyJsonString() { // ObjectMapper mapper = new ObjectMapper(); // // mapper.configure(SerializationFeature.INDENT_OUTPUT, true); // // StringWriter sw = new StringWriter(); // try { // mapper.writeValue(sw, this); // } catch (IOException e) { // return toString(); // } // // return sw.toString(); // } // // /** // * Map to Pretty Json String // * // * @param map map data // * @return Json String // */ // public static String mapToPrettyJsonString(Map<String, Object> map) { // ObjectMapper mapper = new ObjectMapper(); // // mapper.configure(SerializationFeature.INDENT_OUTPUT, true); // // String jsonStr = ""; // try { // jsonStr = mapper.writeValueAsString(map); // } catch (IOException e) { // e.printStackTrace(); // } // // return jsonStr; // } // // } // // Path: src/main/java/com/lesstif/jira/issue/Component.java // @Data // public class Component { // public Component() { // // } // // public Component(String name) { // this.name = name; // } // // public Component(String id, String name) { // this.id = id; // this.name = name; // } // // private String self; // private String id; // private String name; // private String description; // // private Map<String, String> lead; // private String displayName; // private Boolean active; // // private Boolean isAssigneeTypeValid; // } // // Path: src/main/java/com/lesstif/jira/issue/IssueType.java // @Data // @EqualsAndHashCode(callSuper = false) // public class IssueType extends JsonPrettyString { // // Default issue type // public static final String ISSUE_TYPE_BUG = "Bug"; // public static final String ISSUE_TYPE_TASK = "Task"; // public static final String ISSUE_TYPE_IMPROVEMENT = "Improvement"; // public static final String ISSUE_TYPE_SUBTASK = "SubTask"; // public static final String ISSUE_TYPE_NEW_FEATURE = "New Feature"; // // private String self; // private String id; // private String description; // private String iconUrl; // private String name; // private Boolean subtask; // private Integer avatarId; // } // // Path: src/main/java/com/lesstif/jira/issue/Lead.java // @Data // public class Lead { // private String self; // private String name; // private AvatarUrl avatarUrls; // private String displayName; // private Boolean active; // private String key; // } // // Path: src/main/java/com/lesstif/jira/issue/Version.java // @Data // public class Version { // private String self; // private String id; // private String description; // private String name; // private Boolean archived; // private Boolean released; // // @JsonSerialize(using = LocalDateSerializer.class) // @JsonDeserialize(using = LocalDateDeserializer.class) // private LocalDate releaseDate; // // private Boolean overdue; // private String userReleaseDate; // private String projectId; // // @JsonSerialize(using = LocalDateSerializer.class) // @JsonDeserialize(using = LocalDateDeserializer.class) // private LocalDate startDate; // // private String userStartDate; // } // Path: src/main/java/com/lesstif/jira/project/Project.java import java.time.LocalDateTime; import java.util.List; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer; import lombok.EqualsAndHashCode; import lombok.Data; import com.lesstif.jira.JsonPrettyString; import com.lesstif.jira.issue.Component; import com.lesstif.jira.issue.IssueType; import com.lesstif.jira.issue.Lead; import com.lesstif.jira.issue.Version; package com.lesstif.jira.project; /** * @see <a href="https://docs.atlassian.com/software/jira/docs/api/REST/latest/#d2e86">/rest/api/2/project</a> * * @author lesstif * */ @Data @EqualsAndHashCode(callSuper=false) @JsonIgnoreProperties({"assigneeType", "roles" }) public class Project extends JsonPrettyString{ private String expand; private String self; private String id; private String key; private String description; private String name; private String url; @JsonSerialize(using = LocalDateSerializer.class) @JsonDeserialize(using = LocalDateDeserializer.class) private LocalDateTime startDate; private Lead lead; private AvatarUrl avatarUrls; private ProjectCategory projectCategory;
private List<Component> components;
lesstif/jira-rest-client
src/main/java/com/lesstif/jira/project/Project.java
// Path: src/main/java/com/lesstif/jira/JsonPrettyString.java // public class JsonPrettyString { // // final public String toPrettyJsonString() { // ObjectMapper mapper = new ObjectMapper(); // // mapper.configure(SerializationFeature.INDENT_OUTPUT, true); // // StringWriter sw = new StringWriter(); // try { // mapper.writeValue(sw, this); // } catch (IOException e) { // return toString(); // } // // return sw.toString(); // } // // /** // * Map to Pretty Json String // * // * @param map map data // * @return Json String // */ // public static String mapToPrettyJsonString(Map<String, Object> map) { // ObjectMapper mapper = new ObjectMapper(); // // mapper.configure(SerializationFeature.INDENT_OUTPUT, true); // // String jsonStr = ""; // try { // jsonStr = mapper.writeValueAsString(map); // } catch (IOException e) { // e.printStackTrace(); // } // // return jsonStr; // } // // } // // Path: src/main/java/com/lesstif/jira/issue/Component.java // @Data // public class Component { // public Component() { // // } // // public Component(String name) { // this.name = name; // } // // public Component(String id, String name) { // this.id = id; // this.name = name; // } // // private String self; // private String id; // private String name; // private String description; // // private Map<String, String> lead; // private String displayName; // private Boolean active; // // private Boolean isAssigneeTypeValid; // } // // Path: src/main/java/com/lesstif/jira/issue/IssueType.java // @Data // @EqualsAndHashCode(callSuper = false) // public class IssueType extends JsonPrettyString { // // Default issue type // public static final String ISSUE_TYPE_BUG = "Bug"; // public static final String ISSUE_TYPE_TASK = "Task"; // public static final String ISSUE_TYPE_IMPROVEMENT = "Improvement"; // public static final String ISSUE_TYPE_SUBTASK = "SubTask"; // public static final String ISSUE_TYPE_NEW_FEATURE = "New Feature"; // // private String self; // private String id; // private String description; // private String iconUrl; // private String name; // private Boolean subtask; // private Integer avatarId; // } // // Path: src/main/java/com/lesstif/jira/issue/Lead.java // @Data // public class Lead { // private String self; // private String name; // private AvatarUrl avatarUrls; // private String displayName; // private Boolean active; // private String key; // } // // Path: src/main/java/com/lesstif/jira/issue/Version.java // @Data // public class Version { // private String self; // private String id; // private String description; // private String name; // private Boolean archived; // private Boolean released; // // @JsonSerialize(using = LocalDateSerializer.class) // @JsonDeserialize(using = LocalDateDeserializer.class) // private LocalDate releaseDate; // // private Boolean overdue; // private String userReleaseDate; // private String projectId; // // @JsonSerialize(using = LocalDateSerializer.class) // @JsonDeserialize(using = LocalDateDeserializer.class) // private LocalDate startDate; // // private String userStartDate; // }
import java.time.LocalDateTime; import java.util.List; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer; import lombok.EqualsAndHashCode; import lombok.Data; import com.lesstif.jira.JsonPrettyString; import com.lesstif.jira.issue.Component; import com.lesstif.jira.issue.IssueType; import com.lesstif.jira.issue.Lead; import com.lesstif.jira.issue.Version;
package com.lesstif.jira.project; /** * @see <a href="https://docs.atlassian.com/software/jira/docs/api/REST/latest/#d2e86">/rest/api/2/project</a> * * @author lesstif * */ @Data @EqualsAndHashCode(callSuper=false) @JsonIgnoreProperties({"assigneeType", "roles" }) public class Project extends JsonPrettyString{ private String expand; private String self; private String id; private String key; private String description; private String name; private String url; @JsonSerialize(using = LocalDateSerializer.class) @JsonDeserialize(using = LocalDateDeserializer.class) private LocalDateTime startDate; private Lead lead; private AvatarUrl avatarUrls; private ProjectCategory projectCategory; private List<Component> components;
// Path: src/main/java/com/lesstif/jira/JsonPrettyString.java // public class JsonPrettyString { // // final public String toPrettyJsonString() { // ObjectMapper mapper = new ObjectMapper(); // // mapper.configure(SerializationFeature.INDENT_OUTPUT, true); // // StringWriter sw = new StringWriter(); // try { // mapper.writeValue(sw, this); // } catch (IOException e) { // return toString(); // } // // return sw.toString(); // } // // /** // * Map to Pretty Json String // * // * @param map map data // * @return Json String // */ // public static String mapToPrettyJsonString(Map<String, Object> map) { // ObjectMapper mapper = new ObjectMapper(); // // mapper.configure(SerializationFeature.INDENT_OUTPUT, true); // // String jsonStr = ""; // try { // jsonStr = mapper.writeValueAsString(map); // } catch (IOException e) { // e.printStackTrace(); // } // // return jsonStr; // } // // } // // Path: src/main/java/com/lesstif/jira/issue/Component.java // @Data // public class Component { // public Component() { // // } // // public Component(String name) { // this.name = name; // } // // public Component(String id, String name) { // this.id = id; // this.name = name; // } // // private String self; // private String id; // private String name; // private String description; // // private Map<String, String> lead; // private String displayName; // private Boolean active; // // private Boolean isAssigneeTypeValid; // } // // Path: src/main/java/com/lesstif/jira/issue/IssueType.java // @Data // @EqualsAndHashCode(callSuper = false) // public class IssueType extends JsonPrettyString { // // Default issue type // public static final String ISSUE_TYPE_BUG = "Bug"; // public static final String ISSUE_TYPE_TASK = "Task"; // public static final String ISSUE_TYPE_IMPROVEMENT = "Improvement"; // public static final String ISSUE_TYPE_SUBTASK = "SubTask"; // public static final String ISSUE_TYPE_NEW_FEATURE = "New Feature"; // // private String self; // private String id; // private String description; // private String iconUrl; // private String name; // private Boolean subtask; // private Integer avatarId; // } // // Path: src/main/java/com/lesstif/jira/issue/Lead.java // @Data // public class Lead { // private String self; // private String name; // private AvatarUrl avatarUrls; // private String displayName; // private Boolean active; // private String key; // } // // Path: src/main/java/com/lesstif/jira/issue/Version.java // @Data // public class Version { // private String self; // private String id; // private String description; // private String name; // private Boolean archived; // private Boolean released; // // @JsonSerialize(using = LocalDateSerializer.class) // @JsonDeserialize(using = LocalDateDeserializer.class) // private LocalDate releaseDate; // // private Boolean overdue; // private String userReleaseDate; // private String projectId; // // @JsonSerialize(using = LocalDateSerializer.class) // @JsonDeserialize(using = LocalDateDeserializer.class) // private LocalDate startDate; // // private String userStartDate; // } // Path: src/main/java/com/lesstif/jira/project/Project.java import java.time.LocalDateTime; import java.util.List; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer; import lombok.EqualsAndHashCode; import lombok.Data; import com.lesstif.jira.JsonPrettyString; import com.lesstif.jira.issue.Component; import com.lesstif.jira.issue.IssueType; import com.lesstif.jira.issue.Lead; import com.lesstif.jira.issue.Version; package com.lesstif.jira.project; /** * @see <a href="https://docs.atlassian.com/software/jira/docs/api/REST/latest/#d2e86">/rest/api/2/project</a> * * @author lesstif * */ @Data @EqualsAndHashCode(callSuper=false) @JsonIgnoreProperties({"assigneeType", "roles" }) public class Project extends JsonPrettyString{ private String expand; private String self; private String id; private String key; private String description; private String name; private String url; @JsonSerialize(using = LocalDateSerializer.class) @JsonDeserialize(using = LocalDateDeserializer.class) private LocalDateTime startDate; private Lead lead; private AvatarUrl avatarUrls; private ProjectCategory projectCategory; private List<Component> components;
private List<IssueType> issueTypes;
lesstif/jira-rest-client
src/main/java/com/lesstif/jira/project/Project.java
// Path: src/main/java/com/lesstif/jira/JsonPrettyString.java // public class JsonPrettyString { // // final public String toPrettyJsonString() { // ObjectMapper mapper = new ObjectMapper(); // // mapper.configure(SerializationFeature.INDENT_OUTPUT, true); // // StringWriter sw = new StringWriter(); // try { // mapper.writeValue(sw, this); // } catch (IOException e) { // return toString(); // } // // return sw.toString(); // } // // /** // * Map to Pretty Json String // * // * @param map map data // * @return Json String // */ // public static String mapToPrettyJsonString(Map<String, Object> map) { // ObjectMapper mapper = new ObjectMapper(); // // mapper.configure(SerializationFeature.INDENT_OUTPUT, true); // // String jsonStr = ""; // try { // jsonStr = mapper.writeValueAsString(map); // } catch (IOException e) { // e.printStackTrace(); // } // // return jsonStr; // } // // } // // Path: src/main/java/com/lesstif/jira/issue/Component.java // @Data // public class Component { // public Component() { // // } // // public Component(String name) { // this.name = name; // } // // public Component(String id, String name) { // this.id = id; // this.name = name; // } // // private String self; // private String id; // private String name; // private String description; // // private Map<String, String> lead; // private String displayName; // private Boolean active; // // private Boolean isAssigneeTypeValid; // } // // Path: src/main/java/com/lesstif/jira/issue/IssueType.java // @Data // @EqualsAndHashCode(callSuper = false) // public class IssueType extends JsonPrettyString { // // Default issue type // public static final String ISSUE_TYPE_BUG = "Bug"; // public static final String ISSUE_TYPE_TASK = "Task"; // public static final String ISSUE_TYPE_IMPROVEMENT = "Improvement"; // public static final String ISSUE_TYPE_SUBTASK = "SubTask"; // public static final String ISSUE_TYPE_NEW_FEATURE = "New Feature"; // // private String self; // private String id; // private String description; // private String iconUrl; // private String name; // private Boolean subtask; // private Integer avatarId; // } // // Path: src/main/java/com/lesstif/jira/issue/Lead.java // @Data // public class Lead { // private String self; // private String name; // private AvatarUrl avatarUrls; // private String displayName; // private Boolean active; // private String key; // } // // Path: src/main/java/com/lesstif/jira/issue/Version.java // @Data // public class Version { // private String self; // private String id; // private String description; // private String name; // private Boolean archived; // private Boolean released; // // @JsonSerialize(using = LocalDateSerializer.class) // @JsonDeserialize(using = LocalDateDeserializer.class) // private LocalDate releaseDate; // // private Boolean overdue; // private String userReleaseDate; // private String projectId; // // @JsonSerialize(using = LocalDateSerializer.class) // @JsonDeserialize(using = LocalDateDeserializer.class) // private LocalDate startDate; // // private String userStartDate; // }
import java.time.LocalDateTime; import java.util.List; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer; import lombok.EqualsAndHashCode; import lombok.Data; import com.lesstif.jira.JsonPrettyString; import com.lesstif.jira.issue.Component; import com.lesstif.jira.issue.IssueType; import com.lesstif.jira.issue.Lead; import com.lesstif.jira.issue.Version;
package com.lesstif.jira.project; /** * @see <a href="https://docs.atlassian.com/software/jira/docs/api/REST/latest/#d2e86">/rest/api/2/project</a> * * @author lesstif * */ @Data @EqualsAndHashCode(callSuper=false) @JsonIgnoreProperties({"assigneeType", "roles" }) public class Project extends JsonPrettyString{ private String expand; private String self; private String id; private String key; private String description; private String name; private String url; @JsonSerialize(using = LocalDateSerializer.class) @JsonDeserialize(using = LocalDateDeserializer.class) private LocalDateTime startDate; private Lead lead; private AvatarUrl avatarUrls; private ProjectCategory projectCategory; private List<Component> components; private List<IssueType> issueTypes;
// Path: src/main/java/com/lesstif/jira/JsonPrettyString.java // public class JsonPrettyString { // // final public String toPrettyJsonString() { // ObjectMapper mapper = new ObjectMapper(); // // mapper.configure(SerializationFeature.INDENT_OUTPUT, true); // // StringWriter sw = new StringWriter(); // try { // mapper.writeValue(sw, this); // } catch (IOException e) { // return toString(); // } // // return sw.toString(); // } // // /** // * Map to Pretty Json String // * // * @param map map data // * @return Json String // */ // public static String mapToPrettyJsonString(Map<String, Object> map) { // ObjectMapper mapper = new ObjectMapper(); // // mapper.configure(SerializationFeature.INDENT_OUTPUT, true); // // String jsonStr = ""; // try { // jsonStr = mapper.writeValueAsString(map); // } catch (IOException e) { // e.printStackTrace(); // } // // return jsonStr; // } // // } // // Path: src/main/java/com/lesstif/jira/issue/Component.java // @Data // public class Component { // public Component() { // // } // // public Component(String name) { // this.name = name; // } // // public Component(String id, String name) { // this.id = id; // this.name = name; // } // // private String self; // private String id; // private String name; // private String description; // // private Map<String, String> lead; // private String displayName; // private Boolean active; // // private Boolean isAssigneeTypeValid; // } // // Path: src/main/java/com/lesstif/jira/issue/IssueType.java // @Data // @EqualsAndHashCode(callSuper = false) // public class IssueType extends JsonPrettyString { // // Default issue type // public static final String ISSUE_TYPE_BUG = "Bug"; // public static final String ISSUE_TYPE_TASK = "Task"; // public static final String ISSUE_TYPE_IMPROVEMENT = "Improvement"; // public static final String ISSUE_TYPE_SUBTASK = "SubTask"; // public static final String ISSUE_TYPE_NEW_FEATURE = "New Feature"; // // private String self; // private String id; // private String description; // private String iconUrl; // private String name; // private Boolean subtask; // private Integer avatarId; // } // // Path: src/main/java/com/lesstif/jira/issue/Lead.java // @Data // public class Lead { // private String self; // private String name; // private AvatarUrl avatarUrls; // private String displayName; // private Boolean active; // private String key; // } // // Path: src/main/java/com/lesstif/jira/issue/Version.java // @Data // public class Version { // private String self; // private String id; // private String description; // private String name; // private Boolean archived; // private Boolean released; // // @JsonSerialize(using = LocalDateSerializer.class) // @JsonDeserialize(using = LocalDateDeserializer.class) // private LocalDate releaseDate; // // private Boolean overdue; // private String userReleaseDate; // private String projectId; // // @JsonSerialize(using = LocalDateSerializer.class) // @JsonDeserialize(using = LocalDateDeserializer.class) // private LocalDate startDate; // // private String userStartDate; // } // Path: src/main/java/com/lesstif/jira/project/Project.java import java.time.LocalDateTime; import java.util.List; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer; import lombok.EqualsAndHashCode; import lombok.Data; import com.lesstif.jira.JsonPrettyString; import com.lesstif.jira.issue.Component; import com.lesstif.jira.issue.IssueType; import com.lesstif.jira.issue.Lead; import com.lesstif.jira.issue.Version; package com.lesstif.jira.project; /** * @see <a href="https://docs.atlassian.com/software/jira/docs/api/REST/latest/#d2e86">/rest/api/2/project</a> * * @author lesstif * */ @Data @EqualsAndHashCode(callSuper=false) @JsonIgnoreProperties({"assigneeType", "roles" }) public class Project extends JsonPrettyString{ private String expand; private String self; private String id; private String key; private String description; private String name; private String url; @JsonSerialize(using = LocalDateSerializer.class) @JsonDeserialize(using = LocalDateDeserializer.class) private LocalDateTime startDate; private Lead lead; private AvatarUrl avatarUrls; private ProjectCategory projectCategory; private List<Component> components; private List<IssueType> issueTypes;
private List<Version> versions;
lesstif/jira-rest-client
src/main/java/com/lesstif/jira/issue/IssueSearchResult.java
// Path: src/main/java/com/lesstif/jira/JsonPrettyString.java // public class JsonPrettyString { // // final public String toPrettyJsonString() { // ObjectMapper mapper = new ObjectMapper(); // // mapper.configure(SerializationFeature.INDENT_OUTPUT, true); // // StringWriter sw = new StringWriter(); // try { // mapper.writeValue(sw, this); // } catch (IOException e) { // return toString(); // } // // return sw.toString(); // } // // /** // * Map to Pretty Json String // * // * @param map map data // * @return Json String // */ // public static String mapToPrettyJsonString(Map<String, Object> map) { // ObjectMapper mapper = new ObjectMapper(); // // mapper.configure(SerializationFeature.INDENT_OUTPUT, true); // // String jsonStr = ""; // try { // jsonStr = mapper.writeValueAsString(map); // } catch (IOException e) { // e.printStackTrace(); // } // // return jsonStr; // } // // }
import com.lesstif.jira.JsonPrettyString; import java.util.List; import lombok.Data; import lombok.EqualsAndHashCode;
package com.lesstif.jira.issue; @Data @EqualsAndHashCode(callSuper = false)
// Path: src/main/java/com/lesstif/jira/JsonPrettyString.java // public class JsonPrettyString { // // final public String toPrettyJsonString() { // ObjectMapper mapper = new ObjectMapper(); // // mapper.configure(SerializationFeature.INDENT_OUTPUT, true); // // StringWriter sw = new StringWriter(); // try { // mapper.writeValue(sw, this); // } catch (IOException e) { // return toString(); // } // // return sw.toString(); // } // // /** // * Map to Pretty Json String // * // * @param map map data // * @return Json String // */ // public static String mapToPrettyJsonString(Map<String, Object> map) { // ObjectMapper mapper = new ObjectMapper(); // // mapper.configure(SerializationFeature.INDENT_OUTPUT, true); // // String jsonStr = ""; // try { // jsonStr = mapper.writeValueAsString(map); // } catch (IOException e) { // e.printStackTrace(); // } // // return jsonStr; // } // // } // Path: src/main/java/com/lesstif/jira/issue/IssueSearchResult.java import com.lesstif.jira.JsonPrettyString; import java.util.List; import lombok.Data; import lombok.EqualsAndHashCode; package com.lesstif.jira.issue; @Data @EqualsAndHashCode(callSuper = false)
public class IssueSearchResult extends JsonPrettyString{
lesstif/jira-rest-client
src/main/java/com/lesstif/jira/issue/Issue.java
// Path: src/main/java/com/lesstif/jira/JsonPrettyString.java // public class JsonPrettyString { // // final public String toPrettyJsonString() { // ObjectMapper mapper = new ObjectMapper(); // // mapper.configure(SerializationFeature.INDENT_OUTPUT, true); // // StringWriter sw = new StringWriter(); // try { // mapper.writeValue(sw, this); // } catch (IOException e) { // return toString(); // } // // return sw.toString(); // } // // /** // * Map to Pretty Json String // * // * @param map map data // * @return Json String // */ // public static String mapToPrettyJsonString(Map<String, Object> map) { // ObjectMapper mapper = new ObjectMapper(); // // mapper.configure(SerializationFeature.INDENT_OUTPUT, true); // // String jsonStr = ""; // try { // jsonStr = mapper.writeValueAsString(map); // } catch (IOException e) { // e.printStackTrace(); // } // // return jsonStr; // } // // }
import java.io.File; import java.io.IOException; import com.lesstif.jira.JsonPrettyString; import lombok.Data; import lombok.EqualsAndHashCode;
package com.lesstif.jira.issue; @Data @EqualsAndHashCode(callSuper = false)
// Path: src/main/java/com/lesstif/jira/JsonPrettyString.java // public class JsonPrettyString { // // final public String toPrettyJsonString() { // ObjectMapper mapper = new ObjectMapper(); // // mapper.configure(SerializationFeature.INDENT_OUTPUT, true); // // StringWriter sw = new StringWriter(); // try { // mapper.writeValue(sw, this); // } catch (IOException e) { // return toString(); // } // // return sw.toString(); // } // // /** // * Map to Pretty Json String // * // * @param map map data // * @return Json String // */ // public static String mapToPrettyJsonString(Map<String, Object> map) { // ObjectMapper mapper = new ObjectMapper(); // // mapper.configure(SerializationFeature.INDENT_OUTPUT, true); // // String jsonStr = ""; // try { // jsonStr = mapper.writeValueAsString(map); // } catch (IOException e) { // e.printStackTrace(); // } // // return jsonStr; // } // // } // Path: src/main/java/com/lesstif/jira/issue/Issue.java import java.io.File; import java.io.IOException; import com.lesstif.jira.JsonPrettyString; import lombok.Data; import lombok.EqualsAndHashCode; package com.lesstif.jira.issue; @Data @EqualsAndHashCode(callSuper = false)
public class Issue extends JsonPrettyString{
lesstif/jira-rest-client
src/main/java/com/lesstif/jira/issue/Lead.java
// Path: src/main/java/com/lesstif/jira/project/AvatarUrl.java // @Data // public class AvatarUrl { // @JsonProperty("16x16") // private String avatar16; // // @JsonProperty("24x24") // private String avatar24; // // @JsonProperty("32x32") // private String avatar32; // // @JsonProperty("48x48") // private String avatar48; // }
import com.lesstif.jira.project.AvatarUrl; import lombok.Data;
package com.lesstif.jira.issue; @Data public class Lead { private String self; private String name;
// Path: src/main/java/com/lesstif/jira/project/AvatarUrl.java // @Data // public class AvatarUrl { // @JsonProperty("16x16") // private String avatar16; // // @JsonProperty("24x24") // private String avatar24; // // @JsonProperty("32x32") // private String avatar32; // // @JsonProperty("48x48") // private String avatar48; // } // Path: src/main/java/com/lesstif/jira/issue/Lead.java import com.lesstif.jira.project.AvatarUrl; import lombok.Data; package com.lesstif.jira.issue; @Data public class Lead { private String self; private String name;
private AvatarUrl avatarUrls;
lesstif/jira-rest-client
src/main/java/com/lesstif/jira/issue/Priority.java
// Path: src/main/java/com/lesstif/jira/JsonPrettyString.java // public class JsonPrettyString { // // final public String toPrettyJsonString() { // ObjectMapper mapper = new ObjectMapper(); // // mapper.configure(SerializationFeature.INDENT_OUTPUT, true); // // StringWriter sw = new StringWriter(); // try { // mapper.writeValue(sw, this); // } catch (IOException e) { // return toString(); // } // // return sw.toString(); // } // // /** // * Map to Pretty Json String // * // * @param map map data // * @return Json String // */ // public static String mapToPrettyJsonString(Map<String, Object> map) { // ObjectMapper mapper = new ObjectMapper(); // // mapper.configure(SerializationFeature.INDENT_OUTPUT, true); // // String jsonStr = ""; // try { // jsonStr = mapper.writeValueAsString(map); // } catch (IOException e) { // e.printStackTrace(); // } // // return jsonStr; // } // // }
import com.lesstif.jira.JsonPrettyString; import lombok.Data; import lombok.EqualsAndHashCode;
package com.lesstif.jira.issue; @Data @EqualsAndHashCode(callSuper=false)
// Path: src/main/java/com/lesstif/jira/JsonPrettyString.java // public class JsonPrettyString { // // final public String toPrettyJsonString() { // ObjectMapper mapper = new ObjectMapper(); // // mapper.configure(SerializationFeature.INDENT_OUTPUT, true); // // StringWriter sw = new StringWriter(); // try { // mapper.writeValue(sw, this); // } catch (IOException e) { // return toString(); // } // // return sw.toString(); // } // // /** // * Map to Pretty Json String // * // * @param map map data // * @return Json String // */ // public static String mapToPrettyJsonString(Map<String, Object> map) { // ObjectMapper mapper = new ObjectMapper(); // // mapper.configure(SerializationFeature.INDENT_OUTPUT, true); // // String jsonStr = ""; // try { // jsonStr = mapper.writeValueAsString(map); // } catch (IOException e) { // e.printStackTrace(); // } // // return jsonStr; // } // // } // Path: src/main/java/com/lesstif/jira/issue/Priority.java import com.lesstif.jira.JsonPrettyString; import lombok.Data; import lombok.EqualsAndHashCode; package com.lesstif.jira.issue; @Data @EqualsAndHashCode(callSuper=false)
public class Priority extends JsonPrettyString {
lesstif/jira-rest-client
src/main/java/com/lesstif/jira/issue/Reporter.java
// Path: src/main/java/com/lesstif/jira/project/AvatarUrl.java // @Data // public class AvatarUrl { // @JsonProperty("16x16") // private String avatar16; // // @JsonProperty("24x24") // private String avatar24; // // @JsonProperty("32x32") // private String avatar32; // // @JsonProperty("48x48") // private String avatar48; // }
import com.lesstif.jira.project.AvatarUrl; import lombok.Data;
package com.lesstif.jira.issue; @Data public class Reporter { private String self; private String key; private String name; private String emailAddress;
// Path: src/main/java/com/lesstif/jira/project/AvatarUrl.java // @Data // public class AvatarUrl { // @JsonProperty("16x16") // private String avatar16; // // @JsonProperty("24x24") // private String avatar24; // // @JsonProperty("32x32") // private String avatar32; // // @JsonProperty("48x48") // private String avatar48; // } // Path: src/main/java/com/lesstif/jira/issue/Reporter.java import com.lesstif.jira.project.AvatarUrl; import lombok.Data; package com.lesstif.jira.issue; @Data public class Reporter { private String self; private String key; private String name; private String emailAddress;
private AvatarUrl avatarUrls;
lesstif/jira-rest-client
src/test/java/snippets/ZonedDateTimeTest.java
// Path: src/main/java/com/lesstif/jira/issue/Attachment.java // @EqualsAndHashCode(callSuper=false) // @Data // @JsonIgnoreProperties({"properties"}) // public class Attachment extends JsonPrettyString{ // private String id; // private String self; // private String filename; // private Reporter author; // // @JsonSerialize(using = ZonedDateTimeSerializer.class) // @JsonDeserialize(using = MyZonedDateTimeDeserializer.class) // private ZonedDateTime created; // // private Integer size; // private String mimeType; // private String content; // private String thumbnail; // } // // Path: src/main/java/com/lesstif/jira/issue/Issue.java // @Data // @EqualsAndHashCode(callSuper = false) // public class Issue extends JsonPrettyString{ // private String expand; // private String id; // private String self; // private String key; // // private IssueFields fields = new IssueFields(); // // public Issue addAttachment(String filePath) throws IOException { // addAttachment(new File(filePath)); // // return this; // } // // public Issue addAttachment(File file) throws IOException { // fields.addAttachment(file); // // return this; // } // // /** // * check attachment exist // * // * @return boolean true: issue have attachment, false: no attachment // */ // public boolean hasAttachments() { // if (fields.getFileList() != null && fields.getFileList().size() > 0) // return true; // // return false; // } // // // }
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.lesstif.jira.issue.Attachment; import com.lesstif.jira.issue.Issue; import org.apache.commons.configuration.ConfigurationException; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.LocalDateTime; import java.time.OffsetDateTime; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.time.temporal.TemporalAccessor; import java.util.Date; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.Matchers.greaterThan; import static org.junit.Assert.*; import static org.hamcrest.MatcherAssert.assertThat;
System.out.println("odt" + parsedDate); } @Test public void testZonedDateTimeSerializer() throws IOException, ConfigurationException { String jsonContent = "{\n" + " \"self\": \"https://jira.lesstif.com/rest/api/2/attachment/14402\",\n" + " \"filename\": \"bug-description.pdf\",\n" + " \"author\": {\n" + " \"self\": \"https://jira.lesstif.com/rest/api/2/user?username=lesstif\",\n" + " \"key\": \"lesstif\",\n" + " \"name\": \"lesstif\",\n" + " \"avatarUrls\": {\n" + " \"48x48\": \"https://jira.lesstif.com/secure/useravatar?avatarId=10414\",\n" + " \"24x24\": \"https://jira.lesstif.com/secure/useravatar?size=small&avatarId=10414\",\n" + " \"16x16\": \"https://jira.lesstif.com/secure/useravatar?size=xsmall&avatarId=10414\",\n" + " \"32x32\": \"https://jira.lesstif.com/secure/useravatar?size=medium&avatarId=10414\"\n" + " },\n" + " \"displayName\": \"정광섭\",\n" + " \"active\": true\n" + " },\n" + " \"created\": \"2021-11-22T15:01:02.000+0900\",\n" + " \"size\": 594326,\n" + " \"mimeType\": \"application/pdf\",\n" + " \"properties\": {},\n" + " \"content\": \"https://jira.lesstif.com/secure/attachment/14402/bug-description.pdf\"\n" + "}"; ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
// Path: src/main/java/com/lesstif/jira/issue/Attachment.java // @EqualsAndHashCode(callSuper=false) // @Data // @JsonIgnoreProperties({"properties"}) // public class Attachment extends JsonPrettyString{ // private String id; // private String self; // private String filename; // private Reporter author; // // @JsonSerialize(using = ZonedDateTimeSerializer.class) // @JsonDeserialize(using = MyZonedDateTimeDeserializer.class) // private ZonedDateTime created; // // private Integer size; // private String mimeType; // private String content; // private String thumbnail; // } // // Path: src/main/java/com/lesstif/jira/issue/Issue.java // @Data // @EqualsAndHashCode(callSuper = false) // public class Issue extends JsonPrettyString{ // private String expand; // private String id; // private String self; // private String key; // // private IssueFields fields = new IssueFields(); // // public Issue addAttachment(String filePath) throws IOException { // addAttachment(new File(filePath)); // // return this; // } // // public Issue addAttachment(File file) throws IOException { // fields.addAttachment(file); // // return this; // } // // /** // * check attachment exist // * // * @return boolean true: issue have attachment, false: no attachment // */ // public boolean hasAttachments() { // if (fields.getFileList() != null && fields.getFileList().size() > 0) // return true; // // return false; // } // // // } // Path: src/test/java/snippets/ZonedDateTimeTest.java import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.lesstif.jira.issue.Attachment; import com.lesstif.jira.issue.Issue; import org.apache.commons.configuration.ConfigurationException; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.LocalDateTime; import java.time.OffsetDateTime; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.time.temporal.TemporalAccessor; import java.util.Date; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.Matchers.greaterThan; import static org.junit.Assert.*; import static org.hamcrest.MatcherAssert.assertThat; System.out.println("odt" + parsedDate); } @Test public void testZonedDateTimeSerializer() throws IOException, ConfigurationException { String jsonContent = "{\n" + " \"self\": \"https://jira.lesstif.com/rest/api/2/attachment/14402\",\n" + " \"filename\": \"bug-description.pdf\",\n" + " \"author\": {\n" + " \"self\": \"https://jira.lesstif.com/rest/api/2/user?username=lesstif\",\n" + " \"key\": \"lesstif\",\n" + " \"name\": \"lesstif\",\n" + " \"avatarUrls\": {\n" + " \"48x48\": \"https://jira.lesstif.com/secure/useravatar?avatarId=10414\",\n" + " \"24x24\": \"https://jira.lesstif.com/secure/useravatar?size=small&avatarId=10414\",\n" + " \"16x16\": \"https://jira.lesstif.com/secure/useravatar?size=xsmall&avatarId=10414\",\n" + " \"32x32\": \"https://jira.lesstif.com/secure/useravatar?size=medium&avatarId=10414\"\n" + " },\n" + " \"displayName\": \"정광섭\",\n" + " \"active\": true\n" + " },\n" + " \"created\": \"2021-11-22T15:01:02.000+0900\",\n" + " \"size\": 594326,\n" + " \"mimeType\": \"application/pdf\",\n" + " \"properties\": {},\n" + " \"content\": \"https://jira.lesstif.com/secure/attachment/14402/bug-description.pdf\"\n" + "}"; ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
TypeReference<Attachment> ref = new TypeReference<Attachment>() {
lesstif/jira-rest-client
src/main/java/com/lesstif/jira/issue/WorklogElement.java
// Path: src/main/java/com/lesstif/jira/JsonPrettyString.java // public class JsonPrettyString { // // final public String toPrettyJsonString() { // ObjectMapper mapper = new ObjectMapper(); // // mapper.configure(SerializationFeature.INDENT_OUTPUT, true); // // StringWriter sw = new StringWriter(); // try { // mapper.writeValue(sw, this); // } catch (IOException e) { // return toString(); // } // // return sw.toString(); // } // // /** // * Map to Pretty Json String // * // * @param map map data // * @return Json String // */ // public static String mapToPrettyJsonString(Map<String, Object> map) { // ObjectMapper mapper = new ObjectMapper(); // // mapper.configure(SerializationFeature.INDENT_OUTPUT, true); // // String jsonStr = ""; // try { // jsonStr = mapper.writeValueAsString(map); // } catch (IOException e) { // e.printStackTrace(); // } // // return jsonStr; // } // // }
import com.fasterxml.jackson.annotation.JsonProperty; import com.lesstif.jira.JsonPrettyString; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import lombok.Data; import lombok.EqualsAndHashCode;
package com.lesstif.jira.issue; @Data @EqualsAndHashCode(callSuper = false)
// Path: src/main/java/com/lesstif/jira/JsonPrettyString.java // public class JsonPrettyString { // // final public String toPrettyJsonString() { // ObjectMapper mapper = new ObjectMapper(); // // mapper.configure(SerializationFeature.INDENT_OUTPUT, true); // // StringWriter sw = new StringWriter(); // try { // mapper.writeValue(sw, this); // } catch (IOException e) { // return toString(); // } // // return sw.toString(); // } // // /** // * Map to Pretty Json String // * // * @param map map data // * @return Json String // */ // public static String mapToPrettyJsonString(Map<String, Object> map) { // ObjectMapper mapper = new ObjectMapper(); // // mapper.configure(SerializationFeature.INDENT_OUTPUT, true); // // String jsonStr = ""; // try { // jsonStr = mapper.writeValueAsString(map); // } catch (IOException e) { // e.printStackTrace(); // } // // return jsonStr; // } // // } // Path: src/main/java/com/lesstif/jira/issue/WorklogElement.java import com.fasterxml.jackson.annotation.JsonProperty; import com.lesstif.jira.JsonPrettyString; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import lombok.Data; import lombok.EqualsAndHashCode; package com.lesstif.jira.issue; @Data @EqualsAndHashCode(callSuper = false)
public class WorklogElement extends JsonPrettyString implements Comparable<WorklogElement> {
lesstif/jira-rest-client
src/main/java/com/lesstif/jira/issue/IssueFields.java
// Path: src/main/java/com/lesstif/jira/project/Project.java // @Data // @EqualsAndHashCode(callSuper=false) // @JsonIgnoreProperties({"assigneeType", "roles" // }) // public class Project extends JsonPrettyString{ // private String expand; // private String self; // // private String id; // private String key; // // private String description; // private String name; // private String url; // // @JsonSerialize(using = LocalDateSerializer.class) // @JsonDeserialize(using = LocalDateDeserializer.class) // private LocalDateTime startDate; // // private Lead lead; // // private AvatarUrl avatarUrls; // private ProjectCategory projectCategory; // // private List<Component> components; // private List<IssueType> issueTypes; // private List<Version> versions; // // private String projectTypeKey; // // private boolean archived; // }
import java.io.File; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer; import lombok.Data; import lombok.experimental.Accessors; import com.lesstif.jira.project.Project;
package com.lesstif.jira.issue; @Data @JsonIgnoreProperties({"lastViewed", "aggregateprogress" ,"timeoriginalestimate", "aggregatetimespent", "fileList" }) @JsonInclude(value= JsonInclude.Include.NON_EMPTY, content= JsonInclude.Include.NON_NULL) @Accessors(chain=true) public class IssueFields {
// Path: src/main/java/com/lesstif/jira/project/Project.java // @Data // @EqualsAndHashCode(callSuper=false) // @JsonIgnoreProperties({"assigneeType", "roles" // }) // public class Project extends JsonPrettyString{ // private String expand; // private String self; // // private String id; // private String key; // // private String description; // private String name; // private String url; // // @JsonSerialize(using = LocalDateSerializer.class) // @JsonDeserialize(using = LocalDateDeserializer.class) // private LocalDateTime startDate; // // private Lead lead; // // private AvatarUrl avatarUrls; // private ProjectCategory projectCategory; // // private List<Component> components; // private List<IssueType> issueTypes; // private List<Version> versions; // // private String projectTypeKey; // // private boolean archived; // } // Path: src/main/java/com/lesstif/jira/issue/IssueFields.java import java.io.File; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer; import lombok.Data; import lombok.experimental.Accessors; import com.lesstif.jira.project.Project; package com.lesstif.jira.issue; @Data @JsonIgnoreProperties({"lastViewed", "aggregateprogress" ,"timeoriginalestimate", "aggregatetimespent", "fileList" }) @JsonInclude(value= JsonInclude.Include.NON_EMPTY, content= JsonInclude.Include.NON_NULL) @Accessors(chain=true) public class IssueFields {
private Project project;
vocefiscal/vocefiscal-android
Code/src/org/vocefiscal/adapters/TourFlipAdapter.java
// Path: Code/src/org/vocefiscal/fragments/FlipTourFragment.java // public class FlipTourFragment extends Fragment // { // private int position = -1; // // public FlipTourFragment(int position) // { // super(); // this.position = position; // } // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) // { // View rootView = inflater.inflate(R.layout.fragment_flip, container, false); // // ImageView imageFlip = (ImageView) rootView.findViewById(R.id.imageFlip); // // if(position==0) // { // imageFlip.setImageResource(R.drawable.tour_1); // }else if(position==1) // { // imageFlip.setImageResource(R.drawable.tour_2); // }else if(position==2) // { // imageFlip.setImageResource(R.drawable.tour_3); // }else if(position==3) // { // imageFlip.setImageResource(R.drawable.tour_4); // } // else if(position==4) // { // imageFlip.setImageResource(R.drawable.tour_5); // } // else if(position==5) // { // imageFlip.setImageResource(R.drawable.tour_6); // } // else if(position==6) // { // imageFlip.setImageResource(R.drawable.tour_7); // } // else if(position==7) // { // imageFlip.setImageResource(R.drawable.tour_8); // } // return rootView; // } // }
import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import org.vocefiscal.fragments.FlipTourFragment; import android.support.v4.app.Fragment;
/** * */ package org.vocefiscal.adapters; /** * @author andre * */ public class TourFlipAdapter extends FragmentPagerAdapter { public TourFlipAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) {
// Path: Code/src/org/vocefiscal/fragments/FlipTourFragment.java // public class FlipTourFragment extends Fragment // { // private int position = -1; // // public FlipTourFragment(int position) // { // super(); // this.position = position; // } // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) // { // View rootView = inflater.inflate(R.layout.fragment_flip, container, false); // // ImageView imageFlip = (ImageView) rootView.findViewById(R.id.imageFlip); // // if(position==0) // { // imageFlip.setImageResource(R.drawable.tour_1); // }else if(position==1) // { // imageFlip.setImageResource(R.drawable.tour_2); // }else if(position==2) // { // imageFlip.setImageResource(R.drawable.tour_3); // }else if(position==3) // { // imageFlip.setImageResource(R.drawable.tour_4); // } // else if(position==4) // { // imageFlip.setImageResource(R.drawable.tour_5); // } // else if(position==5) // { // imageFlip.setImageResource(R.drawable.tour_6); // } // else if(position==6) // { // imageFlip.setImageResource(R.drawable.tour_7); // } // else if(position==7) // { // imageFlip.setImageResource(R.drawable.tour_8); // } // return rootView; // } // } // Path: Code/src/org/vocefiscal/adapters/TourFlipAdapter.java import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import org.vocefiscal.fragments.FlipTourFragment; import android.support.v4.app.Fragment; /** * */ package org.vocefiscal.adapters; /** * @author andre * */ public class TourFlipAdapter extends FragmentPagerAdapter { public TourFlipAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) {
Fragment fragment = new FlipTourFragment(position);
vocefiscal/vocefiscal-android
Code/src/org/vocefiscal/activities/TourActivity.java
// Path: Code/src/org/vocefiscal/adapters/TourFlipAdapter.java // public class TourFlipAdapter extends FragmentPagerAdapter // { // // public TourFlipAdapter(FragmentManager fm) // { // super(fm); // } // // @Override // public Fragment getItem(int position) // { // Fragment fragment = new FlipTourFragment(position); // return fragment; // } // // @Override // public int getCount() // { // return 8; // } // // }
import org.vocefiscal.R; import org.vocefiscal.adapters.TourFlipAdapter; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageView; import com.flurry.android.FlurryAgent;
if(bundle!=null) { isModoMenu= bundle.getBoolean(MODO_MENU,false); } } primeiraBolinha = (ImageView) findViewById(R.id.primeira_bolinha); segundaBolinha = (ImageView) findViewById(R.id.segunda_bolinha); terceiraBolinha = (ImageView) findViewById(R.id.terceira_bolinha); quartaBolinha = (ImageView) findViewById(R.id.quarta_bolinha); quintaBolinha = (ImageView) findViewById(R.id.quinta_bolinha); sextaBolinha = (ImageView) findViewById(R.id.sexta_bolinha); setimaBolinha = (ImageView) findViewById(R.id.setima_bolinha); oitavaBolinha = (ImageView) findViewById(R.id.oitava_bolinha); comecar = (ImageView)findViewById(R.id.btn_comecar); comecar.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent mainIntent = new Intent(TourActivity.this,HomeActivity.class); startActivity(mainIntent); finish(); } }); //Pager utilizado na passagem de imagens de //Tour na primeira vez que entra no app
// Path: Code/src/org/vocefiscal/adapters/TourFlipAdapter.java // public class TourFlipAdapter extends FragmentPagerAdapter // { // // public TourFlipAdapter(FragmentManager fm) // { // super(fm); // } // // @Override // public Fragment getItem(int position) // { // Fragment fragment = new FlipTourFragment(position); // return fragment; // } // // @Override // public int getCount() // { // return 8; // } // // } // Path: Code/src/org/vocefiscal/activities/TourActivity.java import org.vocefiscal.R; import org.vocefiscal.adapters.TourFlipAdapter; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageView; import com.flurry.android.FlurryAgent; if(bundle!=null) { isModoMenu= bundle.getBoolean(MODO_MENU,false); } } primeiraBolinha = (ImageView) findViewById(R.id.primeira_bolinha); segundaBolinha = (ImageView) findViewById(R.id.segunda_bolinha); terceiraBolinha = (ImageView) findViewById(R.id.terceira_bolinha); quartaBolinha = (ImageView) findViewById(R.id.quarta_bolinha); quintaBolinha = (ImageView) findViewById(R.id.quinta_bolinha); sextaBolinha = (ImageView) findViewById(R.id.sexta_bolinha); setimaBolinha = (ImageView) findViewById(R.id.setima_bolinha); oitavaBolinha = (ImageView) findViewById(R.id.oitava_bolinha); comecar = (ImageView)findViewById(R.id.btn_comecar); comecar.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent mainIntent = new Intent(TourActivity.this,HomeActivity.class); startActivity(mainIntent); finish(); } }); //Pager utilizado na passagem de imagens de //Tour na primeira vez que entra no app
TourFlipAdapter tourFlipAdapter = new TourFlipAdapter(getSupportFragmentManager());
vocefiscal/vocefiscal-android
Code/src/org/vocefiscal/adapters/HomeFlipAdapter.java
// Path: Code/src/org/vocefiscal/fragments/FlipHomeFragment.java // public class FlipHomeFragment extends Fragment // { // private int position = -1; // // public FlipHomeFragment(int position) // { // super(); // this.position = position; // } // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) // { // View rootView = inflater.inflate(R.layout.fragment_flip, container, false); // // ImageView imageFlip = (ImageView) rootView.findViewById(R.id.imageFlip); // // if(position==0) // { // imageFlip.setImageResource(R.drawable.tutorial_home_1); // }else if(position==1) // { // imageFlip.setImageResource(R.drawable.tutorial_home_2); // }else if(position==2) // { // imageFlip.setImageResource(R.drawable.tutorial_home_3); // }else if(position==3) // { // imageFlip.setImageResource(R.drawable.tutorial_home_4); // } // // return rootView; // } // }
import org.vocefiscal.fragments.FlipHomeFragment; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter;
/** * */ package org.vocefiscal.adapters; /** * @author andre * */ public class HomeFlipAdapter extends FragmentPagerAdapter { public HomeFlipAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) {
// Path: Code/src/org/vocefiscal/fragments/FlipHomeFragment.java // public class FlipHomeFragment extends Fragment // { // private int position = -1; // // public FlipHomeFragment(int position) // { // super(); // this.position = position; // } // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) // { // View rootView = inflater.inflate(R.layout.fragment_flip, container, false); // // ImageView imageFlip = (ImageView) rootView.findViewById(R.id.imageFlip); // // if(position==0) // { // imageFlip.setImageResource(R.drawable.tutorial_home_1); // }else if(position==1) // { // imageFlip.setImageResource(R.drawable.tutorial_home_2); // }else if(position==2) // { // imageFlip.setImageResource(R.drawable.tutorial_home_3); // }else if(position==3) // { // imageFlip.setImageResource(R.drawable.tutorial_home_4); // } // // return rootView; // } // } // Path: Code/src/org/vocefiscal/adapters/HomeFlipAdapter.java import org.vocefiscal.fragments.FlipHomeFragment; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; /** * */ package org.vocefiscal.adapters; /** * @author andre * */ public class HomeFlipAdapter extends FragmentPagerAdapter { public HomeFlipAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) {
Fragment fragment = new FlipHomeFragment(position);
vocefiscal/vocefiscal-android
Code/src/org/vocefiscal/amazonaws/AWSUtil.java
// Path: Code/src/org/vocefiscal/communications/CommunicationConstants.java // public interface CommunicationConstants // { // public static final int OK_WITHCONTENT = 200; // public static final int OK_WITHOUTCONTENT = 204; // public static final int NOTFOUND = 404; // public static final int FORBIDDEN = 403; // public static final int TIME_OUT = 0; // public static final int SEM_INTERNET = 1000; // public static final int JSON_PARSE_ERROR = 1001; // public static final int CANCELED = 1002; // // public static final String CONTENTTYPE_PARAM = "Content-Type"; // public static final String CONTENTTYPE_JSON = "application/json; charset=utf-8"; // // public static final Integer WAIT_RETRY = 1000; // // //GMAIL // public static final String EMAIL_USER = "EMAIL_USER"; // public static final String EMAIL_PASSWORD = "EMAIL_PASSWORD"; // public static final String[] EMAIL_TO = new String[]{"EMAIL_TO","EMAIL_TO","EMAIL_TO"}; // // // //AWS COGNITO // public static final String AWS_ACCOUNT_ID = "AWS_ACCOUNT_ID"; // public static final String COGNITO_POOL_ID = "COGNITO_POOL_ID"; // public static final String COGNITO_ROLE_UNAUTH = "COGNITO_ROLE_UNAUTH"; // // //AWS S3 // public static final String PICTURE_BUCKET_NAME = "PICTURE_BUCKET_NAME"; // public static final String JSON_BUCKET_NAME = "JSON_BUCKET_NAME"; // public static final String STATE_STATS_BASE_ADDRESS = "STATE_STATS_BASE_ADDRESS"; // // //Twitter // // public static final String TWITTER_API_KEY = "TWITTER_API_KEY"; // public static final String TWITTER_API_SECRET = "TWITTER_API_SECRET "; // }
import com.amazonaws.android.auth.CognitoCredentialsProvider; import com.amazonaws.services.s3.AmazonS3Client; import org.vocefiscal.communications.CommunicationConstants; import android.content.Context;
/** * */ package org.vocefiscal.amazonaws; /** * @author andre * * This class just handles getting the client since we don't need to have more than * one per application */ public class AWSUtil { private static AmazonS3Client sS3Client; private static CognitoCredentialsProvider sCredProvider; public static CognitoCredentialsProvider getCredProvider(Context context) { if(sCredProvider == null) {
// Path: Code/src/org/vocefiscal/communications/CommunicationConstants.java // public interface CommunicationConstants // { // public static final int OK_WITHCONTENT = 200; // public static final int OK_WITHOUTCONTENT = 204; // public static final int NOTFOUND = 404; // public static final int FORBIDDEN = 403; // public static final int TIME_OUT = 0; // public static final int SEM_INTERNET = 1000; // public static final int JSON_PARSE_ERROR = 1001; // public static final int CANCELED = 1002; // // public static final String CONTENTTYPE_PARAM = "Content-Type"; // public static final String CONTENTTYPE_JSON = "application/json; charset=utf-8"; // // public static final Integer WAIT_RETRY = 1000; // // //GMAIL // public static final String EMAIL_USER = "EMAIL_USER"; // public static final String EMAIL_PASSWORD = "EMAIL_PASSWORD"; // public static final String[] EMAIL_TO = new String[]{"EMAIL_TO","EMAIL_TO","EMAIL_TO"}; // // // //AWS COGNITO // public static final String AWS_ACCOUNT_ID = "AWS_ACCOUNT_ID"; // public static final String COGNITO_POOL_ID = "COGNITO_POOL_ID"; // public static final String COGNITO_ROLE_UNAUTH = "COGNITO_ROLE_UNAUTH"; // // //AWS S3 // public static final String PICTURE_BUCKET_NAME = "PICTURE_BUCKET_NAME"; // public static final String JSON_BUCKET_NAME = "JSON_BUCKET_NAME"; // public static final String STATE_STATS_BASE_ADDRESS = "STATE_STATS_BASE_ADDRESS"; // // //Twitter // // public static final String TWITTER_API_KEY = "TWITTER_API_KEY"; // public static final String TWITTER_API_SECRET = "TWITTER_API_SECRET "; // } // Path: Code/src/org/vocefiscal/amazonaws/AWSUtil.java import com.amazonaws.android.auth.CognitoCredentialsProvider; import com.amazonaws.services.s3.AmazonS3Client; import org.vocefiscal.communications.CommunicationConstants; import android.content.Context; /** * */ package org.vocefiscal.amazonaws; /** * @author andre * * This class just handles getting the client since we don't need to have more than * one per application */ public class AWSUtil { private static AmazonS3Client sS3Client; private static CognitoCredentialsProvider sCredProvider; public static CognitoCredentialsProvider getCredProvider(Context context) { if(sCredProvider == null) {
sCredProvider = new CognitoCredentialsProvider(context,CommunicationConstants.AWS_ACCOUNT_ID, CommunicationConstants.COGNITO_POOL_ID,CommunicationConstants.COGNITO_ROLE_UNAUTH,null);
SevenSpikes/shopify-api-java-wrapper
src/main/java/com/storakle/shopify/domain/WebhookContent.java
// Path: src/main/java/com/storakle/shopify/jackson/FlexDateDeserializer.java // public final class FlexDateDeserializer extends JsonDeserializer<Date> // { // // @Override // public Date deserialize(final JsonParser parser, final DeserializationContext context) throws IOException // { // SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"); // // final String date = parser.getText(); // try // { // return formatter.parse(date); // } // catch (final ParseException ex) // { // // Not worked, so let the default date serializer give it a try. // return DateDeserializer.instance.deserialize(parser, context); // } // } // }
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.storakle.shopify.jackson.FlexDateDeserializer; import lombok.Data; import java.util.Date;
package com.storakle.shopify.domain; @Data public class WebhookContent { @JsonProperty(value = JsonConstants.ID) private Long id; @JsonProperty(value = JsonConstants.TOPIC) private String topic; @JsonProperty(value = JsonConstants.ADDRESS) private String address; @JsonProperty(value = JsonConstants.FORMAT) private String format; @JsonProperty(value = JsonConstants.CREATED_AT)
// Path: src/main/java/com/storakle/shopify/jackson/FlexDateDeserializer.java // public final class FlexDateDeserializer extends JsonDeserializer<Date> // { // // @Override // public Date deserialize(final JsonParser parser, final DeserializationContext context) throws IOException // { // SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"); // // final String date = parser.getText(); // try // { // return formatter.parse(date); // } // catch (final ParseException ex) // { // // Not worked, so let the default date serializer give it a try. // return DateDeserializer.instance.deserialize(parser, context); // } // } // } // Path: src/main/java/com/storakle/shopify/domain/WebhookContent.java import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.storakle.shopify.jackson.FlexDateDeserializer; import lombok.Data; import java.util.Date; package com.storakle.shopify.domain; @Data public class WebhookContent { @JsonProperty(value = JsonConstants.ID) private Long id; @JsonProperty(value = JsonConstants.TOPIC) private String topic; @JsonProperty(value = JsonConstants.ADDRESS) private String address; @JsonProperty(value = JsonConstants.FORMAT) private String format; @JsonProperty(value = JsonConstants.CREATED_AT)
@JsonDeserialize(using = FlexDateDeserializer.class)
SevenSpikes/shopify-api-java-wrapper
src/main/java/com/storakle/shopify/domain/Product.java
// Path: src/main/java/com/storakle/shopify/jackson/FlexDateDeserializer.java // public final class FlexDateDeserializer extends JsonDeserializer<Date> // { // // @Override // public Date deserialize(final JsonParser parser, final DeserializationContext context) throws IOException // { // SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"); // // final String date = parser.getText(); // try // { // return formatter.parse(date); // } // catch (final ParseException ex) // { // // Not worked, so let the default date serializer give it a try. // return DateDeserializer.instance.deserialize(parser, context); // } // } // } // // Path: src/main/java/com/storakle/shopify/jackson/FlexDateSerializer.java // public final class FlexDateSerializer extends JsonSerializer<Date> // { // // @Override // public void serialize(final Date value, final JsonGenerator gen, final SerializerProvider arg2) throws IOException // { // SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"); // gen.writeString(formatter.format(value)); // } // }
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.storakle.shopify.jackson.FlexDateDeserializer; import com.storakle.shopify.jackson.FlexDateSerializer; import lombok.Data; import java.util.Date; import java.util.List;
package com.storakle.shopify.domain; @Data public class Product { @JsonProperty(value = JsonConstants.ID) private long id; @JsonProperty(value = JsonConstants.TITLE) private String title; @JsonProperty(value = JsonConstants.HANDLE) private String handle; @JsonProperty(value = JsonConstants.IMAGE) private Image featuredImage; @JsonProperty(value = JsonConstants.IMAGES) private List<Image> images; @JsonProperty(value = JsonConstants.PUBLISHED_AT)
// Path: src/main/java/com/storakle/shopify/jackson/FlexDateDeserializer.java // public final class FlexDateDeserializer extends JsonDeserializer<Date> // { // // @Override // public Date deserialize(final JsonParser parser, final DeserializationContext context) throws IOException // { // SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"); // // final String date = parser.getText(); // try // { // return formatter.parse(date); // } // catch (final ParseException ex) // { // // Not worked, so let the default date serializer give it a try. // return DateDeserializer.instance.deserialize(parser, context); // } // } // } // // Path: src/main/java/com/storakle/shopify/jackson/FlexDateSerializer.java // public final class FlexDateSerializer extends JsonSerializer<Date> // { // // @Override // public void serialize(final Date value, final JsonGenerator gen, final SerializerProvider arg2) throws IOException // { // SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"); // gen.writeString(formatter.format(value)); // } // } // Path: src/main/java/com/storakle/shopify/domain/Product.java import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.storakle.shopify.jackson.FlexDateDeserializer; import com.storakle.shopify.jackson.FlexDateSerializer; import lombok.Data; import java.util.Date; import java.util.List; package com.storakle.shopify.domain; @Data public class Product { @JsonProperty(value = JsonConstants.ID) private long id; @JsonProperty(value = JsonConstants.TITLE) private String title; @JsonProperty(value = JsonConstants.HANDLE) private String handle; @JsonProperty(value = JsonConstants.IMAGE) private Image featuredImage; @JsonProperty(value = JsonConstants.IMAGES) private List<Image> images; @JsonProperty(value = JsonConstants.PUBLISHED_AT)
@JsonDeserialize(using = FlexDateDeserializer.class)
SevenSpikes/shopify-api-java-wrapper
src/main/java/com/storakle/shopify/domain/Product.java
// Path: src/main/java/com/storakle/shopify/jackson/FlexDateDeserializer.java // public final class FlexDateDeserializer extends JsonDeserializer<Date> // { // // @Override // public Date deserialize(final JsonParser parser, final DeserializationContext context) throws IOException // { // SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"); // // final String date = parser.getText(); // try // { // return formatter.parse(date); // } // catch (final ParseException ex) // { // // Not worked, so let the default date serializer give it a try. // return DateDeserializer.instance.deserialize(parser, context); // } // } // } // // Path: src/main/java/com/storakle/shopify/jackson/FlexDateSerializer.java // public final class FlexDateSerializer extends JsonSerializer<Date> // { // // @Override // public void serialize(final Date value, final JsonGenerator gen, final SerializerProvider arg2) throws IOException // { // SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"); // gen.writeString(formatter.format(value)); // } // }
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.storakle.shopify.jackson.FlexDateDeserializer; import com.storakle.shopify.jackson.FlexDateSerializer; import lombok.Data; import java.util.Date; import java.util.List;
package com.storakle.shopify.domain; @Data public class Product { @JsonProperty(value = JsonConstants.ID) private long id; @JsonProperty(value = JsonConstants.TITLE) private String title; @JsonProperty(value = JsonConstants.HANDLE) private String handle; @JsonProperty(value = JsonConstants.IMAGE) private Image featuredImage; @JsonProperty(value = JsonConstants.IMAGES) private List<Image> images; @JsonProperty(value = JsonConstants.PUBLISHED_AT) @JsonDeserialize(using = FlexDateDeserializer.class)
// Path: src/main/java/com/storakle/shopify/jackson/FlexDateDeserializer.java // public final class FlexDateDeserializer extends JsonDeserializer<Date> // { // // @Override // public Date deserialize(final JsonParser parser, final DeserializationContext context) throws IOException // { // SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"); // // final String date = parser.getText(); // try // { // return formatter.parse(date); // } // catch (final ParseException ex) // { // // Not worked, so let the default date serializer give it a try. // return DateDeserializer.instance.deserialize(parser, context); // } // } // } // // Path: src/main/java/com/storakle/shopify/jackson/FlexDateSerializer.java // public final class FlexDateSerializer extends JsonSerializer<Date> // { // // @Override // public void serialize(final Date value, final JsonGenerator gen, final SerializerProvider arg2) throws IOException // { // SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"); // gen.writeString(formatter.format(value)); // } // } // Path: src/main/java/com/storakle/shopify/domain/Product.java import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.storakle.shopify.jackson.FlexDateDeserializer; import com.storakle.shopify.jackson.FlexDateSerializer; import lombok.Data; import java.util.Date; import java.util.List; package com.storakle.shopify.domain; @Data public class Product { @JsonProperty(value = JsonConstants.ID) private long id; @JsonProperty(value = JsonConstants.TITLE) private String title; @JsonProperty(value = JsonConstants.HANDLE) private String handle; @JsonProperty(value = JsonConstants.IMAGE) private Image featuredImage; @JsonProperty(value = JsonConstants.IMAGES) private List<Image> images; @JsonProperty(value = JsonConstants.PUBLISHED_AT) @JsonDeserialize(using = FlexDateDeserializer.class)
@JsonSerialize(using = FlexDateSerializer.class)
SevenSpikes/shopify-api-java-wrapper
src/main/java/com/storakle/shopify/domain/RecurringApplicationCharge.java
// Path: src/main/java/com/storakle/shopify/jackson/FlexDateDeserializer.java // public final class FlexDateDeserializer extends JsonDeserializer<Date> // { // // @Override // public Date deserialize(final JsonParser parser, final DeserializationContext context) throws IOException // { // SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"); // // final String date = parser.getText(); // try // { // return formatter.parse(date); // } // catch (final ParseException ex) // { // // Not worked, so let the default date serializer give it a try. // return DateDeserializer.instance.deserialize(parser, context); // } // } // }
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.storakle.shopify.jackson.FlexDateDeserializer; import lombok.Data; import java.math.BigDecimal; import java.util.Date;
package com.storakle.shopify.domain; @Data public class RecurringApplicationCharge { @JsonProperty(value = JsonConstants.CHARGE_ID) private String id; @JsonProperty(value = JsonConstants.TEST) private Boolean test; @JsonProperty(value = JsonConstants.PLAN_NAME) private String name; @JsonProperty(value = JsonConstants.PLAN_PRICE) private BigDecimal price; @JsonProperty(value = JsonConstants.TERMS) private String terms; // Pending/Accepted/Declined/Active/Frozen/Canceled @JsonProperty(value = JsonConstants.CHARGE_STATUS) private String status; @JsonProperty(value = JsonConstants.BILLING_ON)
// Path: src/main/java/com/storakle/shopify/jackson/FlexDateDeserializer.java // public final class FlexDateDeserializer extends JsonDeserializer<Date> // { // // @Override // public Date deserialize(final JsonParser parser, final DeserializationContext context) throws IOException // { // SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"); // // final String date = parser.getText(); // try // { // return formatter.parse(date); // } // catch (final ParseException ex) // { // // Not worked, so let the default date serializer give it a try. // return DateDeserializer.instance.deserialize(parser, context); // } // } // } // Path: src/main/java/com/storakle/shopify/domain/RecurringApplicationCharge.java import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.storakle.shopify.jackson.FlexDateDeserializer; import lombok.Data; import java.math.BigDecimal; import java.util.Date; package com.storakle.shopify.domain; @Data public class RecurringApplicationCharge { @JsonProperty(value = JsonConstants.CHARGE_ID) private String id; @JsonProperty(value = JsonConstants.TEST) private Boolean test; @JsonProperty(value = JsonConstants.PLAN_NAME) private String name; @JsonProperty(value = JsonConstants.PLAN_PRICE) private BigDecimal price; @JsonProperty(value = JsonConstants.TERMS) private String terms; // Pending/Accepted/Declined/Active/Frozen/Canceled @JsonProperty(value = JsonConstants.CHARGE_STATUS) private String status; @JsonProperty(value = JsonConstants.BILLING_ON)
@JsonDeserialize(using = FlexDateDeserializer.class)
SevenSpikes/shopify-api-java-wrapper
src/main/java/com/storakle/shopify/jackson/ShopifyJacksonDecoder.java
// Path: src/main/java/com/storakle/shopify/redisson/ShopifyRedissonManager.java // public class ShopifyRedissonManager // { // private String _nodeAddress; // private String _myShopifyUrl; // private RedissonClient _redissonClient; // private final long MAXIMUM_SHOPIFY_CREDITS = 36; // // public ShopifyRedissonManager(String nodeAddress, String myShopifyUrl) // { // _nodeAddress = nodeAddress; // _myShopifyUrl = myShopifyUrl; // } // // public RedissonClient getRedissonClient() // { // if(_redissonClient == null) // { // Config config = new Config(); // config.useElasticacheServers() // .setScanInterval(2000) // cluster state scan interval in milliseconds // .addNodeAddress(_nodeAddress); // // _redissonClient = Redisson.create(config); // } // // return _redissonClient; // } // // public String getMyShopifyUrl() // { // return _myShopifyUrl; // } // // public String getRemainingCreditsKey() // { // return "remainingCredits_" + _myShopifyUrl; // } // // public String getLastRequestTimeKey() // { // return "lastRequestTime_" + _myShopifyUrl; // } // // public String getIsDefaultRemainingCreditsValueSetKey() // { // return "isDefaultRemainingCreditsValueSet" + _myShopifyUrl; // } // // public long getCreditLimit() // { // return MAXIMUM_SHOPIFY_CREDITS; // } // // public long calculateAvalableCredits(long createdCalls) // { // return MAXIMUM_SHOPIFY_CREDITS - createdCalls; // } // }
import com.storakle.shopify.redisson.ShopifyRedissonManager; import feign.Response; import feign.jackson.JacksonDecoder; import org.redisson.api.RAtomicLong; import org.redisson.api.RLock; import org.redisson.api.RedissonClient; import java.io.IOException; import java.lang.reflect.Type; import java.util.Collection;
package com.storakle.shopify.jackson; public class ShopifyJacksonDecoder extends JacksonDecoder {
// Path: src/main/java/com/storakle/shopify/redisson/ShopifyRedissonManager.java // public class ShopifyRedissonManager // { // private String _nodeAddress; // private String _myShopifyUrl; // private RedissonClient _redissonClient; // private final long MAXIMUM_SHOPIFY_CREDITS = 36; // // public ShopifyRedissonManager(String nodeAddress, String myShopifyUrl) // { // _nodeAddress = nodeAddress; // _myShopifyUrl = myShopifyUrl; // } // // public RedissonClient getRedissonClient() // { // if(_redissonClient == null) // { // Config config = new Config(); // config.useElasticacheServers() // .setScanInterval(2000) // cluster state scan interval in milliseconds // .addNodeAddress(_nodeAddress); // // _redissonClient = Redisson.create(config); // } // // return _redissonClient; // } // // public String getMyShopifyUrl() // { // return _myShopifyUrl; // } // // public String getRemainingCreditsKey() // { // return "remainingCredits_" + _myShopifyUrl; // } // // public String getLastRequestTimeKey() // { // return "lastRequestTime_" + _myShopifyUrl; // } // // public String getIsDefaultRemainingCreditsValueSetKey() // { // return "isDefaultRemainingCreditsValueSet" + _myShopifyUrl; // } // // public long getCreditLimit() // { // return MAXIMUM_SHOPIFY_CREDITS; // } // // public long calculateAvalableCredits(long createdCalls) // { // return MAXIMUM_SHOPIFY_CREDITS - createdCalls; // } // } // Path: src/main/java/com/storakle/shopify/jackson/ShopifyJacksonDecoder.java import com.storakle.shopify.redisson.ShopifyRedissonManager; import feign.Response; import feign.jackson.JacksonDecoder; import org.redisson.api.RAtomicLong; import org.redisson.api.RLock; import org.redisson.api.RedissonClient; import java.io.IOException; import java.lang.reflect.Type; import java.util.Collection; package com.storakle.shopify.jackson; public class ShopifyJacksonDecoder extends JacksonDecoder {
private ShopifyRedissonManager _shopifyRedissonManager;
SevenSpikes/shopify-api-java-wrapper
src/main/java/com/storakle/shopify/interceptors/RequestLimitInterceptor.java
// Path: src/main/java/com/storakle/shopify/redisson/ShopifyRedissonManager.java // public class ShopifyRedissonManager // { // private String _nodeAddress; // private String _myShopifyUrl; // private RedissonClient _redissonClient; // private final long MAXIMUM_SHOPIFY_CREDITS = 36; // // public ShopifyRedissonManager(String nodeAddress, String myShopifyUrl) // { // _nodeAddress = nodeAddress; // _myShopifyUrl = myShopifyUrl; // } // // public RedissonClient getRedissonClient() // { // if(_redissonClient == null) // { // Config config = new Config(); // config.useElasticacheServers() // .setScanInterval(2000) // cluster state scan interval in milliseconds // .addNodeAddress(_nodeAddress); // // _redissonClient = Redisson.create(config); // } // // return _redissonClient; // } // // public String getMyShopifyUrl() // { // return _myShopifyUrl; // } // // public String getRemainingCreditsKey() // { // return "remainingCredits_" + _myShopifyUrl; // } // // public String getLastRequestTimeKey() // { // return "lastRequestTime_" + _myShopifyUrl; // } // // public String getIsDefaultRemainingCreditsValueSetKey() // { // return "isDefaultRemainingCreditsValueSet" + _myShopifyUrl; // } // // public long getCreditLimit() // { // return MAXIMUM_SHOPIFY_CREDITS; // } // // public long calculateAvalableCredits(long createdCalls) // { // return MAXIMUM_SHOPIFY_CREDITS - createdCalls; // } // }
import com.storakle.shopify.redisson.ShopifyRedissonManager; import feign.RequestInterceptor; import feign.RequestTemplate; import org.redisson.api.RAtomicLong; import org.redisson.api.RLock; import org.redisson.api.RedissonClient;
package com.storakle.shopify.interceptors; public class RequestLimitInterceptor implements RequestInterceptor {
// Path: src/main/java/com/storakle/shopify/redisson/ShopifyRedissonManager.java // public class ShopifyRedissonManager // { // private String _nodeAddress; // private String _myShopifyUrl; // private RedissonClient _redissonClient; // private final long MAXIMUM_SHOPIFY_CREDITS = 36; // // public ShopifyRedissonManager(String nodeAddress, String myShopifyUrl) // { // _nodeAddress = nodeAddress; // _myShopifyUrl = myShopifyUrl; // } // // public RedissonClient getRedissonClient() // { // if(_redissonClient == null) // { // Config config = new Config(); // config.useElasticacheServers() // .setScanInterval(2000) // cluster state scan interval in milliseconds // .addNodeAddress(_nodeAddress); // // _redissonClient = Redisson.create(config); // } // // return _redissonClient; // } // // public String getMyShopifyUrl() // { // return _myShopifyUrl; // } // // public String getRemainingCreditsKey() // { // return "remainingCredits_" + _myShopifyUrl; // } // // public String getLastRequestTimeKey() // { // return "lastRequestTime_" + _myShopifyUrl; // } // // public String getIsDefaultRemainingCreditsValueSetKey() // { // return "isDefaultRemainingCreditsValueSet" + _myShopifyUrl; // } // // public long getCreditLimit() // { // return MAXIMUM_SHOPIFY_CREDITS; // } // // public long calculateAvalableCredits(long createdCalls) // { // return MAXIMUM_SHOPIFY_CREDITS - createdCalls; // } // } // Path: src/main/java/com/storakle/shopify/interceptors/RequestLimitInterceptor.java import com.storakle.shopify.redisson.ShopifyRedissonManager; import feign.RequestInterceptor; import feign.RequestTemplate; import org.redisson.api.RAtomicLong; import org.redisson.api.RLock; import org.redisson.api.RedissonClient; package com.storakle.shopify.interceptors; public class RequestLimitInterceptor implements RequestInterceptor {
private ShopifyRedissonManager _shopifyRedissonManager;
SevenSpikes/shopify-api-java-wrapper
src/main/java/com/storakle/shopify/domain/Transaction.java
// Path: src/main/java/com/storakle/shopify/jackson/FlexDateDeserializer.java // public final class FlexDateDeserializer extends JsonDeserializer<Date> // { // // @Override // public Date deserialize(final JsonParser parser, final DeserializationContext context) throws IOException // { // SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"); // // final String date = parser.getText(); // try // { // return formatter.parse(date); // } // catch (final ParseException ex) // { // // Not worked, so let the default date serializer give it a try. // return DateDeserializer.instance.deserialize(parser, context); // } // } // } // // Path: src/main/java/com/storakle/shopify/jackson/FlexDateSerializer.java // public final class FlexDateSerializer extends JsonSerializer<Date> // { // // @Override // public void serialize(final Date value, final JsonGenerator gen, final SerializerProvider arg2) throws IOException // { // SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"); // gen.writeString(formatter.format(value)); // } // }
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.storakle.shopify.jackson.FlexDateDeserializer; import com.storakle.shopify.jackson.FlexDateSerializer; import lombok.Data; import java.math.BigDecimal; import java.util.Date;
package com.storakle.shopify.domain; @Data public class Transaction { @JsonProperty(value = JsonConstants.ID) private long id; @JsonProperty(value = JsonConstants.ORDER_ID) private long orderId; @JsonProperty(value = JsonConstants.AMOUNT) private BigDecimal amount; @JsonProperty(value = JsonConstants.KIND) private String kind; @JsonProperty(value = JsonConstants.STATUS) private String status; @JsonProperty(value = JsonConstants.CREATED_AT)
// Path: src/main/java/com/storakle/shopify/jackson/FlexDateDeserializer.java // public final class FlexDateDeserializer extends JsonDeserializer<Date> // { // // @Override // public Date deserialize(final JsonParser parser, final DeserializationContext context) throws IOException // { // SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"); // // final String date = parser.getText(); // try // { // return formatter.parse(date); // } // catch (final ParseException ex) // { // // Not worked, so let the default date serializer give it a try. // return DateDeserializer.instance.deserialize(parser, context); // } // } // } // // Path: src/main/java/com/storakle/shopify/jackson/FlexDateSerializer.java // public final class FlexDateSerializer extends JsonSerializer<Date> // { // // @Override // public void serialize(final Date value, final JsonGenerator gen, final SerializerProvider arg2) throws IOException // { // SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"); // gen.writeString(formatter.format(value)); // } // } // Path: src/main/java/com/storakle/shopify/domain/Transaction.java import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.storakle.shopify.jackson.FlexDateDeserializer; import com.storakle.shopify.jackson.FlexDateSerializer; import lombok.Data; import java.math.BigDecimal; import java.util.Date; package com.storakle.shopify.domain; @Data public class Transaction { @JsonProperty(value = JsonConstants.ID) private long id; @JsonProperty(value = JsonConstants.ORDER_ID) private long orderId; @JsonProperty(value = JsonConstants.AMOUNT) private BigDecimal amount; @JsonProperty(value = JsonConstants.KIND) private String kind; @JsonProperty(value = JsonConstants.STATUS) private String status; @JsonProperty(value = JsonConstants.CREATED_AT)
@JsonDeserialize(using = FlexDateDeserializer.class)
SevenSpikes/shopify-api-java-wrapper
src/main/java/com/storakle/shopify/domain/Transaction.java
// Path: src/main/java/com/storakle/shopify/jackson/FlexDateDeserializer.java // public final class FlexDateDeserializer extends JsonDeserializer<Date> // { // // @Override // public Date deserialize(final JsonParser parser, final DeserializationContext context) throws IOException // { // SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"); // // final String date = parser.getText(); // try // { // return formatter.parse(date); // } // catch (final ParseException ex) // { // // Not worked, so let the default date serializer give it a try. // return DateDeserializer.instance.deserialize(parser, context); // } // } // } // // Path: src/main/java/com/storakle/shopify/jackson/FlexDateSerializer.java // public final class FlexDateSerializer extends JsonSerializer<Date> // { // // @Override // public void serialize(final Date value, final JsonGenerator gen, final SerializerProvider arg2) throws IOException // { // SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"); // gen.writeString(formatter.format(value)); // } // }
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.storakle.shopify.jackson.FlexDateDeserializer; import com.storakle.shopify.jackson.FlexDateSerializer; import lombok.Data; import java.math.BigDecimal; import java.util.Date;
package com.storakle.shopify.domain; @Data public class Transaction { @JsonProperty(value = JsonConstants.ID) private long id; @JsonProperty(value = JsonConstants.ORDER_ID) private long orderId; @JsonProperty(value = JsonConstants.AMOUNT) private BigDecimal amount; @JsonProperty(value = JsonConstants.KIND) private String kind; @JsonProperty(value = JsonConstants.STATUS) private String status; @JsonProperty(value = JsonConstants.CREATED_AT) @JsonDeserialize(using = FlexDateDeserializer.class)
// Path: src/main/java/com/storakle/shopify/jackson/FlexDateDeserializer.java // public final class FlexDateDeserializer extends JsonDeserializer<Date> // { // // @Override // public Date deserialize(final JsonParser parser, final DeserializationContext context) throws IOException // { // SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"); // // final String date = parser.getText(); // try // { // return formatter.parse(date); // } // catch (final ParseException ex) // { // // Not worked, so let the default date serializer give it a try. // return DateDeserializer.instance.deserialize(parser, context); // } // } // } // // Path: src/main/java/com/storakle/shopify/jackson/FlexDateSerializer.java // public final class FlexDateSerializer extends JsonSerializer<Date> // { // // @Override // public void serialize(final Date value, final JsonGenerator gen, final SerializerProvider arg2) throws IOException // { // SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"); // gen.writeString(formatter.format(value)); // } // } // Path: src/main/java/com/storakle/shopify/domain/Transaction.java import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.storakle.shopify.jackson.FlexDateDeserializer; import com.storakle.shopify.jackson.FlexDateSerializer; import lombok.Data; import java.math.BigDecimal; import java.util.Date; package com.storakle.shopify.domain; @Data public class Transaction { @JsonProperty(value = JsonConstants.ID) private long id; @JsonProperty(value = JsonConstants.ORDER_ID) private long orderId; @JsonProperty(value = JsonConstants.AMOUNT) private BigDecimal amount; @JsonProperty(value = JsonConstants.KIND) private String kind; @JsonProperty(value = JsonConstants.STATUS) private String status; @JsonProperty(value = JsonConstants.CREATED_AT) @JsonDeserialize(using = FlexDateDeserializer.class)
@JsonSerialize(using = FlexDateSerializer.class)
SevenSpikes/shopify-api-java-wrapper
src/main/java/com/storakle/shopify/domain/Customer.java
// Path: src/main/java/com/storakle/shopify/jackson/FlexDateDeserializer.java // public final class FlexDateDeserializer extends JsonDeserializer<Date> // { // // @Override // public Date deserialize(final JsonParser parser, final DeserializationContext context) throws IOException // { // SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"); // // final String date = parser.getText(); // try // { // return formatter.parse(date); // } // catch (final ParseException ex) // { // // Not worked, so let the default date serializer give it a try. // return DateDeserializer.instance.deserialize(parser, context); // } // } // } // // Path: src/main/java/com/storakle/shopify/jackson/FlexDateSerializer.java // public final class FlexDateSerializer extends JsonSerializer<Date> // { // // @Override // public void serialize(final Date value, final JsonGenerator gen, final SerializerProvider arg2) throws IOException // { // SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"); // gen.writeString(formatter.format(value)); // } // }
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.storakle.shopify.jackson.FlexDateDeserializer; import com.storakle.shopify.jackson.FlexDateSerializer; import lombok.Data; import java.util.Date; import java.util.List;
package com.storakle.shopify.domain; @Data public class Customer { @JsonProperty(value = JsonConstants.ID) private long id; @JsonProperty(value = JsonConstants.EMAIL) private String email; @JsonProperty(value = JsonConstants.FIRST_NAME) private String firstName; @JsonProperty(value = JsonConstants.LAST_NAME) private String lastName; @JsonProperty(value = JsonConstants.NOTE) private String note; @JsonProperty(value = JsonConstants.TAGS) private String tags; @JsonProperty(value = JsonConstants.ACCEPTS_MARKETING) private Boolean acceptsMarketing; @JsonProperty(value = JsonConstants.CREATED_AT)
// Path: src/main/java/com/storakle/shopify/jackson/FlexDateDeserializer.java // public final class FlexDateDeserializer extends JsonDeserializer<Date> // { // // @Override // public Date deserialize(final JsonParser parser, final DeserializationContext context) throws IOException // { // SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"); // // final String date = parser.getText(); // try // { // return formatter.parse(date); // } // catch (final ParseException ex) // { // // Not worked, so let the default date serializer give it a try. // return DateDeserializer.instance.deserialize(parser, context); // } // } // } // // Path: src/main/java/com/storakle/shopify/jackson/FlexDateSerializer.java // public final class FlexDateSerializer extends JsonSerializer<Date> // { // // @Override // public void serialize(final Date value, final JsonGenerator gen, final SerializerProvider arg2) throws IOException // { // SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"); // gen.writeString(formatter.format(value)); // } // } // Path: src/main/java/com/storakle/shopify/domain/Customer.java import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.storakle.shopify.jackson.FlexDateDeserializer; import com.storakle.shopify.jackson.FlexDateSerializer; import lombok.Data; import java.util.Date; import java.util.List; package com.storakle.shopify.domain; @Data public class Customer { @JsonProperty(value = JsonConstants.ID) private long id; @JsonProperty(value = JsonConstants.EMAIL) private String email; @JsonProperty(value = JsonConstants.FIRST_NAME) private String firstName; @JsonProperty(value = JsonConstants.LAST_NAME) private String lastName; @JsonProperty(value = JsonConstants.NOTE) private String note; @JsonProperty(value = JsonConstants.TAGS) private String tags; @JsonProperty(value = JsonConstants.ACCEPTS_MARKETING) private Boolean acceptsMarketing; @JsonProperty(value = JsonConstants.CREATED_AT)
@JsonDeserialize(using = FlexDateDeserializer.class)
SevenSpikes/shopify-api-java-wrapper
src/main/java/com/storakle/shopify/domain/Customer.java
// Path: src/main/java/com/storakle/shopify/jackson/FlexDateDeserializer.java // public final class FlexDateDeserializer extends JsonDeserializer<Date> // { // // @Override // public Date deserialize(final JsonParser parser, final DeserializationContext context) throws IOException // { // SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"); // // final String date = parser.getText(); // try // { // return formatter.parse(date); // } // catch (final ParseException ex) // { // // Not worked, so let the default date serializer give it a try. // return DateDeserializer.instance.deserialize(parser, context); // } // } // } // // Path: src/main/java/com/storakle/shopify/jackson/FlexDateSerializer.java // public final class FlexDateSerializer extends JsonSerializer<Date> // { // // @Override // public void serialize(final Date value, final JsonGenerator gen, final SerializerProvider arg2) throws IOException // { // SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"); // gen.writeString(formatter.format(value)); // } // }
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.storakle.shopify.jackson.FlexDateDeserializer; import com.storakle.shopify.jackson.FlexDateSerializer; import lombok.Data; import java.util.Date; import java.util.List;
package com.storakle.shopify.domain; @Data public class Customer { @JsonProperty(value = JsonConstants.ID) private long id; @JsonProperty(value = JsonConstants.EMAIL) private String email; @JsonProperty(value = JsonConstants.FIRST_NAME) private String firstName; @JsonProperty(value = JsonConstants.LAST_NAME) private String lastName; @JsonProperty(value = JsonConstants.NOTE) private String note; @JsonProperty(value = JsonConstants.TAGS) private String tags; @JsonProperty(value = JsonConstants.ACCEPTS_MARKETING) private Boolean acceptsMarketing; @JsonProperty(value = JsonConstants.CREATED_AT) @JsonDeserialize(using = FlexDateDeserializer.class)
// Path: src/main/java/com/storakle/shopify/jackson/FlexDateDeserializer.java // public final class FlexDateDeserializer extends JsonDeserializer<Date> // { // // @Override // public Date deserialize(final JsonParser parser, final DeserializationContext context) throws IOException // { // SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"); // // final String date = parser.getText(); // try // { // return formatter.parse(date); // } // catch (final ParseException ex) // { // // Not worked, so let the default date serializer give it a try. // return DateDeserializer.instance.deserialize(parser, context); // } // } // } // // Path: src/main/java/com/storakle/shopify/jackson/FlexDateSerializer.java // public final class FlexDateSerializer extends JsonSerializer<Date> // { // // @Override // public void serialize(final Date value, final JsonGenerator gen, final SerializerProvider arg2) throws IOException // { // SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"); // gen.writeString(formatter.format(value)); // } // } // Path: src/main/java/com/storakle/shopify/domain/Customer.java import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.storakle.shopify.jackson.FlexDateDeserializer; import com.storakle.shopify.jackson.FlexDateSerializer; import lombok.Data; import java.util.Date; import java.util.List; package com.storakle.shopify.domain; @Data public class Customer { @JsonProperty(value = JsonConstants.ID) private long id; @JsonProperty(value = JsonConstants.EMAIL) private String email; @JsonProperty(value = JsonConstants.FIRST_NAME) private String firstName; @JsonProperty(value = JsonConstants.LAST_NAME) private String lastName; @JsonProperty(value = JsonConstants.NOTE) private String note; @JsonProperty(value = JsonConstants.TAGS) private String tags; @JsonProperty(value = JsonConstants.ACCEPTS_MARKETING) private Boolean acceptsMarketing; @JsonProperty(value = JsonConstants.CREATED_AT) @JsonDeserialize(using = FlexDateDeserializer.class)
@JsonSerialize(using = FlexDateSerializer.class)
SevenSpikes/shopify-api-java-wrapper
src/main/java/com/storakle/shopify/domain/Order.java
// Path: src/main/java/com/storakle/shopify/jackson/FlexDateDeserializer.java // public final class FlexDateDeserializer extends JsonDeserializer<Date> // { // // @Override // public Date deserialize(final JsonParser parser, final DeserializationContext context) throws IOException // { // SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"); // // final String date = parser.getText(); // try // { // return formatter.parse(date); // } // catch (final ParseException ex) // { // // Not worked, so let the default date serializer give it a try. // return DateDeserializer.instance.deserialize(parser, context); // } // } // } // // Path: src/main/java/com/storakle/shopify/jackson/FlexDateSerializer.java // public final class FlexDateSerializer extends JsonSerializer<Date> // { // // @Override // public void serialize(final Date value, final JsonGenerator gen, final SerializerProvider arg2) throws IOException // { // SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"); // gen.writeString(formatter.format(value)); // } // }
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.storakle.shopify.jackson.FlexDateDeserializer; import com.storakle.shopify.jackson.FlexDateSerializer; import lombok.Data; import java.math.BigDecimal; import java.util.Date; import java.util.List;
package com.storakle.shopify.domain; @Data public class Order { @JsonProperty(value = JsonConstants.ID) private long id; @JsonProperty(value = JsonConstants.NAME) private String name; @JsonProperty(value = JsonConstants.TOTAL_PRICE) private BigDecimal totalPrice; @JsonProperty(value = JsonConstants.DISCOUNT) private BigDecimal discount; @JsonProperty(value = JsonConstants.FINANCIAL_STATUS) private FinancialStatus financialStatus; @JsonProperty(value = JsonConstants.CUSTOMER) private Customer customer; @JsonProperty(value = JsonConstants.BILLING_ADDRESS) private Address billingAddress; @JsonProperty(value = JsonConstants.SHIPPING_ADDRESS) private Address shippingAddress; @JsonProperty(value = JsonConstants.LINE_ITEMS) private List<LineItem> lineItems; @JsonProperty(value = JsonConstants.CREATED_AT)
// Path: src/main/java/com/storakle/shopify/jackson/FlexDateDeserializer.java // public final class FlexDateDeserializer extends JsonDeserializer<Date> // { // // @Override // public Date deserialize(final JsonParser parser, final DeserializationContext context) throws IOException // { // SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"); // // final String date = parser.getText(); // try // { // return formatter.parse(date); // } // catch (final ParseException ex) // { // // Not worked, so let the default date serializer give it a try. // return DateDeserializer.instance.deserialize(parser, context); // } // } // } // // Path: src/main/java/com/storakle/shopify/jackson/FlexDateSerializer.java // public final class FlexDateSerializer extends JsonSerializer<Date> // { // // @Override // public void serialize(final Date value, final JsonGenerator gen, final SerializerProvider arg2) throws IOException // { // SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"); // gen.writeString(formatter.format(value)); // } // } // Path: src/main/java/com/storakle/shopify/domain/Order.java import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.storakle.shopify.jackson.FlexDateDeserializer; import com.storakle.shopify.jackson.FlexDateSerializer; import lombok.Data; import java.math.BigDecimal; import java.util.Date; import java.util.List; package com.storakle.shopify.domain; @Data public class Order { @JsonProperty(value = JsonConstants.ID) private long id; @JsonProperty(value = JsonConstants.NAME) private String name; @JsonProperty(value = JsonConstants.TOTAL_PRICE) private BigDecimal totalPrice; @JsonProperty(value = JsonConstants.DISCOUNT) private BigDecimal discount; @JsonProperty(value = JsonConstants.FINANCIAL_STATUS) private FinancialStatus financialStatus; @JsonProperty(value = JsonConstants.CUSTOMER) private Customer customer; @JsonProperty(value = JsonConstants.BILLING_ADDRESS) private Address billingAddress; @JsonProperty(value = JsonConstants.SHIPPING_ADDRESS) private Address shippingAddress; @JsonProperty(value = JsonConstants.LINE_ITEMS) private List<LineItem> lineItems; @JsonProperty(value = JsonConstants.CREATED_AT)
@JsonDeserialize(using = FlexDateDeserializer.class)
SevenSpikes/shopify-api-java-wrapper
src/main/java/com/storakle/shopify/domain/Order.java
// Path: src/main/java/com/storakle/shopify/jackson/FlexDateDeserializer.java // public final class FlexDateDeserializer extends JsonDeserializer<Date> // { // // @Override // public Date deserialize(final JsonParser parser, final DeserializationContext context) throws IOException // { // SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"); // // final String date = parser.getText(); // try // { // return formatter.parse(date); // } // catch (final ParseException ex) // { // // Not worked, so let the default date serializer give it a try. // return DateDeserializer.instance.deserialize(parser, context); // } // } // } // // Path: src/main/java/com/storakle/shopify/jackson/FlexDateSerializer.java // public final class FlexDateSerializer extends JsonSerializer<Date> // { // // @Override // public void serialize(final Date value, final JsonGenerator gen, final SerializerProvider arg2) throws IOException // { // SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"); // gen.writeString(formatter.format(value)); // } // }
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.storakle.shopify.jackson.FlexDateDeserializer; import com.storakle.shopify.jackson.FlexDateSerializer; import lombok.Data; import java.math.BigDecimal; import java.util.Date; import java.util.List;
package com.storakle.shopify.domain; @Data public class Order { @JsonProperty(value = JsonConstants.ID) private long id; @JsonProperty(value = JsonConstants.NAME) private String name; @JsonProperty(value = JsonConstants.TOTAL_PRICE) private BigDecimal totalPrice; @JsonProperty(value = JsonConstants.DISCOUNT) private BigDecimal discount; @JsonProperty(value = JsonConstants.FINANCIAL_STATUS) private FinancialStatus financialStatus; @JsonProperty(value = JsonConstants.CUSTOMER) private Customer customer; @JsonProperty(value = JsonConstants.BILLING_ADDRESS) private Address billingAddress; @JsonProperty(value = JsonConstants.SHIPPING_ADDRESS) private Address shippingAddress; @JsonProperty(value = JsonConstants.LINE_ITEMS) private List<LineItem> lineItems; @JsonProperty(value = JsonConstants.CREATED_AT) @JsonDeserialize(using = FlexDateDeserializer.class)
// Path: src/main/java/com/storakle/shopify/jackson/FlexDateDeserializer.java // public final class FlexDateDeserializer extends JsonDeserializer<Date> // { // // @Override // public Date deserialize(final JsonParser parser, final DeserializationContext context) throws IOException // { // SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"); // // final String date = parser.getText(); // try // { // return formatter.parse(date); // } // catch (final ParseException ex) // { // // Not worked, so let the default date serializer give it a try. // return DateDeserializer.instance.deserialize(parser, context); // } // } // } // // Path: src/main/java/com/storakle/shopify/jackson/FlexDateSerializer.java // public final class FlexDateSerializer extends JsonSerializer<Date> // { // // @Override // public void serialize(final Date value, final JsonGenerator gen, final SerializerProvider arg2) throws IOException // { // SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"); // gen.writeString(formatter.format(value)); // } // } // Path: src/main/java/com/storakle/shopify/domain/Order.java import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.storakle.shopify.jackson.FlexDateDeserializer; import com.storakle.shopify.jackson.FlexDateSerializer; import lombok.Data; import java.math.BigDecimal; import java.util.Date; import java.util.List; package com.storakle.shopify.domain; @Data public class Order { @JsonProperty(value = JsonConstants.ID) private long id; @JsonProperty(value = JsonConstants.NAME) private String name; @JsonProperty(value = JsonConstants.TOTAL_PRICE) private BigDecimal totalPrice; @JsonProperty(value = JsonConstants.DISCOUNT) private BigDecimal discount; @JsonProperty(value = JsonConstants.FINANCIAL_STATUS) private FinancialStatus financialStatus; @JsonProperty(value = JsonConstants.CUSTOMER) private Customer customer; @JsonProperty(value = JsonConstants.BILLING_ADDRESS) private Address billingAddress; @JsonProperty(value = JsonConstants.SHIPPING_ADDRESS) private Address shippingAddress; @JsonProperty(value = JsonConstants.LINE_ITEMS) private List<LineItem> lineItems; @JsonProperty(value = JsonConstants.CREATED_AT) @JsonDeserialize(using = FlexDateDeserializer.class)
@JsonSerialize(using = FlexDateSerializer.class)
pearson-enabling-technologies/elasticsearch-approx-plugin
src/main/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TermListFacetExecutor.java
// Path: src/main/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/Constants.java // enum FIELD_DATA_TYPE { // UNDEFINED, // INT, // LONG, // STRING // }
import java.io.IOException; import java.util.List; import java.util.Random; import org.apache.lucene.index.AtomicReader; import org.apache.lucene.index.AtomicReaderContext; import org.apache.lucene.index.DocsEnum; import org.apache.lucene.index.Terms; import org.apache.lucene.index.TermsEnum; import org.apache.lucene.util.Bits; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.BytesRefHash; import org.apache.lucene.util.NumericUtils; import org.elasticsearch.common.lucene.docset.ContextDocIdSet; import org.elasticsearch.index.fielddata.BytesValues; import org.elasticsearch.index.fielddata.BytesValues.Iter; import org.elasticsearch.index.fielddata.IndexFieldData; import org.elasticsearch.index.fielddata.IndexNumericFieldData; import org.elasticsearch.search.facet.FacetExecutor; import org.elasticsearch.search.facet.FacetPhaseExecutionException; import org.elasticsearch.search.facet.InternalFacet; import org.elasticsearch.search.internal.SearchContext; import com.pearson.entech.elasticsearch.search.facet.approx.termlist.Constants.FIELD_DATA_TYPE;
package com.pearson.entech.elasticsearch.search.facet.approx.termlist; public class TermListFacetExecutor extends FacetExecutor { private final Random _random = new Random(0); private final int _maxPerShard; private final String _facetName; private final float _sampleRate; private final boolean _exhaustive;
// Path: src/main/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/Constants.java // enum FIELD_DATA_TYPE { // UNDEFINED, // INT, // LONG, // STRING // } // Path: src/main/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TermListFacetExecutor.java import java.io.IOException; import java.util.List; import java.util.Random; import org.apache.lucene.index.AtomicReader; import org.apache.lucene.index.AtomicReaderContext; import org.apache.lucene.index.DocsEnum; import org.apache.lucene.index.Terms; import org.apache.lucene.index.TermsEnum; import org.apache.lucene.util.Bits; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.BytesRefHash; import org.apache.lucene.util.NumericUtils; import org.elasticsearch.common.lucene.docset.ContextDocIdSet; import org.elasticsearch.index.fielddata.BytesValues; import org.elasticsearch.index.fielddata.BytesValues.Iter; import org.elasticsearch.index.fielddata.IndexFieldData; import org.elasticsearch.index.fielddata.IndexNumericFieldData; import org.elasticsearch.search.facet.FacetExecutor; import org.elasticsearch.search.facet.FacetPhaseExecutionException; import org.elasticsearch.search.facet.InternalFacet; import org.elasticsearch.search.internal.SearchContext; import com.pearson.entech.elasticsearch.search.facet.approx.termlist.Constants.FIELD_DATA_TYPE; package com.pearson.entech.elasticsearch.search.facet.approx.termlist; public class TermListFacetExecutor extends FacetExecutor { private final Random _random = new Random(0); private final int _maxPerShard; private final String _facetName; private final float _sampleRate; private final boolean _exhaustive;
private Constants.FIELD_DATA_TYPE _type;
pearson-enabling-technologies/elasticsearch-approx-plugin
src/main/java/com/pearson/entech/elasticsearch/search/facet/approx/date/internal/CountThenEstimateBytes.java
// Path: src/main/java/com/pearson/entech/elasticsearch/plugin/approx/BytesRefUtils.java // public static void process(final BytesRefHash hash, final Procedure proc) { // int[] ids; // try { // ids = (int[]) getCompactMethod().invoke(hash, __emptyParams); // } catch(final IllegalAccessException e) { // throw new RuntimeException(e); // } catch(final InvocationTargetException e) { // throw new RuntimeException(e); // } // final BytesRef scratch = new BytesRef(); // for(int i = 0; i < ids.length; i++) { // final int id = ids[i]; // if(id < 0) // break; // hash.get(id, scratch); // try { // proc.consume(scratch); // } catch(final Exception e) { // throw new IllegalStateException(e); // } // } // hash.clear(); // } // // Path: src/main/java/com/pearson/entech/elasticsearch/plugin/approx/BytesRefUtils.java // public static interface Procedure { // // /** // * Called once for each BytesRef. // * // * @param ref the BytesRef // * @throws Exception // */ // void consume(BytesRef ref) throws Exception; // // }
import static com.pearson.entech.elasticsearch.plugin.approx.BytesRefUtils.process; import java.io.ByteArrayInputStream; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.lucene.codecs.bloom.MurmurHash2; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.BytesRefHash; import com.clearspring.analytics.stream.cardinality.AdaptiveCounting; import com.clearspring.analytics.stream.cardinality.CardinalityMergeException; import com.clearspring.analytics.stream.cardinality.HyperLogLog; import com.clearspring.analytics.stream.cardinality.HyperLogLogPlus; import com.clearspring.analytics.stream.cardinality.ICardinality; import com.clearspring.analytics.stream.cardinality.LinearCounting; import com.clearspring.analytics.stream.cardinality.LogLog; import com.clearspring.analytics.util.ExternalizableUtil; import com.clearspring.analytics.util.IBuilder; import com.pearson.entech.elasticsearch.plugin.approx.BytesRefUtils.Procedure;
{ if(o instanceof BytesRef) return offerBytesRef((BytesRef) o); else return offerBytesRef(new BytesRef(o.toString())); } @Override public int sizeof() { if(_tipped) return _estimator.sizeof(); return -1; } /** * Returns the tipping point. * * @return the number of entries at which this instance switched from exact to approx mode */ public int getTippingPoint() { return _tippingPoint; } /** * Switch from exact counting to estimation. */ private void tip() { if(!_tipped) { _estimator = _builder.build();
// Path: src/main/java/com/pearson/entech/elasticsearch/plugin/approx/BytesRefUtils.java // public static void process(final BytesRefHash hash, final Procedure proc) { // int[] ids; // try { // ids = (int[]) getCompactMethod().invoke(hash, __emptyParams); // } catch(final IllegalAccessException e) { // throw new RuntimeException(e); // } catch(final InvocationTargetException e) { // throw new RuntimeException(e); // } // final BytesRef scratch = new BytesRef(); // for(int i = 0; i < ids.length; i++) { // final int id = ids[i]; // if(id < 0) // break; // hash.get(id, scratch); // try { // proc.consume(scratch); // } catch(final Exception e) { // throw new IllegalStateException(e); // } // } // hash.clear(); // } // // Path: src/main/java/com/pearson/entech/elasticsearch/plugin/approx/BytesRefUtils.java // public static interface Procedure { // // /** // * Called once for each BytesRef. // * // * @param ref the BytesRef // * @throws Exception // */ // void consume(BytesRef ref) throws Exception; // // } // Path: src/main/java/com/pearson/entech/elasticsearch/search/facet/approx/date/internal/CountThenEstimateBytes.java import static com.pearson.entech.elasticsearch.plugin.approx.BytesRefUtils.process; import java.io.ByteArrayInputStream; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.lucene.codecs.bloom.MurmurHash2; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.BytesRefHash; import com.clearspring.analytics.stream.cardinality.AdaptiveCounting; import com.clearspring.analytics.stream.cardinality.CardinalityMergeException; import com.clearspring.analytics.stream.cardinality.HyperLogLog; import com.clearspring.analytics.stream.cardinality.HyperLogLogPlus; import com.clearspring.analytics.stream.cardinality.ICardinality; import com.clearspring.analytics.stream.cardinality.LinearCounting; import com.clearspring.analytics.stream.cardinality.LogLog; import com.clearspring.analytics.util.ExternalizableUtil; import com.clearspring.analytics.util.IBuilder; import com.pearson.entech.elasticsearch.plugin.approx.BytesRefUtils.Procedure; { if(o instanceof BytesRef) return offerBytesRef((BytesRef) o); else return offerBytesRef(new BytesRef(o.toString())); } @Override public int sizeof() { if(_tipped) return _estimator.sizeof(); return -1; } /** * Returns the tipping point. * * @return the number of entries at which this instance switched from exact to approx mode */ public int getTippingPoint() { return _tippingPoint; } /** * Switch from exact counting to estimation. */ private void tip() { if(!_tipped) { _estimator = _builder.build();
process(_counter, new Procedure() {
pearson-enabling-technologies/elasticsearch-approx-plugin
src/main/java/com/pearson/entech/elasticsearch/search/facet/approx/date/internal/CountThenEstimateBytes.java
// Path: src/main/java/com/pearson/entech/elasticsearch/plugin/approx/BytesRefUtils.java // public static void process(final BytesRefHash hash, final Procedure proc) { // int[] ids; // try { // ids = (int[]) getCompactMethod().invoke(hash, __emptyParams); // } catch(final IllegalAccessException e) { // throw new RuntimeException(e); // } catch(final InvocationTargetException e) { // throw new RuntimeException(e); // } // final BytesRef scratch = new BytesRef(); // for(int i = 0; i < ids.length; i++) { // final int id = ids[i]; // if(id < 0) // break; // hash.get(id, scratch); // try { // proc.consume(scratch); // } catch(final Exception e) { // throw new IllegalStateException(e); // } // } // hash.clear(); // } // // Path: src/main/java/com/pearson/entech/elasticsearch/plugin/approx/BytesRefUtils.java // public static interface Procedure { // // /** // * Called once for each BytesRef. // * // * @param ref the BytesRef // * @throws Exception // */ // void consume(BytesRef ref) throws Exception; // // }
import static com.pearson.entech.elasticsearch.plugin.approx.BytesRefUtils.process; import java.io.ByteArrayInputStream; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.lucene.codecs.bloom.MurmurHash2; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.BytesRefHash; import com.clearspring.analytics.stream.cardinality.AdaptiveCounting; import com.clearspring.analytics.stream.cardinality.CardinalityMergeException; import com.clearspring.analytics.stream.cardinality.HyperLogLog; import com.clearspring.analytics.stream.cardinality.HyperLogLogPlus; import com.clearspring.analytics.stream.cardinality.ICardinality; import com.clearspring.analytics.stream.cardinality.LinearCounting; import com.clearspring.analytics.stream.cardinality.LogLog; import com.clearspring.analytics.util.ExternalizableUtil; import com.clearspring.analytics.util.IBuilder; import com.pearson.entech.elasticsearch.plugin.approx.BytesRefUtils.Procedure;
{ if(o instanceof BytesRef) return offerBytesRef((BytesRef) o); else return offerBytesRef(new BytesRef(o.toString())); } @Override public int sizeof() { if(_tipped) return _estimator.sizeof(); return -1; } /** * Returns the tipping point. * * @return the number of entries at which this instance switched from exact to approx mode */ public int getTippingPoint() { return _tippingPoint; } /** * Switch from exact counting to estimation. */ private void tip() { if(!_tipped) { _estimator = _builder.build();
// Path: src/main/java/com/pearson/entech/elasticsearch/plugin/approx/BytesRefUtils.java // public static void process(final BytesRefHash hash, final Procedure proc) { // int[] ids; // try { // ids = (int[]) getCompactMethod().invoke(hash, __emptyParams); // } catch(final IllegalAccessException e) { // throw new RuntimeException(e); // } catch(final InvocationTargetException e) { // throw new RuntimeException(e); // } // final BytesRef scratch = new BytesRef(); // for(int i = 0; i < ids.length; i++) { // final int id = ids[i]; // if(id < 0) // break; // hash.get(id, scratch); // try { // proc.consume(scratch); // } catch(final Exception e) { // throw new IllegalStateException(e); // } // } // hash.clear(); // } // // Path: src/main/java/com/pearson/entech/elasticsearch/plugin/approx/BytesRefUtils.java // public static interface Procedure { // // /** // * Called once for each BytesRef. // * // * @param ref the BytesRef // * @throws Exception // */ // void consume(BytesRef ref) throws Exception; // // } // Path: src/main/java/com/pearson/entech/elasticsearch/search/facet/approx/date/internal/CountThenEstimateBytes.java import static com.pearson.entech.elasticsearch.plugin.approx.BytesRefUtils.process; import java.io.ByteArrayInputStream; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.lucene.codecs.bloom.MurmurHash2; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.BytesRefHash; import com.clearspring.analytics.stream.cardinality.AdaptiveCounting; import com.clearspring.analytics.stream.cardinality.CardinalityMergeException; import com.clearspring.analytics.stream.cardinality.HyperLogLog; import com.clearspring.analytics.stream.cardinality.HyperLogLogPlus; import com.clearspring.analytics.stream.cardinality.ICardinality; import com.clearspring.analytics.stream.cardinality.LinearCounting; import com.clearspring.analytics.stream.cardinality.LogLog; import com.clearspring.analytics.util.ExternalizableUtil; import com.clearspring.analytics.util.IBuilder; import com.pearson.entech.elasticsearch.plugin.approx.BytesRefUtils.Procedure; { if(o instanceof BytesRef) return offerBytesRef((BytesRef) o); else return offerBytesRef(new BytesRef(o.toString())); } @Override public int sizeof() { if(_tipped) return _estimator.sizeof(); return -1; } /** * Returns the tipping point. * * @return the number of entries at which this instance switched from exact to approx mode */ public int getTippingPoint() { return _tippingPoint; } /** * Switch from exact counting to estimation. */ private void tip() { if(!_tipped) { _estimator = _builder.build();
process(_counter, new Procedure() {
pearson-enabling-technologies/elasticsearch-approx-plugin
src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TermListFacetTest.java
// Path: src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TestUtils.java // public static final Random RANDOM = new Random(0); // // Path: src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TestUtils.java // public static List<Integer> generateRandomInts(final int numOfElements) { // final List<Integer> ret = newArrayList(); // for(int i = 0; i < numOfElements; i++) { // ret.add(RANDOM.nextInt(1000)); // } // return ret; // } // // Path: src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TestUtils.java // public static List<Long> generateRandomLongs(final int numOfElements) { // final List<Long> ret = newArrayList(); // for(int i = 0; i < numOfElements; i++) { // final long val = RANDOM.nextInt(10000); // ret.add(val); // } // return ret; // } // // Path: src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TestUtils.java // public static List<String> generateRandomWords(final int numberOfWords) { // final String[] randomStrings = new String[numberOfWords]; // for(int i = 0; i < numberOfWords; i++) // { // final char[] word = new char[RANDOM.nextInt(8) + 3]; // words of length 3 through 10. (1 and 2 letter words are boring.) // for(int j = 0; j < word.length; j++) // { // word[j] = (char) ('a' + RANDOM.nextInt(26)); // } // randomStrings[i] = new String(word); // } // return newArrayList(randomStrings); // }
import static com.google.common.collect.Lists.newArrayList; import static com.pearson.entech.elasticsearch.search.facet.approx.termlist.TestUtils.RANDOM; import static com.pearson.entech.elasticsearch.search.facet.approx.termlist.TestUtils.generateRandomInts; import static com.pearson.entech.elasticsearch.search.facet.approx.termlist.TestUtils.generateRandomLongs; import static com.pearson.entech.elasticsearch.search.facet.approx.termlist.TestUtils.generateRandomWords; import static org.elasticsearch.node.NodeBuilder.nodeBuilder; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Scanner; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import org.elasticsearch.ElasticSearchException; import org.elasticsearch.action.admin.indices.create.CreateIndexRequest; import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest; import org.elasticsearch.action.bulk.BulkRequestBuilder; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.search.SearchPhaseExecutionException; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.client.Client; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.node.Node; import org.elasticsearch.search.facet.FacetBuilder; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test;
} catch(final Exception ex) { assertTrue(ex instanceof SearchPhaseExecutionException); } } // Helper methods private void testWithFixedIntegers(final String mode) throws Exception { final int[] _words = { 0, 9, 8, 7, 6, 5, 4, 3, 2, 1 }; final List<Integer> words = new ArrayList<Integer>(); for(final int word : _words) words.add(word); final int numOfDocs = _words.length; for(int i = 0; i < _words.length; i++) { putSync(newID(), "", "", _words[i], _words[i]); } final Set<Integer> uniqs = new HashSet<Integer>(); uniqs.addAll(words); assertEquals(numOfDocs, countAll()); final SearchResponse response1 = getTermList(__intField1, _words.length, 1, mode); checkIntSearchResponse(response1, numOfDocs, uniqs.size(), words); } private void testWithRandomStrings(final String mode) throws Exception { final int numOfElements = 100; final int numOfWords = 100;
// Path: src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TestUtils.java // public static final Random RANDOM = new Random(0); // // Path: src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TestUtils.java // public static List<Integer> generateRandomInts(final int numOfElements) { // final List<Integer> ret = newArrayList(); // for(int i = 0; i < numOfElements; i++) { // ret.add(RANDOM.nextInt(1000)); // } // return ret; // } // // Path: src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TestUtils.java // public static List<Long> generateRandomLongs(final int numOfElements) { // final List<Long> ret = newArrayList(); // for(int i = 0; i < numOfElements; i++) { // final long val = RANDOM.nextInt(10000); // ret.add(val); // } // return ret; // } // // Path: src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TestUtils.java // public static List<String> generateRandomWords(final int numberOfWords) { // final String[] randomStrings = new String[numberOfWords]; // for(int i = 0; i < numberOfWords; i++) // { // final char[] word = new char[RANDOM.nextInt(8) + 3]; // words of length 3 through 10. (1 and 2 letter words are boring.) // for(int j = 0; j < word.length; j++) // { // word[j] = (char) ('a' + RANDOM.nextInt(26)); // } // randomStrings[i] = new String(word); // } // return newArrayList(randomStrings); // } // Path: src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TermListFacetTest.java import static com.google.common.collect.Lists.newArrayList; import static com.pearson.entech.elasticsearch.search.facet.approx.termlist.TestUtils.RANDOM; import static com.pearson.entech.elasticsearch.search.facet.approx.termlist.TestUtils.generateRandomInts; import static com.pearson.entech.elasticsearch.search.facet.approx.termlist.TestUtils.generateRandomLongs; import static com.pearson.entech.elasticsearch.search.facet.approx.termlist.TestUtils.generateRandomWords; import static org.elasticsearch.node.NodeBuilder.nodeBuilder; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Scanner; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import org.elasticsearch.ElasticSearchException; import org.elasticsearch.action.admin.indices.create.CreateIndexRequest; import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest; import org.elasticsearch.action.bulk.BulkRequestBuilder; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.search.SearchPhaseExecutionException; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.client.Client; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.node.Node; import org.elasticsearch.search.facet.FacetBuilder; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; } catch(final Exception ex) { assertTrue(ex instanceof SearchPhaseExecutionException); } } // Helper methods private void testWithFixedIntegers(final String mode) throws Exception { final int[] _words = { 0, 9, 8, 7, 6, 5, 4, 3, 2, 1 }; final List<Integer> words = new ArrayList<Integer>(); for(final int word : _words) words.add(word); final int numOfDocs = _words.length; for(int i = 0; i < _words.length; i++) { putSync(newID(), "", "", _words[i], _words[i]); } final Set<Integer> uniqs = new HashSet<Integer>(); uniqs.addAll(words); assertEquals(numOfDocs, countAll()); final SearchResponse response1 = getTermList(__intField1, _words.length, 1, mode); checkIntSearchResponse(response1, numOfDocs, uniqs.size(), words); } private void testWithRandomStrings(final String mode) throws Exception { final int numOfElements = 100; final int numOfWords = 100;
final List<String> words = generateRandomWords(numOfWords);
pearson-enabling-technologies/elasticsearch-approx-plugin
src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TermListFacetTest.java
// Path: src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TestUtils.java // public static final Random RANDOM = new Random(0); // // Path: src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TestUtils.java // public static List<Integer> generateRandomInts(final int numOfElements) { // final List<Integer> ret = newArrayList(); // for(int i = 0; i < numOfElements; i++) { // ret.add(RANDOM.nextInt(1000)); // } // return ret; // } // // Path: src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TestUtils.java // public static List<Long> generateRandomLongs(final int numOfElements) { // final List<Long> ret = newArrayList(); // for(int i = 0; i < numOfElements; i++) { // final long val = RANDOM.nextInt(10000); // ret.add(val); // } // return ret; // } // // Path: src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TestUtils.java // public static List<String> generateRandomWords(final int numberOfWords) { // final String[] randomStrings = new String[numberOfWords]; // for(int i = 0; i < numberOfWords; i++) // { // final char[] word = new char[RANDOM.nextInt(8) + 3]; // words of length 3 through 10. (1 and 2 letter words are boring.) // for(int j = 0; j < word.length; j++) // { // word[j] = (char) ('a' + RANDOM.nextInt(26)); // } // randomStrings[i] = new String(word); // } // return newArrayList(randomStrings); // }
import static com.google.common.collect.Lists.newArrayList; import static com.pearson.entech.elasticsearch.search.facet.approx.termlist.TestUtils.RANDOM; import static com.pearson.entech.elasticsearch.search.facet.approx.termlist.TestUtils.generateRandomInts; import static com.pearson.entech.elasticsearch.search.facet.approx.termlist.TestUtils.generateRandomLongs; import static com.pearson.entech.elasticsearch.search.facet.approx.termlist.TestUtils.generateRandomWords; import static org.elasticsearch.node.NodeBuilder.nodeBuilder; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Scanner; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import org.elasticsearch.ElasticSearchException; import org.elasticsearch.action.admin.indices.create.CreateIndexRequest; import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest; import org.elasticsearch.action.bulk.BulkRequestBuilder; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.search.SearchPhaseExecutionException; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.client.Client; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.node.Node; import org.elasticsearch.search.facet.FacetBuilder; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test;
} } // Helper methods private void testWithFixedIntegers(final String mode) throws Exception { final int[] _words = { 0, 9, 8, 7, 6, 5, 4, 3, 2, 1 }; final List<Integer> words = new ArrayList<Integer>(); for(final int word : _words) words.add(word); final int numOfDocs = _words.length; for(int i = 0; i < _words.length; i++) { putSync(newID(), "", "", _words[i], _words[i]); } final Set<Integer> uniqs = new HashSet<Integer>(); uniqs.addAll(words); assertEquals(numOfDocs, countAll()); final SearchResponse response1 = getTermList(__intField1, _words.length, 1, mode); checkIntSearchResponse(response1, numOfDocs, uniqs.size(), words); } private void testWithRandomStrings(final String mode) throws Exception { final int numOfElements = 100; final int numOfWords = 100; final List<String> words = generateRandomWords(numOfWords);
// Path: src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TestUtils.java // public static final Random RANDOM = new Random(0); // // Path: src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TestUtils.java // public static List<Integer> generateRandomInts(final int numOfElements) { // final List<Integer> ret = newArrayList(); // for(int i = 0; i < numOfElements; i++) { // ret.add(RANDOM.nextInt(1000)); // } // return ret; // } // // Path: src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TestUtils.java // public static List<Long> generateRandomLongs(final int numOfElements) { // final List<Long> ret = newArrayList(); // for(int i = 0; i < numOfElements; i++) { // final long val = RANDOM.nextInt(10000); // ret.add(val); // } // return ret; // } // // Path: src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TestUtils.java // public static List<String> generateRandomWords(final int numberOfWords) { // final String[] randomStrings = new String[numberOfWords]; // for(int i = 0; i < numberOfWords; i++) // { // final char[] word = new char[RANDOM.nextInt(8) + 3]; // words of length 3 through 10. (1 and 2 letter words are boring.) // for(int j = 0; j < word.length; j++) // { // word[j] = (char) ('a' + RANDOM.nextInt(26)); // } // randomStrings[i] = new String(word); // } // return newArrayList(randomStrings); // } // Path: src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TermListFacetTest.java import static com.google.common.collect.Lists.newArrayList; import static com.pearson.entech.elasticsearch.search.facet.approx.termlist.TestUtils.RANDOM; import static com.pearson.entech.elasticsearch.search.facet.approx.termlist.TestUtils.generateRandomInts; import static com.pearson.entech.elasticsearch.search.facet.approx.termlist.TestUtils.generateRandomLongs; import static com.pearson.entech.elasticsearch.search.facet.approx.termlist.TestUtils.generateRandomWords; import static org.elasticsearch.node.NodeBuilder.nodeBuilder; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Scanner; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import org.elasticsearch.ElasticSearchException; import org.elasticsearch.action.admin.indices.create.CreateIndexRequest; import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest; import org.elasticsearch.action.bulk.BulkRequestBuilder; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.search.SearchPhaseExecutionException; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.client.Client; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.node.Node; import org.elasticsearch.search.facet.FacetBuilder; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; } } // Helper methods private void testWithFixedIntegers(final String mode) throws Exception { final int[] _words = { 0, 9, 8, 7, 6, 5, 4, 3, 2, 1 }; final List<Integer> words = new ArrayList<Integer>(); for(final int word : _words) words.add(word); final int numOfDocs = _words.length; for(int i = 0; i < _words.length; i++) { putSync(newID(), "", "", _words[i], _words[i]); } final Set<Integer> uniqs = new HashSet<Integer>(); uniqs.addAll(words); assertEquals(numOfDocs, countAll()); final SearchResponse response1 = getTermList(__intField1, _words.length, 1, mode); checkIntSearchResponse(response1, numOfDocs, uniqs.size(), words); } private void testWithRandomStrings(final String mode) throws Exception { final int numOfElements = 100; final int numOfWords = 100; final List<String> words = generateRandomWords(numOfWords);
int rIndex1 = RANDOM.nextInt(numOfWords);
pearson-enabling-technologies/elasticsearch-approx-plugin
src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TermListFacetTest.java
// Path: src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TestUtils.java // public static final Random RANDOM = new Random(0); // // Path: src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TestUtils.java // public static List<Integer> generateRandomInts(final int numOfElements) { // final List<Integer> ret = newArrayList(); // for(int i = 0; i < numOfElements; i++) { // ret.add(RANDOM.nextInt(1000)); // } // return ret; // } // // Path: src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TestUtils.java // public static List<Long> generateRandomLongs(final int numOfElements) { // final List<Long> ret = newArrayList(); // for(int i = 0; i < numOfElements; i++) { // final long val = RANDOM.nextInt(10000); // ret.add(val); // } // return ret; // } // // Path: src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TestUtils.java // public static List<String> generateRandomWords(final int numberOfWords) { // final String[] randomStrings = new String[numberOfWords]; // for(int i = 0; i < numberOfWords; i++) // { // final char[] word = new char[RANDOM.nextInt(8) + 3]; // words of length 3 through 10. (1 and 2 letter words are boring.) // for(int j = 0; j < word.length; j++) // { // word[j] = (char) ('a' + RANDOM.nextInt(26)); // } // randomStrings[i] = new String(word); // } // return newArrayList(randomStrings); // }
import static com.google.common.collect.Lists.newArrayList; import static com.pearson.entech.elasticsearch.search.facet.approx.termlist.TestUtils.RANDOM; import static com.pearson.entech.elasticsearch.search.facet.approx.termlist.TestUtils.generateRandomInts; import static com.pearson.entech.elasticsearch.search.facet.approx.termlist.TestUtils.generateRandomLongs; import static com.pearson.entech.elasticsearch.search.facet.approx.termlist.TestUtils.generateRandomWords; import static org.elasticsearch.node.NodeBuilder.nodeBuilder; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Scanner; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import org.elasticsearch.ElasticSearchException; import org.elasticsearch.action.admin.indices.create.CreateIndexRequest; import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest; import org.elasticsearch.action.bulk.BulkRequestBuilder; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.search.SearchPhaseExecutionException; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.client.Client; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.node.Node; import org.elasticsearch.search.facet.FacetBuilder; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test;
private void testWithRandomStrings(final String mode) throws Exception { final int numOfElements = 100; final int numOfWords = 100; final List<String> words = generateRandomWords(numOfWords); int rIndex1 = RANDOM.nextInt(numOfWords); int rIndex2 = RANDOM.nextInt(numOfWords); for(int i = 0; i < numOfElements; i++) { putSync(newID(), words.get(rIndex1), words.get(rIndex2), 0, 0); rIndex1++; rIndex1 %= numOfWords; rIndex2++; rIndex2 %= numOfWords; } final Set<String> uniqs = new HashSet<String>(words); assertEquals(numOfElements, countAll()); final SearchResponse response1 = getTermList(__txtField1, numOfElements, 1, mode); final SearchResponse response2 = getTermList(__txtField2, numOfElements, 1, mode); checkStringSearchResponse(response1, numOfElements, uniqs.size(), words); checkStringSearchResponse(response2, numOfElements, uniqs.size(), words); } private void testInts(final String mode) throws Exception { final int testLength = 7; final int maxPerShard = 3;
// Path: src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TestUtils.java // public static final Random RANDOM = new Random(0); // // Path: src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TestUtils.java // public static List<Integer> generateRandomInts(final int numOfElements) { // final List<Integer> ret = newArrayList(); // for(int i = 0; i < numOfElements; i++) { // ret.add(RANDOM.nextInt(1000)); // } // return ret; // } // // Path: src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TestUtils.java // public static List<Long> generateRandomLongs(final int numOfElements) { // final List<Long> ret = newArrayList(); // for(int i = 0; i < numOfElements; i++) { // final long val = RANDOM.nextInt(10000); // ret.add(val); // } // return ret; // } // // Path: src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TestUtils.java // public static List<String> generateRandomWords(final int numberOfWords) { // final String[] randomStrings = new String[numberOfWords]; // for(int i = 0; i < numberOfWords; i++) // { // final char[] word = new char[RANDOM.nextInt(8) + 3]; // words of length 3 through 10. (1 and 2 letter words are boring.) // for(int j = 0; j < word.length; j++) // { // word[j] = (char) ('a' + RANDOM.nextInt(26)); // } // randomStrings[i] = new String(word); // } // return newArrayList(randomStrings); // } // Path: src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TermListFacetTest.java import static com.google.common.collect.Lists.newArrayList; import static com.pearson.entech.elasticsearch.search.facet.approx.termlist.TestUtils.RANDOM; import static com.pearson.entech.elasticsearch.search.facet.approx.termlist.TestUtils.generateRandomInts; import static com.pearson.entech.elasticsearch.search.facet.approx.termlist.TestUtils.generateRandomLongs; import static com.pearson.entech.elasticsearch.search.facet.approx.termlist.TestUtils.generateRandomWords; import static org.elasticsearch.node.NodeBuilder.nodeBuilder; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Scanner; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import org.elasticsearch.ElasticSearchException; import org.elasticsearch.action.admin.indices.create.CreateIndexRequest; import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest; import org.elasticsearch.action.bulk.BulkRequestBuilder; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.search.SearchPhaseExecutionException; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.client.Client; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.node.Node; import org.elasticsearch.search.facet.FacetBuilder; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; private void testWithRandomStrings(final String mode) throws Exception { final int numOfElements = 100; final int numOfWords = 100; final List<String> words = generateRandomWords(numOfWords); int rIndex1 = RANDOM.nextInt(numOfWords); int rIndex2 = RANDOM.nextInt(numOfWords); for(int i = 0; i < numOfElements; i++) { putSync(newID(), words.get(rIndex1), words.get(rIndex2), 0, 0); rIndex1++; rIndex1 %= numOfWords; rIndex2++; rIndex2 %= numOfWords; } final Set<String> uniqs = new HashSet<String>(words); assertEquals(numOfElements, countAll()); final SearchResponse response1 = getTermList(__txtField1, numOfElements, 1, mode); final SearchResponse response2 = getTermList(__txtField2, numOfElements, 1, mode); checkStringSearchResponse(response1, numOfElements, uniqs.size(), words); checkStringSearchResponse(response2, numOfElements, uniqs.size(), words); } private void testInts(final String mode) throws Exception { final int testLength = 7; final int maxPerShard = 3;
final List<Integer> numList = generateRandomInts(testLength);
pearson-enabling-technologies/elasticsearch-approx-plugin
src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TermListFacetTest.java
// Path: src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TestUtils.java // public static final Random RANDOM = new Random(0); // // Path: src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TestUtils.java // public static List<Integer> generateRandomInts(final int numOfElements) { // final List<Integer> ret = newArrayList(); // for(int i = 0; i < numOfElements; i++) { // ret.add(RANDOM.nextInt(1000)); // } // return ret; // } // // Path: src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TestUtils.java // public static List<Long> generateRandomLongs(final int numOfElements) { // final List<Long> ret = newArrayList(); // for(int i = 0; i < numOfElements; i++) { // final long val = RANDOM.nextInt(10000); // ret.add(val); // } // return ret; // } // // Path: src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TestUtils.java // public static List<String> generateRandomWords(final int numberOfWords) { // final String[] randomStrings = new String[numberOfWords]; // for(int i = 0; i < numberOfWords; i++) // { // final char[] word = new char[RANDOM.nextInt(8) + 3]; // words of length 3 through 10. (1 and 2 letter words are boring.) // for(int j = 0; j < word.length; j++) // { // word[j] = (char) ('a' + RANDOM.nextInt(26)); // } // randomStrings[i] = new String(word); // } // return newArrayList(randomStrings); // }
import static com.google.common.collect.Lists.newArrayList; import static com.pearson.entech.elasticsearch.search.facet.approx.termlist.TestUtils.RANDOM; import static com.pearson.entech.elasticsearch.search.facet.approx.termlist.TestUtils.generateRandomInts; import static com.pearson.entech.elasticsearch.search.facet.approx.termlist.TestUtils.generateRandomLongs; import static com.pearson.entech.elasticsearch.search.facet.approx.termlist.TestUtils.generateRandomWords; import static org.elasticsearch.node.NodeBuilder.nodeBuilder; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Scanner; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import org.elasticsearch.ElasticSearchException; import org.elasticsearch.action.admin.indices.create.CreateIndexRequest; import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest; import org.elasticsearch.action.bulk.BulkRequestBuilder; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.search.SearchPhaseExecutionException; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.client.Client; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.node.Node; import org.elasticsearch.search.facet.FacetBuilder; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test;
final SearchResponse response1 = getTermList(file); checkStringSearchResponse(response1, numOfElements, uniqs.size(), words); } private void testWithIntRandomData(final String mode) throws Exception { final int numOfDocumentsToIndex = 100; //200 + RANDOM.nextInt(200); final int numOfWordsToGenerate = 100; //100 + RANDOM.nextInt(100); final List<Integer> nums = generateRandomInts(numOfWordsToGenerate); final Set<Integer> uniqs = new HashSet<Integer>(nums); int rIndex = RANDOM.nextInt(numOfWordsToGenerate); for(int i = 0; i < numOfDocumentsToIndex; i++) { putSync(newID(), "", "", nums.get(rIndex), 0); rIndex++; rIndex %= numOfWordsToGenerate; } final SearchResponse response1 = getTermList(__intField1, numOfWordsToGenerate, 1, mode); checkIntSearchResponse(response1, numOfDocumentsToIndex, uniqs.size(), nums); } private void testWithLongRandomData(final String mode) throws Exception { final int numOfDocumentsToIndex = 200 + RANDOM.nextInt(200); final int numOfWordsToGenerate = 100 + RANDOM.nextInt(100);
// Path: src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TestUtils.java // public static final Random RANDOM = new Random(0); // // Path: src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TestUtils.java // public static List<Integer> generateRandomInts(final int numOfElements) { // final List<Integer> ret = newArrayList(); // for(int i = 0; i < numOfElements; i++) { // ret.add(RANDOM.nextInt(1000)); // } // return ret; // } // // Path: src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TestUtils.java // public static List<Long> generateRandomLongs(final int numOfElements) { // final List<Long> ret = newArrayList(); // for(int i = 0; i < numOfElements; i++) { // final long val = RANDOM.nextInt(10000); // ret.add(val); // } // return ret; // } // // Path: src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TestUtils.java // public static List<String> generateRandomWords(final int numberOfWords) { // final String[] randomStrings = new String[numberOfWords]; // for(int i = 0; i < numberOfWords; i++) // { // final char[] word = new char[RANDOM.nextInt(8) + 3]; // words of length 3 through 10. (1 and 2 letter words are boring.) // for(int j = 0; j < word.length; j++) // { // word[j] = (char) ('a' + RANDOM.nextInt(26)); // } // randomStrings[i] = new String(word); // } // return newArrayList(randomStrings); // } // Path: src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TermListFacetTest.java import static com.google.common.collect.Lists.newArrayList; import static com.pearson.entech.elasticsearch.search.facet.approx.termlist.TestUtils.RANDOM; import static com.pearson.entech.elasticsearch.search.facet.approx.termlist.TestUtils.generateRandomInts; import static com.pearson.entech.elasticsearch.search.facet.approx.termlist.TestUtils.generateRandomLongs; import static com.pearson.entech.elasticsearch.search.facet.approx.termlist.TestUtils.generateRandomWords; import static org.elasticsearch.node.NodeBuilder.nodeBuilder; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Scanner; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import org.elasticsearch.ElasticSearchException; import org.elasticsearch.action.admin.indices.create.CreateIndexRequest; import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest; import org.elasticsearch.action.bulk.BulkRequestBuilder; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.search.SearchPhaseExecutionException; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.client.Client; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.node.Node; import org.elasticsearch.search.facet.FacetBuilder; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; final SearchResponse response1 = getTermList(file); checkStringSearchResponse(response1, numOfElements, uniqs.size(), words); } private void testWithIntRandomData(final String mode) throws Exception { final int numOfDocumentsToIndex = 100; //200 + RANDOM.nextInt(200); final int numOfWordsToGenerate = 100; //100 + RANDOM.nextInt(100); final List<Integer> nums = generateRandomInts(numOfWordsToGenerate); final Set<Integer> uniqs = new HashSet<Integer>(nums); int rIndex = RANDOM.nextInt(numOfWordsToGenerate); for(int i = 0; i < numOfDocumentsToIndex; i++) { putSync(newID(), "", "", nums.get(rIndex), 0); rIndex++; rIndex %= numOfWordsToGenerate; } final SearchResponse response1 = getTermList(__intField1, numOfWordsToGenerate, 1, mode); checkIntSearchResponse(response1, numOfDocumentsToIndex, uniqs.size(), nums); } private void testWithLongRandomData(final String mode) throws Exception { final int numOfDocumentsToIndex = 200 + RANDOM.nextInt(200); final int numOfWordsToGenerate = 100 + RANDOM.nextInt(100);
final List<Long> nums = generateRandomLongs(numOfWordsToGenerate);
pearson-enabling-technologies/elasticsearch-approx-plugin
src/main/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/InternalStringTermListFacet.java
// Path: src/main/java/com/pearson/entech/elasticsearch/plugin/approx/BytesRefUtils.java // public static BytesRefHash deserialize(final StreamInput in) throws IOException { // final BytesRefHash output = new BytesRefHash(); // final int entries = in.readVInt(); // byte[] scratch = null; // for(int i = 0; i < entries; i++) { // final int length = in.readVInt(); // // Reuse previous byte array if long enough, otherwise create new one // if(scratch == null || scratch.length < length) { // scratch = new byte[length]; // } // in.readBytes(scratch, 0, length); // output.add(new BytesRef(scratch, 0, length)); // } // return output; // } // // Path: src/main/java/com/pearson/entech/elasticsearch/plugin/approx/BytesRefUtils.java // public static void merge(final BytesRefHash... hashes) { // if(hashes.length < 1) // throw new IllegalArgumentException("Cannot merge empty array of BytesRefHash objects"); // if(hashes.length == 1) // return; // final AddToHash proc = new AddToHash(hashes[0]); // for(int i = 1; i < hashes.length; i++) { // process(hashes[i], proc); // } // } // // Path: src/main/java/com/pearson/entech/elasticsearch/plugin/approx/BytesRefUtils.java // public static void process(final BytesRefHash hash, final Procedure proc) { // int[] ids; // try { // ids = (int[]) getCompactMethod().invoke(hash, __emptyParams); // } catch(final IllegalAccessException e) { // throw new RuntimeException(e); // } catch(final InvocationTargetException e) { // throw new RuntimeException(e); // } // final BytesRef scratch = new BytesRef(); // for(int i = 0; i < ids.length; i++) { // final int id = ids[i]; // if(id < 0) // break; // hash.get(id, scratch); // try { // proc.consume(scratch); // } catch(final Exception e) { // throw new IllegalStateException(e); // } // } // hash.clear(); // } // // Path: src/main/java/com/pearson/entech/elasticsearch/plugin/approx/BytesRefUtils.java // public static void serialize(final BytesRefHash hash, final StreamOutput out) throws IOException { // final ElasticSearchSerializer proc = new ElasticSearchSerializer(out, hash.size()); // try { // process(hash, proc); // } catch(final IllegalStateException e) { // throw new IOException(e.getCause()); // } // } // // Path: src/main/java/com/pearson/entech/elasticsearch/plugin/approx/BytesRefUtils.java // public static class AsStrings implements Procedure { // // private final String[] _strings; // // private int _ptr; // // private final Constants.FIELD_DATA_TYPE _dataType; // // /** // * Create a new procedure to extract strings into an array of the given size. // * // * @param size the number of elements to accommodate // */ // public AsStrings(final int size, final Constants.FIELD_DATA_TYPE dataType) { // _strings = new String[size]; // _ptr = 0; // _dataType = dataType; // // } // // @Override // public void consume(final BytesRef ref) throws Exception { // // //check both ref length and data type before consuming the ref value // if(ref.length == NumericUtils.BUF_SIZE_LONG && _dataType == Constants.FIELD_DATA_TYPE.LONG) { // _strings[_ptr++] = Long.toString(NumericUtils.prefixCodedToLong(ref)); // } // else if(ref.length == NumericUtils.BUF_SIZE_INT && _dataType == Constants.FIELD_DATA_TYPE.INT) { // _strings[_ptr++] = Integer.toString(NumericUtils.prefixCodedToInt(ref)); // } else // _strings[_ptr++] = ref.utf8ToString(); // } // // /** // * Get an array containing all of the entries converted to strings. // * // * @return the array // */ // public String[] getArray() { // return _strings; // } // // /** // * Get a list view of the array returned by getArray(). // * // * @return the list // */ // public List<String> getList() { // return Arrays.asList(_strings); // } // // }
import static com.pearson.entech.elasticsearch.plugin.approx.BytesRefUtils.deserialize; import static com.pearson.entech.elasticsearch.plugin.approx.BytesRefUtils.merge; import static com.pearson.entech.elasticsearch.plugin.approx.BytesRefUtils.process; import static com.pearson.entech.elasticsearch.plugin.approx.BytesRefUtils.serialize; import java.io.IOException; import java.util.Iterator; import java.util.List; import org.apache.lucene.util.BytesRefHash; import org.elasticsearch.common.Strings; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.bytes.HashedBytesArray; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentBuilderString; import org.elasticsearch.search.facet.Facet; import com.pearson.entech.elasticsearch.plugin.approx.BytesRefUtils.AsStrings;
} else { return new InternalStringTermListFacet(getName(), EMPTY, Constants.FIELD_DATA_TYPE.UNDEFINED); } } public static InternalStringTermListFacet readTermListFacet(final StreamInput in) throws IOException { final InternalStringTermListFacet facet = new InternalStringTermListFacet(); facet.readFrom(in); return facet; } @Override public void writeTo(final StreamOutput out) throws IOException { super.writeTo(out); serialize(_bytesRefs, out); _bytesRefs = null; } @Override public void readFrom(final StreamInput in) throws IOException { super.readFrom(in); _bytesRefs = deserialize(in); } private synchronized void materialize() { if(_strings != null) return; // we need the tuple (datatype, ref.length) to handle the data
// Path: src/main/java/com/pearson/entech/elasticsearch/plugin/approx/BytesRefUtils.java // public static BytesRefHash deserialize(final StreamInput in) throws IOException { // final BytesRefHash output = new BytesRefHash(); // final int entries = in.readVInt(); // byte[] scratch = null; // for(int i = 0; i < entries; i++) { // final int length = in.readVInt(); // // Reuse previous byte array if long enough, otherwise create new one // if(scratch == null || scratch.length < length) { // scratch = new byte[length]; // } // in.readBytes(scratch, 0, length); // output.add(new BytesRef(scratch, 0, length)); // } // return output; // } // // Path: src/main/java/com/pearson/entech/elasticsearch/plugin/approx/BytesRefUtils.java // public static void merge(final BytesRefHash... hashes) { // if(hashes.length < 1) // throw new IllegalArgumentException("Cannot merge empty array of BytesRefHash objects"); // if(hashes.length == 1) // return; // final AddToHash proc = new AddToHash(hashes[0]); // for(int i = 1; i < hashes.length; i++) { // process(hashes[i], proc); // } // } // // Path: src/main/java/com/pearson/entech/elasticsearch/plugin/approx/BytesRefUtils.java // public static void process(final BytesRefHash hash, final Procedure proc) { // int[] ids; // try { // ids = (int[]) getCompactMethod().invoke(hash, __emptyParams); // } catch(final IllegalAccessException e) { // throw new RuntimeException(e); // } catch(final InvocationTargetException e) { // throw new RuntimeException(e); // } // final BytesRef scratch = new BytesRef(); // for(int i = 0; i < ids.length; i++) { // final int id = ids[i]; // if(id < 0) // break; // hash.get(id, scratch); // try { // proc.consume(scratch); // } catch(final Exception e) { // throw new IllegalStateException(e); // } // } // hash.clear(); // } // // Path: src/main/java/com/pearson/entech/elasticsearch/plugin/approx/BytesRefUtils.java // public static void serialize(final BytesRefHash hash, final StreamOutput out) throws IOException { // final ElasticSearchSerializer proc = new ElasticSearchSerializer(out, hash.size()); // try { // process(hash, proc); // } catch(final IllegalStateException e) { // throw new IOException(e.getCause()); // } // } // // Path: src/main/java/com/pearson/entech/elasticsearch/plugin/approx/BytesRefUtils.java // public static class AsStrings implements Procedure { // // private final String[] _strings; // // private int _ptr; // // private final Constants.FIELD_DATA_TYPE _dataType; // // /** // * Create a new procedure to extract strings into an array of the given size. // * // * @param size the number of elements to accommodate // */ // public AsStrings(final int size, final Constants.FIELD_DATA_TYPE dataType) { // _strings = new String[size]; // _ptr = 0; // _dataType = dataType; // // } // // @Override // public void consume(final BytesRef ref) throws Exception { // // //check both ref length and data type before consuming the ref value // if(ref.length == NumericUtils.BUF_SIZE_LONG && _dataType == Constants.FIELD_DATA_TYPE.LONG) { // _strings[_ptr++] = Long.toString(NumericUtils.prefixCodedToLong(ref)); // } // else if(ref.length == NumericUtils.BUF_SIZE_INT && _dataType == Constants.FIELD_DATA_TYPE.INT) { // _strings[_ptr++] = Integer.toString(NumericUtils.prefixCodedToInt(ref)); // } else // _strings[_ptr++] = ref.utf8ToString(); // } // // /** // * Get an array containing all of the entries converted to strings. // * // * @return the array // */ // public String[] getArray() { // return _strings; // } // // /** // * Get a list view of the array returned by getArray(). // * // * @return the list // */ // public List<String> getList() { // return Arrays.asList(_strings); // } // // } // Path: src/main/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/InternalStringTermListFacet.java import static com.pearson.entech.elasticsearch.plugin.approx.BytesRefUtils.deserialize; import static com.pearson.entech.elasticsearch.plugin.approx.BytesRefUtils.merge; import static com.pearson.entech.elasticsearch.plugin.approx.BytesRefUtils.process; import static com.pearson.entech.elasticsearch.plugin.approx.BytesRefUtils.serialize; import java.io.IOException; import java.util.Iterator; import java.util.List; import org.apache.lucene.util.BytesRefHash; import org.elasticsearch.common.Strings; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.bytes.HashedBytesArray; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentBuilderString; import org.elasticsearch.search.facet.Facet; import com.pearson.entech.elasticsearch.plugin.approx.BytesRefUtils.AsStrings; } else { return new InternalStringTermListFacet(getName(), EMPTY, Constants.FIELD_DATA_TYPE.UNDEFINED); } } public static InternalStringTermListFacet readTermListFacet(final StreamInput in) throws IOException { final InternalStringTermListFacet facet = new InternalStringTermListFacet(); facet.readFrom(in); return facet; } @Override public void writeTo(final StreamOutput out) throws IOException { super.writeTo(out); serialize(_bytesRefs, out); _bytesRefs = null; } @Override public void readFrom(final StreamInput in) throws IOException { super.readFrom(in); _bytesRefs = deserialize(in); } private synchronized void materialize() { if(_strings != null) return; // we need the tuple (datatype, ref.length) to handle the data
final AsStrings proc = new AsStrings(_bytesRefs.size(), _dataType);
pearson-enabling-technologies/elasticsearch-approx-plugin
src/main/java/com/pearson/entech/elasticsearch/plugin/approx/BytesRefUtils.java
// Path: src/main/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/Constants.java // public interface Constants { // // int DEFAULT_MAX_PER_SHARD = 1000; // // float DEFAULT_SAMPLE = 1; // // enum MODE { // COLLECTOR, // POST // } // // enum FIELD_DATA_TYPE { // UNDEFINED, // INT, // LONG, // STRING // } // // String COLLECTOR_MODE = "collector"; // String POST_MODE = "post"; // // }
import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.BytesRefHash; import org.apache.lucene.util.NumericUtils; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import com.pearson.entech.elasticsearch.search.facet.approx.termlist.Constants;
*/ public static class AddToHash implements Procedure { private final BytesRefHash _target; /** * Create a new procedure. * * @param target the BytesRefHash to merge into */ public AddToHash(final BytesRefHash target) { _target = target; } @Override public void consume(final BytesRef ref) throws Exception { _target.add(ref); } } /** * Procedure for interpreting a BytesRefHash as a set of UTF8 strings. */ public static class AsStrings implements Procedure { private final String[] _strings; private int _ptr;
// Path: src/main/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/Constants.java // public interface Constants { // // int DEFAULT_MAX_PER_SHARD = 1000; // // float DEFAULT_SAMPLE = 1; // // enum MODE { // COLLECTOR, // POST // } // // enum FIELD_DATA_TYPE { // UNDEFINED, // INT, // LONG, // STRING // } // // String COLLECTOR_MODE = "collector"; // String POST_MODE = "post"; // // } // Path: src/main/java/com/pearson/entech/elasticsearch/plugin/approx/BytesRefUtils.java import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.BytesRefHash; import org.apache.lucene.util.NumericUtils; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import com.pearson.entech.elasticsearch.search.facet.approx.termlist.Constants; */ public static class AddToHash implements Procedure { private final BytesRefHash _target; /** * Create a new procedure. * * @param target the BytesRefHash to merge into */ public AddToHash(final BytesRefHash target) { _target = target; } @Override public void consume(final BytesRef ref) throws Exception { _target.add(ref); } } /** * Procedure for interpreting a BytesRefHash as a set of UTF8 strings. */ public static class AsStrings implements Procedure { private final String[] _strings; private int _ptr;
private final Constants.FIELD_DATA_TYPE _dataType;
pearson-enabling-technologies/elasticsearch-approx-plugin
src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/SerializationTest.java
// Path: src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TestUtils.java // public static List<Integer> generateRandomInts(final int numOfElements) { // final List<Integer> ret = newArrayList(); // for(int i = 0; i < numOfElements; i++) { // ret.add(RANDOM.nextInt(1000)); // } // return ret; // } // // Path: src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TestUtils.java // public static List<Long> generateRandomLongs(final int numOfElements) { // final List<Long> ret = newArrayList(); // for(int i = 0; i < numOfElements; i++) { // final long val = RANDOM.nextInt(10000); // ret.add(val); // } // return ret; // } // // Path: src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TestUtils.java // public static List<String> generateRandomWords(final int numberOfWords) { // final String[] randomStrings = new String[numberOfWords]; // for(int i = 0; i < numberOfWords; i++) // { // final char[] word = new char[RANDOM.nextInt(8) + 3]; // words of length 3 through 10. (1 and 2 letter words are boring.) // for(int j = 0; j < word.length; j++) // { // word[j] = (char) ('a' + RANDOM.nextInt(26)); // } // randomStrings[i] = new String(word); // } // return newArrayList(randomStrings); // }
import static com.pearson.entech.elasticsearch.search.facet.approx.termlist.TestUtils.generateRandomInts; import static com.pearson.entech.elasticsearch.search.facet.approx.termlist.TestUtils.generateRandomLongs; import static com.pearson.entech.elasticsearch.search.facet.approx.termlist.TestUtils.generateRandomWords; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.Collections; import java.util.List; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.BytesRefHash; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.io.stream.BytesStreamInput; import org.elasticsearch.common.io.stream.BytesStreamOutput; import org.elasticsearch.search.facet.InternalFacet; import org.junit.Test;
package com.pearson.entech.elasticsearch.search.facet.approx.termlist; public class SerializationTest { @Test public void testLongSerialization() throws Exception {
// Path: src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TestUtils.java // public static List<Integer> generateRandomInts(final int numOfElements) { // final List<Integer> ret = newArrayList(); // for(int i = 0; i < numOfElements; i++) { // ret.add(RANDOM.nextInt(1000)); // } // return ret; // } // // Path: src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TestUtils.java // public static List<Long> generateRandomLongs(final int numOfElements) { // final List<Long> ret = newArrayList(); // for(int i = 0; i < numOfElements; i++) { // final long val = RANDOM.nextInt(10000); // ret.add(val); // } // return ret; // } // // Path: src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TestUtils.java // public static List<String> generateRandomWords(final int numberOfWords) { // final String[] randomStrings = new String[numberOfWords]; // for(int i = 0; i < numberOfWords; i++) // { // final char[] word = new char[RANDOM.nextInt(8) + 3]; // words of length 3 through 10. (1 and 2 letter words are boring.) // for(int j = 0; j < word.length; j++) // { // word[j] = (char) ('a' + RANDOM.nextInt(26)); // } // randomStrings[i] = new String(word); // } // return newArrayList(randomStrings); // } // Path: src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/SerializationTest.java import static com.pearson.entech.elasticsearch.search.facet.approx.termlist.TestUtils.generateRandomInts; import static com.pearson.entech.elasticsearch.search.facet.approx.termlist.TestUtils.generateRandomLongs; import static com.pearson.entech.elasticsearch.search.facet.approx.termlist.TestUtils.generateRandomWords; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.Collections; import java.util.List; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.BytesRefHash; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.io.stream.BytesStreamInput; import org.elasticsearch.common.io.stream.BytesStreamOutput; import org.elasticsearch.search.facet.InternalFacet; import org.junit.Test; package com.pearson.entech.elasticsearch.search.facet.approx.termlist; public class SerializationTest { @Test public void testLongSerialization() throws Exception {
final List<Long> randomInts = generateRandomLongs(1000);
pearson-enabling-technologies/elasticsearch-approx-plugin
src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/SerializationTest.java
// Path: src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TestUtils.java // public static List<Integer> generateRandomInts(final int numOfElements) { // final List<Integer> ret = newArrayList(); // for(int i = 0; i < numOfElements; i++) { // ret.add(RANDOM.nextInt(1000)); // } // return ret; // } // // Path: src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TestUtils.java // public static List<Long> generateRandomLongs(final int numOfElements) { // final List<Long> ret = newArrayList(); // for(int i = 0; i < numOfElements; i++) { // final long val = RANDOM.nextInt(10000); // ret.add(val); // } // return ret; // } // // Path: src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TestUtils.java // public static List<String> generateRandomWords(final int numberOfWords) { // final String[] randomStrings = new String[numberOfWords]; // for(int i = 0; i < numberOfWords; i++) // { // final char[] word = new char[RANDOM.nextInt(8) + 3]; // words of length 3 through 10. (1 and 2 letter words are boring.) // for(int j = 0; j < word.length; j++) // { // word[j] = (char) ('a' + RANDOM.nextInt(26)); // } // randomStrings[i] = new String(word); // } // return newArrayList(randomStrings); // }
import static com.pearson.entech.elasticsearch.search.facet.approx.termlist.TestUtils.generateRandomInts; import static com.pearson.entech.elasticsearch.search.facet.approx.termlist.TestUtils.generateRandomLongs; import static com.pearson.entech.elasticsearch.search.facet.approx.termlist.TestUtils.generateRandomWords; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.Collections; import java.util.List; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.BytesRefHash; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.io.stream.BytesStreamInput; import org.elasticsearch.common.io.stream.BytesStreamOutput; import org.elasticsearch.search.facet.InternalFacet; import org.junit.Test;
package com.pearson.entech.elasticsearch.search.facet.approx.termlist; public class SerializationTest { @Test public void testLongSerialization() throws Exception { final List<Long> randomInts = generateRandomLongs(1000); final BytesRefHash sentHash = new BytesRefHash(); for(final Long word : randomInts) { sentHash.add(new BytesRef(word.toString())); } final InternalStringTermListFacet sentFacet = new InternalStringTermListFacet("foo", sentHash, Constants.FIELD_DATA_TYPE.INT); final InternalStringTermListFacet receivedFacet = new InternalStringTermListFacet(); serializeAndDeserialize(sentFacet, receivedFacet); assertEquals("foo", receivedFacet.getName()); final List<? extends String> entries = receivedFacet.getEntries(); Collections.sort(randomInts); Collections.sort(entries); for(int i = 0; i < entries.size(); i++) { assertTrue(randomInts.contains(Long.parseLong(entries.get(i)))); } } @Test public void testIntSerialization() throws Exception {
// Path: src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TestUtils.java // public static List<Integer> generateRandomInts(final int numOfElements) { // final List<Integer> ret = newArrayList(); // for(int i = 0; i < numOfElements; i++) { // ret.add(RANDOM.nextInt(1000)); // } // return ret; // } // // Path: src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TestUtils.java // public static List<Long> generateRandomLongs(final int numOfElements) { // final List<Long> ret = newArrayList(); // for(int i = 0; i < numOfElements; i++) { // final long val = RANDOM.nextInt(10000); // ret.add(val); // } // return ret; // } // // Path: src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TestUtils.java // public static List<String> generateRandomWords(final int numberOfWords) { // final String[] randomStrings = new String[numberOfWords]; // for(int i = 0; i < numberOfWords; i++) // { // final char[] word = new char[RANDOM.nextInt(8) + 3]; // words of length 3 through 10. (1 and 2 letter words are boring.) // for(int j = 0; j < word.length; j++) // { // word[j] = (char) ('a' + RANDOM.nextInt(26)); // } // randomStrings[i] = new String(word); // } // return newArrayList(randomStrings); // } // Path: src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/SerializationTest.java import static com.pearson.entech.elasticsearch.search.facet.approx.termlist.TestUtils.generateRandomInts; import static com.pearson.entech.elasticsearch.search.facet.approx.termlist.TestUtils.generateRandomLongs; import static com.pearson.entech.elasticsearch.search.facet.approx.termlist.TestUtils.generateRandomWords; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.Collections; import java.util.List; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.BytesRefHash; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.io.stream.BytesStreamInput; import org.elasticsearch.common.io.stream.BytesStreamOutput; import org.elasticsearch.search.facet.InternalFacet; import org.junit.Test; package com.pearson.entech.elasticsearch.search.facet.approx.termlist; public class SerializationTest { @Test public void testLongSerialization() throws Exception { final List<Long> randomInts = generateRandomLongs(1000); final BytesRefHash sentHash = new BytesRefHash(); for(final Long word : randomInts) { sentHash.add(new BytesRef(word.toString())); } final InternalStringTermListFacet sentFacet = new InternalStringTermListFacet("foo", sentHash, Constants.FIELD_DATA_TYPE.INT); final InternalStringTermListFacet receivedFacet = new InternalStringTermListFacet(); serializeAndDeserialize(sentFacet, receivedFacet); assertEquals("foo", receivedFacet.getName()); final List<? extends String> entries = receivedFacet.getEntries(); Collections.sort(randomInts); Collections.sort(entries); for(int i = 0; i < entries.size(); i++) { assertTrue(randomInts.contains(Long.parseLong(entries.get(i)))); } } @Test public void testIntSerialization() throws Exception {
final List<Integer> randomInts = generateRandomInts(1000);
pearson-enabling-technologies/elasticsearch-approx-plugin
src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/SerializationTest.java
// Path: src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TestUtils.java // public static List<Integer> generateRandomInts(final int numOfElements) { // final List<Integer> ret = newArrayList(); // for(int i = 0; i < numOfElements; i++) { // ret.add(RANDOM.nextInt(1000)); // } // return ret; // } // // Path: src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TestUtils.java // public static List<Long> generateRandomLongs(final int numOfElements) { // final List<Long> ret = newArrayList(); // for(int i = 0; i < numOfElements; i++) { // final long val = RANDOM.nextInt(10000); // ret.add(val); // } // return ret; // } // // Path: src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TestUtils.java // public static List<String> generateRandomWords(final int numberOfWords) { // final String[] randomStrings = new String[numberOfWords]; // for(int i = 0; i < numberOfWords; i++) // { // final char[] word = new char[RANDOM.nextInt(8) + 3]; // words of length 3 through 10. (1 and 2 letter words are boring.) // for(int j = 0; j < word.length; j++) // { // word[j] = (char) ('a' + RANDOM.nextInt(26)); // } // randomStrings[i] = new String(word); // } // return newArrayList(randomStrings); // }
import static com.pearson.entech.elasticsearch.search.facet.approx.termlist.TestUtils.generateRandomInts; import static com.pearson.entech.elasticsearch.search.facet.approx.termlist.TestUtils.generateRandomLongs; import static com.pearson.entech.elasticsearch.search.facet.approx.termlist.TestUtils.generateRandomWords; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.Collections; import java.util.List; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.BytesRefHash; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.io.stream.BytesStreamInput; import org.elasticsearch.common.io.stream.BytesStreamOutput; import org.elasticsearch.search.facet.InternalFacet; import org.junit.Test;
Collections.sort(entries); for(int i = 0; i < entries.size(); i++) { assertTrue(randomInts.contains(Long.parseLong(entries.get(i)))); } } @Test public void testIntSerialization() throws Exception { final List<Integer> randomInts = generateRandomInts(1000); final BytesRefHash sentHash = new BytesRefHash(); for(final Integer word : randomInts) { sentHash.add(new BytesRef(word.toString())); } final InternalStringTermListFacet sentFacet = new InternalStringTermListFacet("foo", sentHash, Constants.FIELD_DATA_TYPE.INT); final InternalStringTermListFacet receivedFacet = new InternalStringTermListFacet(); serializeAndDeserialize(sentFacet, receivedFacet); assertEquals("foo", receivedFacet.getName()); final List<? extends String> entries = receivedFacet.getEntries(); Collections.sort(randomInts); Collections.sort(entries); //assertEquals( randomInts.size(), entries.size()); for(int i = 0; i < entries.size(); i++) { assertTrue(randomInts.contains(Integer.parseInt(entries.get(i)))); } } @Test public void testStringSerialization() throws Exception {
// Path: src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TestUtils.java // public static List<Integer> generateRandomInts(final int numOfElements) { // final List<Integer> ret = newArrayList(); // for(int i = 0; i < numOfElements; i++) { // ret.add(RANDOM.nextInt(1000)); // } // return ret; // } // // Path: src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TestUtils.java // public static List<Long> generateRandomLongs(final int numOfElements) { // final List<Long> ret = newArrayList(); // for(int i = 0; i < numOfElements; i++) { // final long val = RANDOM.nextInt(10000); // ret.add(val); // } // return ret; // } // // Path: src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/TestUtils.java // public static List<String> generateRandomWords(final int numberOfWords) { // final String[] randomStrings = new String[numberOfWords]; // for(int i = 0; i < numberOfWords; i++) // { // final char[] word = new char[RANDOM.nextInt(8) + 3]; // words of length 3 through 10. (1 and 2 letter words are boring.) // for(int j = 0; j < word.length; j++) // { // word[j] = (char) ('a' + RANDOM.nextInt(26)); // } // randomStrings[i] = new String(word); // } // return newArrayList(randomStrings); // } // Path: src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/termlist/SerializationTest.java import static com.pearson.entech.elasticsearch.search.facet.approx.termlist.TestUtils.generateRandomInts; import static com.pearson.entech.elasticsearch.search.facet.approx.termlist.TestUtils.generateRandomLongs; import static com.pearson.entech.elasticsearch.search.facet.approx.termlist.TestUtils.generateRandomWords; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.Collections; import java.util.List; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.BytesRefHash; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.io.stream.BytesStreamInput; import org.elasticsearch.common.io.stream.BytesStreamOutput; import org.elasticsearch.search.facet.InternalFacet; import org.junit.Test; Collections.sort(entries); for(int i = 0; i < entries.size(); i++) { assertTrue(randomInts.contains(Long.parseLong(entries.get(i)))); } } @Test public void testIntSerialization() throws Exception { final List<Integer> randomInts = generateRandomInts(1000); final BytesRefHash sentHash = new BytesRefHash(); for(final Integer word : randomInts) { sentHash.add(new BytesRef(word.toString())); } final InternalStringTermListFacet sentFacet = new InternalStringTermListFacet("foo", sentHash, Constants.FIELD_DATA_TYPE.INT); final InternalStringTermListFacet receivedFacet = new InternalStringTermListFacet(); serializeAndDeserialize(sentFacet, receivedFacet); assertEquals("foo", receivedFacet.getName()); final List<? extends String> entries = receivedFacet.getEntries(); Collections.sort(randomInts); Collections.sort(entries); //assertEquals( randomInts.size(), entries.size()); for(int i = 0; i < entries.size(); i++) { assertTrue(randomInts.contains(Integer.parseInt(entries.get(i)))); } } @Test public void testStringSerialization() throws Exception {
final List<String> randomWords = generateRandomWords(1000);
Esri/vehicle-commander-java
source/VehicleCommander/src/com/esri/vehiclecommander/controller/LocationController.java
// Path: source/VehicleCommander/src/com/esri/vehiclecommander/model/GpsLocationProvider.java // public class GpsLocationProvider extends LocationProvider { // // private final SerialPortGPSWatcher gpsWatcher; // // public GpsLocationProvider() { // gpsWatcher = new SerialPortGPSWatcher(); // } // // @Override // public void start() { // try { // gpsWatcher.start(); // } catch (GPSException ex) { // Logger.getLogger(GpsLocationProvider.class.getName()).log(Level.SEVERE, null, ex); // } // } // // /** // * For this GPS-based provider, pause() simply calls stop(). // */ // @Override // public void pause() { // this.stop(); // } // // @Override // public void stop() { // try { // gpsWatcher.stop(); // } catch (GPSException ex) { // Logger.getLogger(GpsLocationProvider.class.getName()).log(Level.SEVERE, null, ex); // } // } // // @Override // public LocationProviderState getState() { // switch (gpsWatcher.getStatus()) { // case RUNNING: // return LocationProviderState.STARTED; // default: // return LocationProviderState.STOPPED; // } // } // // /** // * Returns this provider's IGPSWatcher. // * @return this provider's IGPSWatcher. // */ // public IGPSWatcher getGpsWatcher() { // return gpsWatcher; // } // // }
import com.esri.core.gps.GPSException; import com.esri.core.gps.IGPSWatcher; import com.esri.core.map.Graphic; import com.esri.map.GPSLayer; import com.esri.militaryapps.model.LocationProvider; import com.esri.militaryapps.model.LocationSimulator; import com.esri.vehiclecommander.model.GpsLocationProvider; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.xml.parsers.ParserConfigurationException; import org.xml.sax.SAXException;
/******************************************************************************* * Copyright 2012-2014 Esri * * 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.esri.vehiclecommander.controller; /** * A location controller for the Vehicle Commander application. */ public class LocationController extends com.esri.militaryapps.controller.LocationController { private final MapController mapController; private final Object selectedWaypointLock = new Object(); private GPSLayer gpsLayer; private Graphic selectedWaypoint = null; /** * Creates a new GPSController. * @param gpsWatcher the IGPSWatcher to be controlled by this GPSController. */ public LocationController( MapController mapController, LocationMode mode, boolean startImmediately) throws IOException, ParserConfigurationException, SAXException { super(mode, startImmediately); this.mapController = mapController; checkAndAddGPSLayer(); } @Override protected LocationProvider createLocationServiceProvider() {
// Path: source/VehicleCommander/src/com/esri/vehiclecommander/model/GpsLocationProvider.java // public class GpsLocationProvider extends LocationProvider { // // private final SerialPortGPSWatcher gpsWatcher; // // public GpsLocationProvider() { // gpsWatcher = new SerialPortGPSWatcher(); // } // // @Override // public void start() { // try { // gpsWatcher.start(); // } catch (GPSException ex) { // Logger.getLogger(GpsLocationProvider.class.getName()).log(Level.SEVERE, null, ex); // } // } // // /** // * For this GPS-based provider, pause() simply calls stop(). // */ // @Override // public void pause() { // this.stop(); // } // // @Override // public void stop() { // try { // gpsWatcher.stop(); // } catch (GPSException ex) { // Logger.getLogger(GpsLocationProvider.class.getName()).log(Level.SEVERE, null, ex); // } // } // // @Override // public LocationProviderState getState() { // switch (gpsWatcher.getStatus()) { // case RUNNING: // return LocationProviderState.STARTED; // default: // return LocationProviderState.STOPPED; // } // } // // /** // * Returns this provider's IGPSWatcher. // * @return this provider's IGPSWatcher. // */ // public IGPSWatcher getGpsWatcher() { // return gpsWatcher; // } // // } // Path: source/VehicleCommander/src/com/esri/vehiclecommander/controller/LocationController.java import com.esri.core.gps.GPSException; import com.esri.core.gps.IGPSWatcher; import com.esri.core.map.Graphic; import com.esri.map.GPSLayer; import com.esri.militaryapps.model.LocationProvider; import com.esri.militaryapps.model.LocationSimulator; import com.esri.vehiclecommander.model.GpsLocationProvider; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.xml.parsers.ParserConfigurationException; import org.xml.sax.SAXException; /******************************************************************************* * Copyright 2012-2014 Esri * * 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.esri.vehiclecommander.controller; /** * A location controller for the Vehicle Commander application. */ public class LocationController extends com.esri.militaryapps.controller.LocationController { private final MapController mapController; private final Object selectedWaypointLock = new Object(); private GPSLayer gpsLayer; private Graphic selectedWaypoint = null; /** * Creates a new GPSController. * @param gpsWatcher the IGPSWatcher to be controlled by this GPSController. */ public LocationController( MapController mapController, LocationMode mode, boolean startImmediately) throws IOException, ParserConfigurationException, SAXException { super(mode, startImmediately); this.mapController = mapController; checkAndAddGPSLayer(); } @Override protected LocationProvider createLocationServiceProvider() {
return new GpsLocationProvider();
google/blockly-android
blocklylib-core/src/main/java/com/google/blockly/android/ui/NameVariableDialog.java
// Path: blocklylib-core/src/main/java/com/google/blockly/utils/LangUtils.java // public class LangUtils { // private LangUtils() { // } // // /** // * Current Language // */ // private static String lang = "en"; // // /** // * Get Language // * @return Language // */ // public static String getLang() { // return lang; // } // // /** // * Set Language // * @param newLang New Language // */ // public static void setLang(String newLang) { // lang = newLang; // } // // /** // * A Map Containing Translations // */ // private static Map<String, String> langMap = new HashMap<>(); // // /** // * Replace Translation String with localized text using Blockly Web's translation files. // * @param value Input Value // * @return Translated String // */ // public static String interpolate(String value) { // for (Map.Entry<String, String> entry : langMap.entrySet()) { // while (value.contains(entry.getKey())) { // value = value.replace(entry.getKey(), entry.getValue()); // } // } // return value; // } // // /** // * Generate Map of translations. // * @param context Context // */ // public static void generateLang(Context context) { // generateLang(context, getLang()); // } // // /** // * Generate Map of translations. // * @param context Context // */ // private static void generateLang(Context context, String lang) { // if (!lang.equals("en")) { // generateLang(context, "en"); // } // // // Attempt to override language string table. Missing values will default to English loaded above. // StringBuilder out = new StringBuilder(); // BufferedReader reader = null; // try { // reader = new BufferedReader( // new InputStreamReader(context.getAssets().open("msg/js/" + lang + ".js"))); // // String line; // while ((line = reader.readLine()) != null) { // out.append(line); // out.append('\n'); // } // } catch (IOException e) { // e.printStackTrace(); // } finally { // if (reader != null) { // try { // reader.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // // String[] lines = out.toString().split("\n"); // for (int i = 0; i < lines.length; i++) { // lines[i] = lines[i].trim(); // if (lines[i].startsWith("Blockly.Msg[\"")) { // boolean alias = false; // // lines[i] = lines[i].substring("Blockly.Msg[\"".length()); // String name = lines[i].substring(0, lines[i].indexOf('"')); // if (lines[i].contains("\"] = \"")) { // lines[i] = lines[i].substring(lines[i].indexOf("\"] = \"") + "\"] = \"".length() - 1); // } else { // lines[i] = lines[i].substring(lines[i].indexOf("\"] = Blockly.Msg[\"") + "\"] = Blockly.Msg[\"".length() - 1); // alias = true; // } // String value = lines[i].substring(1, lines[i].lastIndexOf('"')); // if (alias) { // if (langMap.get("%{BKY_" + value + "}") == null) { // throw new RuntimeException(value + " is not defined."); // } else { // value = langMap.get("%{BKY_" + value + "}"); // } // } // if (value != null) { // langMap.put("%{BKY_" + name + "}", value); // } // } // } // } // }
import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.view.LayoutInflater; import android.view.View; import android.widget.EditText; import android.widget.TextView; import com.google.blockly.android.R; import com.google.blockly.utils.LangUtils;
/* * Copyright 2017 Google Inc. All Rights Reserved. * 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.google.blockly.android.ui; /** * Default dialog window shown when creating or renaming a variable in the workspace. */ public class NameVariableDialog extends DialogFragment { private String mVariable; private DialogInterface.OnClickListener mListener; private EditText mNameEditText; private boolean mIsRename; View nameView; @Override public Dialog onCreateDialog(Bundle savedInstanceBundle) { LayoutInflater inflater = getActivity().getLayoutInflater(); nameView = inflater.inflate(R.layout.name_variable_view, null); mNameEditText = (EditText) nameView.findViewById(R.id.name); mNameEditText.setText(mVariable); TextView description = (TextView) nameView.findViewById(R.id.description); if (mIsRename) { description.setText(
// Path: blocklylib-core/src/main/java/com/google/blockly/utils/LangUtils.java // public class LangUtils { // private LangUtils() { // } // // /** // * Current Language // */ // private static String lang = "en"; // // /** // * Get Language // * @return Language // */ // public static String getLang() { // return lang; // } // // /** // * Set Language // * @param newLang New Language // */ // public static void setLang(String newLang) { // lang = newLang; // } // // /** // * A Map Containing Translations // */ // private static Map<String, String> langMap = new HashMap<>(); // // /** // * Replace Translation String with localized text using Blockly Web's translation files. // * @param value Input Value // * @return Translated String // */ // public static String interpolate(String value) { // for (Map.Entry<String, String> entry : langMap.entrySet()) { // while (value.contains(entry.getKey())) { // value = value.replace(entry.getKey(), entry.getValue()); // } // } // return value; // } // // /** // * Generate Map of translations. // * @param context Context // */ // public static void generateLang(Context context) { // generateLang(context, getLang()); // } // // /** // * Generate Map of translations. // * @param context Context // */ // private static void generateLang(Context context, String lang) { // if (!lang.equals("en")) { // generateLang(context, "en"); // } // // // Attempt to override language string table. Missing values will default to English loaded above. // StringBuilder out = new StringBuilder(); // BufferedReader reader = null; // try { // reader = new BufferedReader( // new InputStreamReader(context.getAssets().open("msg/js/" + lang + ".js"))); // // String line; // while ((line = reader.readLine()) != null) { // out.append(line); // out.append('\n'); // } // } catch (IOException e) { // e.printStackTrace(); // } finally { // if (reader != null) { // try { // reader.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // // String[] lines = out.toString().split("\n"); // for (int i = 0; i < lines.length; i++) { // lines[i] = lines[i].trim(); // if (lines[i].startsWith("Blockly.Msg[\"")) { // boolean alias = false; // // lines[i] = lines[i].substring("Blockly.Msg[\"".length()); // String name = lines[i].substring(0, lines[i].indexOf('"')); // if (lines[i].contains("\"] = \"")) { // lines[i] = lines[i].substring(lines[i].indexOf("\"] = \"") + "\"] = \"".length() - 1); // } else { // lines[i] = lines[i].substring(lines[i].indexOf("\"] = Blockly.Msg[\"") + "\"] = Blockly.Msg[\"".length() - 1); // alias = true; // } // String value = lines[i].substring(1, lines[i].lastIndexOf('"')); // if (alias) { // if (langMap.get("%{BKY_" + value + "}") == null) { // throw new RuntimeException(value + " is not defined."); // } else { // value = langMap.get("%{BKY_" + value + "}"); // } // } // if (value != null) { // langMap.put("%{BKY_" + name + "}", value); // } // } // } // } // } // Path: blocklylib-core/src/main/java/com/google/blockly/android/ui/NameVariableDialog.java import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.view.LayoutInflater; import android.view.View; import android.widget.EditText; import android.widget.TextView; import com.google.blockly.android.R; import com.google.blockly.utils.LangUtils; /* * Copyright 2017 Google Inc. All Rights Reserved. * 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.google.blockly.android.ui; /** * Default dialog window shown when creating or renaming a variable in the workspace. */ public class NameVariableDialog extends DialogFragment { private String mVariable; private DialogInterface.OnClickListener mListener; private EditText mNameEditText; private boolean mIsRename; View nameView; @Override public Dialog onCreateDialog(Bundle savedInstanceBundle) { LayoutInflater inflater = getActivity().getLayoutInflater(); nameView = inflater.inflate(R.layout.name_variable_view, null); mNameEditText = (EditText) nameView.findViewById(R.id.name); mNameEditText.setText(mVariable); TextView description = (TextView) nameView.findViewById(R.id.description); if (mIsRename) { description.setText(
LangUtils.interpolate("%{BKY_RENAME_VARIABLE_TITLE}").replace("%1", mVariable));
google/blockly-android
blocklylib-core/src/main/java/com/google/blockly/android/codegen/CodeGeneratorService.java
// Path: blocklylib-core/src/main/java/com/google/blockly/utils/LangUtils.java // public class LangUtils { // private LangUtils() { // } // // /** // * Current Language // */ // private static String lang = "en"; // // /** // * Get Language // * @return Language // */ // public static String getLang() { // return lang; // } // // /** // * Set Language // * @param newLang New Language // */ // public static void setLang(String newLang) { // lang = newLang; // } // // /** // * A Map Containing Translations // */ // private static Map<String, String> langMap = new HashMap<>(); // // /** // * Replace Translation String with localized text using Blockly Web's translation files. // * @param value Input Value // * @return Translated String // */ // public static String interpolate(String value) { // for (Map.Entry<String, String> entry : langMap.entrySet()) { // while (value.contains(entry.getKey())) { // value = value.replace(entry.getKey(), entry.getValue()); // } // } // return value; // } // // /** // * Generate Map of translations. // * @param context Context // */ // public static void generateLang(Context context) { // generateLang(context, getLang()); // } // // /** // * Generate Map of translations. // * @param context Context // */ // private static void generateLang(Context context, String lang) { // if (!lang.equals("en")) { // generateLang(context, "en"); // } // // // Attempt to override language string table. Missing values will default to English loaded above. // StringBuilder out = new StringBuilder(); // BufferedReader reader = null; // try { // reader = new BufferedReader( // new InputStreamReader(context.getAssets().open("msg/js/" + lang + ".js"))); // // String line; // while ((line = reader.readLine()) != null) { // out.append(line); // out.append('\n'); // } // } catch (IOException e) { // e.printStackTrace(); // } finally { // if (reader != null) { // try { // reader.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // // String[] lines = out.toString().split("\n"); // for (int i = 0; i < lines.length; i++) { // lines[i] = lines[i].trim(); // if (lines[i].startsWith("Blockly.Msg[\"")) { // boolean alias = false; // // lines[i] = lines[i].substring("Blockly.Msg[\"".length()); // String name = lines[i].substring(0, lines[i].indexOf('"')); // if (lines[i].contains("\"] = \"")) { // lines[i] = lines[i].substring(lines[i].indexOf("\"] = \"") + "\"] = \"".length() - 1); // } else { // lines[i] = lines[i].substring(lines[i].indexOf("\"] = Blockly.Msg[\"") + "\"] = Blockly.Msg[\"".length() - 1); // alias = true; // } // String value = lines[i].substring(1, lines[i].lastIndexOf('"')); // if (alias) { // if (langMap.get("%{BKY_" + value + "}") == null) { // throw new RuntimeException(value + " is not defined."); // } else { // value = langMap.get("%{BKY_" + value + "}"); // } // } // if (value != null) { // langMap.put("%{BKY_" + name + "}", value); // } // } // } // } // }
import android.app.Service; import android.content.Intent; import android.os.Binder; import android.os.Build; import android.os.Handler; import android.os.IBinder; import android.support.annotation.Nullable; import android.support.annotation.VisibleForTesting; import android.text.TextUtils; import android.util.Log; import android.webkit.JavascriptInterface; import android.webkit.WebChromeClient; import android.webkit.WebView; import android.webkit.WebViewClient; import com.google.blockly.utils.LangUtils; import org.json.JSONArray; import org.json.JSONException; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.List;
Log.e(TAG, "Couldn't find block definitions file \"" + filename + "\""); return ""; } } else { // Concatenate all definitions into a single stream. JSONArray allBlocks = new JSONArray(); String filename = null; try { if (mDefinitions != null) { Iterator<String> iter = mDefinitions.iterator(); while (iter.hasNext()) { filename = iter.next(); String contents = loadAssetAsUtf8(filename); JSONArray fileBlocks = new JSONArray(contents); for (int i = 0; i < fileBlocks.length(); ++i) { allBlocks.put(fileBlocks.getJSONObject(i)); } } } } catch (IOException|JSONException e) { Log.e(TAG, "Error reading block definitions file \"" + filename + "\""); return ""; } mAllBlocks = allBlocks.toString(); return mAllBlocks; } } @JavascriptInterface public String getLang() {
// Path: blocklylib-core/src/main/java/com/google/blockly/utils/LangUtils.java // public class LangUtils { // private LangUtils() { // } // // /** // * Current Language // */ // private static String lang = "en"; // // /** // * Get Language // * @return Language // */ // public static String getLang() { // return lang; // } // // /** // * Set Language // * @param newLang New Language // */ // public static void setLang(String newLang) { // lang = newLang; // } // // /** // * A Map Containing Translations // */ // private static Map<String, String> langMap = new HashMap<>(); // // /** // * Replace Translation String with localized text using Blockly Web's translation files. // * @param value Input Value // * @return Translated String // */ // public static String interpolate(String value) { // for (Map.Entry<String, String> entry : langMap.entrySet()) { // while (value.contains(entry.getKey())) { // value = value.replace(entry.getKey(), entry.getValue()); // } // } // return value; // } // // /** // * Generate Map of translations. // * @param context Context // */ // public static void generateLang(Context context) { // generateLang(context, getLang()); // } // // /** // * Generate Map of translations. // * @param context Context // */ // private static void generateLang(Context context, String lang) { // if (!lang.equals("en")) { // generateLang(context, "en"); // } // // // Attempt to override language string table. Missing values will default to English loaded above. // StringBuilder out = new StringBuilder(); // BufferedReader reader = null; // try { // reader = new BufferedReader( // new InputStreamReader(context.getAssets().open("msg/js/" + lang + ".js"))); // // String line; // while ((line = reader.readLine()) != null) { // out.append(line); // out.append('\n'); // } // } catch (IOException e) { // e.printStackTrace(); // } finally { // if (reader != null) { // try { // reader.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // // String[] lines = out.toString().split("\n"); // for (int i = 0; i < lines.length; i++) { // lines[i] = lines[i].trim(); // if (lines[i].startsWith("Blockly.Msg[\"")) { // boolean alias = false; // // lines[i] = lines[i].substring("Blockly.Msg[\"".length()); // String name = lines[i].substring(0, lines[i].indexOf('"')); // if (lines[i].contains("\"] = \"")) { // lines[i] = lines[i].substring(lines[i].indexOf("\"] = \"") + "\"] = \"".length() - 1); // } else { // lines[i] = lines[i].substring(lines[i].indexOf("\"] = Blockly.Msg[\"") + "\"] = Blockly.Msg[\"".length() - 1); // alias = true; // } // String value = lines[i].substring(1, lines[i].lastIndexOf('"')); // if (alias) { // if (langMap.get("%{BKY_" + value + "}") == null) { // throw new RuntimeException(value + " is not defined."); // } else { // value = langMap.get("%{BKY_" + value + "}"); // } // } // if (value != null) { // langMap.put("%{BKY_" + name + "}", value); // } // } // } // } // } // Path: blocklylib-core/src/main/java/com/google/blockly/android/codegen/CodeGeneratorService.java import android.app.Service; import android.content.Intent; import android.os.Binder; import android.os.Build; import android.os.Handler; import android.os.IBinder; import android.support.annotation.Nullable; import android.support.annotation.VisibleForTesting; import android.text.TextUtils; import android.util.Log; import android.webkit.JavascriptInterface; import android.webkit.WebChromeClient; import android.webkit.WebView; import android.webkit.WebViewClient; import com.google.blockly.utils.LangUtils; import org.json.JSONArray; import org.json.JSONException; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.List; Log.e(TAG, "Couldn't find block definitions file \"" + filename + "\""); return ""; } } else { // Concatenate all definitions into a single stream. JSONArray allBlocks = new JSONArray(); String filename = null; try { if (mDefinitions != null) { Iterator<String> iter = mDefinitions.iterator(); while (iter.hasNext()) { filename = iter.next(); String contents = loadAssetAsUtf8(filename); JSONArray fileBlocks = new JSONArray(contents); for (int i = 0; i < fileBlocks.length(); ++i) { allBlocks.put(fileBlocks.getJSONObject(i)); } } } } catch (IOException|JSONException e) { Log.e(TAG, "Error reading block definitions file \"" + filename + "\""); return ""; } mAllBlocks = allBlocks.toString(); return mAllBlocks; } } @JavascriptInterface public String getLang() {
return LangUtils.getLang();
google/blockly-android
blocklylib-core/src/main/java/com/google/blockly/android/ui/fieldview/BasicFieldDateView.java
// Path: blocklylib-core/src/main/java/com/google/blockly/model/FieldDate.java // public final class FieldDate extends Field { // private static final String TAG = "FieldDate"; // // // Date format used for serialization. // private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd", Locale.US); // // private final Date mDate = new Date(); // // public FieldDate(String name) { // super(name, TYPE_DATE); // } // // public FieldDate(String name, long milliseconds) { // this(name); // mDate.setTime(milliseconds); // } // // @VisibleForTesting // public FieldDate(String name, String dateString) { // this(name); // if (!setFromString(dateString)) { // throw new IllegalArgumentException("Invalid date: " + dateString); // } // } // // public static FieldDate fromJson(JSONObject json) throws BlockLoadingException { // String name = json.optString("name"); // if (TextUtils.isEmpty(name)) { // throw new BlockLoadingException("field_date \"name\" attribute must not be empty."); // } // FieldDate field = new FieldDate(name); // String dateStr = json.optString("date"); // if (!TextUtils.isEmpty(dateStr) && !field.setFromString(dateStr)) { // throw new BlockLoadingException("Unable to parse date: " + dateStr); // } // return field; // } // // @Override // public FieldDate clone() { // return new FieldDate(getName(), mDate.getTime()); // } // // @Override // public boolean setFromString(String text) { // Date date = null; // try { // date = DATE_FORMAT.parse(text); // setDate(date); // return true; // } catch (ParseException e) { // Log.e(TAG, "Unable to parse date " + text, e); // return false; // } // } // // /** // * @return The date in this field. // */ // public Date getDate() { // return mDate; // } // // /** // * Sets this field to the specified {@link Date}. // */ // public void setDate(Date date) { // if (date == null) { // throw new IllegalArgumentException("Date may not be null."); // } // setTime(date.getTime()); // } // // /** // * @return The string format for the date in this field. // */ // public String getLocalizedDateString() { // return DATE_FORMAT.format(mDate); // } // // /** // * Sets this field to a specific time. // * // * @param millis The time in millis since UNIX Epoch. // */ // public void setTime(long millis) { // long oldTime = mDate.getTime(); // if (millis != oldTime) { // String oldValue = getSerializedValue(); // mDate.setTime(millis); // String newValue = getSerializedValue(); // fireValueChanged(oldValue, newValue); // } // } // // @Override // public String getSerializedValue() { // return DATE_FORMAT.format(mDate); // } // }
import android.content.Context; import android.support.v7.widget.AppCompatTextView; import android.text.Editable; import android.text.TextWatcher; import android.util.AttributeSet; import com.google.blockly.model.Field; import com.google.blockly.model.FieldDate; import java.text.DateFormat;
/* * Copyright 2016 Google Inc. All Rights Reserved. * 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.google.blockly.android.ui.fieldview; /** * Renders a date and a date picker as part of a Block. */ public class BasicFieldDateView extends AppCompatTextView implements FieldView { private static final DateFormat LOCALIZED_FORMAT = DateFormat.getDateInstance(DateFormat.SHORT); protected Field.Observer mFieldObserver = new Field.Observer() { @Override public void onValueChanged(Field field, String oldValue, String newValue) { String dateStr = LOCALIZED_FORMAT.format(mDateField.getDate()); if (!dateStr.contentEquals(getText())) { setText(dateStr); } } };
// Path: blocklylib-core/src/main/java/com/google/blockly/model/FieldDate.java // public final class FieldDate extends Field { // private static final String TAG = "FieldDate"; // // // Date format used for serialization. // private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd", Locale.US); // // private final Date mDate = new Date(); // // public FieldDate(String name) { // super(name, TYPE_DATE); // } // // public FieldDate(String name, long milliseconds) { // this(name); // mDate.setTime(milliseconds); // } // // @VisibleForTesting // public FieldDate(String name, String dateString) { // this(name); // if (!setFromString(dateString)) { // throw new IllegalArgumentException("Invalid date: " + dateString); // } // } // // public static FieldDate fromJson(JSONObject json) throws BlockLoadingException { // String name = json.optString("name"); // if (TextUtils.isEmpty(name)) { // throw new BlockLoadingException("field_date \"name\" attribute must not be empty."); // } // FieldDate field = new FieldDate(name); // String dateStr = json.optString("date"); // if (!TextUtils.isEmpty(dateStr) && !field.setFromString(dateStr)) { // throw new BlockLoadingException("Unable to parse date: " + dateStr); // } // return field; // } // // @Override // public FieldDate clone() { // return new FieldDate(getName(), mDate.getTime()); // } // // @Override // public boolean setFromString(String text) { // Date date = null; // try { // date = DATE_FORMAT.parse(text); // setDate(date); // return true; // } catch (ParseException e) { // Log.e(TAG, "Unable to parse date " + text, e); // return false; // } // } // // /** // * @return The date in this field. // */ // public Date getDate() { // return mDate; // } // // /** // * Sets this field to the specified {@link Date}. // */ // public void setDate(Date date) { // if (date == null) { // throw new IllegalArgumentException("Date may not be null."); // } // setTime(date.getTime()); // } // // /** // * @return The string format for the date in this field. // */ // public String getLocalizedDateString() { // return DATE_FORMAT.format(mDate); // } // // /** // * Sets this field to a specific time. // * // * @param millis The time in millis since UNIX Epoch. // */ // public void setTime(long millis) { // long oldTime = mDate.getTime(); // if (millis != oldTime) { // String oldValue = getSerializedValue(); // mDate.setTime(millis); // String newValue = getSerializedValue(); // fireValueChanged(oldValue, newValue); // } // } // // @Override // public String getSerializedValue() { // return DATE_FORMAT.format(mDate); // } // } // Path: blocklylib-core/src/main/java/com/google/blockly/android/ui/fieldview/BasicFieldDateView.java import android.content.Context; import android.support.v7.widget.AppCompatTextView; import android.text.Editable; import android.text.TextWatcher; import android.util.AttributeSet; import com.google.blockly.model.Field; import com.google.blockly.model.FieldDate; import java.text.DateFormat; /* * Copyright 2016 Google Inc. All Rights Reserved. * 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.google.blockly.android.ui.fieldview; /** * Renders a date and a date picker as part of a Block. */ public class BasicFieldDateView extends AppCompatTextView implements FieldView { private static final DateFormat LOCALIZED_FORMAT = DateFormat.getDateInstance(DateFormat.SHORT); protected Field.Observer mFieldObserver = new Field.Observer() { @Override public void onValueChanged(Field field, String oldValue, String newValue) { String dateStr = LOCALIZED_FORMAT.format(mDateField.getDate()); if (!dateStr.contentEquals(getText())) { setText(dateStr); } } };
protected FieldDate mDateField;
google/blockly-android
blocklylib-core/src/main/java/com/google/blockly/model/FieldVariable.java
// Path: blocklylib-core/src/main/java/com/google/blockly/utils/LangUtils.java // public class LangUtils { // private LangUtils() { // } // // /** // * Current Language // */ // private static String lang = "en"; // // /** // * Get Language // * @return Language // */ // public static String getLang() { // return lang; // } // // /** // * Set Language // * @param newLang New Language // */ // public static void setLang(String newLang) { // lang = newLang; // } // // /** // * A Map Containing Translations // */ // private static Map<String, String> langMap = new HashMap<>(); // // /** // * Replace Translation String with localized text using Blockly Web's translation files. // * @param value Input Value // * @return Translated String // */ // public static String interpolate(String value) { // for (Map.Entry<String, String> entry : langMap.entrySet()) { // while (value.contains(entry.getKey())) { // value = value.replace(entry.getKey(), entry.getValue()); // } // } // return value; // } // // /** // * Generate Map of translations. // * @param context Context // */ // public static void generateLang(Context context) { // generateLang(context, getLang()); // } // // /** // * Generate Map of translations. // * @param context Context // */ // private static void generateLang(Context context, String lang) { // if (!lang.equals("en")) { // generateLang(context, "en"); // } // // // Attempt to override language string table. Missing values will default to English loaded above. // StringBuilder out = new StringBuilder(); // BufferedReader reader = null; // try { // reader = new BufferedReader( // new InputStreamReader(context.getAssets().open("msg/js/" + lang + ".js"))); // // String line; // while ((line = reader.readLine()) != null) { // out.append(line); // out.append('\n'); // } // } catch (IOException e) { // e.printStackTrace(); // } finally { // if (reader != null) { // try { // reader.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // // String[] lines = out.toString().split("\n"); // for (int i = 0; i < lines.length; i++) { // lines[i] = lines[i].trim(); // if (lines[i].startsWith("Blockly.Msg[\"")) { // boolean alias = false; // // lines[i] = lines[i].substring("Blockly.Msg[\"".length()); // String name = lines[i].substring(0, lines[i].indexOf('"')); // if (lines[i].contains("\"] = \"")) { // lines[i] = lines[i].substring(lines[i].indexOf("\"] = \"") + "\"] = \"".length() - 1); // } else { // lines[i] = lines[i].substring(lines[i].indexOf("\"] = Blockly.Msg[\"") + "\"] = Blockly.Msg[\"".length() - 1); // alias = true; // } // String value = lines[i].substring(1, lines[i].lastIndexOf('"')); // if (alias) { // if (langMap.get("%{BKY_" + value + "}") == null) { // throw new RuntimeException(value + " is not defined."); // } else { // value = langMap.get("%{BKY_" + value + "}"); // } // } // if (value != null) { // langMap.put("%{BKY_" + name + "}", value); // } // } // } // } // }
import android.text.TextUtils; import com.google.blockly.utils.BlockLoadingException; import com.google.blockly.utils.LangUtils; import org.json.JSONObject;
/* * Copyright 2016 Google Inc. All Rights Reserved. * 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.google.blockly.model; /** * Adds a variable to an Input. */ public final class FieldVariable extends Field { private String mVariable; public FieldVariable(String name, String variable) { super(name, TYPE_VARIABLE); mVariable = variable; } public static FieldVariable fromJson(JSONObject json) throws BlockLoadingException { String name = json.optString("name"); if (TextUtils.isEmpty(name)) { throw new BlockLoadingException("field_variable \"name\" attribute must not be empty."); }
// Path: blocklylib-core/src/main/java/com/google/blockly/utils/LangUtils.java // public class LangUtils { // private LangUtils() { // } // // /** // * Current Language // */ // private static String lang = "en"; // // /** // * Get Language // * @return Language // */ // public static String getLang() { // return lang; // } // // /** // * Set Language // * @param newLang New Language // */ // public static void setLang(String newLang) { // lang = newLang; // } // // /** // * A Map Containing Translations // */ // private static Map<String, String> langMap = new HashMap<>(); // // /** // * Replace Translation String with localized text using Blockly Web's translation files. // * @param value Input Value // * @return Translated String // */ // public static String interpolate(String value) { // for (Map.Entry<String, String> entry : langMap.entrySet()) { // while (value.contains(entry.getKey())) { // value = value.replace(entry.getKey(), entry.getValue()); // } // } // return value; // } // // /** // * Generate Map of translations. // * @param context Context // */ // public static void generateLang(Context context) { // generateLang(context, getLang()); // } // // /** // * Generate Map of translations. // * @param context Context // */ // private static void generateLang(Context context, String lang) { // if (!lang.equals("en")) { // generateLang(context, "en"); // } // // // Attempt to override language string table. Missing values will default to English loaded above. // StringBuilder out = new StringBuilder(); // BufferedReader reader = null; // try { // reader = new BufferedReader( // new InputStreamReader(context.getAssets().open("msg/js/" + lang + ".js"))); // // String line; // while ((line = reader.readLine()) != null) { // out.append(line); // out.append('\n'); // } // } catch (IOException e) { // e.printStackTrace(); // } finally { // if (reader != null) { // try { // reader.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // // String[] lines = out.toString().split("\n"); // for (int i = 0; i < lines.length; i++) { // lines[i] = lines[i].trim(); // if (lines[i].startsWith("Blockly.Msg[\"")) { // boolean alias = false; // // lines[i] = lines[i].substring("Blockly.Msg[\"".length()); // String name = lines[i].substring(0, lines[i].indexOf('"')); // if (lines[i].contains("\"] = \"")) { // lines[i] = lines[i].substring(lines[i].indexOf("\"] = \"") + "\"] = \"".length() - 1); // } else { // lines[i] = lines[i].substring(lines[i].indexOf("\"] = Blockly.Msg[\"") + "\"] = Blockly.Msg[\"".length() - 1); // alias = true; // } // String value = lines[i].substring(1, lines[i].lastIndexOf('"')); // if (alias) { // if (langMap.get("%{BKY_" + value + "}") == null) { // throw new RuntimeException(value + " is not defined."); // } else { // value = langMap.get("%{BKY_" + value + "}"); // } // } // if (value != null) { // langMap.put("%{BKY_" + name + "}", value); // } // } // } // } // } // Path: blocklylib-core/src/main/java/com/google/blockly/model/FieldVariable.java import android.text.TextUtils; import com.google.blockly.utils.BlockLoadingException; import com.google.blockly.utils.LangUtils; import org.json.JSONObject; /* * Copyright 2016 Google Inc. All Rights Reserved. * 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.google.blockly.model; /** * Adds a variable to an Input. */ public final class FieldVariable extends Field { private String mVariable; public FieldVariable(String name, String variable) { super(name, TYPE_VARIABLE); mVariable = variable; } public static FieldVariable fromJson(JSONObject json) throws BlockLoadingException { String name = json.optString("name"); if (TextUtils.isEmpty(name)) { throw new BlockLoadingException("field_variable \"name\" attribute must not be empty."); }
return new FieldVariable(name, LangUtils.interpolate(json.optString("variable", "item")));
google/blockly-android
blocklylib-core/src/main/java/com/google/blockly/model/FieldDropdown.java
// Path: blocklylib-core/src/main/java/com/google/blockly/utils/LangUtils.java // public class LangUtils { // private LangUtils() { // } // // /** // * Current Language // */ // private static String lang = "en"; // // /** // * Get Language // * @return Language // */ // public static String getLang() { // return lang; // } // // /** // * Set Language // * @param newLang New Language // */ // public static void setLang(String newLang) { // lang = newLang; // } // // /** // * A Map Containing Translations // */ // private static Map<String, String> langMap = new HashMap<>(); // // /** // * Replace Translation String with localized text using Blockly Web's translation files. // * @param value Input Value // * @return Translated String // */ // public static String interpolate(String value) { // for (Map.Entry<String, String> entry : langMap.entrySet()) { // while (value.contains(entry.getKey())) { // value = value.replace(entry.getKey(), entry.getValue()); // } // } // return value; // } // // /** // * Generate Map of translations. // * @param context Context // */ // public static void generateLang(Context context) { // generateLang(context, getLang()); // } // // /** // * Generate Map of translations. // * @param context Context // */ // private static void generateLang(Context context, String lang) { // if (!lang.equals("en")) { // generateLang(context, "en"); // } // // // Attempt to override language string table. Missing values will default to English loaded above. // StringBuilder out = new StringBuilder(); // BufferedReader reader = null; // try { // reader = new BufferedReader( // new InputStreamReader(context.getAssets().open("msg/js/" + lang + ".js"))); // // String line; // while ((line = reader.readLine()) != null) { // out.append(line); // out.append('\n'); // } // } catch (IOException e) { // e.printStackTrace(); // } finally { // if (reader != null) { // try { // reader.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // // String[] lines = out.toString().split("\n"); // for (int i = 0; i < lines.length; i++) { // lines[i] = lines[i].trim(); // if (lines[i].startsWith("Blockly.Msg[\"")) { // boolean alias = false; // // lines[i] = lines[i].substring("Blockly.Msg[\"".length()); // String name = lines[i].substring(0, lines[i].indexOf('"')); // if (lines[i].contains("\"] = \"")) { // lines[i] = lines[i].substring(lines[i].indexOf("\"] = \"") + "\"] = \"".length() - 1); // } else { // lines[i] = lines[i].substring(lines[i].indexOf("\"] = Blockly.Msg[\"") + "\"] = Blockly.Msg[\"".length() - 1); // alias = true; // } // String value = lines[i].substring(1, lines[i].lastIndexOf('"')); // if (alias) { // if (langMap.get("%{BKY_" + value + "}") == null) { // throw new RuntimeException(value + " is not defined."); // } else { // value = langMap.get("%{BKY_" + value + "}"); // } // } // if (value != null) { // langMap.put("%{BKY_" + name + "}", value); // } // } // } // } // }
import android.database.Observable; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.text.TextUtils; import com.google.blockly.utils.BlockLoadingException; import com.google.blockly.utils.LangUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.Collections; import java.util.List;
/** * Loads a FieldDropdown from JSON. This is usually used for the {@link BlockFactory}'s * prototype instances. * * @param json The JSON representing the object. * @return A new FieldDropdown instance. * @throws BlockLoadingException */ public static FieldDropdown fromJson(JSONObject json) throws BlockLoadingException { String name = json.optString("name"); if (TextUtils.isEmpty(name)) { throw new BlockLoadingException("field_dropdown \"name\" attribute must not be empty."); } JSONArray jsonOptions = json.optJSONArray("options"); ArrayList<Option> optionList = null; if (jsonOptions != null) { int count = jsonOptions == null ? 0 :jsonOptions.length(); optionList = new ArrayList<>(count); for (int i = 0; i < count; i++) { JSONArray option = null; try { option = jsonOptions.getJSONArray(i); } catch (JSONException e) { throw new BlockLoadingException("Error reading dropdown options.", e); } if (option != null && option.length() == 2) { try {
// Path: blocklylib-core/src/main/java/com/google/blockly/utils/LangUtils.java // public class LangUtils { // private LangUtils() { // } // // /** // * Current Language // */ // private static String lang = "en"; // // /** // * Get Language // * @return Language // */ // public static String getLang() { // return lang; // } // // /** // * Set Language // * @param newLang New Language // */ // public static void setLang(String newLang) { // lang = newLang; // } // // /** // * A Map Containing Translations // */ // private static Map<String, String> langMap = new HashMap<>(); // // /** // * Replace Translation String with localized text using Blockly Web's translation files. // * @param value Input Value // * @return Translated String // */ // public static String interpolate(String value) { // for (Map.Entry<String, String> entry : langMap.entrySet()) { // while (value.contains(entry.getKey())) { // value = value.replace(entry.getKey(), entry.getValue()); // } // } // return value; // } // // /** // * Generate Map of translations. // * @param context Context // */ // public static void generateLang(Context context) { // generateLang(context, getLang()); // } // // /** // * Generate Map of translations. // * @param context Context // */ // private static void generateLang(Context context, String lang) { // if (!lang.equals("en")) { // generateLang(context, "en"); // } // // // Attempt to override language string table. Missing values will default to English loaded above. // StringBuilder out = new StringBuilder(); // BufferedReader reader = null; // try { // reader = new BufferedReader( // new InputStreamReader(context.getAssets().open("msg/js/" + lang + ".js"))); // // String line; // while ((line = reader.readLine()) != null) { // out.append(line); // out.append('\n'); // } // } catch (IOException e) { // e.printStackTrace(); // } finally { // if (reader != null) { // try { // reader.close(); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // // String[] lines = out.toString().split("\n"); // for (int i = 0; i < lines.length; i++) { // lines[i] = lines[i].trim(); // if (lines[i].startsWith("Blockly.Msg[\"")) { // boolean alias = false; // // lines[i] = lines[i].substring("Blockly.Msg[\"".length()); // String name = lines[i].substring(0, lines[i].indexOf('"')); // if (lines[i].contains("\"] = \"")) { // lines[i] = lines[i].substring(lines[i].indexOf("\"] = \"") + "\"] = \"".length() - 1); // } else { // lines[i] = lines[i].substring(lines[i].indexOf("\"] = Blockly.Msg[\"") + "\"] = Blockly.Msg[\"".length() - 1); // alias = true; // } // String value = lines[i].substring(1, lines[i].lastIndexOf('"')); // if (alias) { // if (langMap.get("%{BKY_" + value + "}") == null) { // throw new RuntimeException(value + " is not defined."); // } else { // value = langMap.get("%{BKY_" + value + "}"); // } // } // if (value != null) { // langMap.put("%{BKY_" + name + "}", value); // } // } // } // } // } // Path: blocklylib-core/src/main/java/com/google/blockly/model/FieldDropdown.java import android.database.Observable; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.text.TextUtils; import com.google.blockly.utils.BlockLoadingException; import com.google.blockly.utils.LangUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Loads a FieldDropdown from JSON. This is usually used for the {@link BlockFactory}'s * prototype instances. * * @param json The JSON representing the object. * @return A new FieldDropdown instance. * @throws BlockLoadingException */ public static FieldDropdown fromJson(JSONObject json) throws BlockLoadingException { String name = json.optString("name"); if (TextUtils.isEmpty(name)) { throw new BlockLoadingException("field_dropdown \"name\" attribute must not be empty."); } JSONArray jsonOptions = json.optJSONArray("options"); ArrayList<Option> optionList = null; if (jsonOptions != null) { int count = jsonOptions == null ? 0 :jsonOptions.length(); optionList = new ArrayList<>(count); for (int i = 0; i < count; i++) { JSONArray option = null; try { option = jsonOptions.getJSONArray(i); } catch (JSONException e) { throw new BlockLoadingException("Error reading dropdown options.", e); } if (option != null && option.length() == 2) { try {
String displayName = LangUtils.interpolate(option.getString(0));
Widen/im4java
src/org/im4java/core/Info.java
// Path: src/org/im4java/process/ArrayListOutputConsumer.java // public class ArrayListOutputConsumer implements OutputConsumer { // // ////////////////////////////////////////////////////////////////////////////// // // /** // The output list. // */ // // private ArrayList<String> iOutputLines = new ArrayList<String>(); // // ////////////////////////////////////////////////////////////////////////////// // // /** // The charset-name for the internal InputStreamReader. // */ // // private String iCharset = null; // // ////////////////////////////////////////////////////////////////////////////// // // /** // Default Constructor. // */ // // public ArrayListOutputConsumer() { // } // // ////////////////////////////////////////////////////////////////////////////// // // /** // Constructor taking a charset-name as argument. // // @param pCharset charset-name for internal InputStreamReader // */ // // public ArrayListOutputConsumer(String pCharset) { // iCharset = pCharset; // } // // ////////////////////////////////////////////////////////////////////////////// // // /** // Return array with output-lines. // */ // // public ArrayList<String> getOutput() { // return iOutputLines; // } // // ////////////////////////////////////////////////////////////////////////////// // // /** // Clear the output. // */ // // public void clear() { // iOutputLines.clear(); // } // // ////////////////////////////////////////////////////////////////////////////// // // /** // * Read command output and save in an internal field. // @see org.im4java.process.OutputConsumer#consumeOutput(java.io.InputStream) // */ // // // public void consumeOutput(InputStream pInputStream) throws IOException { // InputStreamReader isr = null; // if (iCharset == null) { // isr = new InputStreamReader(pInputStream); // } else { // isr = new InputStreamReader(pInputStream,iCharset); // } // BufferedReader reader = new BufferedReader(isr); // String line; // while ((line=reader.readLine()) != null) { // iOutputLines.add(line); // } // reader.close(); // } // }
import java.io.*; import org.im4java.process.ArrayListOutputConsumer; import java.util.*;
/************************************************************************** /* This class implements an image-information object. /* /* Copyright (c) 2009 by Bernhard Bablok (mail@bablokb.de) /* /* This program is free software; you can redistribute it and/or modify /* it under the terms of the GNU Library General Public License as published /* by the Free Software Foundation; either version 2 of the License or /* (at your option) any later version. /* /* This program is distributed in the hope that it will be useful, but /* WITHOUT ANY WARRANTY; without even the implied warranty of /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /* GNU Library General Public License for more details. /* /* You should have received a copy of the GNU Library General Public License /* along with this program; see the file COPYING.LIB. If not, write to /* the Free Software Foundation Inc., 59 Temple Place - Suite 330, /* Boston, MA 02111-1307 USA /**************************************************************************/ package org.im4java.core; /** This class implements an image-information object. The one-argument constructor expects a filename and parses the output of the "identify -verbose" command to create a hashtable of properties. This is the so called complete information. The two-argument constructor has a boolean flag as second argument. If you pass true, the Info-object only creates a set of so called basic information. This is more efficient since only a subset of the attributes of the image are requested and parsed. <p> Since the output of "identify -verbose" is meant as an human-readable interface parsing it is inherently flawed. This implementation interprets every line with a colon as a key-value-pair. This is not necessarely correct, e.g. the comment-field could be multi-line with colons within the comment. </p> <p> An alternative to the Info-class is to use the exiftool-command and the wrapper for it provided by im4java. </p> @version $Revision: 1.14 $ @author $Author: bablokb $ @since 0.95 */ public class Info { ////////////////////////////////////////////////////////////////////////////// /** Internal hashtable with image-attributes. For images with multiple scenes, this hashtable holds the attributes of the last scene. */ private Hashtable<String,String> iAttributes = null; ////////////////////////////////////////////////////////////////////////////// /** List of hashtables with image-attributes. Ther is one element for every scene in the image. @since 1.3.0 */ private LinkedList<Hashtable<String,String>> iAttribList = new LinkedList<Hashtable<String,String>>(); ////////////////////////////////////////////////////////////////////////////// /** Current value of indentation level */ private int iOldIndent=0; ////////////////////////////////////////////////////////////////////////////// /** Current value of attribute-prefix */ private String iPrefix=""; ////////////////////////////////////////////////////////////////////////////// /** This contstructor will automatically parse the full output of identify -verbose. @param pImage Source image @since 0.95 */ public Info(String pImage) throws InfoException { getCompleteInfo(pImage); } ////////////////////////////////////////////////////////////////////////////// /** This constructor creates an Info-object with basic or complete image-information (depending on the second argument). @param pImage Source image @param basic Set to true for basic information, to false for complete info @since 1.2.0 */ public Info(String pImage, boolean basic) throws InfoException { if (!basic) { getCompleteInfo(pImage); } else { getBaseInfo(pImage); } } ////////////////////////////////////////////////////////////////////////////// /** Query complete image-information. @param pImage Source image @since 1.2.0 */ private void getCompleteInfo(String pImage) throws InfoException { IMOperation op = new IMOperation(); op.verbose(); op.addImage(pImage); try { IdentifyCmd identify = new IdentifyCmd();
// Path: src/org/im4java/process/ArrayListOutputConsumer.java // public class ArrayListOutputConsumer implements OutputConsumer { // // ////////////////////////////////////////////////////////////////////////////// // // /** // The output list. // */ // // private ArrayList<String> iOutputLines = new ArrayList<String>(); // // ////////////////////////////////////////////////////////////////////////////// // // /** // The charset-name for the internal InputStreamReader. // */ // // private String iCharset = null; // // ////////////////////////////////////////////////////////////////////////////// // // /** // Default Constructor. // */ // // public ArrayListOutputConsumer() { // } // // ////////////////////////////////////////////////////////////////////////////// // // /** // Constructor taking a charset-name as argument. // // @param pCharset charset-name for internal InputStreamReader // */ // // public ArrayListOutputConsumer(String pCharset) { // iCharset = pCharset; // } // // ////////////////////////////////////////////////////////////////////////////// // // /** // Return array with output-lines. // */ // // public ArrayList<String> getOutput() { // return iOutputLines; // } // // ////////////////////////////////////////////////////////////////////////////// // // /** // Clear the output. // */ // // public void clear() { // iOutputLines.clear(); // } // // ////////////////////////////////////////////////////////////////////////////// // // /** // * Read command output and save in an internal field. // @see org.im4java.process.OutputConsumer#consumeOutput(java.io.InputStream) // */ // // // public void consumeOutput(InputStream pInputStream) throws IOException { // InputStreamReader isr = null; // if (iCharset == null) { // isr = new InputStreamReader(pInputStream); // } else { // isr = new InputStreamReader(pInputStream,iCharset); // } // BufferedReader reader = new BufferedReader(isr); // String line; // while ((line=reader.readLine()) != null) { // iOutputLines.add(line); // } // reader.close(); // } // } // Path: src/org/im4java/core/Info.java import java.io.*; import org.im4java.process.ArrayListOutputConsumer; import java.util.*; /************************************************************************** /* This class implements an image-information object. /* /* Copyright (c) 2009 by Bernhard Bablok (mail@bablokb.de) /* /* This program is free software; you can redistribute it and/or modify /* it under the terms of the GNU Library General Public License as published /* by the Free Software Foundation; either version 2 of the License or /* (at your option) any later version. /* /* This program is distributed in the hope that it will be useful, but /* WITHOUT ANY WARRANTY; without even the implied warranty of /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /* GNU Library General Public License for more details. /* /* You should have received a copy of the GNU Library General Public License /* along with this program; see the file COPYING.LIB. If not, write to /* the Free Software Foundation Inc., 59 Temple Place - Suite 330, /* Boston, MA 02111-1307 USA /**************************************************************************/ package org.im4java.core; /** This class implements an image-information object. The one-argument constructor expects a filename and parses the output of the "identify -verbose" command to create a hashtable of properties. This is the so called complete information. The two-argument constructor has a boolean flag as second argument. If you pass true, the Info-object only creates a set of so called basic information. This is more efficient since only a subset of the attributes of the image are requested and parsed. <p> Since the output of "identify -verbose" is meant as an human-readable interface parsing it is inherently flawed. This implementation interprets every line with a colon as a key-value-pair. This is not necessarely correct, e.g. the comment-field could be multi-line with colons within the comment. </p> <p> An alternative to the Info-class is to use the exiftool-command and the wrapper for it provided by im4java. </p> @version $Revision: 1.14 $ @author $Author: bablokb $ @since 0.95 */ public class Info { ////////////////////////////////////////////////////////////////////////////// /** Internal hashtable with image-attributes. For images with multiple scenes, this hashtable holds the attributes of the last scene. */ private Hashtable<String,String> iAttributes = null; ////////////////////////////////////////////////////////////////////////////// /** List of hashtables with image-attributes. Ther is one element for every scene in the image. @since 1.3.0 */ private LinkedList<Hashtable<String,String>> iAttribList = new LinkedList<Hashtable<String,String>>(); ////////////////////////////////////////////////////////////////////////////// /** Current value of indentation level */ private int iOldIndent=0; ////////////////////////////////////////////////////////////////////////////// /** Current value of attribute-prefix */ private String iPrefix=""; ////////////////////////////////////////////////////////////////////////////// /** This contstructor will automatically parse the full output of identify -verbose. @param pImage Source image @since 0.95 */ public Info(String pImage) throws InfoException { getCompleteInfo(pImage); } ////////////////////////////////////////////////////////////////////////////// /** This constructor creates an Info-object with basic or complete image-information (depending on the second argument). @param pImage Source image @param basic Set to true for basic information, to false for complete info @since 1.2.0 */ public Info(String pImage, boolean basic) throws InfoException { if (!basic) { getCompleteInfo(pImage); } else { getBaseInfo(pImage); } } ////////////////////////////////////////////////////////////////////////////// /** Query complete image-information. @param pImage Source image @since 1.2.0 */ private void getCompleteInfo(String pImage) throws InfoException { IMOperation op = new IMOperation(); op.verbose(); op.addImage(pImage); try { IdentifyCmd identify = new IdentifyCmd();
ArrayListOutputConsumer output = new ArrayListOutputConsumer();
karlnicholas/votesmart
src/main/java/org/votesmart/classes/LeadershipClass.java
// Path: src/main/java/org/votesmart/data/Leaders.java // @XmlRootElement(name="leaders") // public class Leaders extends GeneralInfoBase { // // public ArrayList<Leader> leader; // // @XmlType(name="leader", namespace="leaders") // public static class Leader { // public String candidateId; // public String firstName; // public String middleName; // public String lastName; // public String suffix; // public String position; // public String officeId; // public String title; // } // } // // Path: src/main/java/org/votesmart/data/Leadership.java // @XmlRootElement(name="leadership") // public class Leadership extends GeneralInfoBase { // // public ArrayList<Position> position; // // @XmlType(name="position", namespace="leadership") // public static class Position { // public String leadershipId; // public String name; // public String officeId; // public String officeName; // } // }
import org.votesmart.api.*; import org.votesmart.data.Leaders; import org.votesmart.data.Leadership;
package org.votesmart.classes; /** * <pre> * Leadership Class * * * - Required * * - Multiple rows * * Leadership.getPositions() * Gets leadership positions by state and office * Input: stateId(default: 'NA'), officeId(default: All) * Output: {@link Leadership} * * Leadership.getOfficials() * Gets officials that hold the leadership role in certain states. * Input: leadershipId*, stateId(default: 'NA') * Output: {@link Leaders} * * ============== EXAMPLE USAGE ============= * * // Leadership class * LeadershipClass leadershipClass = new LeadershipClass(); * * Leadership leadership = leadershipClass.getPositions(); * * // all positions * leadership = leadershipClass.getPositions(state.stateId); * * // all positions for office in state * leadership = leadershipClass.getPositions(state.stateId, office.officeId); * Leadership.Position position = leadership.position.get(0); * </pre> * */ public class LeadershipClass extends ClassesBase { /** * Constructor for testing purposes. * * @param api */ public LeadershipClass(VoteSmartAPI api) { super(api); } /** * Default Constructor */ public LeadershipClass() throws VoteSmartException { super(); } /** * Gets leadership positions by state and office. * * @return {@link Leadership}: */
// Path: src/main/java/org/votesmart/data/Leaders.java // @XmlRootElement(name="leaders") // public class Leaders extends GeneralInfoBase { // // public ArrayList<Leader> leader; // // @XmlType(name="leader", namespace="leaders") // public static class Leader { // public String candidateId; // public String firstName; // public String middleName; // public String lastName; // public String suffix; // public String position; // public String officeId; // public String title; // } // } // // Path: src/main/java/org/votesmart/data/Leadership.java // @XmlRootElement(name="leadership") // public class Leadership extends GeneralInfoBase { // // public ArrayList<Position> position; // // @XmlType(name="position", namespace="leadership") // public static class Position { // public String leadershipId; // public String name; // public String officeId; // public String officeName; // } // } // Path: src/main/java/org/votesmart/classes/LeadershipClass.java import org.votesmart.api.*; import org.votesmart.data.Leaders; import org.votesmart.data.Leadership; package org.votesmart.classes; /** * <pre> * Leadership Class * * * - Required * * - Multiple rows * * Leadership.getPositions() * Gets leadership positions by state and office * Input: stateId(default: 'NA'), officeId(default: All) * Output: {@link Leadership} * * Leadership.getOfficials() * Gets officials that hold the leadership role in certain states. * Input: leadershipId*, stateId(default: 'NA') * Output: {@link Leaders} * * ============== EXAMPLE USAGE ============= * * // Leadership class * LeadershipClass leadershipClass = new LeadershipClass(); * * Leadership leadership = leadershipClass.getPositions(); * * // all positions * leadership = leadershipClass.getPositions(state.stateId); * * // all positions for office in state * leadership = leadershipClass.getPositions(state.stateId, office.officeId); * Leadership.Position position = leadership.position.get(0); * </pre> * */ public class LeadershipClass extends ClassesBase { /** * Constructor for testing purposes. * * @param api */ public LeadershipClass(VoteSmartAPI api) { super(api); } /** * Default Constructor */ public LeadershipClass() throws VoteSmartException { super(); } /** * Gets leadership positions by state and office. * * @return {@link Leadership}: */
public Leadership getPositions() throws VoteSmartException, VoteSmartErrorException {
karlnicholas/votesmart
src/main/java/org/votesmart/classes/LeadershipClass.java
// Path: src/main/java/org/votesmart/data/Leaders.java // @XmlRootElement(name="leaders") // public class Leaders extends GeneralInfoBase { // // public ArrayList<Leader> leader; // // @XmlType(name="leader", namespace="leaders") // public static class Leader { // public String candidateId; // public String firstName; // public String middleName; // public String lastName; // public String suffix; // public String position; // public String officeId; // public String title; // } // } // // Path: src/main/java/org/votesmart/data/Leadership.java // @XmlRootElement(name="leadership") // public class Leadership extends GeneralInfoBase { // // public ArrayList<Position> position; // // @XmlType(name="position", namespace="leadership") // public static class Position { // public String leadershipId; // public String name; // public String officeId; // public String officeName; // } // }
import org.votesmart.api.*; import org.votesmart.data.Leaders; import org.votesmart.data.Leadership;
package org.votesmart.classes; /** * <pre> * Leadership Class * * * - Required * * - Multiple rows * * Leadership.getPositions() * Gets leadership positions by state and office * Input: stateId(default: 'NA'), officeId(default: All) * Output: {@link Leadership} * * Leadership.getOfficials() * Gets officials that hold the leadership role in certain states. * Input: leadershipId*, stateId(default: 'NA') * Output: {@link Leaders} * * ============== EXAMPLE USAGE ============= * * // Leadership class * LeadershipClass leadershipClass = new LeadershipClass(); * * Leadership leadership = leadershipClass.getPositions(); * * // all positions * leadership = leadershipClass.getPositions(state.stateId); * * // all positions for office in state * leadership = leadershipClass.getPositions(state.stateId, office.officeId); * Leadership.Position position = leadership.position.get(0); * </pre> * */ public class LeadershipClass extends ClassesBase { /** * Constructor for testing purposes. * * @param api */ public LeadershipClass(VoteSmartAPI api) { super(api); } /** * Default Constructor */ public LeadershipClass() throws VoteSmartException { super(); } /** * Gets leadership positions by state and office. * * @return {@link Leadership}: */ public Leadership getPositions() throws VoteSmartException, VoteSmartErrorException { return api.query("Leadership.getPositions", new ArgMap(), Leadership.class ); } /** * Gets leadership positions by state and office. * * @param stateId * @return {@link Leadership}: */ public Leadership getPositions(String stateId) throws VoteSmartException, VoteSmartErrorException { return api.query("Leadership.getPositions", new ArgMap("stateId", stateId), Leadership.class ); } /** * Gets leadership positions by state and office. * * @param stateId * @param officeId * @return {@link Leadership}: */ public Leadership getPositions(String stateId, String officeId) throws VoteSmartException, VoteSmartErrorException { return api.query("Leadership.getPositions", new ArgMap("stateId", stateId, "officeId", officeId), Leadership.class ); } /** * Gets officials that hold the leadership role in certain states. * * @param leadershipId * @return {@link Leaders}: */
// Path: src/main/java/org/votesmart/data/Leaders.java // @XmlRootElement(name="leaders") // public class Leaders extends GeneralInfoBase { // // public ArrayList<Leader> leader; // // @XmlType(name="leader", namespace="leaders") // public static class Leader { // public String candidateId; // public String firstName; // public String middleName; // public String lastName; // public String suffix; // public String position; // public String officeId; // public String title; // } // } // // Path: src/main/java/org/votesmart/data/Leadership.java // @XmlRootElement(name="leadership") // public class Leadership extends GeneralInfoBase { // // public ArrayList<Position> position; // // @XmlType(name="position", namespace="leadership") // public static class Position { // public String leadershipId; // public String name; // public String officeId; // public String officeName; // } // } // Path: src/main/java/org/votesmart/classes/LeadershipClass.java import org.votesmart.api.*; import org.votesmart.data.Leaders; import org.votesmart.data.Leadership; package org.votesmart.classes; /** * <pre> * Leadership Class * * * - Required * * - Multiple rows * * Leadership.getPositions() * Gets leadership positions by state and office * Input: stateId(default: 'NA'), officeId(default: All) * Output: {@link Leadership} * * Leadership.getOfficials() * Gets officials that hold the leadership role in certain states. * Input: leadershipId*, stateId(default: 'NA') * Output: {@link Leaders} * * ============== EXAMPLE USAGE ============= * * // Leadership class * LeadershipClass leadershipClass = new LeadershipClass(); * * Leadership leadership = leadershipClass.getPositions(); * * // all positions * leadership = leadershipClass.getPositions(state.stateId); * * // all positions for office in state * leadership = leadershipClass.getPositions(state.stateId, office.officeId); * Leadership.Position position = leadership.position.get(0); * </pre> * */ public class LeadershipClass extends ClassesBase { /** * Constructor for testing purposes. * * @param api */ public LeadershipClass(VoteSmartAPI api) { super(api); } /** * Default Constructor */ public LeadershipClass() throws VoteSmartException { super(); } /** * Gets leadership positions by state and office. * * @return {@link Leadership}: */ public Leadership getPositions() throws VoteSmartException, VoteSmartErrorException { return api.query("Leadership.getPositions", new ArgMap(), Leadership.class ); } /** * Gets leadership positions by state and office. * * @param stateId * @return {@link Leadership}: */ public Leadership getPositions(String stateId) throws VoteSmartException, VoteSmartErrorException { return api.query("Leadership.getPositions", new ArgMap("stateId", stateId), Leadership.class ); } /** * Gets leadership positions by state and office. * * @param stateId * @param officeId * @return {@link Leadership}: */ public Leadership getPositions(String stateId, String officeId) throws VoteSmartException, VoteSmartErrorException { return api.query("Leadership.getPositions", new ArgMap("stateId", stateId, "officeId", officeId), Leadership.class ); } /** * Gets officials that hold the leadership role in certain states. * * @param leadershipId * @return {@link Leaders}: */
public Leaders getOfficials(String leadershipId) throws VoteSmartException, VoteSmartErrorException {
karlnicholas/votesmart
src/main/java/org/votesmart/classes/OfficialsClass.java
// Path: src/main/java/org/votesmart/data/CandidateList.java // @XmlRootElement(name="candidateList") // public class CandidateList extends GeneralInfoBase { // public String zipMessage; // public List<Candidate> candidate; // // @XmlType(name="candidate", namespace="candidateList") // public static class Candidate extends CandidateMed { // public String candidateId; // public String prefferedName; // public String officeParties; // public String officeStatus; // public String officeDistrictId; // public String officeDistrictName; // public String officeTypeId; // public String officeId; // public String officeName; // public String officeStateId; // } // // }
import org.votesmart.api.*; import org.votesmart.data.CandidateList;
package org.votesmart.classes; /** * <pre> * Officials Class * * * - Required * * - Multiple rows * * Officials.getStatewide() * This method grabs a list of officials according to state representation * Input: stateId(default: 'NA') * Output: {@link CandidateList} * * Officials.getByOfficeState() * This method grabs a list of officials according to office and state representation. * Input: officeId*, stateId(default: 'NA') * Output: {@link CandidateList} * * Officials.getByOfficeTypeState() * This method grabs a list of officials according to office type and state representation. * Input: officeTypeId*, stateId(default: 'NA') * Output: {@link CandidateList} * * Officials.getByLastname() * This method grabs a list of officials according to a lastName match. * Input: lastName* * Output: {@link CandidateList} * * Officials.getByLevenshtein() * This method grabs a list of officials according to a fuzzy lastName match. * Input: lastName* * Output: {@link CandidateList} * * Officials.getByDistrict() * This method grabs a list of officials according to the district they are running for. * Input: districtId* * Output: {@link CandidateList} * * Officials.getByZip() * This method grabs a list of officials according to the zip code they represent. * Input: zip5*, zip4(default: NULL) * Output: {@link CandidateList} * * =============== EXAMPLE USAGE ==================== * * // Officials * OfficialsClass officialsClass = new OfficialsClass(); * * // Officials * CandidateList candidates = officialsClass.getStatewide(); * * // Officials for State * candidates = officialsClass.getStatewide(state.stateId); * CandidateList.Candidate candidate = candidates.candidate.get(0); * * // Officials for last officeType (Legislature), for state * candidates = officialsClass.getByOfficeTypeState(officeType.officeTypeId, state.stateId); * candidate = candidates.candidate.get(0); * </pre> * */ public class OfficialsClass extends ClassesBase { /** * Constructor for testing purposes * * @param api */ public OfficialsClass(VoteSmartAPI api) { super(api); } /** * Default constructor */ public OfficialsClass() throws VoteSmartException { super(); } /** * This method grabs a list of officials according to state representation. * * @return {@link CandidateList} */
// Path: src/main/java/org/votesmart/data/CandidateList.java // @XmlRootElement(name="candidateList") // public class CandidateList extends GeneralInfoBase { // public String zipMessage; // public List<Candidate> candidate; // // @XmlType(name="candidate", namespace="candidateList") // public static class Candidate extends CandidateMed { // public String candidateId; // public String prefferedName; // public String officeParties; // public String officeStatus; // public String officeDistrictId; // public String officeDistrictName; // public String officeTypeId; // public String officeId; // public String officeName; // public String officeStateId; // } // // } // Path: src/main/java/org/votesmart/classes/OfficialsClass.java import org.votesmart.api.*; import org.votesmart.data.CandidateList; package org.votesmart.classes; /** * <pre> * Officials Class * * * - Required * * - Multiple rows * * Officials.getStatewide() * This method grabs a list of officials according to state representation * Input: stateId(default: 'NA') * Output: {@link CandidateList} * * Officials.getByOfficeState() * This method grabs a list of officials according to office and state representation. * Input: officeId*, stateId(default: 'NA') * Output: {@link CandidateList} * * Officials.getByOfficeTypeState() * This method grabs a list of officials according to office type and state representation. * Input: officeTypeId*, stateId(default: 'NA') * Output: {@link CandidateList} * * Officials.getByLastname() * This method grabs a list of officials according to a lastName match. * Input: lastName* * Output: {@link CandidateList} * * Officials.getByLevenshtein() * This method grabs a list of officials according to a fuzzy lastName match. * Input: lastName* * Output: {@link CandidateList} * * Officials.getByDistrict() * This method grabs a list of officials according to the district they are running for. * Input: districtId* * Output: {@link CandidateList} * * Officials.getByZip() * This method grabs a list of officials according to the zip code they represent. * Input: zip5*, zip4(default: NULL) * Output: {@link CandidateList} * * =============== EXAMPLE USAGE ==================== * * // Officials * OfficialsClass officialsClass = new OfficialsClass(); * * // Officials * CandidateList candidates = officialsClass.getStatewide(); * * // Officials for State * candidates = officialsClass.getStatewide(state.stateId); * CandidateList.Candidate candidate = candidates.candidate.get(0); * * // Officials for last officeType (Legislature), for state * candidates = officialsClass.getByOfficeTypeState(officeType.officeTypeId, state.stateId); * candidate = candidates.candidate.get(0); * </pre> * */ public class OfficialsClass extends ClassesBase { /** * Constructor for testing purposes * * @param api */ public OfficialsClass(VoteSmartAPI api) { super(api); } /** * Default constructor */ public OfficialsClass() throws VoteSmartException { super(); } /** * This method grabs a list of officials according to state representation. * * @return {@link CandidateList} */
public CandidateList getStatewide() throws VoteSmartException, VoteSmartErrorException {
karlnicholas/votesmart
src/main/java/org/votesmart/classes/CandidatesClass.java
// Path: src/main/java/org/votesmart/data/CandidateList.java // @XmlRootElement(name="candidateList") // public class CandidateList extends GeneralInfoBase { // public String zipMessage; // public List<Candidate> candidate; // // @XmlType(name="candidate", namespace="candidateList") // public static class Candidate extends CandidateMed { // public String candidateId; // public String prefferedName; // public String officeParties; // public String officeStatus; // public String officeDistrictId; // public String officeDistrictName; // public String officeTypeId; // public String officeId; // public String officeName; // public String officeStateId; // } // // }
import org.votesmart.api.*; import org.votesmart.data.CandidateList;
package org.votesmart.classes; /** * <pre> * Candidates Class * * * - Required * * - Multiple rows * * Candidates.getByOfficeState() * This method grabs a list of candidates according to office and state representation. * Input: officeId*, stateId(default: 'NA'), electionYear(default: >= current year), stageId * Output: {@link CandidateList} * * Candidates.getByOfficeTypeState() * This method grabs a list of candidates according to office type and state representation. * Input: officeTypeId*, stateId(default: 'NA'), electionYear(default: >= current year), stageId * Output: {@link CandidateList} * * Candidates.getByLastname() * This method grabs a list of candidates according to a lastname match. * Input: lastName*, electionYear(default: >= current year), stageId * Output: {@link CandidateList} * * Candidates.getByLevenshtein() * This method grabs a list of candidates according to a fuzzy lastname match. * Input: lastName*, electionYear(default: >= current year), stageId * Output: {@link CandidateList} * * Candidates.getByElection() * This method grabs a list of candidates according to the election they are running in. * Input: electionId*, stageId * Output: {@link CandidateList} * * Candidates.getByDistrict() * This method grabs a list of candidates according to the district they represent. * Input: districtId*, electionYear(default: >= current year), stageId * Output: {@link CandidateList} * * Candidates.getByZip() * This method grabs a list of candidates according to the zip code they represent. * Input: zip5*, electionYear(default: >= current year), zip4(default: NULL), stageId * Output: {@link CandidateList} * * ========= EXAMPLE USAGE ============= * * CandidatesClass candidatesClass = new CandidatesClass(); * * // Candidates for last office, for state * CandidateList candidates = candidatesClass.getByOfficeState(office.officeId, state.stateId); * * // Candidates for last office, for state * candidates = candidatesClass.getByOfficeTypeState(officeType.officeTypeId, state.stateId); *</pre> */ public class CandidatesClass extends ClassesBase { /** * Constructor for testing purposes. * * @param api */ public CandidatesClass(VoteSmartAPI api) { super(api); } /** * Default Constructor */ public CandidatesClass() throws VoteSmartException { super(); } /** * This method grabs a list of candidates according to office and state representation. * * @param officeId * @return {@link CandidateList}: list of detailed candidate information. */
// Path: src/main/java/org/votesmart/data/CandidateList.java // @XmlRootElement(name="candidateList") // public class CandidateList extends GeneralInfoBase { // public String zipMessage; // public List<Candidate> candidate; // // @XmlType(name="candidate", namespace="candidateList") // public static class Candidate extends CandidateMed { // public String candidateId; // public String prefferedName; // public String officeParties; // public String officeStatus; // public String officeDistrictId; // public String officeDistrictName; // public String officeTypeId; // public String officeId; // public String officeName; // public String officeStateId; // } // // } // Path: src/main/java/org/votesmart/classes/CandidatesClass.java import org.votesmart.api.*; import org.votesmart.data.CandidateList; package org.votesmart.classes; /** * <pre> * Candidates Class * * * - Required * * - Multiple rows * * Candidates.getByOfficeState() * This method grabs a list of candidates according to office and state representation. * Input: officeId*, stateId(default: 'NA'), electionYear(default: >= current year), stageId * Output: {@link CandidateList} * * Candidates.getByOfficeTypeState() * This method grabs a list of candidates according to office type and state representation. * Input: officeTypeId*, stateId(default: 'NA'), electionYear(default: >= current year), stageId * Output: {@link CandidateList} * * Candidates.getByLastname() * This method grabs a list of candidates according to a lastname match. * Input: lastName*, electionYear(default: >= current year), stageId * Output: {@link CandidateList} * * Candidates.getByLevenshtein() * This method grabs a list of candidates according to a fuzzy lastname match. * Input: lastName*, electionYear(default: >= current year), stageId * Output: {@link CandidateList} * * Candidates.getByElection() * This method grabs a list of candidates according to the election they are running in. * Input: electionId*, stageId * Output: {@link CandidateList} * * Candidates.getByDistrict() * This method grabs a list of candidates according to the district they represent. * Input: districtId*, electionYear(default: >= current year), stageId * Output: {@link CandidateList} * * Candidates.getByZip() * This method grabs a list of candidates according to the zip code they represent. * Input: zip5*, electionYear(default: >= current year), zip4(default: NULL), stageId * Output: {@link CandidateList} * * ========= EXAMPLE USAGE ============= * * CandidatesClass candidatesClass = new CandidatesClass(); * * // Candidates for last office, for state * CandidateList candidates = candidatesClass.getByOfficeState(office.officeId, state.stateId); * * // Candidates for last office, for state * candidates = candidatesClass.getByOfficeTypeState(officeType.officeTypeId, state.stateId); *</pre> */ public class CandidatesClass extends ClassesBase { /** * Constructor for testing purposes. * * @param api */ public CandidatesClass(VoteSmartAPI api) { super(api); } /** * Default Constructor */ public CandidatesClass() throws VoteSmartException { super(); } /** * This method grabs a list of candidates according to office and state representation. * * @param officeId * @return {@link CandidateList}: list of detailed candidate information. */
public CandidateList getByOfficeState(String officeId) throws VoteSmartException, VoteSmartErrorException {
karlnicholas/votesmart
src/main/java/org/votesmart/classes/StateClass.java
// Path: src/main/java/org/votesmart/data/State.java // @XmlRootElement(name="state") // public class State extends GeneralInfoBase { // // public Details details; // // @XmlType(name="details", namespace="state") // public static class Details { // public String stateId; // public String stateType; // public String name; // public String nickName; // public String capital; // public String area; // public String population; // public String statehood; // public String motto; // public String flower; // public String tree; // public String bird; // public String highPoint; // public String lowPoint; // public String bicameral; // public String upperLegis; // public String lowerLegis; // public String ltGov; // public String senators; // public String reps; // public String termLimit; // public String termLength; // public URL billUrl; // public URL voteUrl; // public String voterReg; // public String primaryDate; // public String generalDate; // public String absenteeWho; // public String absenteeHow; // public String absenteeWhen; // public String largestCity; // public String rollUpper; // public String rollLower; // public String usCircuit; // } // } // // Path: src/main/java/org/votesmart/data/StateList.java // @XmlRootElement(name="stateList") // public class StateList extends GeneralInfoBase { // public List list; // // @XmlType(name="list", namespace="stateList") // public static class List { // public ArrayList<State> state; // // @XmlType(name="state", namespace="stateList") // public static class State { // public String stateId; // public String name; // } // } // }
import org.votesmart.api.*; import org.votesmart.data.State; import org.votesmart.data.StateList;
package org.votesmart.classes; /** * <pre> * State Class * * State.getStateIDs() * This method grabs a simple state ID and name list for mapping ID to state names. * Input: none * Output: {@link StateList} * * State.getState() * This method grabs a various data we keep on a state * Input: stateId* * Output: {@link State} * * ============== EXAMPLE USAGE ============= * * StateClass stateClass = new StateClass(); * * StateList allStates = stateClass.getStateIDs(); * StateList.List.State state = null; * for( StateList.List.State aState: allStates.list.state ) { * if (aState.name.equals("California")) { * state = aState; * break; * } * } * // Get State Details * State stateDetail = stateClass.getState(state.stateId); * </pre> * */ public class StateClass extends ClassesBase { /** * Constructor for testing purposes * * @param api */ public StateClass(VoteSmartAPI api) { super(api); } /** * Default Constructor */ public StateClass() throws VoteSmartException { super(); } /** * This method grabs a simple state ID and name list for mapping ID to state names. * * @return {@link StateList} */
// Path: src/main/java/org/votesmart/data/State.java // @XmlRootElement(name="state") // public class State extends GeneralInfoBase { // // public Details details; // // @XmlType(name="details", namespace="state") // public static class Details { // public String stateId; // public String stateType; // public String name; // public String nickName; // public String capital; // public String area; // public String population; // public String statehood; // public String motto; // public String flower; // public String tree; // public String bird; // public String highPoint; // public String lowPoint; // public String bicameral; // public String upperLegis; // public String lowerLegis; // public String ltGov; // public String senators; // public String reps; // public String termLimit; // public String termLength; // public URL billUrl; // public URL voteUrl; // public String voterReg; // public String primaryDate; // public String generalDate; // public String absenteeWho; // public String absenteeHow; // public String absenteeWhen; // public String largestCity; // public String rollUpper; // public String rollLower; // public String usCircuit; // } // } // // Path: src/main/java/org/votesmart/data/StateList.java // @XmlRootElement(name="stateList") // public class StateList extends GeneralInfoBase { // public List list; // // @XmlType(name="list", namespace="stateList") // public static class List { // public ArrayList<State> state; // // @XmlType(name="state", namespace="stateList") // public static class State { // public String stateId; // public String name; // } // } // } // Path: src/main/java/org/votesmart/classes/StateClass.java import org.votesmart.api.*; import org.votesmart.data.State; import org.votesmart.data.StateList; package org.votesmart.classes; /** * <pre> * State Class * * State.getStateIDs() * This method grabs a simple state ID and name list for mapping ID to state names. * Input: none * Output: {@link StateList} * * State.getState() * This method grabs a various data we keep on a state * Input: stateId* * Output: {@link State} * * ============== EXAMPLE USAGE ============= * * StateClass stateClass = new StateClass(); * * StateList allStates = stateClass.getStateIDs(); * StateList.List.State state = null; * for( StateList.List.State aState: allStates.list.state ) { * if (aState.name.equals("California")) { * state = aState; * break; * } * } * // Get State Details * State stateDetail = stateClass.getState(state.stateId); * </pre> * */ public class StateClass extends ClassesBase { /** * Constructor for testing purposes * * @param api */ public StateClass(VoteSmartAPI api) { super(api); } /** * Default Constructor */ public StateClass() throws VoteSmartException { super(); } /** * This method grabs a simple state ID and name list for mapping ID to state names. * * @return {@link StateList} */
public StateList getStateIDs() throws VoteSmartException, VoteSmartErrorException {
karlnicholas/votesmart
src/main/java/org/votesmart/classes/StateClass.java
// Path: src/main/java/org/votesmart/data/State.java // @XmlRootElement(name="state") // public class State extends GeneralInfoBase { // // public Details details; // // @XmlType(name="details", namespace="state") // public static class Details { // public String stateId; // public String stateType; // public String name; // public String nickName; // public String capital; // public String area; // public String population; // public String statehood; // public String motto; // public String flower; // public String tree; // public String bird; // public String highPoint; // public String lowPoint; // public String bicameral; // public String upperLegis; // public String lowerLegis; // public String ltGov; // public String senators; // public String reps; // public String termLimit; // public String termLength; // public URL billUrl; // public URL voteUrl; // public String voterReg; // public String primaryDate; // public String generalDate; // public String absenteeWho; // public String absenteeHow; // public String absenteeWhen; // public String largestCity; // public String rollUpper; // public String rollLower; // public String usCircuit; // } // } // // Path: src/main/java/org/votesmart/data/StateList.java // @XmlRootElement(name="stateList") // public class StateList extends GeneralInfoBase { // public List list; // // @XmlType(name="list", namespace="stateList") // public static class List { // public ArrayList<State> state; // // @XmlType(name="state", namespace="stateList") // public static class State { // public String stateId; // public String name; // } // } // }
import org.votesmart.api.*; import org.votesmart.data.State; import org.votesmart.data.StateList;
package org.votesmart.classes; /** * <pre> * State Class * * State.getStateIDs() * This method grabs a simple state ID and name list for mapping ID to state names. * Input: none * Output: {@link StateList} * * State.getState() * This method grabs a various data we keep on a state * Input: stateId* * Output: {@link State} * * ============== EXAMPLE USAGE ============= * * StateClass stateClass = new StateClass(); * * StateList allStates = stateClass.getStateIDs(); * StateList.List.State state = null; * for( StateList.List.State aState: allStates.list.state ) { * if (aState.name.equals("California")) { * state = aState; * break; * } * } * // Get State Details * State stateDetail = stateClass.getState(state.stateId); * </pre> * */ public class StateClass extends ClassesBase { /** * Constructor for testing purposes * * @param api */ public StateClass(VoteSmartAPI api) { super(api); } /** * Default Constructor */ public StateClass() throws VoteSmartException { super(); } /** * This method grabs a simple state ID and name list for mapping ID to state names. * * @return {@link StateList} */ public StateList getStateIDs() throws VoteSmartException, VoteSmartErrorException { return api.query("State.getStateIDs", null, StateList.class ); } /** * This method grabs a various data we keep on a state. * Input: stateId* * * @param stateId * @return {@link State} */
// Path: src/main/java/org/votesmart/data/State.java // @XmlRootElement(name="state") // public class State extends GeneralInfoBase { // // public Details details; // // @XmlType(name="details", namespace="state") // public static class Details { // public String stateId; // public String stateType; // public String name; // public String nickName; // public String capital; // public String area; // public String population; // public String statehood; // public String motto; // public String flower; // public String tree; // public String bird; // public String highPoint; // public String lowPoint; // public String bicameral; // public String upperLegis; // public String lowerLegis; // public String ltGov; // public String senators; // public String reps; // public String termLimit; // public String termLength; // public URL billUrl; // public URL voteUrl; // public String voterReg; // public String primaryDate; // public String generalDate; // public String absenteeWho; // public String absenteeHow; // public String absenteeWhen; // public String largestCity; // public String rollUpper; // public String rollLower; // public String usCircuit; // } // } // // Path: src/main/java/org/votesmart/data/StateList.java // @XmlRootElement(name="stateList") // public class StateList extends GeneralInfoBase { // public List list; // // @XmlType(name="list", namespace="stateList") // public static class List { // public ArrayList<State> state; // // @XmlType(name="state", namespace="stateList") // public static class State { // public String stateId; // public String name; // } // } // } // Path: src/main/java/org/votesmart/classes/StateClass.java import org.votesmart.api.*; import org.votesmart.data.State; import org.votesmart.data.StateList; package org.votesmart.classes; /** * <pre> * State Class * * State.getStateIDs() * This method grabs a simple state ID and name list for mapping ID to state names. * Input: none * Output: {@link StateList} * * State.getState() * This method grabs a various data we keep on a state * Input: stateId* * Output: {@link State} * * ============== EXAMPLE USAGE ============= * * StateClass stateClass = new StateClass(); * * StateList allStates = stateClass.getStateIDs(); * StateList.List.State state = null; * for( StateList.List.State aState: allStates.list.state ) { * if (aState.name.equals("California")) { * state = aState; * break; * } * } * // Get State Details * State stateDetail = stateClass.getState(state.stateId); * </pre> * */ public class StateClass extends ClassesBase { /** * Constructor for testing purposes * * @param api */ public StateClass(VoteSmartAPI api) { super(api); } /** * Default Constructor */ public StateClass() throws VoteSmartException { super(); } /** * This method grabs a simple state ID and name list for mapping ID to state names. * * @return {@link StateList} */ public StateList getStateIDs() throws VoteSmartException, VoteSmartErrorException { return api.query("State.getStateIDs", null, StateList.class ); } /** * This method grabs a various data we keep on a state. * Input: stateId* * * @param stateId * @return {@link State} */
public State getState(String stateId) throws VoteSmartException, VoteSmartErrorException {
karlnicholas/votesmart
src/main/java/org/votesmart/api/VoteSmartErrorException.java
// Path: src/main/java/org/votesmart/data/ErrorBase.java // @XmlRootElement(name="error") // public class ErrorBase { // // public String errorMessage; // }
import org.votesmart.data.ErrorBase;
package org.votesmart.api; /** * <pre> * This exception will be thrown when VoteSmart.org returns an error message. * So, it does not indicate an error with the program, but rather * that one of the parameters passed to one of the method calls * is probably incorrect. See what the message says. * </pre> * */ public class VoteSmartErrorException extends Exception { private static final long serialVersionUID = 2196788960724030978L;
// Path: src/main/java/org/votesmart/data/ErrorBase.java // @XmlRootElement(name="error") // public class ErrorBase { // // public String errorMessage; // } // Path: src/main/java/org/votesmart/api/VoteSmartErrorException.java import org.votesmart.data.ErrorBase; package org.votesmart.api; /** * <pre> * This exception will be thrown when VoteSmart.org returns an error message. * So, it does not indicate an error with the program, but rather * that one of the parameters passed to one of the method calls * is probably incorrect. See what the message says. * </pre> * */ public class VoteSmartErrorException extends Exception { private static final long serialVersionUID = 2196788960724030978L;
public ErrorBase errorBase;
karlnicholas/votesmart
src/test/java/org/votesmart/testapi/TestVoteSmartBase.java
// Path: src/main/java/org/votesmart/api/ArgMap.java // public class ArgMap extends TreeMap<String, String> { // private static final long serialVersionUID = -2664255408377082118L; // // public ArgMap(String... args ) { // for ( int i=0; i<args.length; i+=2) { // this.put(args[i], args[i+1]); // } // } // } // // Path: src/main/java/org/votesmart/api/VoteSmartAPI.java // public interface VoteSmartAPI { // public <T> T query(String method, ArgMap argMap, Class<T> responseType) throws VoteSmartException, VoteSmartErrorException; // } // // Path: src/main/java/org/votesmart/api/VoteSmartErrorException.java // public class VoteSmartErrorException extends Exception { // private static final long serialVersionUID = 2196788960724030978L; // public ErrorBase errorBase; // public String method; // public ArgMap argMap; // public VoteSmartErrorException(ErrorBase errorBase, String method, ArgMap argMap) { // super(errorBase.errorMessage); // this.errorBase = errorBase; // this.method = method; // this.argMap = argMap; // } // } // // Path: src/main/java/org/votesmart/api/VoteSmartException.java // public class VoteSmartException extends Exception { // private static final long serialVersionUID = 6179623710020364382L; // // public VoteSmartException (Exception e ) { // super(e); // } // // public VoteSmartException (String msg) { // super(msg); // } // // public VoteSmartException(String msg, Exception e ) { // super(msg, e); // } // } // // Path: src/main/java/org/votesmart/data/GeneralInfoBase.java // public class GeneralInfoBase extends ErrorBase { // // public GeneralInfo generalInfo; // // public static class GeneralInfo { // public String title; // public String linkBack; // } // // // }
import static org.junit.Assert.*; import java.util.ResourceBundle; import org.junit.AfterClass; import org.junit.BeforeClass; import org.votesmart.api.ArgMap; import org.votesmart.api.VoteSmartAPI; import org.votesmart.api.VoteSmartErrorException; import org.votesmart.api.VoteSmartException; import org.votesmart.data.GeneralInfoBase;
package org.votesmart.testapi; /** * Base class for all Test classes. * */ public class TestVoteSmartBase implements VoteSmartAPI { protected static TestVoteSmart api;
// Path: src/main/java/org/votesmart/api/ArgMap.java // public class ArgMap extends TreeMap<String, String> { // private static final long serialVersionUID = -2664255408377082118L; // // public ArgMap(String... args ) { // for ( int i=0; i<args.length; i+=2) { // this.put(args[i], args[i+1]); // } // } // } // // Path: src/main/java/org/votesmart/api/VoteSmartAPI.java // public interface VoteSmartAPI { // public <T> T query(String method, ArgMap argMap, Class<T> responseType) throws VoteSmartException, VoteSmartErrorException; // } // // Path: src/main/java/org/votesmart/api/VoteSmartErrorException.java // public class VoteSmartErrorException extends Exception { // private static final long serialVersionUID = 2196788960724030978L; // public ErrorBase errorBase; // public String method; // public ArgMap argMap; // public VoteSmartErrorException(ErrorBase errorBase, String method, ArgMap argMap) { // super(errorBase.errorMessage); // this.errorBase = errorBase; // this.method = method; // this.argMap = argMap; // } // } // // Path: src/main/java/org/votesmart/api/VoteSmartException.java // public class VoteSmartException extends Exception { // private static final long serialVersionUID = 6179623710020364382L; // // public VoteSmartException (Exception e ) { // super(e); // } // // public VoteSmartException (String msg) { // super(msg); // } // // public VoteSmartException(String msg, Exception e ) { // super(msg, e); // } // } // // Path: src/main/java/org/votesmart/data/GeneralInfoBase.java // public class GeneralInfoBase extends ErrorBase { // // public GeneralInfo generalInfo; // // public static class GeneralInfo { // public String title; // public String linkBack; // } // // // } // Path: src/test/java/org/votesmart/testapi/TestVoteSmartBase.java import static org.junit.Assert.*; import java.util.ResourceBundle; import org.junit.AfterClass; import org.junit.BeforeClass; import org.votesmart.api.ArgMap; import org.votesmart.api.VoteSmartAPI; import org.votesmart.api.VoteSmartErrorException; import org.votesmart.api.VoteSmartException; import org.votesmart.data.GeneralInfoBase; package org.votesmart.testapi; /** * Base class for all Test classes. * */ public class TestVoteSmartBase implements VoteSmartAPI { protected static TestVoteSmart api;
private static GeneralInfoBase generalInfoBase;
karlnicholas/votesmart
src/test/java/org/votesmart/testapi/TestVoteSmartBase.java
// Path: src/main/java/org/votesmart/api/ArgMap.java // public class ArgMap extends TreeMap<String, String> { // private static final long serialVersionUID = -2664255408377082118L; // // public ArgMap(String... args ) { // for ( int i=0; i<args.length; i+=2) { // this.put(args[i], args[i+1]); // } // } // } // // Path: src/main/java/org/votesmart/api/VoteSmartAPI.java // public interface VoteSmartAPI { // public <T> T query(String method, ArgMap argMap, Class<T> responseType) throws VoteSmartException, VoteSmartErrorException; // } // // Path: src/main/java/org/votesmart/api/VoteSmartErrorException.java // public class VoteSmartErrorException extends Exception { // private static final long serialVersionUID = 2196788960724030978L; // public ErrorBase errorBase; // public String method; // public ArgMap argMap; // public VoteSmartErrorException(ErrorBase errorBase, String method, ArgMap argMap) { // super(errorBase.errorMessage); // this.errorBase = errorBase; // this.method = method; // this.argMap = argMap; // } // } // // Path: src/main/java/org/votesmart/api/VoteSmartException.java // public class VoteSmartException extends Exception { // private static final long serialVersionUID = 6179623710020364382L; // // public VoteSmartException (Exception e ) { // super(e); // } // // public VoteSmartException (String msg) { // super(msg); // } // // public VoteSmartException(String msg, Exception e ) { // super(msg, e); // } // } // // Path: src/main/java/org/votesmart/data/GeneralInfoBase.java // public class GeneralInfoBase extends ErrorBase { // // public GeneralInfo generalInfo; // // public static class GeneralInfo { // public String title; // public String linkBack; // } // // // }
import static org.junit.Assert.*; import java.util.ResourceBundle; import org.junit.AfterClass; import org.junit.BeforeClass; import org.votesmart.api.ArgMap; import org.votesmart.api.VoteSmartAPI; import org.votesmart.api.VoteSmartErrorException; import org.votesmart.api.VoteSmartException; import org.votesmart.data.GeneralInfoBase;
package org.votesmart.testapi; /** * Base class for all Test classes. * */ public class TestVoteSmartBase implements VoteSmartAPI { protected static TestVoteSmart api; private static GeneralInfoBase generalInfoBase; @BeforeClass public static void setup() { api = new TestVoteSmart(ResourceBundle.getBundle("votesmart")); }
// Path: src/main/java/org/votesmart/api/ArgMap.java // public class ArgMap extends TreeMap<String, String> { // private static final long serialVersionUID = -2664255408377082118L; // // public ArgMap(String... args ) { // for ( int i=0; i<args.length; i+=2) { // this.put(args[i], args[i+1]); // } // } // } // // Path: src/main/java/org/votesmart/api/VoteSmartAPI.java // public interface VoteSmartAPI { // public <T> T query(String method, ArgMap argMap, Class<T> responseType) throws VoteSmartException, VoteSmartErrorException; // } // // Path: src/main/java/org/votesmart/api/VoteSmartErrorException.java // public class VoteSmartErrorException extends Exception { // private static final long serialVersionUID = 2196788960724030978L; // public ErrorBase errorBase; // public String method; // public ArgMap argMap; // public VoteSmartErrorException(ErrorBase errorBase, String method, ArgMap argMap) { // super(errorBase.errorMessage); // this.errorBase = errorBase; // this.method = method; // this.argMap = argMap; // } // } // // Path: src/main/java/org/votesmart/api/VoteSmartException.java // public class VoteSmartException extends Exception { // private static final long serialVersionUID = 6179623710020364382L; // // public VoteSmartException (Exception e ) { // super(e); // } // // public VoteSmartException (String msg) { // super(msg); // } // // public VoteSmartException(String msg, Exception e ) { // super(msg, e); // } // } // // Path: src/main/java/org/votesmart/data/GeneralInfoBase.java // public class GeneralInfoBase extends ErrorBase { // // public GeneralInfo generalInfo; // // public static class GeneralInfo { // public String title; // public String linkBack; // } // // // } // Path: src/test/java/org/votesmart/testapi/TestVoteSmartBase.java import static org.junit.Assert.*; import java.util.ResourceBundle; import org.junit.AfterClass; import org.junit.BeforeClass; import org.votesmart.api.ArgMap; import org.votesmart.api.VoteSmartAPI; import org.votesmart.api.VoteSmartErrorException; import org.votesmart.api.VoteSmartException; import org.votesmart.data.GeneralInfoBase; package org.votesmart.testapi; /** * Base class for all Test classes. * */ public class TestVoteSmartBase implements VoteSmartAPI { protected static TestVoteSmart api; private static GeneralInfoBase generalInfoBase; @BeforeClass public static void setup() { api = new TestVoteSmart(ResourceBundle.getBundle("votesmart")); }
public <T> T query(String method, ArgMap argMap, Class<T> responseType) throws VoteSmartException, VoteSmartErrorException {
karlnicholas/votesmart
src/test/java/org/votesmart/testapi/TestVoteSmartBase.java
// Path: src/main/java/org/votesmart/api/ArgMap.java // public class ArgMap extends TreeMap<String, String> { // private static final long serialVersionUID = -2664255408377082118L; // // public ArgMap(String... args ) { // for ( int i=0; i<args.length; i+=2) { // this.put(args[i], args[i+1]); // } // } // } // // Path: src/main/java/org/votesmart/api/VoteSmartAPI.java // public interface VoteSmartAPI { // public <T> T query(String method, ArgMap argMap, Class<T> responseType) throws VoteSmartException, VoteSmartErrorException; // } // // Path: src/main/java/org/votesmart/api/VoteSmartErrorException.java // public class VoteSmartErrorException extends Exception { // private static final long serialVersionUID = 2196788960724030978L; // public ErrorBase errorBase; // public String method; // public ArgMap argMap; // public VoteSmartErrorException(ErrorBase errorBase, String method, ArgMap argMap) { // super(errorBase.errorMessage); // this.errorBase = errorBase; // this.method = method; // this.argMap = argMap; // } // } // // Path: src/main/java/org/votesmart/api/VoteSmartException.java // public class VoteSmartException extends Exception { // private static final long serialVersionUID = 6179623710020364382L; // // public VoteSmartException (Exception e ) { // super(e); // } // // public VoteSmartException (String msg) { // super(msg); // } // // public VoteSmartException(String msg, Exception e ) { // super(msg, e); // } // } // // Path: src/main/java/org/votesmart/data/GeneralInfoBase.java // public class GeneralInfoBase extends ErrorBase { // // public GeneralInfo generalInfo; // // public static class GeneralInfo { // public String title; // public String linkBack; // } // // // }
import static org.junit.Assert.*; import java.util.ResourceBundle; import org.junit.AfterClass; import org.junit.BeforeClass; import org.votesmart.api.ArgMap; import org.votesmart.api.VoteSmartAPI; import org.votesmart.api.VoteSmartErrorException; import org.votesmart.api.VoteSmartException; import org.votesmart.data.GeneralInfoBase;
package org.votesmart.testapi; /** * Base class for all Test classes. * */ public class TestVoteSmartBase implements VoteSmartAPI { protected static TestVoteSmart api; private static GeneralInfoBase generalInfoBase; @BeforeClass public static void setup() { api = new TestVoteSmart(ResourceBundle.getBundle("votesmart")); }
// Path: src/main/java/org/votesmart/api/ArgMap.java // public class ArgMap extends TreeMap<String, String> { // private static final long serialVersionUID = -2664255408377082118L; // // public ArgMap(String... args ) { // for ( int i=0; i<args.length; i+=2) { // this.put(args[i], args[i+1]); // } // } // } // // Path: src/main/java/org/votesmart/api/VoteSmartAPI.java // public interface VoteSmartAPI { // public <T> T query(String method, ArgMap argMap, Class<T> responseType) throws VoteSmartException, VoteSmartErrorException; // } // // Path: src/main/java/org/votesmart/api/VoteSmartErrorException.java // public class VoteSmartErrorException extends Exception { // private static final long serialVersionUID = 2196788960724030978L; // public ErrorBase errorBase; // public String method; // public ArgMap argMap; // public VoteSmartErrorException(ErrorBase errorBase, String method, ArgMap argMap) { // super(errorBase.errorMessage); // this.errorBase = errorBase; // this.method = method; // this.argMap = argMap; // } // } // // Path: src/main/java/org/votesmart/api/VoteSmartException.java // public class VoteSmartException extends Exception { // private static final long serialVersionUID = 6179623710020364382L; // // public VoteSmartException (Exception e ) { // super(e); // } // // public VoteSmartException (String msg) { // super(msg); // } // // public VoteSmartException(String msg, Exception e ) { // super(msg, e); // } // } // // Path: src/main/java/org/votesmart/data/GeneralInfoBase.java // public class GeneralInfoBase extends ErrorBase { // // public GeneralInfo generalInfo; // // public static class GeneralInfo { // public String title; // public String linkBack; // } // // // } // Path: src/test/java/org/votesmart/testapi/TestVoteSmartBase.java import static org.junit.Assert.*; import java.util.ResourceBundle; import org.junit.AfterClass; import org.junit.BeforeClass; import org.votesmart.api.ArgMap; import org.votesmart.api.VoteSmartAPI; import org.votesmart.api.VoteSmartErrorException; import org.votesmart.api.VoteSmartException; import org.votesmart.data.GeneralInfoBase; package org.votesmart.testapi; /** * Base class for all Test classes. * */ public class TestVoteSmartBase implements VoteSmartAPI { protected static TestVoteSmart api; private static GeneralInfoBase generalInfoBase; @BeforeClass public static void setup() { api = new TestVoteSmart(ResourceBundle.getBundle("votesmart")); }
public <T> T query(String method, ArgMap argMap, Class<T> responseType) throws VoteSmartException, VoteSmartErrorException {
karlnicholas/votesmart
src/test/java/org/votesmart/testapi/TestVoteSmartBase.java
// Path: src/main/java/org/votesmart/api/ArgMap.java // public class ArgMap extends TreeMap<String, String> { // private static final long serialVersionUID = -2664255408377082118L; // // public ArgMap(String... args ) { // for ( int i=0; i<args.length; i+=2) { // this.put(args[i], args[i+1]); // } // } // } // // Path: src/main/java/org/votesmart/api/VoteSmartAPI.java // public interface VoteSmartAPI { // public <T> T query(String method, ArgMap argMap, Class<T> responseType) throws VoteSmartException, VoteSmartErrorException; // } // // Path: src/main/java/org/votesmart/api/VoteSmartErrorException.java // public class VoteSmartErrorException extends Exception { // private static final long serialVersionUID = 2196788960724030978L; // public ErrorBase errorBase; // public String method; // public ArgMap argMap; // public VoteSmartErrorException(ErrorBase errorBase, String method, ArgMap argMap) { // super(errorBase.errorMessage); // this.errorBase = errorBase; // this.method = method; // this.argMap = argMap; // } // } // // Path: src/main/java/org/votesmart/api/VoteSmartException.java // public class VoteSmartException extends Exception { // private static final long serialVersionUID = 6179623710020364382L; // // public VoteSmartException (Exception e ) { // super(e); // } // // public VoteSmartException (String msg) { // super(msg); // } // // public VoteSmartException(String msg, Exception e ) { // super(msg, e); // } // } // // Path: src/main/java/org/votesmart/data/GeneralInfoBase.java // public class GeneralInfoBase extends ErrorBase { // // public GeneralInfo generalInfo; // // public static class GeneralInfo { // public String title; // public String linkBack; // } // // // }
import static org.junit.Assert.*; import java.util.ResourceBundle; import org.junit.AfterClass; import org.junit.BeforeClass; import org.votesmart.api.ArgMap; import org.votesmart.api.VoteSmartAPI; import org.votesmart.api.VoteSmartErrorException; import org.votesmart.api.VoteSmartException; import org.votesmart.data.GeneralInfoBase;
package org.votesmart.testapi; /** * Base class for all Test classes. * */ public class TestVoteSmartBase implements VoteSmartAPI { protected static TestVoteSmart api; private static GeneralInfoBase generalInfoBase; @BeforeClass public static void setup() { api = new TestVoteSmart(ResourceBundle.getBundle("votesmart")); }
// Path: src/main/java/org/votesmart/api/ArgMap.java // public class ArgMap extends TreeMap<String, String> { // private static final long serialVersionUID = -2664255408377082118L; // // public ArgMap(String... args ) { // for ( int i=0; i<args.length; i+=2) { // this.put(args[i], args[i+1]); // } // } // } // // Path: src/main/java/org/votesmart/api/VoteSmartAPI.java // public interface VoteSmartAPI { // public <T> T query(String method, ArgMap argMap, Class<T> responseType) throws VoteSmartException, VoteSmartErrorException; // } // // Path: src/main/java/org/votesmart/api/VoteSmartErrorException.java // public class VoteSmartErrorException extends Exception { // private static final long serialVersionUID = 2196788960724030978L; // public ErrorBase errorBase; // public String method; // public ArgMap argMap; // public VoteSmartErrorException(ErrorBase errorBase, String method, ArgMap argMap) { // super(errorBase.errorMessage); // this.errorBase = errorBase; // this.method = method; // this.argMap = argMap; // } // } // // Path: src/main/java/org/votesmart/api/VoteSmartException.java // public class VoteSmartException extends Exception { // private static final long serialVersionUID = 6179623710020364382L; // // public VoteSmartException (Exception e ) { // super(e); // } // // public VoteSmartException (String msg) { // super(msg); // } // // public VoteSmartException(String msg, Exception e ) { // super(msg, e); // } // } // // Path: src/main/java/org/votesmart/data/GeneralInfoBase.java // public class GeneralInfoBase extends ErrorBase { // // public GeneralInfo generalInfo; // // public static class GeneralInfo { // public String title; // public String linkBack; // } // // // } // Path: src/test/java/org/votesmart/testapi/TestVoteSmartBase.java import static org.junit.Assert.*; import java.util.ResourceBundle; import org.junit.AfterClass; import org.junit.BeforeClass; import org.votesmart.api.ArgMap; import org.votesmart.api.VoteSmartAPI; import org.votesmart.api.VoteSmartErrorException; import org.votesmart.api.VoteSmartException; import org.votesmart.data.GeneralInfoBase; package org.votesmart.testapi; /** * Base class for all Test classes. * */ public class TestVoteSmartBase implements VoteSmartAPI { protected static TestVoteSmart api; private static GeneralInfoBase generalInfoBase; @BeforeClass public static void setup() { api = new TestVoteSmart(ResourceBundle.getBundle("votesmart")); }
public <T> T query(String method, ArgMap argMap, Class<T> responseType) throws VoteSmartException, VoteSmartErrorException {
karlnicholas/votesmart
src/main/java/org/votesmart/api/VoteSmart.java
// Path: src/main/java/org/votesmart/data/ErrorBase.java // @XmlRootElement(name="error") // public class ErrorBase { // // public String errorMessage; // }
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.util.ResourceBundle; import java.util.logging.Logger; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import javax.xml.transform.stream.StreamSource; import org.votesmart.data.ErrorBase;
* * @param method * @param argMap * @param responseType * @throws VoteSmartErrorException * */ public <T> T query(String method, ArgMap argMap, Class<T> responseType) throws VoteSmartException, VoteSmartErrorException { BufferedReader reader = null; HttpURLConnection conn = null; String charSet = "utf-8"; try { if ( isCaching(method, argMap) ) { File file = getCacheFile(method, argMap); long fileLength = file.length(); logger.fine("Length of File in cache:" + fileLength + ": " + file.getName()); if ( fileLength == 0L ) { VoteSmart.cacheFileFromAPI(method, argMap, file); } reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), charSet)); } else { conn = VoteSmart.getConnectionFromAPI(method, argMap); charSet = getCharset(conn); reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), charSet)); } JAXBElement<T> e = unmarshaller.unmarshal( new StreamSource( reader ), responseType ); if ( e.getName().getLocalPart().equals("error") ) { // ErrorBase error = unmarshaller.unmarshal( new StreamSource( reader = new StringReader(XMLStr) ), ErrorBase.class ).getValue();
// Path: src/main/java/org/votesmart/data/ErrorBase.java // @XmlRootElement(name="error") // public class ErrorBase { // // public String errorMessage; // } // Path: src/main/java/org/votesmart/api/VoteSmart.java import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.util.ResourceBundle; import java.util.logging.Logger; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import javax.xml.transform.stream.StreamSource; import org.votesmart.data.ErrorBase; * * @param method * @param argMap * @param responseType * @throws VoteSmartErrorException * */ public <T> T query(String method, ArgMap argMap, Class<T> responseType) throws VoteSmartException, VoteSmartErrorException { BufferedReader reader = null; HttpURLConnection conn = null; String charSet = "utf-8"; try { if ( isCaching(method, argMap) ) { File file = getCacheFile(method, argMap); long fileLength = file.length(); logger.fine("Length of File in cache:" + fileLength + ": " + file.getName()); if ( fileLength == 0L ) { VoteSmart.cacheFileFromAPI(method, argMap, file); } reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), charSet)); } else { conn = VoteSmart.getConnectionFromAPI(method, argMap); charSet = getCharset(conn); reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), charSet)); } JAXBElement<T> e = unmarshaller.unmarshal( new StreamSource( reader ), responseType ); if ( e.getName().getLocalPart().equals("error") ) { // ErrorBase error = unmarshaller.unmarshal( new StreamSource( reader = new StringReader(XMLStr) ), ErrorBase.class ).getValue();
throw new VoteSmartErrorException( ((ErrorBase)e.getValue()), method, argMap );
karlnicholas/votesmart
src/main/java/org/votesmart/classes/LocalClass.java
// Path: src/main/java/org/votesmart/data/Cities.java // @XmlRootElement(name="cities") // public class Cities extends GeneralInfoBase { // // public ArrayList<City> city; // // @XmlType(name="city", namespace="cities") // public static class City { // public String localId; // public String name; // public URL url; // } // } // // Path: src/main/java/org/votesmart/data/Counties.java // @XmlRootElement(name="counties") // public class Counties extends GeneralInfoBase { // // public ArrayList<County> county; // // @XmlType(name="county", namespace="counties") // public static class County { // public String localId; // public String name; // public URL url; // } // } // // Path: src/main/java/org/votesmart/data/LocalCandidateList.java // @XmlRootElement(name="candidatelist") // public class LocalCandidateList extends GeneralInfoBase { // public ArrayList<Candidate> candidate; // // @XmlType(name="candidate", namespace="candidatelist") // public static class Candidate { // public String candidateId; // public String firstName; // public String nickName; // public String middleName; // public String lastName; // public String suffix; // public String title; // public String electionParties; // public String electionDistrictId; // public String electionStateId; // public String officeParties; // public String officeDistrictId; // public String officeDistrictName; // public String officeStateId; // public String officeId; // public String officeName; // public String officeTypeId; // } // }
import org.votesmart.api.*; import org.votesmart.data.Cities; import org.votesmart.data.Counties; import org.votesmart.data.LocalCandidateList;
package org.votesmart.classes; /** * <pre> * Local Class * * Local.getCounties() * Fetches counties in a state * Input: stateId* * Output: {@link Counties} * * Local.getCities() * Fetches cities in a state * Input: stateId* * Output: {@link Cities} * * Local.getOfficials() * Fetches officials for a locality * Input: localId* * Output: {@link LocalCandidateList} * * ============= EXAMPLE USAGE ============= * * LocalClass localClass = new LocalClass(); * * // get counties * Counties counties = localClass.getCounties(state.stateId); * Counties.County county = counties.county.get(0); * * // get cities * Cities cities = localClass.getCities(state.stateId); * Cities.City city = cities.city.get(0); * * // county official * LocalCandidateList localCandidates = localClass.getOfficials(county.localId); * LocalCandidateList.Candidate localCandidate = localCandidates.candidate.get(0); * </pre> */ public class LocalClass extends ClassesBase { /** * Constructor for testing purposes. * * @param api */ public LocalClass(VoteSmartAPI api) { super(api); } /** * Default Constructor */ public LocalClass() throws VoteSmartException { super(); } /** * Fetches counties in a state. * * @param stateId * @return {@link Counties}: */
// Path: src/main/java/org/votesmart/data/Cities.java // @XmlRootElement(name="cities") // public class Cities extends GeneralInfoBase { // // public ArrayList<City> city; // // @XmlType(name="city", namespace="cities") // public static class City { // public String localId; // public String name; // public URL url; // } // } // // Path: src/main/java/org/votesmart/data/Counties.java // @XmlRootElement(name="counties") // public class Counties extends GeneralInfoBase { // // public ArrayList<County> county; // // @XmlType(name="county", namespace="counties") // public static class County { // public String localId; // public String name; // public URL url; // } // } // // Path: src/main/java/org/votesmart/data/LocalCandidateList.java // @XmlRootElement(name="candidatelist") // public class LocalCandidateList extends GeneralInfoBase { // public ArrayList<Candidate> candidate; // // @XmlType(name="candidate", namespace="candidatelist") // public static class Candidate { // public String candidateId; // public String firstName; // public String nickName; // public String middleName; // public String lastName; // public String suffix; // public String title; // public String electionParties; // public String electionDistrictId; // public String electionStateId; // public String officeParties; // public String officeDistrictId; // public String officeDistrictName; // public String officeStateId; // public String officeId; // public String officeName; // public String officeTypeId; // } // } // Path: src/main/java/org/votesmart/classes/LocalClass.java import org.votesmart.api.*; import org.votesmart.data.Cities; import org.votesmart.data.Counties; import org.votesmart.data.LocalCandidateList; package org.votesmart.classes; /** * <pre> * Local Class * * Local.getCounties() * Fetches counties in a state * Input: stateId* * Output: {@link Counties} * * Local.getCities() * Fetches cities in a state * Input: stateId* * Output: {@link Cities} * * Local.getOfficials() * Fetches officials for a locality * Input: localId* * Output: {@link LocalCandidateList} * * ============= EXAMPLE USAGE ============= * * LocalClass localClass = new LocalClass(); * * // get counties * Counties counties = localClass.getCounties(state.stateId); * Counties.County county = counties.county.get(0); * * // get cities * Cities cities = localClass.getCities(state.stateId); * Cities.City city = cities.city.get(0); * * // county official * LocalCandidateList localCandidates = localClass.getOfficials(county.localId); * LocalCandidateList.Candidate localCandidate = localCandidates.candidate.get(0); * </pre> */ public class LocalClass extends ClassesBase { /** * Constructor for testing purposes. * * @param api */ public LocalClass(VoteSmartAPI api) { super(api); } /** * Default Constructor */ public LocalClass() throws VoteSmartException { super(); } /** * Fetches counties in a state. * * @param stateId * @return {@link Counties}: */
public Counties getCounties(String stateId) throws VoteSmartException, VoteSmartErrorException {
karlnicholas/votesmart
src/main/java/org/votesmart/classes/LocalClass.java
// Path: src/main/java/org/votesmart/data/Cities.java // @XmlRootElement(name="cities") // public class Cities extends GeneralInfoBase { // // public ArrayList<City> city; // // @XmlType(name="city", namespace="cities") // public static class City { // public String localId; // public String name; // public URL url; // } // } // // Path: src/main/java/org/votesmart/data/Counties.java // @XmlRootElement(name="counties") // public class Counties extends GeneralInfoBase { // // public ArrayList<County> county; // // @XmlType(name="county", namespace="counties") // public static class County { // public String localId; // public String name; // public URL url; // } // } // // Path: src/main/java/org/votesmart/data/LocalCandidateList.java // @XmlRootElement(name="candidatelist") // public class LocalCandidateList extends GeneralInfoBase { // public ArrayList<Candidate> candidate; // // @XmlType(name="candidate", namespace="candidatelist") // public static class Candidate { // public String candidateId; // public String firstName; // public String nickName; // public String middleName; // public String lastName; // public String suffix; // public String title; // public String electionParties; // public String electionDistrictId; // public String electionStateId; // public String officeParties; // public String officeDistrictId; // public String officeDistrictName; // public String officeStateId; // public String officeId; // public String officeName; // public String officeTypeId; // } // }
import org.votesmart.api.*; import org.votesmart.data.Cities; import org.votesmart.data.Counties; import org.votesmart.data.LocalCandidateList;
package org.votesmart.classes; /** * <pre> * Local Class * * Local.getCounties() * Fetches counties in a state * Input: stateId* * Output: {@link Counties} * * Local.getCities() * Fetches cities in a state * Input: stateId* * Output: {@link Cities} * * Local.getOfficials() * Fetches officials for a locality * Input: localId* * Output: {@link LocalCandidateList} * * ============= EXAMPLE USAGE ============= * * LocalClass localClass = new LocalClass(); * * // get counties * Counties counties = localClass.getCounties(state.stateId); * Counties.County county = counties.county.get(0); * * // get cities * Cities cities = localClass.getCities(state.stateId); * Cities.City city = cities.city.get(0); * * // county official * LocalCandidateList localCandidates = localClass.getOfficials(county.localId); * LocalCandidateList.Candidate localCandidate = localCandidates.candidate.get(0); * </pre> */ public class LocalClass extends ClassesBase { /** * Constructor for testing purposes. * * @param api */ public LocalClass(VoteSmartAPI api) { super(api); } /** * Default Constructor */ public LocalClass() throws VoteSmartException { super(); } /** * Fetches counties in a state. * * @param stateId * @return {@link Counties}: */ public Counties getCounties(String stateId) throws VoteSmartException, VoteSmartErrorException { return api.query("Local.getCounties", new ArgMap("stateId", stateId), Counties.class ); } /** * Fetches cities in a state. * * @param stateId * @return {@link Cities}: */
// Path: src/main/java/org/votesmart/data/Cities.java // @XmlRootElement(name="cities") // public class Cities extends GeneralInfoBase { // // public ArrayList<City> city; // // @XmlType(name="city", namespace="cities") // public static class City { // public String localId; // public String name; // public URL url; // } // } // // Path: src/main/java/org/votesmart/data/Counties.java // @XmlRootElement(name="counties") // public class Counties extends GeneralInfoBase { // // public ArrayList<County> county; // // @XmlType(name="county", namespace="counties") // public static class County { // public String localId; // public String name; // public URL url; // } // } // // Path: src/main/java/org/votesmart/data/LocalCandidateList.java // @XmlRootElement(name="candidatelist") // public class LocalCandidateList extends GeneralInfoBase { // public ArrayList<Candidate> candidate; // // @XmlType(name="candidate", namespace="candidatelist") // public static class Candidate { // public String candidateId; // public String firstName; // public String nickName; // public String middleName; // public String lastName; // public String suffix; // public String title; // public String electionParties; // public String electionDistrictId; // public String electionStateId; // public String officeParties; // public String officeDistrictId; // public String officeDistrictName; // public String officeStateId; // public String officeId; // public String officeName; // public String officeTypeId; // } // } // Path: src/main/java/org/votesmart/classes/LocalClass.java import org.votesmart.api.*; import org.votesmart.data.Cities; import org.votesmart.data.Counties; import org.votesmart.data.LocalCandidateList; package org.votesmart.classes; /** * <pre> * Local Class * * Local.getCounties() * Fetches counties in a state * Input: stateId* * Output: {@link Counties} * * Local.getCities() * Fetches cities in a state * Input: stateId* * Output: {@link Cities} * * Local.getOfficials() * Fetches officials for a locality * Input: localId* * Output: {@link LocalCandidateList} * * ============= EXAMPLE USAGE ============= * * LocalClass localClass = new LocalClass(); * * // get counties * Counties counties = localClass.getCounties(state.stateId); * Counties.County county = counties.county.get(0); * * // get cities * Cities cities = localClass.getCities(state.stateId); * Cities.City city = cities.city.get(0); * * // county official * LocalCandidateList localCandidates = localClass.getOfficials(county.localId); * LocalCandidateList.Candidate localCandidate = localCandidates.candidate.get(0); * </pre> */ public class LocalClass extends ClassesBase { /** * Constructor for testing purposes. * * @param api */ public LocalClass(VoteSmartAPI api) { super(api); } /** * Default Constructor */ public LocalClass() throws VoteSmartException { super(); } /** * Fetches counties in a state. * * @param stateId * @return {@link Counties}: */ public Counties getCounties(String stateId) throws VoteSmartException, VoteSmartErrorException { return api.query("Local.getCounties", new ArgMap("stateId", stateId), Counties.class ); } /** * Fetches cities in a state. * * @param stateId * @return {@link Cities}: */
public Cities getCities(String stateId) throws VoteSmartException, VoteSmartErrorException {
karlnicholas/votesmart
src/main/java/org/votesmart/classes/LocalClass.java
// Path: src/main/java/org/votesmart/data/Cities.java // @XmlRootElement(name="cities") // public class Cities extends GeneralInfoBase { // // public ArrayList<City> city; // // @XmlType(name="city", namespace="cities") // public static class City { // public String localId; // public String name; // public URL url; // } // } // // Path: src/main/java/org/votesmart/data/Counties.java // @XmlRootElement(name="counties") // public class Counties extends GeneralInfoBase { // // public ArrayList<County> county; // // @XmlType(name="county", namespace="counties") // public static class County { // public String localId; // public String name; // public URL url; // } // } // // Path: src/main/java/org/votesmart/data/LocalCandidateList.java // @XmlRootElement(name="candidatelist") // public class LocalCandidateList extends GeneralInfoBase { // public ArrayList<Candidate> candidate; // // @XmlType(name="candidate", namespace="candidatelist") // public static class Candidate { // public String candidateId; // public String firstName; // public String nickName; // public String middleName; // public String lastName; // public String suffix; // public String title; // public String electionParties; // public String electionDistrictId; // public String electionStateId; // public String officeParties; // public String officeDistrictId; // public String officeDistrictName; // public String officeStateId; // public String officeId; // public String officeName; // public String officeTypeId; // } // }
import org.votesmart.api.*; import org.votesmart.data.Cities; import org.votesmart.data.Counties; import org.votesmart.data.LocalCandidateList;
package org.votesmart.classes; /** * <pre> * Local Class * * Local.getCounties() * Fetches counties in a state * Input: stateId* * Output: {@link Counties} * * Local.getCities() * Fetches cities in a state * Input: stateId* * Output: {@link Cities} * * Local.getOfficials() * Fetches officials for a locality * Input: localId* * Output: {@link LocalCandidateList} * * ============= EXAMPLE USAGE ============= * * LocalClass localClass = new LocalClass(); * * // get counties * Counties counties = localClass.getCounties(state.stateId); * Counties.County county = counties.county.get(0); * * // get cities * Cities cities = localClass.getCities(state.stateId); * Cities.City city = cities.city.get(0); * * // county official * LocalCandidateList localCandidates = localClass.getOfficials(county.localId); * LocalCandidateList.Candidate localCandidate = localCandidates.candidate.get(0); * </pre> */ public class LocalClass extends ClassesBase { /** * Constructor for testing purposes. * * @param api */ public LocalClass(VoteSmartAPI api) { super(api); } /** * Default Constructor */ public LocalClass() throws VoteSmartException { super(); } /** * Fetches counties in a state. * * @param stateId * @return {@link Counties}: */ public Counties getCounties(String stateId) throws VoteSmartException, VoteSmartErrorException { return api.query("Local.getCounties", new ArgMap("stateId", stateId), Counties.class ); } /** * Fetches cities in a state. * * @param stateId * @return {@link Cities}: */ public Cities getCities(String stateId) throws VoteSmartException, VoteSmartErrorException { return api.query("Local.getCities", new ArgMap("stateId", stateId), Cities.class ); } /** * Fetches officials for a locality. * * @param localId * @return {@link LocalCandidateList}: */
// Path: src/main/java/org/votesmart/data/Cities.java // @XmlRootElement(name="cities") // public class Cities extends GeneralInfoBase { // // public ArrayList<City> city; // // @XmlType(name="city", namespace="cities") // public static class City { // public String localId; // public String name; // public URL url; // } // } // // Path: src/main/java/org/votesmart/data/Counties.java // @XmlRootElement(name="counties") // public class Counties extends GeneralInfoBase { // // public ArrayList<County> county; // // @XmlType(name="county", namespace="counties") // public static class County { // public String localId; // public String name; // public URL url; // } // } // // Path: src/main/java/org/votesmart/data/LocalCandidateList.java // @XmlRootElement(name="candidatelist") // public class LocalCandidateList extends GeneralInfoBase { // public ArrayList<Candidate> candidate; // // @XmlType(name="candidate", namespace="candidatelist") // public static class Candidate { // public String candidateId; // public String firstName; // public String nickName; // public String middleName; // public String lastName; // public String suffix; // public String title; // public String electionParties; // public String electionDistrictId; // public String electionStateId; // public String officeParties; // public String officeDistrictId; // public String officeDistrictName; // public String officeStateId; // public String officeId; // public String officeName; // public String officeTypeId; // } // } // Path: src/main/java/org/votesmart/classes/LocalClass.java import org.votesmart.api.*; import org.votesmart.data.Cities; import org.votesmart.data.Counties; import org.votesmart.data.LocalCandidateList; package org.votesmart.classes; /** * <pre> * Local Class * * Local.getCounties() * Fetches counties in a state * Input: stateId* * Output: {@link Counties} * * Local.getCities() * Fetches cities in a state * Input: stateId* * Output: {@link Cities} * * Local.getOfficials() * Fetches officials for a locality * Input: localId* * Output: {@link LocalCandidateList} * * ============= EXAMPLE USAGE ============= * * LocalClass localClass = new LocalClass(); * * // get counties * Counties counties = localClass.getCounties(state.stateId); * Counties.County county = counties.county.get(0); * * // get cities * Cities cities = localClass.getCities(state.stateId); * Cities.City city = cities.city.get(0); * * // county official * LocalCandidateList localCandidates = localClass.getOfficials(county.localId); * LocalCandidateList.Candidate localCandidate = localCandidates.candidate.get(0); * </pre> */ public class LocalClass extends ClassesBase { /** * Constructor for testing purposes. * * @param api */ public LocalClass(VoteSmartAPI api) { super(api); } /** * Default Constructor */ public LocalClass() throws VoteSmartException { super(); } /** * Fetches counties in a state. * * @param stateId * @return {@link Counties}: */ public Counties getCounties(String stateId) throws VoteSmartException, VoteSmartErrorException { return api.query("Local.getCounties", new ArgMap("stateId", stateId), Counties.class ); } /** * Fetches cities in a state. * * @param stateId * @return {@link Cities}: */ public Cities getCities(String stateId) throws VoteSmartException, VoteSmartErrorException { return api.query("Local.getCities", new ArgMap("stateId", stateId), Cities.class ); } /** * Fetches officials for a locality. * * @param localId * @return {@link LocalCandidateList}: */
public LocalCandidateList getOfficials(String localId) throws VoteSmartException, VoteSmartErrorException {
karlnicholas/votesmart
src/main/java/org/votesmart/classes/MeasureClass.java
// Path: src/main/java/org/votesmart/data/Measure.java // @XmlRootElement(name="measure") // public class Measure extends GeneralInfoBase { // public String measureId; // public String measureCode; // public String title; // public String outcome; // public String electionDate; // public String electionType; // public String source; // public URL url; // public String summary; // public URL summaryUrl; // public String measureText; // public URL textUrl; // public URL proUrl; // public URL conUrl; // public String yes; // public String no; // } // // Path: src/main/java/org/votesmart/data/Measures.java // @XmlRootElement(name="measures") // public class Measures extends GeneralInfoBase { // // public ArrayList<Measure> measure; // // @XmlType(name="measure", namespace="measures") // public static class Measure { // public String measureId; // public String measureCode; // public String title; // public String outcome; // } // // }
import org.votesmart.api.*; import org.votesmart.data.Measure; import org.votesmart.data.Measures;
package org.votesmart.classes; /** * <pre> * Ballot Measure Class * * - Required * * - Multiple rows * * Measure.getMeasuresByYearState * This method returns a list of state ballot measures in a given year. * Input: year*, stateId* * Output: {@link Measures} * * This method returns a single Ballot Measure detail. * Input: measureId* * Output: {@link Measure} * * =========== EXAMPLE USAGE ================= * * // Ballot Measures * MeasureClass measureClass = new MeasureClass(); * * // Get measures in 2012 state election * Measures measures = measureClass.getMeasuresByYearState("2012", state.stateId); * * Measure measure = measureClass.getMeasure(measures.measure.get(0).measureId); * </pre> * */ public class MeasureClass extends ClassesBase { /** * Constructor for testing purposes. * * @param api */ public MeasureClass(VoteSmartAPI api) { super(api); } /** * Default Constructor */ public MeasureClass() throws VoteSmartException { super(); } /** * This method returns a list of state ballot measures in a given year. * * @param year * @param stateId * @return {@link Measures}: List of minimal measure information. */
// Path: src/main/java/org/votesmart/data/Measure.java // @XmlRootElement(name="measure") // public class Measure extends GeneralInfoBase { // public String measureId; // public String measureCode; // public String title; // public String outcome; // public String electionDate; // public String electionType; // public String source; // public URL url; // public String summary; // public URL summaryUrl; // public String measureText; // public URL textUrl; // public URL proUrl; // public URL conUrl; // public String yes; // public String no; // } // // Path: src/main/java/org/votesmart/data/Measures.java // @XmlRootElement(name="measures") // public class Measures extends GeneralInfoBase { // // public ArrayList<Measure> measure; // // @XmlType(name="measure", namespace="measures") // public static class Measure { // public String measureId; // public String measureCode; // public String title; // public String outcome; // } // // } // Path: src/main/java/org/votesmart/classes/MeasureClass.java import org.votesmart.api.*; import org.votesmart.data.Measure; import org.votesmart.data.Measures; package org.votesmart.classes; /** * <pre> * Ballot Measure Class * * - Required * * - Multiple rows * * Measure.getMeasuresByYearState * This method returns a list of state ballot measures in a given year. * Input: year*, stateId* * Output: {@link Measures} * * This method returns a single Ballot Measure detail. * Input: measureId* * Output: {@link Measure} * * =========== EXAMPLE USAGE ================= * * // Ballot Measures * MeasureClass measureClass = new MeasureClass(); * * // Get measures in 2012 state election * Measures measures = measureClass.getMeasuresByYearState("2012", state.stateId); * * Measure measure = measureClass.getMeasure(measures.measure.get(0).measureId); * </pre> * */ public class MeasureClass extends ClassesBase { /** * Constructor for testing purposes. * * @param api */ public MeasureClass(VoteSmartAPI api) { super(api); } /** * Default Constructor */ public MeasureClass() throws VoteSmartException { super(); } /** * This method returns a list of state ballot measures in a given year. * * @param year * @param stateId * @return {@link Measures}: List of minimal measure information. */
public Measures getMeasuresByYearState(String year, String stateId) throws VoteSmartException, VoteSmartErrorException {
karlnicholas/votesmart
src/main/java/org/votesmart/classes/MeasureClass.java
// Path: src/main/java/org/votesmart/data/Measure.java // @XmlRootElement(name="measure") // public class Measure extends GeneralInfoBase { // public String measureId; // public String measureCode; // public String title; // public String outcome; // public String electionDate; // public String electionType; // public String source; // public URL url; // public String summary; // public URL summaryUrl; // public String measureText; // public URL textUrl; // public URL proUrl; // public URL conUrl; // public String yes; // public String no; // } // // Path: src/main/java/org/votesmart/data/Measures.java // @XmlRootElement(name="measures") // public class Measures extends GeneralInfoBase { // // public ArrayList<Measure> measure; // // @XmlType(name="measure", namespace="measures") // public static class Measure { // public String measureId; // public String measureCode; // public String title; // public String outcome; // } // // }
import org.votesmart.api.*; import org.votesmart.data.Measure; import org.votesmart.data.Measures;
package org.votesmart.classes; /** * <pre> * Ballot Measure Class * * - Required * * - Multiple rows * * Measure.getMeasuresByYearState * This method returns a list of state ballot measures in a given year. * Input: year*, stateId* * Output: {@link Measures} * * This method returns a single Ballot Measure detail. * Input: measureId* * Output: {@link Measure} * * =========== EXAMPLE USAGE ================= * * // Ballot Measures * MeasureClass measureClass = new MeasureClass(); * * // Get measures in 2012 state election * Measures measures = measureClass.getMeasuresByYearState("2012", state.stateId); * * Measure measure = measureClass.getMeasure(measures.measure.get(0).measureId); * </pre> * */ public class MeasureClass extends ClassesBase { /** * Constructor for testing purposes. * * @param api */ public MeasureClass(VoteSmartAPI api) { super(api); } /** * Default Constructor */ public MeasureClass() throws VoteSmartException { super(); } /** * This method returns a list of state ballot measures in a given year. * * @param year * @param stateId * @return {@link Measures}: List of minimal measure information. */ public Measures getMeasuresByYearState(String year, String stateId) throws VoteSmartException, VoteSmartErrorException { return api.query("Measure.getMeasuresByYearState", new ArgMap("year", year, "stateId", stateId), Measures.class ); } /** * This method returns a single Ballot Measure detail. * * @param measureId * @return {@link Measure}: detail on single measure */
// Path: src/main/java/org/votesmart/data/Measure.java // @XmlRootElement(name="measure") // public class Measure extends GeneralInfoBase { // public String measureId; // public String measureCode; // public String title; // public String outcome; // public String electionDate; // public String electionType; // public String source; // public URL url; // public String summary; // public URL summaryUrl; // public String measureText; // public URL textUrl; // public URL proUrl; // public URL conUrl; // public String yes; // public String no; // } // // Path: src/main/java/org/votesmart/data/Measures.java // @XmlRootElement(name="measures") // public class Measures extends GeneralInfoBase { // // public ArrayList<Measure> measure; // // @XmlType(name="measure", namespace="measures") // public static class Measure { // public String measureId; // public String measureCode; // public String title; // public String outcome; // } // // } // Path: src/main/java/org/votesmart/classes/MeasureClass.java import org.votesmart.api.*; import org.votesmart.data.Measure; import org.votesmart.data.Measures; package org.votesmart.classes; /** * <pre> * Ballot Measure Class * * - Required * * - Multiple rows * * Measure.getMeasuresByYearState * This method returns a list of state ballot measures in a given year. * Input: year*, stateId* * Output: {@link Measures} * * This method returns a single Ballot Measure detail. * Input: measureId* * Output: {@link Measure} * * =========== EXAMPLE USAGE ================= * * // Ballot Measures * MeasureClass measureClass = new MeasureClass(); * * // Get measures in 2012 state election * Measures measures = measureClass.getMeasuresByYearState("2012", state.stateId); * * Measure measure = measureClass.getMeasure(measures.measure.get(0).measureId); * </pre> * */ public class MeasureClass extends ClassesBase { /** * Constructor for testing purposes. * * @param api */ public MeasureClass(VoteSmartAPI api) { super(api); } /** * Default Constructor */ public MeasureClass() throws VoteSmartException { super(); } /** * This method returns a list of state ballot measures in a given year. * * @param year * @param stateId * @return {@link Measures}: List of minimal measure information. */ public Measures getMeasuresByYearState(String year, String stateId) throws VoteSmartException, VoteSmartErrorException { return api.query("Measure.getMeasuresByYearState", new ArgMap("year", year, "stateId", stateId), Measures.class ); } /** * This method returns a single Ballot Measure detail. * * @param measureId * @return {@link Measure}: detail on single measure */
public Measure getMeasure(String measureId) throws VoteSmartException, VoteSmartErrorException {
karlnicholas/votesmart
src/main/java/org/votesmart/classes/ElectionClass.java
// Path: src/main/java/org/votesmart/data/Elections.java // @XmlRootElement(name="elections") // public class Elections extends GeneralInfoBase { // // public ArrayList<ElectionStage> election; // // @XmlType(name="election", namespace="elections") // public static class ElectionStage extends Election { // public ArrayList<Stage> stage; // // @XmlType(name="stage", namespace="elections.election") // public static class Stage { // public String stageId; // public String name; // public String stateId; // public String electionDate; // public String filingDeadline; // public String npatMailed; // } // } // } // // Path: src/main/java/org/votesmart/data/ElectionByZip.java // @XmlRootElement(name="elections") // public class ElectionByZip extends GeneralInfoBase { // public ArrayList<Election> election; // } // // Path: src/main/java/org/votesmart/data/StageCandidates.java // @XmlRootElement(name="stagecandidates") // public class StageCandidates extends GeneralInfoBase { // // public ArrayList<Election> election; // public ArrayList<Candidate> candidate; // // @XmlType(name="election", namespace="stagecandidates") // public static class Election { // public String electionId; // public String name; // public String stage; // public String stateId; // } // // @XmlType(name="candidate", namespace="stagecandidates") // public static class Candidate { // public String candidateId; // public String officeId; // public String district; // public String firstName; // public String middleName; // public String lastName; // public String suffix; // public String party; // public String status; // public String voteCount; // public String votePercent; // } // }
import org.votesmart.api.*; import org.votesmart.data.Elections; import org.votesmart.data.ElectionByZip; import org.votesmart.data.StageCandidates;
package org.votesmart.classes; /** * <pre> * Election Class * * * - Required * * - Multiple rows * * Election.getElection * This method grabs district basic election data according to electionId * Input: electionId* * Output: {@link Elections} * * Election.getElectionByYearState * This method grabs district basic election data according to year and stateid. * Input: year*, stateId(default: 'NA') * Output: {@link Elections} * * Election.getElectionByZip * This method grabs district basic election data according to zip code. * Input: zip5*, zip4(default: NULL), year(default: &gr;=current year * Output: {@link ElectionByZip} * * Election.getStageCandidates * This method grabs district basic election data according to electionId and stageId. Per state lists of a Presidential election are available by specifying the stateId. * Input: electionId*, stageId*, party (Default: ALL(NULL)), districtId (Default: All(NULL)), stateId (Default: election.stateId) * Output: {@link StageCandidates} * * ============ EXAMPLE USAGE ============== * * ElectionClass electionClass = new ElectionClass(); * * // look up 2012 elections * Elections elections = electionClass.getElectionByYearState("2012", state.stateId); * Elections.ElectionStage election = elections.election.get(0); * Elections.ElectionStage.Stage stage = elections.election.get(0).stage.get(0); * * // a specific election * elections = electionClass.getElection(election.electionId); * election = elections.election.get(0); * </pre> * */ public class ElectionClass extends ClassesBase { /** * Constructor for testing purposes. * * @param api */ public ElectionClass(VoteSmartAPI api) { super(api); } /** * Default Constructor */ public ElectionClass() throws VoteSmartException { super(); } /** * This method grabs district IDs according to the office and state. * * @param electionId * @return {@link Elections}: */
// Path: src/main/java/org/votesmart/data/Elections.java // @XmlRootElement(name="elections") // public class Elections extends GeneralInfoBase { // // public ArrayList<ElectionStage> election; // // @XmlType(name="election", namespace="elections") // public static class ElectionStage extends Election { // public ArrayList<Stage> stage; // // @XmlType(name="stage", namespace="elections.election") // public static class Stage { // public String stageId; // public String name; // public String stateId; // public String electionDate; // public String filingDeadline; // public String npatMailed; // } // } // } // // Path: src/main/java/org/votesmart/data/ElectionByZip.java // @XmlRootElement(name="elections") // public class ElectionByZip extends GeneralInfoBase { // public ArrayList<Election> election; // } // // Path: src/main/java/org/votesmart/data/StageCandidates.java // @XmlRootElement(name="stagecandidates") // public class StageCandidates extends GeneralInfoBase { // // public ArrayList<Election> election; // public ArrayList<Candidate> candidate; // // @XmlType(name="election", namespace="stagecandidates") // public static class Election { // public String electionId; // public String name; // public String stage; // public String stateId; // } // // @XmlType(name="candidate", namespace="stagecandidates") // public static class Candidate { // public String candidateId; // public String officeId; // public String district; // public String firstName; // public String middleName; // public String lastName; // public String suffix; // public String party; // public String status; // public String voteCount; // public String votePercent; // } // } // Path: src/main/java/org/votesmart/classes/ElectionClass.java import org.votesmart.api.*; import org.votesmart.data.Elections; import org.votesmart.data.ElectionByZip; import org.votesmart.data.StageCandidates; package org.votesmart.classes; /** * <pre> * Election Class * * * - Required * * - Multiple rows * * Election.getElection * This method grabs district basic election data according to electionId * Input: electionId* * Output: {@link Elections} * * Election.getElectionByYearState * This method grabs district basic election data according to year and stateid. * Input: year*, stateId(default: 'NA') * Output: {@link Elections} * * Election.getElectionByZip * This method grabs district basic election data according to zip code. * Input: zip5*, zip4(default: NULL), year(default: &gr;=current year * Output: {@link ElectionByZip} * * Election.getStageCandidates * This method grabs district basic election data according to electionId and stageId. Per state lists of a Presidential election are available by specifying the stateId. * Input: electionId*, stageId*, party (Default: ALL(NULL)), districtId (Default: All(NULL)), stateId (Default: election.stateId) * Output: {@link StageCandidates} * * ============ EXAMPLE USAGE ============== * * ElectionClass electionClass = new ElectionClass(); * * // look up 2012 elections * Elections elections = electionClass.getElectionByYearState("2012", state.stateId); * Elections.ElectionStage election = elections.election.get(0); * Elections.ElectionStage.Stage stage = elections.election.get(0).stage.get(0); * * // a specific election * elections = electionClass.getElection(election.electionId); * election = elections.election.get(0); * </pre> * */ public class ElectionClass extends ClassesBase { /** * Constructor for testing purposes. * * @param api */ public ElectionClass(VoteSmartAPI api) { super(api); } /** * Default Constructor */ public ElectionClass() throws VoteSmartException { super(); } /** * This method grabs district IDs according to the office and state. * * @param electionId * @return {@link Elections}: */
public Elections getElection(String electionId) throws VoteSmartException, VoteSmartErrorException {
karlnicholas/votesmart
src/main/java/org/votesmart/classes/ElectionClass.java
// Path: src/main/java/org/votesmart/data/Elections.java // @XmlRootElement(name="elections") // public class Elections extends GeneralInfoBase { // // public ArrayList<ElectionStage> election; // // @XmlType(name="election", namespace="elections") // public static class ElectionStage extends Election { // public ArrayList<Stage> stage; // // @XmlType(name="stage", namespace="elections.election") // public static class Stage { // public String stageId; // public String name; // public String stateId; // public String electionDate; // public String filingDeadline; // public String npatMailed; // } // } // } // // Path: src/main/java/org/votesmart/data/ElectionByZip.java // @XmlRootElement(name="elections") // public class ElectionByZip extends GeneralInfoBase { // public ArrayList<Election> election; // } // // Path: src/main/java/org/votesmart/data/StageCandidates.java // @XmlRootElement(name="stagecandidates") // public class StageCandidates extends GeneralInfoBase { // // public ArrayList<Election> election; // public ArrayList<Candidate> candidate; // // @XmlType(name="election", namespace="stagecandidates") // public static class Election { // public String electionId; // public String name; // public String stage; // public String stateId; // } // // @XmlType(name="candidate", namespace="stagecandidates") // public static class Candidate { // public String candidateId; // public String officeId; // public String district; // public String firstName; // public String middleName; // public String lastName; // public String suffix; // public String party; // public String status; // public String voteCount; // public String votePercent; // } // }
import org.votesmart.api.*; import org.votesmart.data.Elections; import org.votesmart.data.ElectionByZip; import org.votesmart.data.StageCandidates;
package org.votesmart.classes; /** * <pre> * Election Class * * * - Required * * - Multiple rows * * Election.getElection * This method grabs district basic election data according to electionId * Input: electionId* * Output: {@link Elections} * * Election.getElectionByYearState * This method grabs district basic election data according to year and stateid. * Input: year*, stateId(default: 'NA') * Output: {@link Elections} * * Election.getElectionByZip * This method grabs district basic election data according to zip code. * Input: zip5*, zip4(default: NULL), year(default: &gr;=current year * Output: {@link ElectionByZip} * * Election.getStageCandidates * This method grabs district basic election data according to electionId and stageId. Per state lists of a Presidential election are available by specifying the stateId. * Input: electionId*, stageId*, party (Default: ALL(NULL)), districtId (Default: All(NULL)), stateId (Default: election.stateId) * Output: {@link StageCandidates} * * ============ EXAMPLE USAGE ============== * * ElectionClass electionClass = new ElectionClass(); * * // look up 2012 elections * Elections elections = electionClass.getElectionByYearState("2012", state.stateId); * Elections.ElectionStage election = elections.election.get(0); * Elections.ElectionStage.Stage stage = elections.election.get(0).stage.get(0); * * // a specific election * elections = electionClass.getElection(election.electionId); * election = elections.election.get(0); * </pre> * */ public class ElectionClass extends ClassesBase { /** * Constructor for testing purposes. * * @param api */ public ElectionClass(VoteSmartAPI api) { super(api); } /** * Default Constructor */ public ElectionClass() throws VoteSmartException { super(); } /** * This method grabs district IDs according to the office and state. * * @param electionId * @return {@link Elections}: */ public Elections getElection(String electionId) throws VoteSmartException, VoteSmartErrorException { return api.query("Election.getElection", new ArgMap("electionId", electionId), Elections.class ); } /** * This method grabs district basic election data according to year and stateid. * * @param year * @return {@link Elections} */ public Elections getElectionByYearState(String year) throws VoteSmartException, VoteSmartErrorException { return api.query("Election.getElectionByYearState", new ArgMap("year", year), Elections.class ); } /** * This method grabs district basic election data according to year and stateid. * * @param year * @param stateId * @return {@link Elections}: */ public Elections getElectionByYearState(String year, String stateId) throws VoteSmartException, VoteSmartErrorException { return api.query("Election.getElectionByYearState", new ArgMap("year", year, "stateId", stateId), Elections.class ); } /** * This method grabs district basic election data according to zip code. * * @param zip5 * @return {@link ElectionByZip}: */
// Path: src/main/java/org/votesmart/data/Elections.java // @XmlRootElement(name="elections") // public class Elections extends GeneralInfoBase { // // public ArrayList<ElectionStage> election; // // @XmlType(name="election", namespace="elections") // public static class ElectionStage extends Election { // public ArrayList<Stage> stage; // // @XmlType(name="stage", namespace="elections.election") // public static class Stage { // public String stageId; // public String name; // public String stateId; // public String electionDate; // public String filingDeadline; // public String npatMailed; // } // } // } // // Path: src/main/java/org/votesmart/data/ElectionByZip.java // @XmlRootElement(name="elections") // public class ElectionByZip extends GeneralInfoBase { // public ArrayList<Election> election; // } // // Path: src/main/java/org/votesmart/data/StageCandidates.java // @XmlRootElement(name="stagecandidates") // public class StageCandidates extends GeneralInfoBase { // // public ArrayList<Election> election; // public ArrayList<Candidate> candidate; // // @XmlType(name="election", namespace="stagecandidates") // public static class Election { // public String electionId; // public String name; // public String stage; // public String stateId; // } // // @XmlType(name="candidate", namespace="stagecandidates") // public static class Candidate { // public String candidateId; // public String officeId; // public String district; // public String firstName; // public String middleName; // public String lastName; // public String suffix; // public String party; // public String status; // public String voteCount; // public String votePercent; // } // } // Path: src/main/java/org/votesmart/classes/ElectionClass.java import org.votesmart.api.*; import org.votesmart.data.Elections; import org.votesmart.data.ElectionByZip; import org.votesmart.data.StageCandidates; package org.votesmart.classes; /** * <pre> * Election Class * * * - Required * * - Multiple rows * * Election.getElection * This method grabs district basic election data according to electionId * Input: electionId* * Output: {@link Elections} * * Election.getElectionByYearState * This method grabs district basic election data according to year and stateid. * Input: year*, stateId(default: 'NA') * Output: {@link Elections} * * Election.getElectionByZip * This method grabs district basic election data according to zip code. * Input: zip5*, zip4(default: NULL), year(default: &gr;=current year * Output: {@link ElectionByZip} * * Election.getStageCandidates * This method grabs district basic election data according to electionId and stageId. Per state lists of a Presidential election are available by specifying the stateId. * Input: electionId*, stageId*, party (Default: ALL(NULL)), districtId (Default: All(NULL)), stateId (Default: election.stateId) * Output: {@link StageCandidates} * * ============ EXAMPLE USAGE ============== * * ElectionClass electionClass = new ElectionClass(); * * // look up 2012 elections * Elections elections = electionClass.getElectionByYearState("2012", state.stateId); * Elections.ElectionStage election = elections.election.get(0); * Elections.ElectionStage.Stage stage = elections.election.get(0).stage.get(0); * * // a specific election * elections = electionClass.getElection(election.electionId); * election = elections.election.get(0); * </pre> * */ public class ElectionClass extends ClassesBase { /** * Constructor for testing purposes. * * @param api */ public ElectionClass(VoteSmartAPI api) { super(api); } /** * Default Constructor */ public ElectionClass() throws VoteSmartException { super(); } /** * This method grabs district IDs according to the office and state. * * @param electionId * @return {@link Elections}: */ public Elections getElection(String electionId) throws VoteSmartException, VoteSmartErrorException { return api.query("Election.getElection", new ArgMap("electionId", electionId), Elections.class ); } /** * This method grabs district basic election data according to year and stateid. * * @param year * @return {@link Elections} */ public Elections getElectionByYearState(String year) throws VoteSmartException, VoteSmartErrorException { return api.query("Election.getElectionByYearState", new ArgMap("year", year), Elections.class ); } /** * This method grabs district basic election data according to year and stateid. * * @param year * @param stateId * @return {@link Elections}: */ public Elections getElectionByYearState(String year, String stateId) throws VoteSmartException, VoteSmartErrorException { return api.query("Election.getElectionByYearState", new ArgMap("year", year, "stateId", stateId), Elections.class ); } /** * This method grabs district basic election data according to zip code. * * @param zip5 * @return {@link ElectionByZip}: */
public ElectionByZip getElectionByZip(String zip5) throws VoteSmartException, VoteSmartErrorException {
karlnicholas/votesmart
src/main/java/org/votesmart/classes/OfficeClass.java
// Path: src/main/java/org/votesmart/data/Branches.java // @XmlRootElement(name="branches") // public class Branches extends GeneralInfoBase { // // public ArrayList<Branch> branch; // // @XmlType(name="branch", namespace="branches") // public static class Branch { // public String officeBranchId; // public String name; // } // // } // // Path: src/main/java/org/votesmart/data/Levels.java // @XmlRootElement(name="levels") // public class Levels extends GeneralInfoBase { // // public ArrayList<Level> level; // // @XmlType(name="level", namespace="levels") // public static class Level { // public String officeLevelId; // public String name; // } // // } // // Path: src/main/java/org/votesmart/data/OfficeTypes.java // @XmlRootElement(name="officeTypes") // public class OfficeTypes extends GeneralInfoBase { // public ArrayList<Type> type; // // @XmlType(name="type", namespace="office") // public static class Type { // public String officeTypeId; // public String officeLevelId; // public String officeBranchId; // public String name; // } // } // // Path: src/main/java/org/votesmart/data/Offices.java // @XmlRootElement(name="offices") // public class Offices extends GeneralInfoBase { // public ArrayList<Office> office; // // @XmlType(name="office", namespace="offices") // public static class Office { // public String officeId; // public String officeTypeId; // public String officeLevelId; // public String officeBranchId; // public String name; // public String title; // public String shortTitle; // } // // }
import org.votesmart.api.*; import org.votesmart.data.Branches; import org.votesmart.data.Levels; import org.votesmart.data.OfficeTypes; import org.votesmart.data.Offices;
package org.votesmart.classes; /** * <pre> * Office Class * * Office.getTypes * This method dumps all office types we keep track of * Input: none * Output: {@link OfficeTypes} * * Office.getBranches * This method dumps the branches of government and their IDs * Input: none * Output: {@link Branches} * * Office.getLevels * This method dumps the levels of government and their IDs * Input: none * Output: {@link Levels} * * Office.getOfficesByType * This method dumps offices we keep track of according to type. * Input: officeTypeId* * Output: {@link Offices} * * Office.getOfficesByLevel * This method dumps offices we keep track of according to level. * Input: levelId* * Output: {@link Offices} * * Office.getOfficesByTypeLevel * This method dumps offices we keep track of according to type and level. * Input: officeTypeId*, levelId* * Output: {@link Offices} * * Office.getOfficesByBranchLevel * This method dumps offices we keep track of according to branch and level. * Input: branchId*, levelId* * Output: {@link Offices} * * ============== EXAMPLE USAGE ============ * * // Get general Information about offices * OfficeClass officeClass = new OfficeClass(); * * // get Office.getBranches * Branches branches = officeClass.getBranches(); * Branches.Branch officeBranch = branches.branch.get(1); * * // Office.getTypes * OfficeTypes officeTypes = officeClass.getTypes(); * OfficeTypes.Type officeType = officeTypes.type.get(5); * * // Office.getLevels * Levels levels = officeClass.getLevels(); * Levels.Level officeLevel = levels.level.get(1); * </pre> * */ public class OfficeClass extends ClassesBase { /** * Constructor for testing purposes. * * @param api */ public OfficeClass(VoteSmartAPI api) { super(api); } /** * Default Constructor */ public OfficeClass() throws VoteSmartException { super(); } /** * This method dumps all office types we keep track of. * * @return {@link OfficeTypes}: */
// Path: src/main/java/org/votesmart/data/Branches.java // @XmlRootElement(name="branches") // public class Branches extends GeneralInfoBase { // // public ArrayList<Branch> branch; // // @XmlType(name="branch", namespace="branches") // public static class Branch { // public String officeBranchId; // public String name; // } // // } // // Path: src/main/java/org/votesmart/data/Levels.java // @XmlRootElement(name="levels") // public class Levels extends GeneralInfoBase { // // public ArrayList<Level> level; // // @XmlType(name="level", namespace="levels") // public static class Level { // public String officeLevelId; // public String name; // } // // } // // Path: src/main/java/org/votesmart/data/OfficeTypes.java // @XmlRootElement(name="officeTypes") // public class OfficeTypes extends GeneralInfoBase { // public ArrayList<Type> type; // // @XmlType(name="type", namespace="office") // public static class Type { // public String officeTypeId; // public String officeLevelId; // public String officeBranchId; // public String name; // } // } // // Path: src/main/java/org/votesmart/data/Offices.java // @XmlRootElement(name="offices") // public class Offices extends GeneralInfoBase { // public ArrayList<Office> office; // // @XmlType(name="office", namespace="offices") // public static class Office { // public String officeId; // public String officeTypeId; // public String officeLevelId; // public String officeBranchId; // public String name; // public String title; // public String shortTitle; // } // // } // Path: src/main/java/org/votesmart/classes/OfficeClass.java import org.votesmart.api.*; import org.votesmart.data.Branches; import org.votesmart.data.Levels; import org.votesmart.data.OfficeTypes; import org.votesmart.data.Offices; package org.votesmart.classes; /** * <pre> * Office Class * * Office.getTypes * This method dumps all office types we keep track of * Input: none * Output: {@link OfficeTypes} * * Office.getBranches * This method dumps the branches of government and their IDs * Input: none * Output: {@link Branches} * * Office.getLevels * This method dumps the levels of government and their IDs * Input: none * Output: {@link Levels} * * Office.getOfficesByType * This method dumps offices we keep track of according to type. * Input: officeTypeId* * Output: {@link Offices} * * Office.getOfficesByLevel * This method dumps offices we keep track of according to level. * Input: levelId* * Output: {@link Offices} * * Office.getOfficesByTypeLevel * This method dumps offices we keep track of according to type and level. * Input: officeTypeId*, levelId* * Output: {@link Offices} * * Office.getOfficesByBranchLevel * This method dumps offices we keep track of according to branch and level. * Input: branchId*, levelId* * Output: {@link Offices} * * ============== EXAMPLE USAGE ============ * * // Get general Information about offices * OfficeClass officeClass = new OfficeClass(); * * // get Office.getBranches * Branches branches = officeClass.getBranches(); * Branches.Branch officeBranch = branches.branch.get(1); * * // Office.getTypes * OfficeTypes officeTypes = officeClass.getTypes(); * OfficeTypes.Type officeType = officeTypes.type.get(5); * * // Office.getLevels * Levels levels = officeClass.getLevels(); * Levels.Level officeLevel = levels.level.get(1); * </pre> * */ public class OfficeClass extends ClassesBase { /** * Constructor for testing purposes. * * @param api */ public OfficeClass(VoteSmartAPI api) { super(api); } /** * Default Constructor */ public OfficeClass() throws VoteSmartException { super(); } /** * This method dumps all office types we keep track of. * * @return {@link OfficeTypes}: */
public OfficeTypes getTypes() throws VoteSmartException, VoteSmartErrorException {
karlnicholas/votesmart
src/main/java/org/votesmart/classes/OfficeClass.java
// Path: src/main/java/org/votesmart/data/Branches.java // @XmlRootElement(name="branches") // public class Branches extends GeneralInfoBase { // // public ArrayList<Branch> branch; // // @XmlType(name="branch", namespace="branches") // public static class Branch { // public String officeBranchId; // public String name; // } // // } // // Path: src/main/java/org/votesmart/data/Levels.java // @XmlRootElement(name="levels") // public class Levels extends GeneralInfoBase { // // public ArrayList<Level> level; // // @XmlType(name="level", namespace="levels") // public static class Level { // public String officeLevelId; // public String name; // } // // } // // Path: src/main/java/org/votesmart/data/OfficeTypes.java // @XmlRootElement(name="officeTypes") // public class OfficeTypes extends GeneralInfoBase { // public ArrayList<Type> type; // // @XmlType(name="type", namespace="office") // public static class Type { // public String officeTypeId; // public String officeLevelId; // public String officeBranchId; // public String name; // } // } // // Path: src/main/java/org/votesmart/data/Offices.java // @XmlRootElement(name="offices") // public class Offices extends GeneralInfoBase { // public ArrayList<Office> office; // // @XmlType(name="office", namespace="offices") // public static class Office { // public String officeId; // public String officeTypeId; // public String officeLevelId; // public String officeBranchId; // public String name; // public String title; // public String shortTitle; // } // // }
import org.votesmart.api.*; import org.votesmart.data.Branches; import org.votesmart.data.Levels; import org.votesmart.data.OfficeTypes; import org.votesmart.data.Offices;
package org.votesmart.classes; /** * <pre> * Office Class * * Office.getTypes * This method dumps all office types we keep track of * Input: none * Output: {@link OfficeTypes} * * Office.getBranches * This method dumps the branches of government and their IDs * Input: none * Output: {@link Branches} * * Office.getLevels * This method dumps the levels of government and their IDs * Input: none * Output: {@link Levels} * * Office.getOfficesByType * This method dumps offices we keep track of according to type. * Input: officeTypeId* * Output: {@link Offices} * * Office.getOfficesByLevel * This method dumps offices we keep track of according to level. * Input: levelId* * Output: {@link Offices} * * Office.getOfficesByTypeLevel * This method dumps offices we keep track of according to type and level. * Input: officeTypeId*, levelId* * Output: {@link Offices} * * Office.getOfficesByBranchLevel * This method dumps offices we keep track of according to branch and level. * Input: branchId*, levelId* * Output: {@link Offices} * * ============== EXAMPLE USAGE ============ * * // Get general Information about offices * OfficeClass officeClass = new OfficeClass(); * * // get Office.getBranches * Branches branches = officeClass.getBranches(); * Branches.Branch officeBranch = branches.branch.get(1); * * // Office.getTypes * OfficeTypes officeTypes = officeClass.getTypes(); * OfficeTypes.Type officeType = officeTypes.type.get(5); * * // Office.getLevels * Levels levels = officeClass.getLevels(); * Levels.Level officeLevel = levels.level.get(1); * </pre> * */ public class OfficeClass extends ClassesBase { /** * Constructor for testing purposes. * * @param api */ public OfficeClass(VoteSmartAPI api) { super(api); } /** * Default Constructor */ public OfficeClass() throws VoteSmartException { super(); } /** * This method dumps all office types we keep track of. * * @return {@link OfficeTypes}: */ public OfficeTypes getTypes() throws VoteSmartException, VoteSmartErrorException { return api.query("Office.getTypes", null, OfficeTypes.class ); } /** * This method dumps the branches of government and their IDs. * * @return {@link Branches}: */
// Path: src/main/java/org/votesmart/data/Branches.java // @XmlRootElement(name="branches") // public class Branches extends GeneralInfoBase { // // public ArrayList<Branch> branch; // // @XmlType(name="branch", namespace="branches") // public static class Branch { // public String officeBranchId; // public String name; // } // // } // // Path: src/main/java/org/votesmart/data/Levels.java // @XmlRootElement(name="levels") // public class Levels extends GeneralInfoBase { // // public ArrayList<Level> level; // // @XmlType(name="level", namespace="levels") // public static class Level { // public String officeLevelId; // public String name; // } // // } // // Path: src/main/java/org/votesmart/data/OfficeTypes.java // @XmlRootElement(name="officeTypes") // public class OfficeTypes extends GeneralInfoBase { // public ArrayList<Type> type; // // @XmlType(name="type", namespace="office") // public static class Type { // public String officeTypeId; // public String officeLevelId; // public String officeBranchId; // public String name; // } // } // // Path: src/main/java/org/votesmart/data/Offices.java // @XmlRootElement(name="offices") // public class Offices extends GeneralInfoBase { // public ArrayList<Office> office; // // @XmlType(name="office", namespace="offices") // public static class Office { // public String officeId; // public String officeTypeId; // public String officeLevelId; // public String officeBranchId; // public String name; // public String title; // public String shortTitle; // } // // } // Path: src/main/java/org/votesmart/classes/OfficeClass.java import org.votesmart.api.*; import org.votesmart.data.Branches; import org.votesmart.data.Levels; import org.votesmart.data.OfficeTypes; import org.votesmart.data.Offices; package org.votesmart.classes; /** * <pre> * Office Class * * Office.getTypes * This method dumps all office types we keep track of * Input: none * Output: {@link OfficeTypes} * * Office.getBranches * This method dumps the branches of government and their IDs * Input: none * Output: {@link Branches} * * Office.getLevels * This method dumps the levels of government and their IDs * Input: none * Output: {@link Levels} * * Office.getOfficesByType * This method dumps offices we keep track of according to type. * Input: officeTypeId* * Output: {@link Offices} * * Office.getOfficesByLevel * This method dumps offices we keep track of according to level. * Input: levelId* * Output: {@link Offices} * * Office.getOfficesByTypeLevel * This method dumps offices we keep track of according to type and level. * Input: officeTypeId*, levelId* * Output: {@link Offices} * * Office.getOfficesByBranchLevel * This method dumps offices we keep track of according to branch and level. * Input: branchId*, levelId* * Output: {@link Offices} * * ============== EXAMPLE USAGE ============ * * // Get general Information about offices * OfficeClass officeClass = new OfficeClass(); * * // get Office.getBranches * Branches branches = officeClass.getBranches(); * Branches.Branch officeBranch = branches.branch.get(1); * * // Office.getTypes * OfficeTypes officeTypes = officeClass.getTypes(); * OfficeTypes.Type officeType = officeTypes.type.get(5); * * // Office.getLevels * Levels levels = officeClass.getLevels(); * Levels.Level officeLevel = levels.level.get(1); * </pre> * */ public class OfficeClass extends ClassesBase { /** * Constructor for testing purposes. * * @param api */ public OfficeClass(VoteSmartAPI api) { super(api); } /** * Default Constructor */ public OfficeClass() throws VoteSmartException { super(); } /** * This method dumps all office types we keep track of. * * @return {@link OfficeTypes}: */ public OfficeTypes getTypes() throws VoteSmartException, VoteSmartErrorException { return api.query("Office.getTypes", null, OfficeTypes.class ); } /** * This method dumps the branches of government and their IDs. * * @return {@link Branches}: */
public Branches getBranches() throws VoteSmartException, VoteSmartErrorException {
karlnicholas/votesmart
src/main/java/org/votesmart/classes/OfficeClass.java
// Path: src/main/java/org/votesmart/data/Branches.java // @XmlRootElement(name="branches") // public class Branches extends GeneralInfoBase { // // public ArrayList<Branch> branch; // // @XmlType(name="branch", namespace="branches") // public static class Branch { // public String officeBranchId; // public String name; // } // // } // // Path: src/main/java/org/votesmart/data/Levels.java // @XmlRootElement(name="levels") // public class Levels extends GeneralInfoBase { // // public ArrayList<Level> level; // // @XmlType(name="level", namespace="levels") // public static class Level { // public String officeLevelId; // public String name; // } // // } // // Path: src/main/java/org/votesmart/data/OfficeTypes.java // @XmlRootElement(name="officeTypes") // public class OfficeTypes extends GeneralInfoBase { // public ArrayList<Type> type; // // @XmlType(name="type", namespace="office") // public static class Type { // public String officeTypeId; // public String officeLevelId; // public String officeBranchId; // public String name; // } // } // // Path: src/main/java/org/votesmart/data/Offices.java // @XmlRootElement(name="offices") // public class Offices extends GeneralInfoBase { // public ArrayList<Office> office; // // @XmlType(name="office", namespace="offices") // public static class Office { // public String officeId; // public String officeTypeId; // public String officeLevelId; // public String officeBranchId; // public String name; // public String title; // public String shortTitle; // } // // }
import org.votesmart.api.*; import org.votesmart.data.Branches; import org.votesmart.data.Levels; import org.votesmart.data.OfficeTypes; import org.votesmart.data.Offices;
package org.votesmart.classes; /** * <pre> * Office Class * * Office.getTypes * This method dumps all office types we keep track of * Input: none * Output: {@link OfficeTypes} * * Office.getBranches * This method dumps the branches of government and their IDs * Input: none * Output: {@link Branches} * * Office.getLevels * This method dumps the levels of government and their IDs * Input: none * Output: {@link Levels} * * Office.getOfficesByType * This method dumps offices we keep track of according to type. * Input: officeTypeId* * Output: {@link Offices} * * Office.getOfficesByLevel * This method dumps offices we keep track of according to level. * Input: levelId* * Output: {@link Offices} * * Office.getOfficesByTypeLevel * This method dumps offices we keep track of according to type and level. * Input: officeTypeId*, levelId* * Output: {@link Offices} * * Office.getOfficesByBranchLevel * This method dumps offices we keep track of according to branch and level. * Input: branchId*, levelId* * Output: {@link Offices} * * ============== EXAMPLE USAGE ============ * * // Get general Information about offices * OfficeClass officeClass = new OfficeClass(); * * // get Office.getBranches * Branches branches = officeClass.getBranches(); * Branches.Branch officeBranch = branches.branch.get(1); * * // Office.getTypes * OfficeTypes officeTypes = officeClass.getTypes(); * OfficeTypes.Type officeType = officeTypes.type.get(5); * * // Office.getLevels * Levels levels = officeClass.getLevels(); * Levels.Level officeLevel = levels.level.get(1); * </pre> * */ public class OfficeClass extends ClassesBase { /** * Constructor for testing purposes. * * @param api */ public OfficeClass(VoteSmartAPI api) { super(api); } /** * Default Constructor */ public OfficeClass() throws VoteSmartException { super(); } /** * This method dumps all office types we keep track of. * * @return {@link OfficeTypes}: */ public OfficeTypes getTypes() throws VoteSmartException, VoteSmartErrorException { return api.query("Office.getTypes", null, OfficeTypes.class ); } /** * This method dumps the branches of government and their IDs. * * @return {@link Branches}: */ public Branches getBranches() throws VoteSmartException, VoteSmartErrorException { return api.query("Office.getBranches", null, Branches.class ); } /** * This method dumps the levels of government and their IDs. * * @return {@link Levels}: */
// Path: src/main/java/org/votesmart/data/Branches.java // @XmlRootElement(name="branches") // public class Branches extends GeneralInfoBase { // // public ArrayList<Branch> branch; // // @XmlType(name="branch", namespace="branches") // public static class Branch { // public String officeBranchId; // public String name; // } // // } // // Path: src/main/java/org/votesmart/data/Levels.java // @XmlRootElement(name="levels") // public class Levels extends GeneralInfoBase { // // public ArrayList<Level> level; // // @XmlType(name="level", namespace="levels") // public static class Level { // public String officeLevelId; // public String name; // } // // } // // Path: src/main/java/org/votesmart/data/OfficeTypes.java // @XmlRootElement(name="officeTypes") // public class OfficeTypes extends GeneralInfoBase { // public ArrayList<Type> type; // // @XmlType(name="type", namespace="office") // public static class Type { // public String officeTypeId; // public String officeLevelId; // public String officeBranchId; // public String name; // } // } // // Path: src/main/java/org/votesmart/data/Offices.java // @XmlRootElement(name="offices") // public class Offices extends GeneralInfoBase { // public ArrayList<Office> office; // // @XmlType(name="office", namespace="offices") // public static class Office { // public String officeId; // public String officeTypeId; // public String officeLevelId; // public String officeBranchId; // public String name; // public String title; // public String shortTitle; // } // // } // Path: src/main/java/org/votesmart/classes/OfficeClass.java import org.votesmart.api.*; import org.votesmart.data.Branches; import org.votesmart.data.Levels; import org.votesmart.data.OfficeTypes; import org.votesmart.data.Offices; package org.votesmart.classes; /** * <pre> * Office Class * * Office.getTypes * This method dumps all office types we keep track of * Input: none * Output: {@link OfficeTypes} * * Office.getBranches * This method dumps the branches of government and their IDs * Input: none * Output: {@link Branches} * * Office.getLevels * This method dumps the levels of government and their IDs * Input: none * Output: {@link Levels} * * Office.getOfficesByType * This method dumps offices we keep track of according to type. * Input: officeTypeId* * Output: {@link Offices} * * Office.getOfficesByLevel * This method dumps offices we keep track of according to level. * Input: levelId* * Output: {@link Offices} * * Office.getOfficesByTypeLevel * This method dumps offices we keep track of according to type and level. * Input: officeTypeId*, levelId* * Output: {@link Offices} * * Office.getOfficesByBranchLevel * This method dumps offices we keep track of according to branch and level. * Input: branchId*, levelId* * Output: {@link Offices} * * ============== EXAMPLE USAGE ============ * * // Get general Information about offices * OfficeClass officeClass = new OfficeClass(); * * // get Office.getBranches * Branches branches = officeClass.getBranches(); * Branches.Branch officeBranch = branches.branch.get(1); * * // Office.getTypes * OfficeTypes officeTypes = officeClass.getTypes(); * OfficeTypes.Type officeType = officeTypes.type.get(5); * * // Office.getLevels * Levels levels = officeClass.getLevels(); * Levels.Level officeLevel = levels.level.get(1); * </pre> * */ public class OfficeClass extends ClassesBase { /** * Constructor for testing purposes. * * @param api */ public OfficeClass(VoteSmartAPI api) { super(api); } /** * Default Constructor */ public OfficeClass() throws VoteSmartException { super(); } /** * This method dumps all office types we keep track of. * * @return {@link OfficeTypes}: */ public OfficeTypes getTypes() throws VoteSmartException, VoteSmartErrorException { return api.query("Office.getTypes", null, OfficeTypes.class ); } /** * This method dumps the branches of government and their IDs. * * @return {@link Branches}: */ public Branches getBranches() throws VoteSmartException, VoteSmartErrorException { return api.query("Office.getBranches", null, Branches.class ); } /** * This method dumps the levels of government and their IDs. * * @return {@link Levels}: */
public Levels getLevels() throws VoteSmartException, VoteSmartErrorException {