text
stringlengths 10
2.72M
|
|---|
/*
* This file is part of Gradoop.
*
* Gradoop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Gradoop is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Gradoop. If not, see <http://www.gnu.org/licenses/>.
*/
package de.scads.gradoop_service.server;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import javax.annotation.PostConstruct;
import javax.servlet.ServletContext;
import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.MatrixParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.commons.lang3.StringUtils;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.JoinFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.operators.MapOperator;
import org.apache.flink.api.java.tuple.Tuple2;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;
import org.gradoop.common.model.impl.id.GradoopId;
import org.gradoop.common.model.impl.pojo.Edge;
import org.gradoop.common.model.impl.pojo.Vertex;
import org.gradoop.flink.model.api.epgm.GraphCollection;
import org.gradoop.flink.model.api.epgm.LogicalGraph;
import org.gradoop.flink.model.impl.functions.epgm.Id;
import org.gradoop.flink.model.impl.operators.grouping.GroupingStrategy;
import org.gradoop.flink.model.impl.operators.matching.common.MatchStrategy;
import org.gradoop.flink.model.impl.operators.matching.common.statistics.GraphStatistics;
import org.gradoop.flink.util.GradoopFlinkConfig;
import org.gradoop.gretl.graph.operations.SchemaGraph;
import org.gradoop.gretl.graph.operations.expand.ExpandGraph;
import org.uni_leipzig.biggr.builder.GradoopFlowBuilder;
import org.uni_leipzig.biggr.builder.pojo.GradoopOperatorFlow;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import de.scads.gradoop_service.server.helper.FileUploadHelper;
import de.scads.gradoop_service.server.helper.GraphHelper;
import de.scads.gradoop_service.server.helper.MetaDataHelper;
import de.scads.gradoop_service.server.helper.PatternMatchingHelper;
import de.scads.gradoop_service.server.helper.RDFGraphHelper;
import de.scads.gradoop_service.server.helper.ServiceHelper;
import de.scads.gradoop_service.server.helper.clustering.ClusteringHelper;
import de.scads.gradoop_service.server.helper.edge_fusion.EdgeFusionHelper;
import de.scads.gradoop_service.server.helper.filtering.FilteringHelper;
import de.scads.gradoop_service.server.helper.gelly.GellyHelper;
import de.scads.gradoop_service.server.helper.grouping.GroupingHelper;
import de.scads.gradoop_service.server.helper.linking.LinkingHelper;
import de.scads.gradoop_service.server.helper.vertex_fusion.CountValues;
import de.scads.gradoop_service.server.helper.vertex_fusion.VertexFusionOperator;
import de.scads.gradoop_service.server.sampling.PageRankSampling;
import de.scads.gradoop_service.server.sampling.RandomEdgeSampling;
/**
* Handles REST requests to the server.
*/
@Path("")
public class RequestHandler {
@Context
private ServletContext context;
@PostConstruct
public void init() {
if (context != null && "true".equals(context.getInitParameter("local.exec"))) {
ServiceHelper.setLocalExecution();
}
}
/**
* Creates a list of all available databases from the file structure under the /data/ folder.
*
* @return List of folders (databases) under the /data/ folder.
*/
@GET
@Path("/databases")
@Produces("application/json;charset=utf-8")
public Response getDatabases() throws IOException, URISyntaxException {
JSONArray jsonArray = new JSONArray();
String[] databases = GraphHelper.getExistingGraphs(context);
Arrays.sort(databases);
// return the found databases to the client
for (String database : databases) {
jsonArray.put(database);
}
return Response.ok(jsonArray.toString()).build();
}
/**
* Creates a list of all available workflows from the file structure under the /workflow/ folder.
*
* @return List of workflows under the /workflow/ folder.
*/
@GET
@Path("/filenames/{type}")
@Produces("application/json;charset=utf-8")
public Response getFileNames(@PathParam("type") String type) throws IOException, URISyntaxException {
JSONArray jsonArray = GraphHelper.getExistingFileNames(GraphHelper.getPath(type, context));
return Response.ok(jsonArray.toString()).build();
}
/**
* Creates a list of all available workflows from the file structure under the /workflow/ folder.
*
* @return List of workflows under the /workflow/ folder.
*/
@GET
@Path("/workflows")
@Produces("application/json;charset=utf-8")
public Response getWorkflows() throws IOException, URISyntaxException {
JSONArray jsonArray = GraphHelper.getExistingWorkflows(context);
return Response.ok(jsonArray.toString()).build();
}
/**
* Creates a json string containing all valid operations that could be executed during filtering.
*
* @return json string
*/
@GET
@Path("/filterOperations")
@Produces("application/json;charset=utf-8")
public Response getFilterOperations() {
return Response.ok(FilteringHelper.getFilterOperations()).build();
}
/**
* Takes a graphIdentifier name via a POST request and returns the keys of all
* vertex and edge properties, and a boolean value specifying if the property has a numerical
* type. The return is a string in the JSON format, for easy usage in a JavaScript web page.
*
* @param graphIdentifier name of the loaded graph
* @return A JSON containing the vertices and edges property keys
*/
@GET
@Path("/keys/{graph}")
@Produces("application/json;charset=utf-8")
public Response getKeysAndLabels(@PathParam("graph") String graphIdentifier) throws IOException {
return Response.ok(MetaDataHelper.getGraphMetaData(graphIdentifier, context).toString()).build();
}
/**
* Takes a list of graphIdentifier names via a POST request and returns combined metaData for the given graphIdentifierList.
* The return is a string in the JSON format.
*
* @param graphIdentifierList JSON array containing graphIdentifiers
* @return A JSON containing combined metaData for the given graphIdentifiers
*/
@POST
@Path("/combinedKeys")
@Consumes("application/json;charset=utf-8")
public Response getCombinedKeysAndLabels(String graphIdentifierList) throws IOException, JSONException, InterruptedException {
return Response.ok(MetaDataHelper.getCombinedGraphMetaData(graphIdentifierList, context).toString()).build();
}
@POST
@Path("/linkingKeys")
@Consumes("application/json;charset=utf-8")
public Response getLinkingKeysAndLabels(String inputList) throws IOException, JSONException, InterruptedException {
JSONArray resultArray = new JSONArray(inputList);
HashSet<String> allGraphs = new HashSet<String>();
for(int i = 0; i < resultArray.length(); i++) {
JSONObject jsonObject = resultArray.getJSONObject(i);
if(jsonObject.getString("type").equals("Graph")) {
String graphIdentifier = jsonObject.getString("identifier");
JSONObject metaData = MetaDataHelper.getGraphMetaData(graphIdentifier, context);
jsonObject.put("metaData", metaData.toString());
allGraphs.add(graphIdentifier);
}
else if(jsonObject.getString("type").equals("SubWorkflow")) {
JSONObject metaData = MetaDataHelper.getCombinedGraphMetaData(jsonObject.getString("value"), context);
jsonObject.put("metaData", metaData.toString());
JSONArray graphIdentifiers = jsonObject.getJSONArray("value");
for(int j = 0; j < graphIdentifiers.length(); j++) {
allGraphs.add(graphIdentifiers.getString(j));
}
}
else if(jsonObject.getString("type").equals("AllGraphs")) {
JSONArray allGraphsJSONArray = new JSONArray();
for(String s: allGraphs) {
allGraphsJSONArray.put(s);
}
JSONObject metaData = MetaDataHelper.getCombinedGraphMetaData(allGraphsJSONArray.toString(), context);
jsonObject.put("metaData", metaData.toString());
}
resultArray.put(i, jsonObject);
}
return Response.ok(new JSONObject().put("data", resultArray).toString()).build();
}
/**
* Get the complete graph in cytoscape-conform form.
*
* @param graphIdentifier name of the graph
* @param sampling Type of the sampling (optional)
* @param threshold Sampling threshold (optional)
* @return Response containing the graph as a JSON, in cytoscape conform format.
* @throws JSONException if JSON creation fails
* @throws IOException if reading fails
*/
@GET
@Path("/graph/{graph}")
@Produces("application/json;charset=utf-8")
public Response getGraph(@PathParam("graph") String graphIdentifier,
@MatrixParam("sampling") @DefaultValue("") String sampling,
@MatrixParam("threshold") @DefaultValue("0.0") float threshold) throws Exception {
LogicalGraph graph = GraphHelper.getGraph(graphIdentifier,context);
switch (sampling) {
case "Node Sampling":
graph = graph.sampleRandomNodes(threshold);
break;
case "Edge Sampling":
graph = new RandomEdgeSampling(threshold, 0L).execute(graph);
break;
case "PageRank Sampling":
graph = new PageRankSampling(0.5, threshold).execute(graph);
break;
default:
// Ignore.
}
String json = GraphHelper.getCytoJsonGraph(graph);
return Response.ok(json).build();
}
/**
* Gets graph from an RDF endpoint
*
* @param outputGraphIdentifier graph identifier
* @param rdfGraphConfig configuration to obtain the graph, that contains RDF endpoint and SPARQL query
* @return Response containing the graph as a JSON, in cytoscape conform format
*/
@POST
@Path("/rdfgraph/")
@Produces("application/json;charset=utf-8")
public Response getRDFGraph(@QueryParam("outGraph") String outputGraphIdentifier,
String rdfGraphConfig) throws Exception {
LogicalGraph graph = null;
if(GraphHelper.graphExists(outputGraphIdentifier, context)) {
System.out.println("requesting existing graph: " + outputGraphIdentifier);
graph = GraphHelper.getGraph(outputGraphIdentifier, context);
}
else {
graph = RDFGraphHelper.getRDFGraph(rdfGraphConfig, ServiceHelper.getConfig());
if (StringUtils.isNotEmpty(outputGraphIdentifier)) {
GraphHelper.storeGraph(graph, outputGraphIdentifier, context, true);
}
}
String json = GraphHelper.getCytoJsonGraph(graph);
return Response.ok(json).build();
}
/**
* Returns information regarding of whether the graph exists or not
*
* @param graphIdentifier identifier of the graph to be checked
* @return JSON response containing key-value pair "graphExists":[true/false]
*/
@GET
@Path("/graphExists/{graph}")
@Produces("application/json;charset=utf-8")
public Response graphExists(@PathParam("graph") String graphIdentifier) throws Exception {
JSONObject response = new JSONObject();
if(GraphHelper.graphExists(graphIdentifier, context)){
response.put("graphExists", Boolean.TRUE);
}
else {
response.put("graphExists", Boolean.FALSE);
}
return Response.ok(response.toString()).build();
}
@GET
@Path("/renameGraph/{graph}")
@Produces("application/json;charset=utf-8")
public Response renameGraph(@PathParam("graph") String oldGraphIdentifier,
@QueryParam("outGraph") String newGraphIdentifier) throws Exception {
JSONObject response = new JSONObject();
if(!oldGraphIdentifier.equals(newGraphIdentifier)) {
GraphHelper.deleteGraph(newGraphIdentifier, context);
if(GraphHelper.renameGraph(oldGraphIdentifier, newGraphIdentifier, context)){
response.put("success", Boolean.TRUE);
}
else {
response.put("success", Boolean.FALSE);
}
}
else {
response.put("success", Boolean.TRUE);
}
return Response.ok(response.toString()).build();
}
/**
* Get the complete graph in cytoscape-conform form.
*
* @param graphIdentifier name of the graph
* @param sampling Type of the sampling (optional)
* @param threshold Sampling threshold (optional)
* @return Response containing the graph as a JSON, in cytoscape conform format.
* @throws JSONException if JSON creation fails
* @throws IOException if reading fails
*/
@GET
@Path("/graph/sampling/{graph}")
@Produces("application/json;charset=utf-8")
public Response getSampledGraph(@PathParam("graph") String graphIdentifier,
@MatrixParam("sampling") @DefaultValue("") String sampling,
@MatrixParam("threshold") @DefaultValue("0.0") float threshold,
@MatrixParam("outGraph") @DefaultValue("") String outputGraphIdentifier) throws Exception {
LogicalGraph graph = GraphHelper.getGraph(graphIdentifier,context);
switch (sampling) {
case "Node Sampling":
graph = graph.sampleRandomNodes(threshold);
break;
case "Edge Sampling":
graph = new RandomEdgeSampling(threshold, 0L).execute(graph);
break;
case "PageRank Sampling":
graph = new PageRankSampling(0.5, threshold).execute(graph);
break;
default:
break;
}
String json = "";
if (StringUtils.isNotEmpty(outputGraphIdentifier)) {
if(graphIdentifier.equals(outputGraphIdentifier)) {
outputGraphIdentifier = outputGraphIdentifier + "_" + Integer.toHexString(new Random().nextInt(Integer.MAX_VALUE));
GraphHelper.storeGraph(graph, outputGraphIdentifier, context, true);
json = GraphHelper.getCytoJsonGraph(graph);
GraphHelper.deleteGraph(graphIdentifier, context);
GraphHelper.renameGraph(outputGraphIdentifier, graphIdentifier, context);
}
else {
GraphHelper.storeGraph(graph, outputGraphIdentifier, context, true);
json = GraphHelper.getCytoJsonGraph(graph);
}
}
else {
json = GraphHelper.getCytoJsonGraph(graph);
}
return Response.ok(json).build();
}
/**
* Calculates the graph schema for a given graph
*
* @param graphIdentifier - name of the graph
* @param outputGraphIdentifier - the identifier of the schema to be stored
* @return Response containing the graph as a JSON, in cytoscape conform format.
* @throws JSONException if JSON creation fails
* @throws IOException if reading or writing fails
*/
@GET
@Path("/graph/schema/{graph}")
@Produces("application/json;charset=utf-8")
public Response getSchemaGraph(@PathParam("graph") String graphIdentifier,
@QueryParam("outGraph") String outputGraphIdentifier) throws Exception {
LogicalGraph graph = GraphHelper.getGraph(graphIdentifier,context);
LogicalGraph outputGraph = SchemaGraph.extract(graph);
String json = "";
if (StringUtils.isNotEmpty(outputGraphIdentifier)) {
if(graphIdentifier.equals(outputGraphIdentifier)) {
outputGraphIdentifier = outputGraphIdentifier + "_" + Integer.toHexString(new Random().nextInt(Integer.MAX_VALUE));
GraphHelper.storeGraph(outputGraph, outputGraphIdentifier, context, true);
json = GraphHelper.getCytoJsonGraph(graph);
GraphHelper.deleteGraph(graphIdentifier, context);
GraphHelper.renameGraph(outputGraphIdentifier, graphIdentifier, context);
}
else {
GraphHelper.storeGraph(outputGraph, outputGraphIdentifier, context, true);
json = GraphHelper.getCytoJsonGraph(graph);
}
}
else {
json = GraphHelper.getCytoJsonGraph(graph);
}
return Response.ok(json).build();
}
/**
* @param graphIdentifier - the name of the graph
* @param groupingStrat - the {@link GroupingStrategy}. Has to be "GROUP_COMBINE" (default) or "GROUP_REDUCE".
* @param outputGraphIdentifier - the identifier for the grouped graph if it should be stored
* @param groupingConfig - a json string defining which vertex and egde properties for which type has to be grouped
* @return Response containing the graph as a JSON, in cytoscape conform format.
* @throws JSONException if JSON creation fails
* @throws IOException if reading or writing fails
*/
@POST
@Path("/graph/grouping/{graph}")
@Consumes("application/json;charset=utf-8")
@Produces("application/json;charset=utf-8")
public Response groupByTypeAndAttributes(@PathParam("graph") String graphIdentifier,
@DefaultValue("GROUP_COMBINE") @QueryParam("grpStrat") String groupingStrat,
@QueryParam("outGraph") String outputGraphIdentifier,
String groupingConfig) throws Exception {
LogicalGraph graph = GraphHelper.getGraph(graphIdentifier,context);
JsonParser parser = new JsonParser();
JsonArray array = parser.parse(groupingConfig).getAsJsonObject().get(GroupingHelper.ARRAY_IDENTIFIER).getAsJsonArray();
for (JsonElement element : array) {
JsonObject configElement = element.getAsJsonObject();
String type = configElement.get(GroupingHelper.GROUPING_PRIMITIVE).getAsString();
String label = configElement.get(GroupingHelper.GROUPING_LABEL).getAsString();
if (configElement.has(GroupingHelper.GROUPING_NEIGHBORS)) {
String neighbor = configElement.get(GroupingHelper.GROUPING_NEIGHBORS).getAsString();
graph= annotateWithNeighbor(graph, label, neighbor);
}
}
LogicalGraph outputGraph = GroupingHelper.buildGroupingWorkflow(groupingStrat, groupingConfig).execute(graph);
String json = "";
if (StringUtils.isNotEmpty(outputGraphIdentifier)) {
if(graphIdentifier.equals(outputGraphIdentifier)) {
outputGraphIdentifier = outputGraphIdentifier + "_" + Integer.toHexString(new Random().nextInt(Integer.MAX_VALUE));
GraphHelper.storeGraph(outputGraph, outputGraphIdentifier, context, true);
json = GraphHelper.getCytoJsonGraph(outputGraph);
GraphHelper.deleteGraph(graphIdentifier, context);
GraphHelper.renameGraph(outputGraphIdentifier, graphIdentifier, context);
}
else {
GraphHelper.storeGraph(outputGraph, outputGraphIdentifier, context, true);
json = GraphHelper.getCytoJsonGraph(outputGraph);
}
}
else {
json = GraphHelper.getCytoJsonGraph(outputGraph);
}
return Response.ok(json).build();
}
public LogicalGraph annotateWithNeighbor(LogicalGraph graph, String groupedElement, String neighborLabel){
// //get all Vertices with given label
DataSet<Vertex> tagVertices = graph.getVertices().filter(new FilterFunction<Vertex>() {
@Override
public boolean filter(Vertex value) throws Exception {
return value.getLabel().equals(neighborLabel);
}
});
DataSet<Vertex> personVertices = graph.getVertices().filter(new FilterFunction<Vertex>() {
@Override
public boolean filter(Vertex value) throws Exception {
return value.getLabel().equals(groupedElement);
}
});
DataSet<Vertex> outgoing = personVertices.join(graph.getEdges()).where("id").equalTo("sourceId").
join(tagVertices).where(new KeySelector<Tuple2<Vertex,Edge>, GradoopId>() {
@Override
public GradoopId getKey(Tuple2<Vertex, Edge> value) throws Exception {
return value.f1.getTargetId();
}
}).equalTo("id").with(new JoinFunction<Tuple2<Vertex,Edge>,Vertex, Vertex>() {
@Override
public Vertex join(Tuple2<Vertex, Edge> first, Vertex second) throws Exception {
first.f0.setProperty("_neighbor_", second.getId());
return first.f0;
}
});
DataSet<Vertex> incoming = personVertices.join(graph.getEdges()).where("id").equalTo("targetId").
join(tagVertices).where(new KeySelector<Tuple2<Vertex,Edge>, GradoopId>() {
@Override
public GradoopId getKey(Tuple2<Vertex, Edge> value) throws Exception {
return value.f1.getSourceId();
}
}).equalTo("id").with(new JoinFunction<Tuple2<Vertex,Edge>,Vertex, Vertex>() {
@Override
public Vertex join(Tuple2<Vertex, Edge> first, Vertex second) throws Exception {
first.f0.setProperty("_neighbor_", second.getId());
return first.f0;
}
});
DataSet inAndOut=incoming.union(outgoing).distinct("id");
DataSet allVertices= graph.getVertices().leftOuterJoin(inAndOut).where("id").equalTo("id").with(new JoinFunction<Vertex, Vertex, Vertex>(){
@Override
public Vertex join(Vertex first, Vertex second) throws Exception {
if(second!=null)
return second;
return first;
}
});
graph = graph.getConfig().getLogicalGraphFactory().fromDataSets(allVertices, graph.getEdges());
return graph;
}
@POST
@Path("/graph/edge_fusion/{graph}")
@Consumes("application/json;charset=utf-8")
@Produces("application/json;charset=utf-8")
public Response edgeFusion(@PathParam("graph") String graphIdentifier,
@QueryParam("outGraph") String outputGraphIdentifier,
String edgeFusionConfig) throws Exception {
LogicalGraph inputGraph = GraphHelper.getGraph(graphIdentifier,context);
LogicalGraph outputGraph = EdgeFusionHelper.performEdgeFusion(inputGraph, edgeFusionConfig);
String json = "";
if (StringUtils.isNotEmpty(outputGraphIdentifier)) {
if(graphIdentifier.equals(outputGraphIdentifier)) {
outputGraphIdentifier = outputGraphIdentifier + "_" + Integer.toHexString(new Random().nextInt(Integer.MAX_VALUE));
GraphHelper.storeGraph(outputGraph, outputGraphIdentifier, context, true);
json = GraphHelper.getCytoJsonGraph(outputGraph);
GraphHelper.deleteGraph(graphIdentifier, context);
GraphHelper.renameGraph(outputGraphIdentifier, graphIdentifier, context);
}
else {
GraphHelper.storeGraph(outputGraph, outputGraphIdentifier, context, true);
json = GraphHelper.getCytoJsonGraph(outputGraph);
}
}
else {
json = GraphHelper.getCytoJsonGraph(outputGraph);
}
return Response.ok(json).build();
}
@POST
@Path("/graph/vertex_fusion/{graph}")
@Consumes("application/json;charset=utf-8")
@Produces("application/json;charset=utf-8")
public Response vertexFusion(@PathParam("graph") String graphIdentifier,
@QueryParam("outGraph") String outputGraphIdentifier,
String vertexFusionConfig) throws Exception {
LogicalGraph inputGraph = GraphHelper.getGraph(graphIdentifier,context);
LogicalGraph outputGraph = inputGraph.callForGraph(new VertexFusionOperator(vertexFusionConfig, new CountValues()));
String json = "";
if (StringUtils.isNotEmpty(outputGraphIdentifier)) {
if(graphIdentifier.equals(outputGraphIdentifier)) {
outputGraphIdentifier = outputGraphIdentifier + "_" + Integer.toHexString(new Random().nextInt(Integer.MAX_VALUE));
GraphHelper.storeGraph(outputGraph, outputGraphIdentifier, context, true);
json = GraphHelper.getCytoJsonGraph(outputGraph);
GraphHelper.deleteGraph(graphIdentifier, context);
GraphHelper.renameGraph(outputGraphIdentifier, graphIdentifier, context);
}
else {
GraphHelper.storeGraph(outputGraph, outputGraphIdentifier, context, true);
json = GraphHelper.getCytoJsonGraph(outputGraph);
}
}
else {
json = GraphHelper.getCytoJsonGraph(outputGraph);
}
return Response.ok(json).build();
}
@POST
@Path("/graph/pattern_match/{graph}")
@Consumes("application/json;charset=utf-8")
@Produces("application/json;charset=utf-8")
public Response pattern_match(@PathParam("graph") String graphIdentifier,
@QueryParam("outGraph") String outputGraphIdentifier,
String patternMatchingConfig) throws Exception {
LogicalGraph graph = GraphHelper.getGraph(graphIdentifier,context);
LogicalGraph outputGraph = PatternMatchingHelper.runPatternMatching(graph, patternMatchingConfig);
String json = "";
if (StringUtils.isNotEmpty(outputGraphIdentifier)) {
if(graphIdentifier.equals(outputGraphIdentifier)) {
outputGraphIdentifier = outputGraphIdentifier + "_" + Integer.toHexString(new Random().nextInt(Integer.MAX_VALUE));
GraphHelper.storeGraph(outputGraph, outputGraphIdentifier, context, true);
json = GraphHelper.getCytoJsonGraph(outputGraph);
GraphHelper.deleteGraph(graphIdentifier, context);
GraphHelper.renameGraph(outputGraphIdentifier, graphIdentifier, context);
}
else {
GraphHelper.storeGraph(outputGraph, outputGraphIdentifier, context, true);
json = GraphHelper.getCytoJsonGraph(outputGraph);
}
}
else {
json = GraphHelper.getCytoJsonGraph(outputGraph);
}
return Response.ok(json).build();
}
/**
* Creates a vertex or edge induced subgraph where defined filter criterion are met and stores it with the name
* of the given identifier.
*
* @param graphIdentifier - name of the graph
* @param filteredGraphIdentifier - the identifier to store the filtered graph
* @param filterConfig - JSON configuration for filtering the graph
* @return Response containing the graph as a JSON, in cytoscape conform format.
* @throws JSONException if JSON creation fails
* @throws IOException if reading or writing fails
*/
@POST
@Path("/graph/filter/{graph}")
@Consumes("application/json;charset=utf-8")
@Produces("application/json;charset=utf-8")
public Response filterGraph(@PathParam("graph") String graphIdentifier,
@QueryParam("outGraph") String outputGraphIdentifier,
String filterConfig) throws Exception {
LogicalGraph graph = GraphHelper.getGraph(graphIdentifier,context);
LogicalGraph subGraph = FilteringHelper.createSubGraph(graph, filterConfig);
String json = "";
if (StringUtils.isNotEmpty(outputGraphIdentifier)) {
if(graphIdentifier.equals(outputGraphIdentifier)) {
outputGraphIdentifier = outputGraphIdentifier + "_" + Integer.toHexString(new Random().nextInt(Integer.MAX_VALUE));
GraphHelper.storeGraph(subGraph, outputGraphIdentifier, context, true);
json = GraphHelper.getCytoJsonGraph(subGraph);
GraphHelper.deleteGraph(graphIdentifier, context);
GraphHelper.renameGraph(outputGraphIdentifier, graphIdentifier, context);
}
else {
GraphHelper.storeGraph(subGraph, outputGraphIdentifier, context, true);
json = GraphHelper.getCytoJsonGraph(subGraph);
}
}
else {
json = GraphHelper.getCytoJsonGraph(subGraph);
}
return Response.ok(json).build();
}
/**
* Creates a clustered graph
*
* @param graphIdentifier - name of the graph
* @param outputGraphIdentifier - the identifier to store the clustered graph
* @param clusteringConfig - JSON configuration for clustering the graph
* @return Response containing the graph as a JSON, in cytoscape conform format.
* @throws JSONException if JSON creation fails
* @throws IOException if reading or writing fails
*/
@POST
@Path("/graph/clustering/{graph}")
@Consumes("application/json;charset=utf-8")
@Produces("application/json;charset=utf-8")
public Response clusterGraph(@PathParam("graph") String graphIdentifier,
@QueryParam("outGraph") String outputGraphIdentifier,
String clusteringConfig) throws Exception {
LogicalGraph graph = GraphHelper.getGraph(graphIdentifier,context);
LogicalGraph outputGraph = ClusteringHelper.runClustering(graph, clusteringConfig);
String json = "";
if (StringUtils.isNotEmpty(outputGraphIdentifier)) {
if(graphIdentifier.equals(outputGraphIdentifier)) {
outputGraphIdentifier = outputGraphIdentifier + "_" + Integer.toHexString(new Random().nextInt(Integer.MAX_VALUE));
GraphHelper.storeGraph(outputGraph, outputGraphIdentifier, context, true);
json = GraphHelper.getCytoJsonGraph(outputGraph);
GraphHelper.deleteGraph(graphIdentifier, context);
GraphHelper.renameGraph(outputGraphIdentifier, graphIdentifier, context);
}
else {
GraphHelper.storeGraph(outputGraph, outputGraphIdentifier, context, true);
json = GraphHelper.getCytoJsonGraph(outputGraph);
}
}
else {
json = GraphHelper.getCytoJsonGraph(outputGraph);
}
return Response.ok(json).build();
}
@POST
@Path("/graph/cypher/{graph}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response cypherQuery(@PathParam("graph") String graphIdentifier,
@QueryParam("outGraph") String outputGraphIdentifier,
@FormParam("cypher-query") String cypherQuery,
@FormParam("cypher-attach-attr") @DefaultValue("on") String setAttachAttr,
@FormParam("cypher-constr-pattern") String constructionPattern) throws Exception {
// Apparently checkboxes are encoded with "on" and "off"
final boolean attachAttr = setAttachAttr.equals("on");
LogicalGraph graph = GraphHelper.getGraph(graphIdentifier, context);
// TODO: Get and store actual GraphStatistics by graphIdentifier
GraphStatistics stats = new GraphStatistics(1,1,1,1);
if (cypherQuery == null || cypherQuery.isEmpty()) {
return Response.status(Response.Status.BAD_REQUEST).build();
}
// Making sure to use an empty construction pattern by default.
if (Objects.toString(constructionPattern, "").isEmpty()) {
constructionPattern = null;
}
GraphCollection cypher = graph.cypher(cypherQuery, constructionPattern, attachAttr,
MatchStrategy.HOMOMORPHISM, MatchStrategy.ISOMORPHISM, stats);
LogicalGraph outputGraph = graph.getConfig().getLogicalGraphFactory()
.fromDataSets(cypher.getVertices().distinct(new Id<>()), cypher.getEdges().distinct(new Id<>()));
String json = "";
if (StringUtils.isNotEmpty(outputGraphIdentifier)) {
if(graphIdentifier.equals(outputGraphIdentifier)) {
outputGraphIdentifier = outputGraphIdentifier + "_" + Integer.toHexString(new Random().nextInt(Integer.MAX_VALUE));
GraphHelper.storeGraph(outputGraph, outputGraphIdentifier, context, true);
json = GraphHelper.getCytoJsonGraph(outputGraph);
GraphHelper.deleteGraph(graphIdentifier, context);
GraphHelper.renameGraph(outputGraphIdentifier, graphIdentifier, context);
}
else {
GraphHelper.storeGraph(outputGraph, outputGraphIdentifier, context, true);
json = GraphHelper.getCytoJsonGraph(outputGraph);
}
}
else {
json = GraphHelper.getCytoJsonGraph(outputGraph);
}
return Response.ok(json).build();
}
@GET
@Path("/graph/expand/{graph}")
@Produces(MediaType.APPLICATION_JSON)
public Response expand(@PathParam("graph") String graphIdentifier,
@QueryParam("outGraph") String outputGraphIdentifier,
@QueryParam("typeProperty") String typeProperty) throws Exception {
LogicalGraph graph = GraphHelper.getGraph(graphIdentifier, context);
System.out.println("Calling expand");
LogicalGraph outputGraph = graph.callForGraph(new ExpandGraph(Objects.toString(typeProperty, "").isEmpty() ?
ExpandGraph.DEFAULT_PROPERTY_KEY : typeProperty));
String json = "";
if (StringUtils.isNotEmpty(outputGraphIdentifier)) {
if(graphIdentifier.equals(outputGraphIdentifier)) {
outputGraphIdentifier = outputGraphIdentifier + "_" + Integer.toHexString(new Random().nextInt(Integer.MAX_VALUE));
GraphHelper.storeGraph(outputGraph, outputGraphIdentifier, context, true);
json = GraphHelper.getCytoJsonGraph(outputGraph);
GraphHelper.deleteGraph(graphIdentifier, context);
GraphHelper.renameGraph(outputGraphIdentifier, graphIdentifier, context);
}
else {
GraphHelper.storeGraph(outputGraph, outputGraphIdentifier, context, true);
json = GraphHelper.getCytoJsonGraph(outputGraph);
}
}
else {
json = GraphHelper.getCytoJsonGraph(outputGraph);
}
return Response.ok(json).build();
}
/**
* Creates a new graph by computing a similarity Graph and adding edges between similar nodes to the input graph.
*
* @param similarityGraphIdentifier - the identifier to store the linked graph
* @param config - JSON configuration which describes linking configuration und an array of input graphs
* @return Response containing the graph as a JSON, in cytoscape conform format.
* @throws JSONException if JSON creation fails
* @throws IOException if reading or writing fails
*/
@POST
@Path("/graph/linking")
@Consumes("application/json;charset=utf-8")
@Produces("application/json;charset=utf-8")
public Response dedupGraph(@QueryParam("linkedGraph") String outputGraphIdentifier,
String config) throws Exception {
JSONObject configObject = new JSONObject(config);
String linkingConfig = configObject.getString("linkingConfig");
// contains json array with matching pairs of saved graphs and names used to refer to them in the UI
String inputGraphs = configObject.getString("inputGraphs");
// performs preprocessing and outputs combined input graph
LogicalGraph inputGraph = LinkingHelper.prepareInputGraph(inputGraphs, context);
LogicalGraph outputGraph = LinkingHelper.runLinking(inputGraph, linkingConfig);
JSONArray inputGraphsArray = new JSONArray(inputGraphs);
boolean hasEqualGraph = false;
String graphIdentifier = "";
for(int i = 0; i < inputGraphsArray.length(); i++) {
String inputGraphIdentifier = inputGraphsArray.getJSONObject(i).getString("inputGraphIdentifier");
if(inputGraphIdentifier.equals(outputGraphIdentifier)) {
hasEqualGraph = true;
graphIdentifier = inputGraphIdentifier;
}
}
String json = "";
if (StringUtils.isNotEmpty(outputGraphIdentifier)) {
if(hasEqualGraph) {
outputGraphIdentifier = outputGraphIdentifier + "_" + Integer.toHexString(new Random().nextInt(Integer.MAX_VALUE));
GraphHelper.storeGraph(outputGraph, outputGraphIdentifier, context, true);
json = GraphHelper.getCytoJsonGraph(outputGraph);
GraphHelper.deleteGraph(graphIdentifier, context);
GraphHelper.renameGraph(outputGraphIdentifier, graphIdentifier, context);
}
else {
GraphHelper.storeGraph(outputGraph, outputGraphIdentifier, context, true);
json = GraphHelper.getCytoJsonGraph(outputGraph);
}
}
else {
json = GraphHelper.getCytoJsonGraph(outputGraph);
}
return Response.ok(json).build();
}
/**
* Creates a new graph where every vertex has a "ccId" for it's corresponding weakly connected component
*
* @param graphIdentifier - name of the inputgraph
* @param outputGraphIdentifier - the identifier to store the graph with the connected components ids
* @return Response containing the graph as a JSON, in cytoscape conform format.
* @throws JSONException if JSON creation fails
* @throws IOException if reading or writing fails
*/
@GET
@Path("/graph/wcc/{graph}")
@Consumes("application/json;charset=utf-8")
@Produces("application/json;charset=utf-8")
public Response weaklyConnectedComponents(@PathParam("graph") String graphIdentifier,
@QueryParam("outGraph") String outputGraphIdentifier) throws Exception {
LogicalGraph graph = GraphHelper.getGraph(graphIdentifier, context);
LogicalGraph outputGraph = GellyHelper.calculateConnectedComponents(graph);
String json = "";
if (StringUtils.isNotEmpty(outputGraphIdentifier)) {
if(graphIdentifier.equals(outputGraphIdentifier)) {
outputGraphIdentifier = outputGraphIdentifier + "_" + Integer.toHexString(new Random().nextInt(Integer.MAX_VALUE));
GraphHelper.storeGraph(outputGraph, outputGraphIdentifier, context, true);
json = GraphHelper.getCytoJsonGraph(outputGraph);
GraphHelper.deleteGraph(graphIdentifier, context);
GraphHelper.renameGraph(outputGraphIdentifier, graphIdentifier, context);
}
else {
GraphHelper.storeGraph(outputGraph, outputGraphIdentifier, context, true);
json = GraphHelper.getCytoJsonGraph(outputGraph);
}
}
else {
json = GraphHelper.getCytoJsonGraph(outputGraph);
}
return Response.ok(json).build();
}
/**
* Creates a new graph where every vertex has a "pagerank" calculated by gelly
*
* @param graphIdentifier - name of the inputgraph
* @param prGraphIdentifier - the identifier to store the graph with the pageranks
* @return Response containing the graph as a JSON, in cytoscape conform format.
* @throws JSONException if JSON creation fails
* @throws IOException if reading or writing fails
*/
@GET
@Path("/graph/pr/{graph}")
@Consumes("application/json;charset=utf-8")
@Produces("application/json;charset=utf-8")
public Response pageRank(@PathParam("graph") String graphIdentifier,
@QueryParam("outGraph") String outputGraphIdentifier,
@DefaultValue("0.85") @QueryParam("damping") Double dampingFactor,
@DefaultValue("30") @QueryParam("iter") Integer iterations) throws Exception {
LogicalGraph graph = GraphHelper.getGraph(graphIdentifier,context);
LogicalGraph outputGraph = GellyHelper.calculatePageRank(graph, dampingFactor, iterations);
String json = "";
if (StringUtils.isNotEmpty(outputGraphIdentifier)) {
if(graphIdentifier.equals(outputGraphIdentifier)) {
outputGraphIdentifier = outputGraphIdentifier + "_" + Integer.toHexString(new Random().nextInt(Integer.MAX_VALUE));
GraphHelper.storeGraph(outputGraph, outputGraphIdentifier, context, true);
json = GraphHelper.getCytoJsonGraph(outputGraph);
GraphHelper.deleteGraph(graphIdentifier, context);
GraphHelper.renameGraph(outputGraphIdentifier, graphIdentifier, context);
}
else {
GraphHelper.storeGraph(outputGraph, outputGraphIdentifier, context, true);
json = GraphHelper.getCytoJsonGraph(outputGraph);
}
}
else {
json = GraphHelper.getCytoJsonGraph(outputGraph);
}
return Response.ok(json).build();
}
/**
* Creates a new graph where every vertex has a "pagerank" calculated by gelly
*
* @param graphIdentifier - name of the inputgraph
* @param otherGraphIdentifier - name of the other input graph
* @param outGraph - the identifier to store the graph with the pageranks
* @return Response containing the graph as a JSON, in cytoscape conform format.
* @throws JSONException if JSON creation fails
* @throws IOException if reading or writing fails
*/
@GET
@Path("/graph/binary/{graph}/{otherGraph}")
@Consumes("application/json;charset=utf-8")
@Produces("application/json;charset=utf-8")
public Response binaryOperation(@PathParam("graph") String graphIdentifier,
@PathParam("otherGraph") String otherGraphIdentifier,
@QueryParam("op") String operation,
@QueryParam("outGraph") String outputGraphIdentifier) throws Exception {
LogicalGraph graph = GraphHelper.getGraph(graphIdentifier,context);
LogicalGraph otherGraph = GraphHelper.getGraph(otherGraphIdentifier,context);
LogicalGraph outputGraph = null;
if (operation.equals("combination")) {
outputGraph = graph.combine(otherGraph);
} else if(operation.equals("overlap")) {
outputGraph = graph.overlap(otherGraph);
} else if(operation.equals("exclusion")) {
outputGraph = graph.exclude(otherGraph);
}
String json = "";
if (StringUtils.isNotEmpty(outputGraphIdentifier) && outputGraph != null) {
if(graphIdentifier.equals(outputGraphIdentifier)) {
outputGraphIdentifier = outputGraphIdentifier + "_" + Integer.toHexString(new Random().nextInt(Integer.MAX_VALUE));
GraphHelper.storeGraph(outputGraph, outputGraphIdentifier, context, true);
json = GraphHelper.getCytoJsonGraph(outputGraph);
GraphHelper.deleteGraph(graphIdentifier, context);
GraphHelper.renameGraph(outputGraphIdentifier, graphIdentifier, context);
}
else {
GraphHelper.storeGraph(outputGraph, outputGraphIdentifier, context, true);
json = GraphHelper.getCytoJsonGraph(outputGraph);
}
}
else {
json = GraphHelper.getCytoJsonGraph(outputGraph);
}
return Response.ok(json).build();
}
/**
* Returns text response to caller containing uploaded file location
*
* @return error response in case of missing parameters an internal
* exception or success response if file has been stored
* successfully
*/
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Path("/upload/{graph}/{element}")
public Response uploadFile(@PathParam("graph") String graphIdentifier,
@PathParam("element") String graphElementType,
@FormDataParam("file") InputStream uploadedInputStream,
@FormDataParam("file") FormDataContentDisposition fileDetail) {
// check if all form parameters are provided
if (uploadedInputStream == null || fileDetail == null)
return Response.status(400).entity("Invalid form data").build();
// create our destination folder, if it not exists
try {
FileUploadHelper.createFolderIfNotExists(graphIdentifier, graphElementType, context);
} catch (IOException | SecurityException se) {
return Response.status(500)
.entity("Can not create destination folder on server")
.build();
}
String uploadedFileLocation;
try {
uploadedFileLocation = FileUploadHelper.saveToFile(uploadedInputStream, graphIdentifier,
graphElementType, fileDetail.getFileName(), context);
} catch (IOException e) {
return Response.status(500).entity("Can not save file").build();
}
return Response.status(200)
.entity("File saved to " + uploadedFileLocation).build();
}
@POST
@Path("/colors/{filename}")
@Consumes(MediaType.APPLICATION_JSON)
public Response uploadConfig(@PathParam("filename") String filename,
String data){
// check if all form parameters are provided
//InputStream uploadedInputStream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8.name()));
if (data == null )
return Response.status(400).entity("Invalid form data").build();
// create our destination folder, if it not exists
String uploadedFileLocation;
try {
uploadedFileLocation = FileUploadHelper.saveColorsToFile(data, filename, context);
} catch (IOException e) {
return Response.status(500).entity("Can not save file").build();
}
return Response.status(200)
.entity(filename +" saved to " + uploadedFileLocation).build();
}
/**
* save config-data (colors) as json file to current graph directory
*
* @param graphIdentifier current graph
* @param data data to be stored
* @return error response in case of missing parameters an internal
* exception or success response if file has been stored
* successfully
*/
@POST
@Path("/upload/{graph}")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response uploadJSON(@PathParam("graph") String graphIdentifier,
@FormParam("name") String filename,
@FormParam("file") String data){
// check if all form parameters are provided
//InputStream uploadedInputStream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8.name()));
if (data == null )
return Response.status(400).entity("Invalid form data").build();
// create our destination folder, if it not exists
String uploadedFileLocation;
try {
uploadedFileLocation = FileUploadHelper.saveToJSON(data, graphIdentifier, filename, context);
} catch (IOException e) {
return Response.status(500).entity("Can not save file").build();
}
return Response.status(200)
.entity(filename +" saved to " + uploadedFileLocation).build();
}
/**
*
* @return JSON Array of nodes and corresponding colors
*/
@GET
@Path("/json/{type}")
//@Consumes("application/json;charset=utf-8")
//@Produces("application/json;charset=utf-8")
public Response getJSONFile(@PathParam("type") String identifier, @QueryParam("json") String filename) throws IOException, URISyntaxException {
try {
String path = GraphHelper.getPath(identifier, context);
//Logger.getLogger(RequestHandler.class.getName()).log(Level.INFO, "Reading from {0}", filename);
JSONObject jsonFile = MetaDataHelper.readJSONFile(path, filename);
if (jsonFile == null) {
return Response.ok("null").build();
} else {
return Response.ok(jsonFile.toString()).build();
}
} catch (JSONException e) {
e.printStackTrace();
}
return Response.status(Response.Status.NOT_FOUND).build();
}
/**
*
* @return JSON Array of nodes and corresponding colors from graph folder
*/
@GET
@Path("/graph")
//@Consumes("application/json;charset=utf-8")
//@Produces("application/json;charset=utf-8")
public Response getJSONFileFromGraph(@QueryParam("graph") String graphIdentifier, @QueryParam("json") String filename) throws IOException, URISyntaxException {
try {
String path = GraphHelper.getGraphPath(graphIdentifier, context);
JSONObject jsonFile = MetaDataHelper.readJSONFile(path, filename);
if (jsonFile == null) {
return Response.ok("null").build();
} else {
return Response.ok(jsonFile.toString()).build();
}
} catch (JSONException e) {
e.printStackTrace();
}
return Response.status(Response.Status.NOT_FOUND).build();
}
/**
* Recomputates graph metadata for existing graphs and returns status message.
* If recomputation was successful additionally returns contents of the new metadata file.
* @return status message after recalculating graph metadata
*/
@GET
@Path("/updateMetaData/{graph}")
//@Consumes("application/json;charset=utf-8")
//@Produces("application/json;charset=utf-8")
public Response updateMetaData(
@PathParam("graph") String graphIdentifier,
@QueryParam("json") String filename) throws IOException, URISyntaxException {
try {
List<String> existingGraphs = Arrays.asList(GraphHelper.getExistingGraphs(context));
if (existingGraphs.contains(graphIdentifier)) {
JSONObject metaData = MetaDataHelper.updateGraphMetaData(graphIdentifier, context);
return Response.ok("Metadata for graph \"" + graphIdentifier + "\" successfully updated.<br><br>" + metaData).build();
}
else {
return Response.ok("Graph \"" + graphIdentifier + "\" does not exist").build();
}
} catch (Exception e) {
e.printStackTrace();
}
return Response.ok("Error during metadata recalculation for graph " + graphIdentifier).build();
}
@POST
@Path("/workflow/compute/")
@Consumes("application/json;charset=utf-8")
@Produces("application/json;charset=utf-8")
public Response computeWorkflow(String builderConfig) throws Exception {
JSONObject builderConfigObject = new JSONObject(builderConfig);
JSONArray builderConfigArray = (JSONArray)builderConfigObject.get("connections");
// searching for the identifier of the output graph before we change identifier to path
String outputGraph = "";
for(int i = 0; i < builderConfigArray.length(); i++ ) {
String className = ((JSONObject)((JSONObject)builderConfigArray.get(i)).get("to")).getString("className");
if(className.equals("org.uni_leipzig.biggr.builder.constructors.JSONDataSinkConstructor")) {
outputGraph = ((JSONObject)((JSONObject)((JSONObject)builderConfigArray.get(i)).get("to")).get("arguments")).getString("path");
}
}
// changing graph identifier to graph path, due to graph path data is not available on the client side
for(int i = 0; i < builderConfigArray.length(); i++ ) {
String className = ((JSONObject)((JSONObject)builderConfigArray.get(i)).get("from")).getString("className");
// data source can be both source and target of the connection
// data sink can be only target of the connection
if(className.equals("org.uni_leipzig.biggr.builder.constructors.JSONDataSourceConstructor") ) {
String graphIdentifier = ((JSONObject)((JSONObject)((JSONObject)builderConfigArray.get(i)).get("from")).get("arguments")).getString("path");
String graphPath = GraphHelper.getGraphPath(graphIdentifier, context);
((JSONObject)((JSONObject)((JSONObject)builderConfigArray.get(i)).get("from")).get("arguments")).put("path", graphPath);
}
className = ((JSONObject)((JSONObject)builderConfigArray.get(i)).get("to")).getString("className");
if(className.equals("org.uni_leipzig.biggr.builder.constructors.JSONDataSourceConstructor")
|| className.equals("org.uni_leipzig.biggr.builder.constructors.JSONDataSinkConstructor") ) {
String graphIdentifier = ((JSONObject)((JSONObject)((JSONObject)builderConfigArray.get(i)).get("to")).get("arguments")).getString("path");
String graphPath = GraphHelper.getGraphPath(graphIdentifier, context);
((JSONObject)((JSONObject)((JSONObject)builderConfigArray.get(i)).get("to")).get("arguments")).put("path", graphPath);
}
}
// removing identifiers from edges
for(int i = 0; i < builderConfigArray.length(); i++ ) {
JSONObject jsonObject = builderConfigArray.getJSONObject(i);
jsonObject.remove("identifier");
builderConfigArray.put(i, jsonObject);
}
builderConfigObject.put("connections", builderConfigArray);
// computing workflow using gradoop-builder
GradoopOperatorFlow operatorFlow = new ObjectMapper().readValue(builderConfigObject.toString().getBytes(), GradoopOperatorFlow.class);
ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
GradoopFlinkConfig gfc = GradoopFlinkConfig.createConfig(env);
GradoopFlowBuilder.createFlinkJob(gfc, operatorFlow);
env.execute();
// getting output graph and sending it to the front-end
LogicalGraph graph = GraphHelper.getGraph(outputGraph,context);
String graphJson = GraphHelper.getCytoJsonGraph(graph);
JSONObject output = new JSONObject();
output.put("data", graphJson);
output.put("name", outputGraph);
return Response.ok(output.toString()).build();
}
@POST
@Path("/workflow/save/{workflow}")
@Consumes("application/json;charset=utf-8")
public Response saveWorkflow(
@PathParam("workflow") String workflowName,
String workflowConfig) throws Exception {
try {
FileUploadHelper.saveWorkflowToFile(workflowName, workflowConfig, context);
return Response.ok(new JSONObject().put("message", "workflow saved").toString()).build();
} catch (IOException e) {
return Response.status(500).entity("Can not save file").build();
}
}
@GET
@Path("/workflow/load/{workflow}")
@Consumes("application/json;charset=utf-8")
@Produces("application/json;charset=utf-8")
public Response getWorkflow(
@PathParam("workflow") String workflowName) throws Exception {
JSONObject workflowObject = MetaDataHelper.readWorkflowFile(workflowName, context);
return Response.ok(workflowObject.toString()).build();
}
}
|
package com.isg.ifrend.core.service.mli;
import java.util.List;
public class CardServiceImpl implements CardService {
@Override
public List doCardMaintenance(Object cardMaintenanceModel) {
// TODO Auto-generated method stub
return null;
}
@Override
public String addCardReport(Object cardModel) {
// TODO Auto-generated method stub
return null;
}
@Override
public String deleteCardReport(Object cardReportModel) {
// TODO Auto-generated method stub
return null;
}
@Override
public String updateCardReport(Object cardReportModel) {
// TODO Auto-generated method stub
return null;
}
@Override
public List searchCardReport(Object searchParams) {
// TODO Auto-generated method stub
return null;
}
}
|
import java.util.*;
public class CoveringSegments {
private static List<Integer> optimalPoints(List<Segment> segments) {
//write your code here
segments.sort(Comparator.comparingInt(o -> o.start));
System.out.println(segments);
List<Integer> points = new ArrayList<>();
while (!segments.isEmpty()) {
Segment segmentToCompare = segments.get(0);
segments.remove(0);
if(segments.isEmpty()) {
points.add(segmentToCompare.end);
break;
}
Segment nexSegment = segments.get(0);
}
return points;
}
private static int findCommonMostRighPoint(Segment first, Segment second) {
return -1;
}
private static class Segment {
int start, end;
Segment(int start, int end) {
this.start = start;
this.end = end;
}
@Override
public String toString() {
return "Segment{" +
"start=" + start +
", end=" + end +
'}';
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
List<Segment> segments = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
int start, end;
start = scanner.nextInt();
end = scanner.nextInt();
segments.add(i, new Segment(start, end));
}
List<Integer> points = optimalPoints(segments);
System.out.println(points.size());
for (int point : points) {
System.out.print(point + " ");
}
}
}
|
package student_player;
import java.util.ArrayList;
import java.util.List;
import boardgame.Move;
import coordinates.Coord;
import coordinates.Coordinates;
import tablut.TablutBoardState;
import tablut.TablutMove;
public class MuscoviteAttacker {
public static Move getOpeningMove(TablutBoardState bs) {
return Minimax.getBestMove(bs, TablutBoardState.MUSCOVITE, 2);
}
public static double evaluatePosition(TablutBoardState bs, TablutMove move) {
if (bs.gameOver()) {
if (bs.getWinner() == TablutBoardState.MUSCOVITE) {
return 100000 - bs.getTurnNumber();
} else {
return -100000;
}
}
double value = 1000;
//Muscovites reward keeping our own pieces rather than taking the Swedes
value += bs.getNumberPlayerPieces(TablutBoardState.MUSCOVITE) * 60;
value -= bs.getNumberPlayerPieces(TablutBoardState.SWEDE) * 40;
//Get corners that are cutoff
List<Coord> cutoffCorners = MyTools.getCutoffCorners(bs);
value += cutoffCorners.size() * 30;
//Get power positions
List<Coord> powerPositions = MyTools.getMuscovitePowerPositions(bs);
Coord kingPosition = bs.getKingPosition();
for(Coord coord : powerPositions) {
//Reward power positions, even greater if they are near the king
value += 10;
if (coord.distance(bs.getKingPosition()) <= 3) {
value += 40;
}
}
//Reward the muscovites for building partial barricades, enroute to entirely barricading a corner
List<Coord> partialCutOffCornerCoords = MyTools.getMuscovitePartialCutoffCornerCoords(bs, powerPositions);
value += 7 * partialCutOffCornerCoords.size();
//Further reward building barricades near the king
for(Coord coord: partialCutOffCornerCoords) {
if (kingPosition.maxDifference(coord) <= 3) {
value += 5;
}
}
//Don't let the king get to a a wall
if (kingPosition.x == 0 || kingPosition.x == 8 || kingPosition.y == 0 || kingPosition.y == 8)
value -= 50;
return value;
}
}
|
/**
* Copyright 2004 Juan Heyns. All rights reserved. Redistribution and use in
* source and binary forms, with or without modification, are permitted provided
* that the following conditions are met: 1. Redistributions of source code must
* retain the above copyright notice, this list of conditions and the following
* disclaimer. 2. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution. THIS
* SOFTWARE IS PROVIDED BY JUAN HEYNS ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL JUAN HEYNS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions
* contained in the software and documentation are those of the authors and
* should not be interpreted as representing official policies, either expressed
* or implied, of Juan Heyns.
*/
package datepicker;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import javax.swing.JFormattedTextField;
public class DateComponentFormatter extends JFormattedTextField.AbstractFormatter
{
private static final long serialVersionUID = 5997312768041129127L;
@Override
public Object stringToValue(final String text) throws ParseException
{
if (text == null || text.equals("")) //$NON-NLS-1$
{
return null;
}
final DateFormat format =
ComponentFormatDefaults.getInstance().getFormat(ComponentFormatDefaults.Key.SELECTED_DATE_FIELD);
final Date date = format.parse(text);
final Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar;
}
@Override
public String valueToString(final Object value) throws ParseException
{
final Calendar cal = (Calendar) value;
if (cal == null)
{
return ""; //$NON-NLS-1$
}
final DateFormat format =
ComponentFormatDefaults.getInstance().getFormat(ComponentFormatDefaults.Key.SELECTED_DATE_FIELD);
return format.format(cal.getTime());
}
}
|
package p1;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class KeyLstener extends JFrame implements KeyListener
{
double num1=0.0,num2=0.0,sum=0.0,sub=0.0,mult=1,div=0.0;
JTextField txt1,txt2,txt3;
JLabel lbl1,lbl2,lbl3,lbl4,lbl5;
public KeyLstener(String a)
{
super(a);
Container c=this.getContentPane();
c.setLayout(null);
c.setBackground(Color.cyan);
lbl1=new JLabel("Enter first number");
lbl1.setBounds(70,50,200,20);
lbl1.setForeground(Color.blue);
txt1=new JTextField();
txt1.setBounds(290,50,150,20);
txt1.addKeyListener(this);
lbl2=new JLabel("Enter second number");
lbl2.setBounds(70,90,200,20);
lbl2.setForeground(Color.blue);
lbl4=new JLabel("F1=SUM, F2=SUBTARACT, F3=MULTIPLCATION");
lbl5=new JLabel("F4=DIVISION, ESC=EXIT, DELETE=TO CLAER BOX");
lbl4.setBounds(20,160,350,25);
lbl5.setBounds(20,190,350,30);
c.add(lbl4);
c.add(lbl5);
txt2=new JTextField();
txt2.setBounds(290,90,150,20);
txt2.addKeyListener(this);
lbl3=new JLabel("Result");
lbl3.setBounds(70,130,200,20);
lbl3.setForeground(Color.blue);
txt3=new JTextField();
txt3.setBounds(290,130,150,20);
c.add(lbl1);
c.add(lbl2);
c.add(txt1);
c.add(txt2);
c.add(lbl3);
c.add(txt3);
}
void accept()
{
num1=Double.parseDouble(JOptionPane.showInputDialog(null,"Enter first number"));
txt1.setText(String.valueOf(num1));
num2=Double.parseDouble(JOptionPane.showInputDialog(null,"Enter second number"));
txt2.setText(String.valueOf(num2));
}
void clear()
{
txt1.setText("");
txt2.setText("");
txt3.setText("");
}
void sum_cal()
{
accept();
sum=num1+num2;
}
void sub_cal()
{
accept();
sub=num1-num2;
}
void mult_cal()
{
accept();
mult=num1*num2;
}
void div_cal()
{
accept();
div=num1/num2;
}
public void keyPressed(KeyEvent ke)
{
if(ke.getKeyCode()==ke.VK_F1)
{
clear();
sum_cal();
txt3.setText(String.valueOf(sum));
}
if(ke.getKeyCode()==ke.VK_F2)
{
clear();
sub_cal();
txt3.setText(String.valueOf(sub));
}
if(ke.getKeyCode()==ke.VK_F3)
{
clear();
mult_cal();
txt3.setText(String.valueOf(mult));
}
if(ke.getKeyCode()==ke.VK_F4)
{
clear();
div_cal();
txt3.setText(String.valueOf(div));
}
if(ke.getKeyCode()==ke.VK_ESCAPE)
{
System.exit(0);
}
if(ke.getKeyCode()==ke.VK_DELETE)
{
clear();
}
}
public void keyTyped(KeyEvent ke)
{
}
public void keyReleased(KeyEvent ke)
{
}
}
|
package com.example.clickplaymusic;
import android.content.Intent;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
// Variables to increase and the volume by
int volumeInc = 30;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Creating a MediaPlayer object
MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.sample_3s);;
// calling OncompletionListener to release the resources of the object when the playback
// is complete
// mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener(){
// @Override
// public void onCompletion(MediaPlayer mediaPlayer){
// mediaPlayer.reset();
// mediaPlayer.release();
// }
//});
// To find the TextView containing the skip forward text
TextView skipForward = (TextView) findViewById(R.id.skip_forward);
// Setting up onclick listener on the skip forward text
skipForward.setOnClickListener(new View.OnClickListener() {
// To override the method from View Interface so that when the text is clicked it performs the
// mentioned action
@Override
public void onClick(View v) {
int currentPosition = mediaPlayer.getCurrentPosition();
mediaPlayer.seekTo(currentPosition + 60000);
}
});
// To find the TextView containing the skip back text
TextView skipBack = (TextView) findViewById(R.id.skip_back);
// Setting up onclick listener on the skip forward text
skipBack.setOnClickListener(new View.OnClickListener() {
// To override the method from View Interface so that when the text is clicked it performs the
// mentioned action
@Override
public void onClick(View v) {
int currentPosition = mediaPlayer.getCurrentPosition();
mediaPlayer.seekTo(currentPosition - 60000);
}
});
// To find the TextView containing the play text
TextView playButton = (TextView) findViewById(R.id.play_music);
// Setting up onclick listener on the skip forward text
playButton.setOnClickListener(new View.OnClickListener() {
// To override the method from View Interface so that when the text is clicked it performs the
// mentioned action
@Override
public void onClick(View v) {
mediaPlayer.start();
}
});
// To find the TextView containing the pause text
TextView pauseButton = (TextView) findViewById(R.id.pause_music);
// Setting up onclick listener on the skip forward text
pauseButton.setOnClickListener(new View.OnClickListener() {
// To override the method from View Interface so that when the text is clicked it performs the
// mentioned action
@Override
public void onClick(View v) {
mediaPlayer.pause();
}
});
// To find the TextView containing the volume up text
TextView volumeUp = (TextView) findViewById(R.id.volume_up);
// Setting up onclick listener on the skip forward text
volumeUp.setOnClickListener(new View.OnClickListener() {
// To override the method from View Interface so that when the text is clicked it performs the
// mentioned action
@Override
public void onClick(View v) {
int maxVolume = 50;
float log1 = (float) (1-(Math.log(maxVolume - volumeInc) / Math.log(maxVolume)));
mediaPlayer.setVolume(log1, log1);
if(volumeInc < 50){
volumeInc += 4;
}
}
});
// To find the TextView containing the volume down text
TextView volumeDown = (TextView) findViewById(R.id.volume_down);
// Setting up onclick listener on the skip forward text
volumeDown.setOnClickListener(new View.OnClickListener() {
// To override the method from View Interface so that when the text is clicked it performs the
// mentioned action
@Override
public void onClick(View v) {
int maxVolume = 50;
float log1 = (float) (1-(Math.log(maxVolume - volumeInc) / Math.log(maxVolume)));
mediaPlayer.setVolume(log1, log1);
if(volumeInc > 0){
volumeInc -= 4;
}
}
});
}
}
|
package com.yucel.library.service;
import java.util.List;
import com.yucel.library.model.Author;
public interface AuthorService {
List<Author> getAllAuthors();
void saveAuthor(Author author);
Author getAuthorById(long id);
void deleteAuthor(long id);
}
|
package com.techboon.domain.enumeration;
/**
* The Mupan enumeration.
*/
public enum Mupan {
MP1, MP2, MP3
}
|
package com.git.cloud.handler.automation.os.impl;
import java.util.HashMap;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.git.cloud.common.enums.RmHostType;
import com.git.cloud.handler.automation.os.OpenstackCommonHandler;
import com.git.cloud.handler.automation.se.boc.SeConstants;
import com.git.cloud.iaas.openstack.IaasInstanceFactory;
import com.git.cloud.iaas.openstack.model.OpenstackIdentityModel;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
/**
* 查询服务器挂载的卷
* @author SunHailong
* @version 版本号 2017-4-4
*/
public class GetServerVolumeHandler extends OpenstackCommonHandler {
private static Logger logger = LoggerFactory.getLogger(GetServerVolumeHandler.class);
@SuppressWarnings("unchecked")
@Override
public void executeOperate(HashMap<String, Object> reqMap) throws Exception {
String rrinfoId = (String) reqMap.get(SeConstants.RRINFO_ID);
HashMap<String, String> deviceParams;
List<String> deviceIdList = getAutomationService().getDeviceIdsSort(rrinfoId);
String logCommon = "";
for(int i=0 ; i<deviceIdList.size() ; i++) {
logCommon = "创建第" + (i+1) + "个数据盘";
logger.debug(logCommon + "开始...");
deviceParams = (HashMap<String, String>) reqMap.get(deviceIdList.get(i));
String domainName = deviceParams.get("DOMAIN_NAME");
String version = deviceParams.get("VERSION");
if(version == null || "".equals(version)) {
throw new Exception("VERSION为空,请检查参数[VERSION].");
}
String manageOneIp = deviceParams.get("MANAGE_ONE_IP");
if(manageOneIp == null || "".equals(manageOneIp)) {
throw new Exception("MANAGE_ONE_IP为空,请检查参数[MANAGE_ONE_IP].");
}
String openstackIp = deviceParams.get("OPENSTACK_IP");
if(openstackIp == null || "".equals(openstackIp)) {
throw new Exception("服务器IP地址为空,请检查参数[OPENSTACK_IP].");
}
String projectId = deviceParams.get("PROJECT_ID");
if(projectId == null || "".equals(projectId)) {
throw new Exception("ProjectId为空,请检查参数[PROJECT_ID].");
}
String targetServerId = deviceParams.get("TARGET_SERVER_ID");
if(targetServerId == null || "".equals(targetServerId)) {
throw new Exception("计算实例Id为空,请检查参数[TARGET_SERVER_ID].");
}
String hostType = deviceParams.get("HOST_TYPE");
if(hostType == null || "".equals(hostType)) {
throw new Exception("主机类型为空,请检查参数[HOST_TYPE].");
}
String projectName = deviceParams.get("PROJECT_NAME");
if(projectName == null || "".equals(projectName)) {
throw new Exception("ProjectName为空,请检查参数[PROJECT_NAME].");
}
Boolean isVm = null;
if(hostType.equals(RmHostType.VIRTUAL.getValue())) {
isVm = true;
} else if(hostType.equals(RmHostType.PHYSICAL.getValue())) {
isVm = false;
} else {
throw new Exception("主机类型HOST_TYPE不识别,HOST_TYPE=" + hostType);
}
OpenstackIdentityModel model = new OpenstackIdentityModel();
model.setVersion(version);
model.setOpenstackIp(openstackIp);
model.setDomainName(domainName);
model.setManageOneIp(manageOneIp);
model.setProjectId(projectId);
model.setProjectName(projectName);
String jsonData = IaasInstanceFactory.computeInstance(version).getServerVolume(model, targetServerId, isVm);
logger.debug("服务器[" + deviceIdList.get(i) + "]挂载的卷:" + jsonData);
logger.debug(logCommon + "完成,开始进行数据处理...");
JSONObject json = JSONObject.fromObject(jsonData);
JSONObject subJson;
JSONArray array = json.getJSONArray("volumeAttachments");
StringBuffer volumeIds = new StringBuffer();
for(int j=0 ; j<array.size() ; j++) {
subJson = array.getJSONObject(j);
if(j > 0) {
volumeIds.append(",");
}
volumeIds.append(subJson.getString("volumeId"));
}
setHandleResultParam(deviceIdList.get(i), "DATA_VOLUME_ID", volumeIds.toString());
logger.debug(logCommon + "结束...");
}
// 保存流程参数
this.saveParam(reqMap);
}
}
|
package orm.integ.eao.model;
public interface HasId {
public String getId();
public void setId(Object id);
}
|
package me.ninabernick.cookingapplication.Location;
import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.google.android.gms.maps.GoogleMap;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import me.ninabernick.cookingapplication.R;
public class StoreListFragment extends Fragment implements StoreAdapter.MapListener {
GoogleMap mMap;
double latitude;
double longitude;
List<HashMap<String, String>> nearbyPlacesList;
StoreAdapter storeAdapter;
RecyclerView rvMyStores;
BottomNavigationView bottomNavigationView;
ProgressBar loadingView;
LinearLayoutManager llm;
private StoreListFragmentListener listener;
public interface StoreListFragmentListener {
void oneStoreMap(String latitude, String longitude);
}
public static StoreListFragment newInstance(Double latitude, Double longitude) {
StoreListFragment storeListFragment = new StoreListFragment();
Bundle args = new Bundle();
args.putDouble("Latitude", latitude);
args.putDouble("Longitude", longitude);
storeListFragment.setArguments(args);
return storeListFragment;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof StoreListFragmentListener) {
this.listener = (StoreListFragmentListener) context;
}
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
longitude = getArguments().getDouble("Longitude", 0);
latitude = getArguments().getDouble("Latitude", 0);
nearbyPlacesList = new ArrayList<>();
storeAdapter = new StoreAdapter(nearbyPlacesList, getFragmentManager(), this);
}
private String getUrl(double latitude, double longitude, String nearbyPlace) {
StringBuilder googlePlacesUrl = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
googlePlacesUrl.append("location=" + latitude + "," + longitude);
googlePlacesUrl.append("&radius=" + 10000);
googlePlacesUrl.append("&type=" + nearbyPlace);
googlePlacesUrl.append("&sensor=true");
googlePlacesUrl.append("&type=" + nearbyPlace);
googlePlacesUrl.append("&key=" + "AIzaSyD_gosGg3qBnX2WOj6-fglzL49kTMO-KuY");
Log.d("getUrl", googlePlacesUrl.toString());
return (googlePlacesUrl.toString());
}
private class getStoreList extends AsyncTask<Object, String, String> {
String googlePlacesData;
GoogleMap mMap;
String url;
@Override
protected String doInBackground(Object... params) {
try {
Log.d("GetNearbyPlacesData", "doInBackground entered");
mMap = (GoogleMap) params[0];
url = (String) params[1];
DownloadUrl downloadUrl = new DownloadUrl();
Log.i("This is url", "Google Places url: " + url);
googlePlacesData = downloadUrl.readUrl(url);
Log.i("This is googlePlacesData", "Google Places Data: " + googlePlacesData);
Log.d("GooglePlacesReadTask", "doInBackground Exit");
} catch (Exception e) {
Log.d("GooglePlacesReadTask", e.toString());
}
return googlePlacesData;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.d("Checking URL in StoreListFragment", url);
Log.d("GooglePlacesReadTask", "onPostExecute Entered");
DataParser dataParser = new DataParser();
List<HashMap<String, String>> nearbyPlaces = dataParser.parse(result);
nearbyPlacesList.clear();
nearbyPlacesList.addAll(nearbyPlaces);
Log.d("GooglePlacesReadTask", "onPostExecute Exit");
storeAdapter.notifyDataSetChanged();
loadingView.setVisibility(View.INVISIBLE);
Log.d("Adapter", "Not Different Data Set");
}
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup parent, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_storelist, parent, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
loadingView = (ProgressBar) view.findViewById(R.id.pbLoading);
rvMyStores = view.findViewById(R.id.rvMyStores);
rvMyStores.setLayoutManager(new SnappingLinearLayoutManager(getContext()));
rvMyStores.setHasFixedSize(true);
rvMyStores.setAdapter(storeAdapter);
calltoNearbyList();
bottomNavigationView = (BottomNavigationView) view.findViewById(R.id.top_navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.distance:
loadingView.setVisibility(View.VISIBLE);
bottomNavigationView.getMenu().getItem(1).setIcon(R.drawable.rating);
rvMyStores.smoothScrollToPosition(0);
calltoNearbyList();
return true;
case R.id.rating:
loadingView.setVisibility(View.VISIBLE);
bottomNavigationView.getMenu().getItem(1).setIcon(R.drawable.rating_filled);
rvMyStores.smoothScrollToPosition(0);
calltoProminenceList();
return true;
case R.id.price:
loadingView.setVisibility(View.VISIBLE);
bottomNavigationView.getMenu().getItem(1).setIcon(R.drawable.rating);
rvMyStores.smoothScrollToPosition(0);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
sortListPrice();
loadingView.setVisibility(View.INVISIBLE);
}
}, 100);
return true;
}
return false;
}
});
}
public void calltoProminenceList() {
String url = getUrl(latitude, longitude, "supermarket");
Log.i("This is url prom", "Url: " + url);
Object[] DataTransfer = new Object[2];
DataTransfer[0] = mMap;
DataTransfer[1] = url;
Log.d("onClick", url);
getStoreList getStorelistData = new getStoreList();
getStorelistData.execute(DataTransfer);
}
public void calltoNearbyList() {
String url = getDistanceUrl(latitude, longitude, "supermarket");
Log.i("This is url dist", "Url: " + url);
Object[] DataTransfer = new Object[2];
DataTransfer[0] = mMap;
DataTransfer[1] = url;
Log.d("onClick", url);
getStoreList getStorelistData = new getStoreList();
getStorelistData.execute(DataTransfer);
}
public void sortListPrice() {
Collections.sort(nearbyPlacesList, new Comparator<HashMap<String, String>>() {
public int compare(HashMap<String, String> obj1, HashMap<String, String> obj2) {
return obj2.get("price_level").compareTo(obj1.get("price_level"));
}
});
storeAdapter.notifyDataSetChanged();
}
private String getDistanceUrl(double latitude, double longitude, String nearbyPlace) {
StringBuilder googlePlacesUrl = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
googlePlacesUrl.append("location=" + latitude + "," + longitude);
googlePlacesUrl.append("&rankby=distance");
googlePlacesUrl.append("&type=" + nearbyPlace);
googlePlacesUrl.append("&sensor=true");
googlePlacesUrl.append("&type=" + nearbyPlace);
googlePlacesUrl.append("&key=" + "AIzaSyD_gosGg3qBnX2WOj6-fglzL49kTMO-KuY");
Log.d("getUrl", googlePlacesUrl.toString());
return (googlePlacesUrl.toString());
}
@Override
public void onMapDetailsClicked(String longitude, String latitude) {
listener.oneStoreMap(longitude, latitude);
}
public void findLocationClicked(Double latitude, Double longitude) {
for (HashMap<String, String> hashMap : nearbyPlacesList) {
if (Double.parseDouble(hashMap.get("lat")) == latitude) {
if (Double.parseDouble(hashMap.get("lng")) == longitude) {
final int position = nearbyPlacesList.indexOf(hashMap);
rvMyStores.smoothScrollToPosition(position);
View rightview = rvMyStores.getChildAt(position);
for (int i = 0; i < nearbyPlacesList.size(); i++) {
View view = rvMyStores.getChildAt(i);
if (view != null) {
TextView textView = (TextView) view.findViewById(R.id.tvStoreName);
if (position == i) {
Log.i("textview", "textview" + textView.toString());
textView.setTextColor(ContextCompat.getColor(getContext(), R.color.lightGray));
} else {
textView.setTextColor(ContextCompat.getColor(getContext(), R.color.darkPurple));
}
}
}
}
}
}
}
}
|
package com.egova.eagleyes.vm;
import android.app.Application;
import com.egova.baselibrary.model.BaseResponse;
import com.egova.baselibrary.model.Lcee;
import com.egova.baselibrary.model.NameTextValue;
import com.egova.eagleyes.model.respose.LogHistory;
import com.egova.eagleyes.model.respose.PersonInfo;
import com.egova.eagleyes.repository.UserInfoRepository;
import com.egova.eagleyes.repository.imp.UserInfoRepositoryImp;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.arch.core.util.Function;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Transformations;
/**
* 用户中心
*/
public class UserViewModel extends AndroidViewModel {
private UserInfoRepository repository;
//图片上传统计
private MutableLiveData<String> takePhotoParams = new MutableLiveData<>();
private LiveData<Lcee<BaseResponse<List<NameTextValue<Integer>>>>> takePhotoData;
//我的--工作记录
private MutableLiveData<String> logHistoryParams = new MutableLiveData<>();
private LiveData<Lcee<BaseResponse<List<LogHistory>>>> logHistoryData;
//警员列表
private MutableLiveData<String> personListParam = new MutableLiveData<>();
private LiveData<Lcee<BaseResponse<List<PersonInfo>>>> personListData;
public UserViewModel(@NonNull Application application) {
super(application);
repository = new UserInfoRepositoryImp();
}
//图片上传统计
public LiveData<Lcee<BaseResponse<List<NameTextValue<Integer>>>>> getTakePhotoData() {
if (takePhotoData == null) {
takePhotoData = Transformations.switchMap(takePhotoParams, new Function<String, LiveData<Lcee<BaseResponse<List<NameTextValue<Integer>>>>>>() {
@Override
public LiveData<Lcee<BaseResponse<List<NameTextValue<Integer>>>>> apply(String input) {
return repository.getTakePhotoStatistics();
}
});
}
return takePhotoData;
}
//我的-工作记录
public LiveData<Lcee<BaseResponse<List<LogHistory>>>> getLogHistoryData() {
if (logHistoryData == null) {
logHistoryData = Transformations.switchMap(logHistoryParams, new Function<String, LiveData<Lcee<BaseResponse<List<LogHistory>>>>>() {
@Override
public LiveData<Lcee<BaseResponse<List<LogHistory>>>> apply(String input) {
return repository.getLogHistory();
}
});
}
return logHistoryData;
}
//所有警员列表
public LiveData<Lcee<BaseResponse<List<PersonInfo>>>> getPersonListData() {
if (personListData == null) {
personListData = Transformations.switchMap(personListParam, new Function<String, LiveData<Lcee<BaseResponse<List<PersonInfo>>>>>() {
@Override
public LiveData<Lcee<BaseResponse<List<PersonInfo>>>> apply(String input) {
return repository.getAllPersonList();
}
});
}
return personListData;
}
/**
* 获取图片上传统计
*/
public void loadTakePhotoData() {
takePhotoParams.setValue("");
}
/**
* 我的-工作记录
*/
public void loadLogHistoryData() {
logHistoryParams.setValue("");
}
//所有警员列表
public void loadAllPerson() {
personListParam.setValue("");
}
}
|
package com.flushoutsolutions.foheart.modules;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import com.flushoutsolutions.foheart.application.FoHeart;
import org.json.JSONException;
import org.json.JSONObject;
public class Spacer
{
public View viSpace;
private String container;
public String name;
public int height = 10;
public ViewGroup layout;
public void initialize(String view, String name, ViewGroup layout, String properties) throws JSONException
{
this.container = view;
this.name = name;
this.layout = layout;
JSONObject jsonProperties = new JSONObject(properties);
if (!jsonProperties.isNull("height"))
this.height = jsonProperties.getInt("height");
}
public void render()
{
viSpace = new View(FoHeart.getAppContext());
viSpace.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, height));
this.layout.addView(viSpace);
}
}
|
package at.fhv.teama.easyticket.server.security;
import at.fhv.teama.easyticket.server.user.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.ldap.userdetails.LdapAuthoritiesPopulator;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.Collection;
import java.util.stream.Collectors;
@Component
@RequiredArgsConstructor
public class AuthoritiesPopulator implements LdapAuthoritiesPopulator {
private final UserRepository userRepository;
@Override
public Collection<? extends GrantedAuthority> getGrantedAuthorities(
DirContextOperations userData, String username) {
return userRepository
.findById(username)
.map(
u ->
u.getRoles().stream()
.map(role -> new SimpleGrantedAuthority("ROLE_" + role))
.collect(Collectors.toList()))
.orElse(Arrays.asList(new SimpleGrantedAuthority("ROLE_USER")));
}
}
|
package listeners;
import handlers.Handler;
import java.net.DatagramPacket;
import java.net.InetAddress;
public class MDBListener extends Listener {
public MDBListener(InetAddress addr, int port) {
super(addr, port);
}
@Override
public void handler(DatagramPacket dataPacket) {
new Thread(new Handler(dataPacket)).start();
}
// Start Log of PUTCHUNK
}
|
package Problem_1168;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
int N = Integer.parseInt(str.split(" ")[0]);
int K = Integer.parseInt(str.split(" ")[1])-1;
StringBuilder sb = new StringBuilder("<");
ArrayList<Integer> arr = new ArrayList<>();
ArrayList<Integer> ans = new ArrayList<>();
for(int i = 0; i < N; i++) arr.add(i+1) ;
int idx =0;
for(int i = 0; i< N; i++) {
idx += K;
idx %= arr.size();
int tmp = arr.get(idx);
ans.add(tmp);
arr.remove(idx);
}
for(int i = 0; i<ans.size()-1;i++) sb.append(ans.get(i)).append(", ");
sb.append(ans.get(ans.size()-1)).append(">");
System.out.println(sb);
}
}
|
package top.qifansfc.study_springboot.service;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.qifansfc.study_springboot.domain.User;
import top.qifansfc.study_springboot.dao.UserDao;
import top.qifansfc.study_springboot.exception.UserException;
import top.qifansfc.study_springboot.util.Result;
import top.qifansfc.study_springboot.util.ReturnResult;
import java.util.List;
@Service
@MapperScan("top.qifansfc.study_springboot.dao")
public class UserServiceImpl implements UserService{
@Autowired
private UserDao userDao;
@Override
public Result getUserById(Integer id) throws Exception{
Result result;
if (id==null){
throw new UserException(-2,"未指定参数id或参数id为空");
}
User user=userDao.getUserById(id);
if (user==null){
throw new UserException(-3,"没有此用户");
}
result=ReturnResult.success(user);
return result;
}
@Override
public Result getAllUser() throws Exception {
Result result;
List<User> users=userDao.getAllUser();
if (users.isEmpty()){
throw new UserException(-2,"没有用户");
}
result=ReturnResult.success(users);
return result;
}
@Override
public Result insertUser(User user) throws Exception {
Result result;
if (userDao.insertUser(user)>0){
result=ReturnResult.success("添加"+user.toString()+"成功");
}else{
result=ReturnResult.failed(-1,"添加"+user.toString()+"失败");
}
return result;
}
@Override
public Result updateUser(User user) throws Exception {
Result result;
if (userDao.updateUser(user)>0){
result=ReturnResult.success("更新"+user.toString()+"成功");
}else{
result=ReturnResult.failed(-1,"更新"+user.toString()+"失败");
}
return result;
}
@Override
public Result deleteUserById(Integer id) throws Exception {
Result result;
User user=userDao.getUserById(id);
if (userDao.deleteUserById(id)>0){
result=ReturnResult.success("删除"+user.toString()+"成功");
}else{
result=ReturnResult.failed(-1,"删除"+user.toString()+"失败");
}
return result;
}
}
|
package Service;
import Dao.model.SaleGoods;
import junit.framework.TestCase;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = {"file:src/main/webapp/WEB-INF/mvc-dispatcher-servlet.xml","file:src/main/webapp/WEB-INF/spring-mybatis.xml"})
public class RePublishSearchResultServiceTest extends TestCase {
@Autowired
RePublishGoodsService rePublishGoodsService;
@Test
public void testUpdateGoodsInformation() throws Exception {
SaleGoods saleGoods = new SaleGoods();
saleGoods.setSalegoodsid(4);
saleGoods.setHeadline("魔声");
saleGoods.setPrice(1000.0);
saleGoods.setDescription("头戴耳机");
saleGoods.setPhonenumber("1234567890");
saleGoods.setContactor("dongdong");
saleGoods.setSdid(4);
saleGoods.setUserid(5);
saleGoods.setGoodsflag(0);
System.out.print(rePublishGoodsService.updateGoodsInformation(saleGoods));
}
}
|
package fr.doranco.designpattern.bridge;
public class CarteGraphique {
public void dessiner(String[] triangles) {
// Dessiner les triangles
}
}
|
package ch.zuehlke.fullstack.hackathon.service;
import ch.zuehlke.fullstack.hackathon.model.Badge;
import ch.zuehlke.fullstack.hackathon.model.Rating;
import ch.zuehlke.fullstack.hackathon.model.Skill;
import ch.zuehlke.fullstack.hackathon.model.Training;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class BadgeServiceTest {
private static final String VALID_ID = "feva";
private RatingService ratingService;
private SkillService skillService;
private TrainingService trainingService;
private BadgeService testee;
@BeforeEach
void setUp() {
this.ratingService = mock(RatingService.class);
this.skillService = mock(SkillService.class);
this.trainingService = mock(TrainingService.class);
this.testee = new BadgeService(ratingService, skillService, trainingService);
}
@Test
void addBadgesForJavaKnowledge_overCountThresholdAndEarnedBadgesNull_throws() {
assertThrows(NullPointerException.class,
() -> testee.addBadgesForJavaKnowledge(null, 11));
}
@Test
void addBadgesForJavaKnowledge_overCountThreshold_addsJavaBadgeToEarnedBadges() {
List<Badge> earnedBadges = new ArrayList<>();
testee.addBadgesForJavaKnowledge(earnedBadges, 11);
assertEquals(1, earnedBadges.size());
assertEquals(2, earnedBadges.get(0).getId());
assertEquals("King of Java", earnedBadges.get(0).getDescription());
}
@Test
void addBadgesForJavaKnowledge_underCountThreshold_nothingHappens() {
List<Badge> earnedBadges = new ArrayList<>();
testee.addBadgesForJavaKnowledge(earnedBadges, 9);
assertEquals(0, earnedBadges.size());
}
@Test
void addBadgesForWebKnowledge_overCountThresholdAndEarnedBadgesNull_throws() {
assertThrows(NullPointerException.class,
() -> testee.addBadgesForWebKnowledge(null, 11));
}
@Test
void addBadgesForWebKnowledge_overCountThreshold_addsWebBadgeToEarnedBadges() {
List<Badge> earnedBadges = new ArrayList<>();
testee.addBadgesForWebKnowledge(earnedBadges, 11);
assertEquals(1, earnedBadges.size());
assertEquals(5, earnedBadges.get(0).getId());
assertEquals("Master of Web Technologies", earnedBadges.get(0).getDescription());
}
@Test
void addBadgesForWebKnowledge_underCountThreshold_nothingHappens() {
List<Badge> earnedBadges = new ArrayList<>();
testee.addBadgesForWebKnowledge(earnedBadges, 9);
assertEquals(0, earnedBadges.size());
}
@Test
void addBadgesForRatings_overPointsThresholdAndEarnedBadgesNull_throws() {
Rating highRating = new Rating(VALID_ID, 0, 260);
assertThrows(NullPointerException.class, () -> testee.addBadgesForRatings(null, List.of(highRating)));
}
@Test
void addBadgesForRatings_overPointsThreshold_addsExpertVotesBadge() {
List<Badge> earnedBadges = new ArrayList<>();
Rating highRating = new Rating(VALID_ID, 0, 260);
testee.addBadgesForRatings(earnedBadges, List.of(highRating));
assertEquals(1, earnedBadges.size());
assertEquals(3, earnedBadges.get(0).getId());
assertEquals("5 Expert Votes for a skill", earnedBadges.get(0).getDescription());
}
@Test
void addBadgesForRatings_twoRatingsOverPointsThreshold_addsExpertVotesBadgeOnce() {
List<Badge> earnedBadges = new ArrayList<>();
Rating highRating = new Rating(VALID_ID, 0, 260);
Rating anotherHighRating = new Rating(VALID_ID, 2, 260);
testee.addBadgesForRatings(earnedBadges, List.of(highRating, anotherHighRating));
assertEquals(1, earnedBadges.size());
}
@Test
void computeMatchingBadge_hackathonKeywordMatched_returnOptionalOfHackathonBadge() {
Training aHackathonTraining = new Training("Full Stack Java Hackathon", 0, List.of(), 2);
Optional<Badge> result = testee.computeMatchingBadge(aHackathonTraining);
assertTrue(result.isPresent());
assertEquals(1, result.get().getId());
assertEquals("Hackathon", result.get().getDescription());
}
@Test
void computeMatchingBadge_noKeywordsMatched_returnEmptyOptional() {
Training training = new Training("Test", 0, List.of(), 2);
Optional<Badge> result = testee.computeMatchingBadge(training);
assertTrue(result.isEmpty());
}
@Test
void getBadges_withTrainingsAndRatingsMatchingThresholdsAndSkills_returnEarnedBadges() {
Rating highRating = new Rating(VALID_ID, 0, 260);
Training aHackathonTraining = new Training("Full Stack Java Hackathon", 0, List.of(), 2);
Training aJavaTraining = new Training("Java Course", 1, List.of(), 3);
Training aWebTraining = new Training("Javascript Course", 2, List.of(), 4);
Skill javaInsightSkill = new Skill(0, "Java Ecosystem Description", "Java Ecosystem", "EXPERT");
Skill webInsightSkill = new Skill(1, "Angular and html and css knowledge", "Web technologies", "PROFICIENT");
when(trainingService.getTrainingsFromCurrentAndLastYear(VALID_ID)).thenReturn(List.of(aJavaTraining, aHackathonTraining, aWebTraining));
when(ratingService.getRatings(VALID_ID)).thenReturn(List.of(highRating));
when(skillService.getSkillsWithCalculatedPoints(VALID_ID)).thenReturn(
new ArrayList<>(Arrays.asList(javaInsightSkill, webInsightSkill)));
List<Badge> result = testee.getBadges(VALID_ID);
assertEquals(2, result.size());
assertTrue(result.stream().anyMatch(badge ->
badge.getId() == 1 && badge.getDescription().equals("Hackathon")
));
assertTrue(result.stream().anyMatch(badge ->
badge.getId() == 3 && badge.getDescription().equals("5 Expert Votes for a skill")
));
}
}
|
import java.util.Scanner;
public class Solution {
static int minpath = Integer.MAX_VALUE;
static class MyPoint {
int x, y;
boolean visited;
public MyPoint(int x, int y) {
this.x = x;
this.y = y;
this.visited = false;
}
public int getLength(MyPoint point) {
return Math.abs(this.x - point.x) + Math.abs(this.y - point.y);
}
}
public static void caculate(MyPoint start, MyPoint[] points, int sum, int count) {
for (int i = 0; i < points.length; i++) {
if (points[i].visited){
continue;
}
points[i].visited = true;
count++;
sum += start.getLength(points[i]);
if (count == points.length){
sum += points[i].getLength(new MyPoint(0,0)); //需要回到起始点
minpath = Math.min(minpath, sum);
}
caculate(points[i], points, sum,count);
points[i].visited = false;
count--;
sum -= start.getLength(points[i]);
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num = Integer.parseInt(scanner.nextLine().trim());
MyPoint[] points = new MyPoint[num];
for (int i = 0; i < num; i++) {
String[] locations = scanner.nextLine().trim().split(",");
points[i] = new MyPoint(Integer.parseInt(locations[0]), Integer.parseInt(locations[1]));
}
caculate(new MyPoint(0,0),points,0,0);
System.out.println(minpath);
}
}
|
package View;
import algorithms.search.AState;
import algorithms.search.MazeState;
import algorithms.search.Solution;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.image.Image;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
/**
* This class represents a Solution displayer canvas
*/
public class SolutionDisplayer extends Canvas implements Displayer {
private ArrayList<AState> solutionPath;
private StringProperty ImageFileNameSolutionPath = new SimpleStringProperty();
@Override
public void redraw(Object... objects) {
if (objects.length == 2 && objects[0] instanceof int[][] && objects[1] instanceof Solution) {
try {
Image solutionPathImage = new Image(new FileInputStream(ImageFileNameSolutionPath.get()));
GraphicsContext gc = getGraphicsContext2D();
gc.clearRect(0, 0, getWidth(), getHeight());
int[][] maze = (int[][]) objects[0];
double canvasHeight = getHeight();
double canvasWidth = getWidth();
double cellHeight = canvasHeight / maze.length;
double cellWidth = canvasWidth / maze[0].length;
for (AState state : solutionPath) {
MazeState mazeState = (MazeState) state;
gc.drawImage(solutionPathImage, mazeState.getPosition().getColumnIndex() * cellWidth,
mazeState.getPosition().getRowIndex() * cellHeight, cellWidth, cellHeight);
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
/**
* ets the array representing the maze and the path of the solution of the maze
* @param maze - the array representing the maze
* @param solution - the path of the solution of the maze
*/
public void setSolution(int[][] maze,Solution solution) {
this.solutionPath = solution.getSolutionPath();
redraw(maze, solution);
}
@Override
public void ResetZooming(double x,double y)
{
setScaleX(x);
setScaleY(y);
redraw();
}
public String getImageFileNameSolutionPath() {
return ImageFileNameSolutionPath.get();
}
public void setImageFileNameSolutionPath(String imageFileNameCharacter) {
this.ImageFileNameSolutionPath.set(imageFileNameCharacter);
}
}
|
package program.oops;
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter the number: ");
int n= s.nextInt();
int var=1;
//int fact=1;
for(int i=n;i>=1;i--) {
//fact= fact*i;
var=var*i;
}
System.out.println(var);
}
}
|
package ua.bellkross.client;
import android.os.AsyncTask;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import ua.bellkross.client.adapters.ArrayListRooms;
import ua.bellkross.client.adapters.GridViewAdapter;
import ua.bellkross.client.database.DBHelper;
import ua.bellkross.client.model.Room;
import ua.bellkross.client.model.Task;
import static ua.bellkross.client.RoomsActivity.LOG_TAG;
public class ClientTask extends AsyncTask<Void, Void, Void> {
public static final String IP = "192.168.0.101";
public static final int PORT = 80;
private Socket socket;
private BufferedReader in;
private PrintWriter out;
private Resender resend;
private String login;
private boolean refreshWithoutNotify = false;
private static ClientTask instance;
public ClientTask(String login) {
this.login = login;
instance = this;
}
public static ClientTask getInstance(String login) {
return instance == null ? new ClientTask(login) : instance;
}
public static ClientTask getInstance() {
return instance;
}
@Override
protected Void doInBackground(Void... voids) {
try {
InetAddress ipAddress = InetAddress.getByName(IP);
this.socket = new Socket(ipAddress, PORT);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
resend = new Resender();
resend.execute();
out = new PrintWriter(socket.getOutputStream(), true);
push(login);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public synchronized void push(final String message) {
new Thread(new Runnable() {
@Override
public void run() {
out.printf(message);
}
}).start();
Log.d(LOG_TAG, "message \"" + message + "\" pushed");
}
public void close() {
try {
resend.setStop();
in.close();
out.close();
socket.close();
} catch (Exception e) {
Log.d(LOG_TAG, "Thread's haven't closed");
}
}
private class Resender extends AsyncTask<Void, Void, Void> {
private boolean stoped;
public void setStop() {
stoped = true;
}
@Override
protected Void doInBackground(Void... voids) {
try {
while (!stoped) {
final String str = in.readLine();
Log.d(LOG_TAG, "read = " + str);
int command = Integer.parseInt(str.substring(0, 1));
Log.d(LOG_TAG, "command = " + command);
readCommand(str, command);
}
} catch (IOException e) {
Log.d(LOG_TAG, "Ошибка при получении сообщения.");
e.printStackTrace();
}
return null;
}
}
private void readCommand(String data, int command) {
switch (command) {
case 7:
String data2 = data.substring(data.indexOf('&')+1);
Log.d(LOG_TAG,"Data2 = " + data2);
ArrayList<Room> roomsAL = new ArrayList<>();
ArrayList<Task> tasksAL = new ArrayList<>();
try {
JSONArray tasks = new JSONArray(data2);
int serverDbID;
int roomID;
String text, nameOfCreator;
int state;
for (int i = 0; i < tasks.length(); ++i) {
JSONObject task = (JSONObject) tasks.get(i);
serverDbID = task.getInt("id");
roomID = task.getInt("fk");
text = task.getString("text");
nameOfCreator = task.getString("creator");
state = task.getInt("state");
Task newTask = new Task(serverDbID, roomID, text, nameOfCreator, state);
tasksAL.add(newTask);
}
JSONArray rooms = new JSONArray(data.substring(1));
int serverDbIDr;
String nameR;
String passwordR;
for (int i = 0; i < rooms.length(); ++i) {
JSONObject room = (JSONObject) rooms.get(i);
serverDbIDr = room.getInt("id");
nameR = room.getString("name");
passwordR = room.getString("pass");
Room newRoom = new Room(nameR, passwordR, serverDbIDr);
for (Task task : tasksAL) {
if (task.getRoomID() == newRoom.getServerDbID()) {
newRoom.getTasks().add(task);
}
}
roomsAL.add(newRoom);
}
if(refreshWithoutNotify) {
refreshWithoutNotify(roomsAL);
refreshWithoutNotify = false;
}else{
GridViewAdapter.getInstance().refresh(roomsAL);
}
} catch (JSONException e) {
Log.d(LOG_TAG, e.toString());
}
break;
}
}
private void refreshWithoutNotify(ArrayList<Room> rooms) {
ArrayListRooms.getInstance().clear();
ArrayListRooms.getInstance().addAll(DBHelper.getInstance().refresh(rooms));
Log.d(LOG_TAG,"method rwoutn alr" + ArrayListRooms.getInstance().get(0).getTasks());
}
public void setRefreshWithoutNotify(boolean refreshWithoutNotify) {
this.refreshWithoutNotify = refreshWithoutNotify;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
}
|
package com.codingchili.instance.model.dialog;
import com.codingchili.instance.model.events.Event;
import com.codingchili.instance.model.events.EventType;
import com.codingchili.core.listener.Request;
/**
* @author Robin Duda
*/
public class DialogEvent implements Event {
private Request request;
private String source;
public DialogEvent setSource(String sourceId) {
this.source = sourceId;
return this;
}
@Override
public String getSource() {
return source;
}
@Override
public EventType getRoute() {
return EventType.dialog;
}
public Request getRequest() {
return request;
}
public DialogEvent setRequest(Request request) {
this.request = request;
return this;
}
}
|
package com.lanyage.seckill.dao;
import com.lanyage.seckill.entity.SuccessKilled;
import org.apache.ibatis.annotations.Param;
/**
* Created by lanyage on 2017/11/5.
*/
public interface SuccessKilledDao {
/**
* 插入购买明细,可过滤重复,如果影响行数=1,表示更新的行数
*
* @param sekillId
* @param userPhone
* @return
* 插入的行数
*/
int insertSuccessKilled(@Param("seckillId")long sekillId,@Param("userPhone")long userPhone);
/**
* 查询SuccessKilled并携带秒杀seckill对象
*
* @param seckillId
* @return
*/
SuccessKilled queryByIdWithSeckill(@Param("seckillId")long seckillId, @Param("userPhone")long userPhone);
}
|
package de.hdm.softwarepraktikum.shared;
import java.sql.Timestamp;
import java.util.ArrayList;
import com.google.gwt.user.client.rpc.AsyncCallback;
import de.hdm.softwarepraktikum.shared.bo.Group;
import de.hdm.softwarepraktikum.shared.bo.Item;
import de.hdm.softwarepraktikum.shared.bo.ListItem;
import de.hdm.softwarepraktikum.shared.bo.Person;
import de.hdm.softwarepraktikum.shared.bo.ShoppingList;
import de.hdm.softwarepraktikum.shared.bo.Store;
import de.hdm.softwarepraktikum.shared.report.ItemsByGroupReport;
import de.hdm.softwarepraktikum.shared.report.ItemsByPersonReport;
/*Asynchrones Interface fuer den Reportgenerator
*
*
*/
public interface ReportGeneratorAsync {
public void init(AsyncCallback<Void> callback) throws IllegalArgumentException;
void getReportOfGroupBetweenDates(Boolean filterPerson, Person p, Group g, Store s, Timestamp from, Timestamp to,
AsyncCallback<ItemsByGroupReport> callback);
public void getAllItems(AsyncCallback<ArrayList<Item>> callback) throws IllegalArgumentException;
public void getAllStores(AsyncCallback<ArrayList<Store>> callback);;
void getAllGroups(Person p, AsyncCallback<ArrayList<Group>> callback);
public void AddImprint(AsyncCallback<Void> callback) throws IllegalArgumentException;
void getReportOfPerson(Person p, Store s, Group g, AsyncCallback<ItemsByPersonReport> callback);
void getReportOfGroup(Boolean filterPerson, Person p, Group g, Store s, AsyncCallback<ItemsByGroupReport> callback);
void getReportOfPersonBetweenDates(Person p, Store s, Group g, Timestamp from, Timestamp to, AsyncCallback<ItemsByPersonReport> callback);
void getAllPersons(AsyncCallback<ArrayList<Person>> callback);
}
|
import org.junit.Assert;
import org.junit.Test;
import java.util.Dictionary;
import java.util.function.BiPredicate;
public class ValidadorCombinadoTest {
@Test
public void devePermitirCombinarVariosTiposDeValidadores() {
Validador validador = new Validador();
ICustomPredicate<String, Integer, String> predicate = (String s1, Integer n, String s2) -> s1.length() > s2.length() && s1.length() > n && s2.length() > n;
Dictionary<String, String> resultado = validador
.garantirQue((Integer i) -> i > 10, 11,Mensagem.semIdentificador("Teste", "número inválido"))
.naoPermitirQue((Integer i) -> i <= 10, 11,Mensagem.semIdentificador("Teste", "número inválido"))
.garantirQue((String s) -> s.length() > 10 , "mauro",Mensagem.semIdentificador("StringTamanho", "Nome inválido"))
.garantirQue((String s, Integer n) -> s.length() < n, "teste", 11,Mensagem.semIdentificador("StringTamanho", "Nome inválido"))
.garantirQue(predicate, "mauro", 5, "leal",Mensagem.semIdentificador("CustomPredicate", "parâmetros inválidos"))
.obterResultado();
Assert.assertEquals(2, resultado.size());
Assert.assertNotNull(resultado.get("StringTamanho"));
Assert.assertNotNull(resultado.get("CustomPredicate"));
}
}
|
//------------------------------------------------------------------------------
// Copyright (c) 2012 Microsoft Corporation. All rights reserved.
//
// Description: See the class level JavaDoc comments.
//------------------------------------------------------------------------------
package com.microsoft.live;
/**
* Represents any functionality related to downloads that works with the Live Connect
* Representational State Transfer (REST) API.
*/
public interface LiveDownloadOperationListener {
/**
* Called when the associated download operation call completes.
* @param operation The {@link LiveDownloadOperation} object.
*/
public void onDownloadCompleted(LiveDownloadOperation operation);
/**
* Called when the associated download operation call fails.
* @param exception The error returned by the REST operation call.
* @param operation The {@link LiveDownloadOperation} object.
*/
public void onDownloadFailed(LiveOperationException exception,
LiveDownloadOperation operation);
/**
* Updates the progression of the download.
* @param totalBytes The total bytes downloaded.
* @param bytesRemaining The bytes remaining to download.
* @param operation The {@link LiveDownloadOperation} object.
*/
public void onDownloadProgress(int totalBytes,
int bytesRemaining,
LiveDownloadOperation operation);
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* 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
*
* https://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 org.springframework.web.servlet.tags.form;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import jakarta.servlet.jsp.JspException;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.PropertyAccessorFactory;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
/**
* Abstract base class to provide common methods for implementing
* databinding-aware JSP tags for rendering <i>multiple</i>
* HTML '{@code input}' elements with a '{@code type}'
* of '{@code checkbox}' or '{@code radio}'.
*
* @author Juergen Hoeller
* @author Scott Andrews
* @since 2.5.2
*/
@SuppressWarnings("serial")
public abstract class AbstractMultiCheckedElementTag extends AbstractCheckedElementTag {
/**
* The HTML '{@code span}' tag.
*/
private static final String SPAN_TAG = "span";
/**
* The {@link java.util.Collection}, {@link java.util.Map} or array of objects
* used to generate the '{@code input type="checkbox/radio"}' tags.
*/
@Nullable
private Object items;
/**
* The name of the property mapped to the '{@code value}' attribute
* of the '{@code input type="checkbox/radio"}' tag.
*/
@Nullable
private String itemValue;
/**
* The value to be displayed as part of the '{@code input type="checkbox/radio"}' tag.
*/
@Nullable
private String itemLabel;
/**
* The HTML element used to enclose the '{@code input type="checkbox/radio"}' tag.
*/
private String element = SPAN_TAG;
/**
* Delimiter to use between each '{@code input type="checkbox/radio"}' tags.
*/
@Nullable
private String delimiter;
/**
* Set the {@link java.util.Collection}, {@link java.util.Map} or array of objects
* used to generate the '{@code input type="checkbox/radio"}' tags.
* <p>Typically a runtime expression.
* @param items said items
*/
public void setItems(Object items) {
Assert.notNull(items, "'items' must not be null");
this.items = items;
}
/**
* Get the {@link java.util.Collection}, {@link java.util.Map} or array of objects
* used to generate the '{@code input type="checkbox/radio"}' tags.
*/
@Nullable
protected Object getItems() {
return this.items;
}
/**
* Set the name of the property mapped to the '{@code value}' attribute
* of the '{@code input type="checkbox/radio"}' tag.
* <p>May be a runtime expression.
*/
public void setItemValue(String itemValue) {
Assert.hasText(itemValue, "'itemValue' must not be empty");
this.itemValue = itemValue;
}
/**
* Get the name of the property mapped to the '{@code value}' attribute
* of the '{@code input type="checkbox/radio"}' tag.
*/
@Nullable
protected String getItemValue() {
return this.itemValue;
}
/**
* Set the value to be displayed as part of the
* '{@code input type="checkbox/radio"}' tag.
* <p>May be a runtime expression.
*/
public void setItemLabel(String itemLabel) {
Assert.hasText(itemLabel, "'itemLabel' must not be empty");
this.itemLabel = itemLabel;
}
/**
* Get the value to be displayed as part of the
* '{@code input type="checkbox/radio"}' tag.
*/
@Nullable
protected String getItemLabel() {
return this.itemLabel;
}
/**
* Set the delimiter to be used between each
* '{@code input type="checkbox/radio"}' tag.
* <p>By default, there is <em>no</em> delimiter.
*/
public void setDelimiter(String delimiter) {
this.delimiter = delimiter;
}
/**
* Return the delimiter to be used between each
* '{@code input type="radio"}' tag.
*/
@Nullable
public String getDelimiter() {
return this.delimiter;
}
/**
* Set the HTML element used to enclose the
* '{@code input type="checkbox/radio"}' tag.
* <p>Defaults to an HTML '{@code <span/>}' tag.
*/
public void setElement(String element) {
Assert.hasText(element, "'element' cannot be null or blank");
this.element = element;
}
/**
* Get the HTML element used to enclose
* '{@code input type="checkbox/radio"}' tag.
*/
public String getElement() {
return this.element;
}
/**
* Appends a counter to a specified id as well,
* since we're dealing with multiple HTML elements.
*/
@Override
protected String resolveId() throws JspException {
Object id = evaluate("id", getId());
if (id != null) {
String idString = id.toString();
return (StringUtils.hasText(idString) ? TagIdGenerator.nextId(idString, this.pageContext) : null);
}
return autogenerateId();
}
/**
* Renders the '{@code input type="radio"}' element with the configured
* {@link #setItems(Object)} values. Marks the element as checked if the
* value matches the bound value.
*/
@Override
@SuppressWarnings("rawtypes")
protected int writeTagContent(TagWriter tagWriter) throws JspException {
Object items = getItems();
Object itemsObject = (items instanceof String ? evaluate("items", items) : items);
String itemValue = getItemValue();
String itemLabel = getItemLabel();
String valueProperty =
(itemValue != null ? ObjectUtils.getDisplayString(evaluate("itemValue", itemValue)) : null);
String labelProperty =
(itemLabel != null ? ObjectUtils.getDisplayString(evaluate("itemLabel", itemLabel)) : null);
Class<?> boundType = getBindStatus().getValueType();
if (itemsObject == null && boundType != null && boundType.isEnum()) {
itemsObject = boundType.getEnumConstants();
}
if (itemsObject == null) {
throw new IllegalArgumentException("Attribute 'items' is required and must be a Collection, an Array or a Map");
}
if (itemsObject.getClass().isArray()) {
Object[] itemsArray = (Object[]) itemsObject;
for (int i = 0; i < itemsArray.length; i++) {
Object item = itemsArray[i];
writeObjectEntry(tagWriter, valueProperty, labelProperty, item, i);
}
}
else if (itemsObject instanceof Collection<?> optionCollection) {
int itemIndex = 0;
for (Iterator<?> it = optionCollection.iterator(); it.hasNext(); itemIndex++) {
Object item = it.next();
writeObjectEntry(tagWriter, valueProperty, labelProperty, item, itemIndex);
}
}
else if (itemsObject instanceof final Map<?, ?> optionMap) {
int itemIndex = 0;
for (Iterator it = optionMap.entrySet().iterator(); it.hasNext(); itemIndex++) {
Map.Entry entry = (Map.Entry) it.next();
writeMapEntry(tagWriter, valueProperty, labelProperty, entry, itemIndex);
}
}
else {
throw new IllegalArgumentException("Attribute 'items' must be an array, a Collection or a Map");
}
return SKIP_BODY;
}
private void writeObjectEntry(TagWriter tagWriter, @Nullable String valueProperty,
@Nullable String labelProperty, Object item, int itemIndex) throws JspException {
BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(item);
Object renderValue;
if (valueProperty != null) {
renderValue = wrapper.getPropertyValue(valueProperty);
}
else if (item instanceof Enum<?> enumValue) {
renderValue = enumValue.name();
}
else {
renderValue = item;
}
Object renderLabel = (labelProperty != null ? wrapper.getPropertyValue(labelProperty) : item);
writeElementTag(tagWriter, item, renderValue, renderLabel, itemIndex);
}
private void writeMapEntry(TagWriter tagWriter, @Nullable String valueProperty,
@Nullable String labelProperty, Map.Entry<?, ?> entry, int itemIndex) throws JspException {
Object mapKey = entry.getKey();
Object mapValue = entry.getValue();
BeanWrapper mapKeyWrapper = PropertyAccessorFactory.forBeanPropertyAccess(mapKey);
BeanWrapper mapValueWrapper = PropertyAccessorFactory.forBeanPropertyAccess(mapValue);
Object renderValue = (valueProperty != null ?
mapKeyWrapper.getPropertyValue(valueProperty) : mapKey.toString());
Object renderLabel = (labelProperty != null ?
mapValueWrapper.getPropertyValue(labelProperty) : mapValue.toString());
writeElementTag(tagWriter, mapKey, renderValue, renderLabel, itemIndex);
}
private void writeElementTag(TagWriter tagWriter, Object item, @Nullable Object value,
@Nullable Object label, int itemIndex) throws JspException {
tagWriter.startTag(getElement());
if (itemIndex > 0) {
Object resolvedDelimiter = evaluate("delimiter", getDelimiter());
if (resolvedDelimiter != null) {
tagWriter.appendValue(resolvedDelimiter.toString());
}
}
tagWriter.startTag("input");
String id = resolveId();
Assert.state(id != null, "Attribute 'id' is required");
writeOptionalAttribute(tagWriter, "id", id);
writeOptionalAttribute(tagWriter, "name", getName());
writeOptionalAttributes(tagWriter);
tagWriter.writeAttribute("type", getInputType());
renderFromValue(item, value, tagWriter);
tagWriter.endTag();
tagWriter.startTag("label");
tagWriter.writeAttribute("for", id);
tagWriter.appendValue(convertToDisplayString(label));
tagWriter.endTag();
tagWriter.endTag();
}
}
|
import java.util.Random;
import java.util.Scanner;
public class 입력받아사칙연산 {
public static void main(String[] args) {
System.out.println("화면에 아무 숫자나 입력하세요:)" );
int userInputNumber = 0;
Scanner s = new Scanner(System.in);
System.out.print(">>");
userInputNumber = s.nextInt();
System.out.println("이번엔 제가 랜덤숫자를 생성합니다:)" );
int randNum;
randNum = 0;
Random r = new Random();
randNum = r.nextInt(10);
System.out.println(">>"+randNum);
int a = userInputNumber+randNum;
int b = userInputNumber-randNum;
int c = userInputNumber*randNum;
double d = (int)userInputNumber/randNum;
int e = userInputNumber%randNum;
System.out.println("지금부터 제가 사칙연산을 합니다:)" );
System.out.println("입력된 두개의숫자 "+userInputNumber+","+randNum+" 을 더하면 "+a+" ♥"
+"\r입력된 두개의숫자 "+userInputNumber+","+randNum+" 을 빼면 "+b+" ♥"
+"\r입력된 두개의숫자 "+userInputNumber+","+randNum+" 을 곱하면 "+c+" ♥"
+"\r입력된 두개의숫자 "+userInputNumber+","+randNum+" 을 나누면 "+d+" ♥"
+"\r입력된 두개의숫자 "+userInputNumber+","+randNum+" 의 나머지는 "+e+" ♥");
}
}
|
package com.mygdx.game;
import com.badlogic.gdx.ScreenAdapter;
public class MainMenu extends ScreenAdapter {
public MainMenu() {
}
@Override
public void render(float delta) {
}
@Override
public void dispose() {
}
}
|
package be.steformations.tunsajan.jd.datasheet.mapper;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
import be.steformations.java_data.timesheets.entities.Prestation;
public class MapperPrestation implements RowMapper<Prestation>{
@Override
public Prestation mapRow(ResultSet rs, int row) throws SQLException {
return null;
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package morpion;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.util.ArrayList;
import java.util.Observable;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
/**
*
* @author lienardr
*/
public class VueClassement extends Observable{
private JFrame window;
private JScrollPane scroll;
public VueClassement(ArrayList <String> nomsJoueurs, ArrayList<Integer> victoires, ArrayList<Integer> nuls, ArrayList<Integer> defaites){
window = new JFrame("Morpion");
window.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
// Définit la taille de la fenêtre en pixels
window.setSize(1200, 800);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
window.setLocation(dim.width/2-window.getSize().width/2, dim.height/2-window.getSize().height/2);
JPanel mainPanel = new JPanel(new BorderLayout());
window.add(mainPanel) ;
JPanel middlePanel = new JPanel (new GridLayout(nomsJoueurs.size()+1, 5));
scroll = new JScrollPane(middlePanel);
mainPanel.add(scroll, BorderLayout.CENTER);
middlePanel.add(new JLabel("Noms Joueurs : "));
middlePanel.add(new JLabel("Victoires :"));
middlePanel.add(new JLabel("Nuls :"));
middlePanel.add(new JLabel("Défaites :"));
middlePanel.add(new JLabel("Classement :"));
for(Integer i = 0; i<nomsJoueurs.size(); i++ ){
middlePanel.add(new JLabel(nomsJoueurs.get(i)));
middlePanel.add(new JLabel(victoires.get(i).toString()));
middlePanel.add(new JLabel(nuls.get(i).toString()));
middlePanel.add(new JLabel(defaites.get(i).toString()));
Integer pos = i+1;
middlePanel.add(new JLabel(pos.toString()));
}
}
public void afficher() {
this.window.setVisible(true);
}
public void close() {
this.window.dispose();
}
}
|
package gov.nih.mipav.model.algorithms.itk;
import InsightToolkit.*;
import gov.nih.mipav.model.structures.*;
public class PItkImage2
{
/** Contains the itk smart pointer, which will delete our image data
* unless we keep it around. The only common base type is Object. */
private Object m_SmartPointer = null;
/** 2D itk image, specialized for data type. */
private itkImageBase2 m_itkImageBase2 = null;
protected void finalize() {
m_itkImageBase2 = null;
// avoid 'local variable never read' warning. Harmless.
if (m_SmartPointer != null) {
m_SmartPointer = null;
}
}
/** Create instance of itkImage, matching Mipav image type, if possible.
* Wrapper around itk smart pointer and the more useful image pointer.
* @param model_image_type as defined by consts in ModelStorageBase
*/
public PItkImage2(int model_image_type) {
switch (model_image_type) {
case ModelImage.BYTE:
{
itkImageSC2_Pointer kImageITK_p = itkImageSC2.itkImageSC2_New();
m_SmartPointer = kImageITK_p;
m_itkImageBase2 = kImageITK_p.GetPointer();
break;
}
case ModelImage.UBYTE:
case ModelImage.ARGB:
{
itkImageUC2_Pointer kImageITK_p = itkImageUC2.itkImageUC2_New();
m_SmartPointer = kImageITK_p;
m_itkImageBase2 = kImageITK_p.GetPointer();
break;
}
case ModelImage.SHORT:
{
itkImageSS2_Pointer kImageITK_p = itkImageSS2.itkImageSS2_New();
m_SmartPointer = kImageITK_p;
m_itkImageBase2 = kImageITK_p.GetPointer();
break;
}
case ModelImage.USHORT:
case ModelImage.ARGB_USHORT:
{
itkImageUS2_Pointer kImageITK_p = itkImageUS2.itkImageUS2_New();
m_SmartPointer = kImageITK_p;
m_itkImageBase2 = kImageITK_p.GetPointer();
break;
}
case ModelImage.INTEGER:
{
itkImageSI2_Pointer kImageITK_p = itkImageSI2.itkImageSI2_New();
m_SmartPointer = kImageITK_p;
m_itkImageBase2 = kImageITK_p.GetPointer();
break;
}
case ModelImage.UINTEGER:
{
itkImageUI2_Pointer kImageITK_p = itkImageUI2.itkImageUI2_New();
m_SmartPointer = kImageITK_p;
m_itkImageBase2 = kImageITK_p.GetPointer();
break;
}
case ModelImage.LONG:
{
// Possible signed/unsigned mismatch here. SL2 is not avail in Itk.
itkImageUL2_Pointer kImageITK_p = itkImageUL2.itkImageUL2_New();
m_SmartPointer = kImageITK_p;
m_itkImageBase2 = kImageITK_p.GetPointer();
break;
}
case ModelImage.FLOAT:
case ModelImage.ARGB_FLOAT:
{
// Create instance of ITK 2D image of floating point values
itkImageF2_Pointer kImageITK_p = itkImageF2.itkImageF2_New();
m_SmartPointer = kImageITK_p;
m_itkImageBase2 = kImageITK_p.GetPointer();
break;
}
case ModelImage.DOUBLE:
{
// Create instance of ITK 2D image of floating point values
itkImageD2_Pointer kImageITK_p = itkImageD2.itkImageD2_New();
m_SmartPointer = kImageITK_p;
m_itkImageBase2 = kImageITK_p.GetPointer();
break;
}
case ModelImage.BOOLEAN:
case ModelImage.COMPLEX:
case ModelImage.DCOMPLEX:
break;
default:
assert(false);
break;
}
}
/** Create wrapper of existing itkImage.
* Wrapper around itk smart pointer and the more useful image pointer.
* @param smart_pointer existing Itk smart pointer to Itk image.
*/
public PItkImage2(Object smart_pointer) {
m_itkImageBase2 = (itkImageBase2)AutoItkLoader.invokeMethod("GetPointer", smart_pointer);
if (m_itkImageBase2 != null) {
m_SmartPointer = smart_pointer;
}
}
/** Access the 2D image
* @return 2D Itk image. null if Mipav type doesn't have corresponding itk type.
*/
public itkImageBase2 img() {
return m_itkImageBase2;
}
}
|
package com.god.gl.vaccination.main.login;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.EditText;
import com.god.gl.vaccination.R;
import com.god.gl.vaccination.apputils.TextStringUtils;
import com.god.gl.vaccination.base.BaseActivity;
import com.god.gl.vaccination.common.CommonUrl;
import com.god.gl.vaccination.main.login.bean.SiteBean;
import com.god.gl.vaccination.util.GsonUtil;
import com.god.gl.vaccination.util.ToastUtils;
import com.god.gl.vaccination.util.Utils;
import com.god.gl.vaccination.util.okgo.OkGoUtil;
import com.god.gl.vaccination.util.okgo.callback.OnResponse;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import jsc.kit.wheel.base.WheelItem;
import jsc.kit.wheel.dialog.ColumnWheelDialog;
import jsc.kit.wheel.dialog.DateTimeWheelDialog;
/**
* @author gl
* @date 2018/12/5
* @desc
*/
public class RegisterActivity extends BaseActivity {
@BindView(R.id.et_brithday)
EditText mEtBrithday;
@BindView(R.id.et_point)
EditText mEtPoint;
@BindView(R.id.et_phone)
EditText mEtPhone;
@BindView(R.id.et_pwd)
EditText mEtPwd;
@BindView(R.id.et_comPwd)
EditText mEtComPwd;
private ColumnWheelDialog mWheelDialog;
private DateTimeWheelDialog mDateTimeWheelDialog;
private WheelItem[] mWheelItems;
private List<SiteBean.DataBean.SiteListBean> mDataBeanList;
private String mSiteId;
private String phone;
private String pwd;
private String time;
private String comPwd;
@Override
protected int getActivityViewById() {
return R.layout.activity_register;
}
@Override
protected void initView(Bundle savedInstanceState) {
}
@Override
protected void handleData() {
mDataBeanList = new ArrayList<>();
getSite();
}
@OnClick(R.id.btn_register)
void register() {
if (TextStringUtils.isEmpty(mEtPhone)){
ToastUtils.showMsg(mContext, "请输入手机号");
return;
}
if (!Utils.isMobile(mEtPhone.getText().toString())){
ToastUtils.showMsg(mContext, "请输入正确手机号码");
return;
}
if (TextStringUtils.isEmpty(mEtBrithday)){
ToastUtils.showMsg(mContext, "请输入婴儿出生日期");
return;
}
if (TextStringUtils.isEmpty(mEtPoint)){
ToastUtils.showMsg(mContext, "请选择服务站点");
return;
}
if (TextStringUtils.isEmpty(mEtPwd)){
ToastUtils.showMsg(mContext, "请输入密码");
return;
}
pwd = mEtPwd.getText().toString().trim();
if (pwd.length()<6){
ToastUtils.showMsg(mContext,"密码不能少于6位");
return;
}
if (TextStringUtils.isEmpty(mEtComPwd)){
ToastUtils.showMsg(mContext, "请输入确认密码");
return;
}
comPwd = mEtComPwd.getText().toString().trim();
if (!pwd.equals(comPwd)){
ToastUtils.showMsg(mContext, "两次密码不一致");
return;
}
phone = mEtPhone.getText().toString();
time = mEtBrithday.getText().toString();
register(phone,time,mSiteId,pwd,comPwd);
}
@OnClick(R.id.et_point)
void getPoint() {
if (null != mWheelItems) {
if (null == mWheelDialog) {
mWheelDialog = createDialog();
}
mWheelDialog.show();
}
}
@OnClick(R.id.et_brithday)
void getBrithday() {
createTimeDialog();
}
private void register(String phone, String birthday, String siteId, String password, String Conpassword) {
Map<String, String> params = new HashMap<>();
params.put("mobile", phone);
params.put("born_at", birthday);
params.put("site_id", siteId);
params.put("password", password);
params.put("password_confirm", Conpassword);
OkGoUtil.request(mContext, true, CommonUrl.REGISTER, getTAG(), params,
new OnResponse<String>() {
@Override
public void responseOk(String temp) {
ToastUtils.showMsg(mContext,"注册成功");
finish();
}
@Override
public void responseFail(String msg) {
ToastUtils.showMsg(mContext,msg);
}
});
}
private void getSite() {
Map<String, String> params = new HashMap<>();
OkGoUtil.request(mContext, true, CommonUrl.SITELIST, getTAG(), params,
new OnResponse<String>() {
@Override
public void responseOk(String temp) {
SiteBean siteBean = GsonUtil.jsonToBean(temp, SiteBean.class);
mDataBeanList.clear();
mDataBeanList.addAll(siteBean.data.site_list);
getItems(siteBean.data);
}
@Override
public void responseFail(String msg) {
}
});
}
private ColumnWheelDialog createDialog() {
ColumnWheelDialog<WheelItem, WheelItem, WheelItem, WheelItem, WheelItem> dialog = new ColumnWheelDialog<>(mContext);
dialog.show();
dialog.setTitle("选择站点");
dialog.setCancelButton("取消", null);
dialog.setOKButton("确定", new ColumnWheelDialog.OnClickCallBack<WheelItem, WheelItem, WheelItem, WheelItem, WheelItem>() {
@Override
public boolean callBack(View v, @Nullable WheelItem item0, @Nullable WheelItem item1, @Nullable WheelItem item2, @Nullable WheelItem item3, @Nullable WheelItem item4) {
String result = "";
if (item0 != null) {
result = item0.getShowText();
for (SiteBean.DataBean.SiteListBean siteListBean : mDataBeanList) {
if (siteListBean.name.endsWith(result)) {
mSiteId = String.valueOf(siteListBean.id);
break;
}
}
}
mEtPoint.setText(result);
return false;
}
});
dialog.setItems(
mWheelItems,
null,
null,
null,
null
);
return dialog;
}
private WheelItem[] getItems(SiteBean.DataBean dataBean) {
mWheelItems = new WheelItem[dataBean.site_list.size()];
for (int i = 0; i < dataBean.site_list.size(); i++) {
mWheelItems[i] = new WheelItem(dataBean.site_list.get(i).name);
}
return mWheelItems;
}
private DateTimeWheelDialog createTimeDialog() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, 1990);
calendar.set(Calendar.MONTH, 0);
calendar.set(Calendar.DAY_OF_MONTH, 1);
Date startDate = calendar.getTime();
calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, 2200);
Date endDate = calendar.getTime();
if (null == mDateTimeWheelDialog) {
mDateTimeWheelDialog = new DateTimeWheelDialog(mContext);
}
mDateTimeWheelDialog.show();
mDateTimeWheelDialog.setTitle("选择婴儿出生日期");
int config = DateTimeWheelDialog.SHOW_YEAR_MONTH_DAY;
mDateTimeWheelDialog.configShowUI(config);
mDateTimeWheelDialog.setCancelButton("取消", null);
mDateTimeWheelDialog.setOKButton("确定", new DateTimeWheelDialog.OnClickCallBack() {
@Override
public boolean callBack(View v, @NonNull Date selectedDate) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
mEtBrithday.setText(dateFormat.format(selectedDate));
return false;
}
});
mDateTimeWheelDialog.setDateArea(startDate, endDate, true);
mDateTimeWheelDialog.updateSelectedDate(new Date());
return mDateTimeWheelDialog;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// TODO: add setContentView(...) invocation
ButterKnife.bind(this);
}
}
|
package dao;
import java.util.ArrayList;
import dto.Movie;
public class MovieRepository {
private ArrayList<Movie> listOfMovies = new ArrayList<Movie>();
private static MovieRepository instance = new MovieRepository();
public static MovieRepository getInstance() {
return instance;
}
public void addMovie(Movie movie) {
listOfMovies.add(movie);
}
public MovieRepository() {
Movie movie1 = new Movie("M001", "신세계", "느와르");
movie1.setMovie_audience(4689161);
movie1.setMovie_class("청소년 관람 불가");
movie1.setMovie_url("M001.jpg");
movie1.setMovie_story("2013년에 개봉한 대한민국의 갱스터 느와르 영화. 이정재, 최민식, 황정민, 박성웅이 주연을 맡았으며, 부당거래와 악마를 보았다의 시나리오(각본)를 담당하면서 충무로의 스타 작가로 떠오른 박훈정이 영화 혈투 이후 두번째로 메가폰을 잡은 작품이다. 사나이픽처스의 창립작.");
Movie movie2 = new Movie("M002", "괴물", "스릴러");
movie2.setMovie_audience(13019740);
movie2.setMovie_class("12세 이상 관람가");
movie2.setMovie_url("M002.jpg");
movie2.setMovie_story("《괴물》(怪物)은 2006년 7월 27일에 개봉한 봉준호 감독이 기획·제작한 영화이다. 2000년에 발생한 주한미군 한강 독극물 무단 방류 사건을 모티브로 하여, 소시민들이 거대한 괴물을 물리친다는 통쾌한 카타르시스를 전달하기 위해, 모든 계층이 지켜볼 수 있는 블록버스터 괴수 영화로 방향을 잡았다고 한다.");
Movie movie3 = new Movie("M003", "겨울왕국2", "애니메이션");
movie3.setMovie_audience(13747792);
movie3.setMovie_class("전체관람가");
movie3.setMovie_url("M003.jpg");
movie3.setMovie_story("겨울왕국 2(Frozen II)는 2019년 미국 월트 디즈니 애니메이션 스튜디오에서 제작한 3D 컴퓨터 애니메이션 뮤지컬 판타지 영화로 엘사의 힘의 기원을 찾고 아렌델을 위기로부터 구하기 위해 엘사와 안나가 진실을 찾으러 마법의 숲으로 모험을 떠나는 이야기를 그린다.");
listOfMovies.add(movie1);
listOfMovies.add(movie2);
listOfMovies.add(movie3);
}
//영화목록 가져오는 메소드
public ArrayList<Movie> getAllMovies(){
return listOfMovies;
}
//영화 상세 정보를 가져오는 메소드
public Movie getMovieById(String movie_id) {
Movie movieById = null;
for (int i=0; i<listOfMovies.size(); i++) {
Movie movie = listOfMovies.get(i);
if(movie != null && movie.getMovie_id() != null && movie.getMovie_id().equals(movie_id)) {
movieById = movie;
break;
}
}
return movieById;
}
}
|
package com.metoo.manage.admin.action;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.nutz.json.Json;
import org.nutz.json.JsonFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.metoo.core.annotation.SecurityMapping;
import com.metoo.core.mv.JModelAndView;
import com.metoo.core.tools.CommUtil;
import com.metoo.foundation.domain.Article;
import com.metoo.foundation.domain.Goods;
import com.metoo.foundation.domain.GroupGoods;
import com.metoo.foundation.domain.GroupLifeGoods;
import com.metoo.foundation.domain.Store;
import com.metoo.foundation.domain.SysConfig;
import com.metoo.foundation.service.IArticleService;
import com.metoo.foundation.service.IGoodsService;
import com.metoo.foundation.service.IGroupGoodsService;
import com.metoo.foundation.service.IGroupLifeGoodsService;
import com.metoo.foundation.service.IStoreService;
import com.metoo.foundation.service.ISysConfigService;
import com.metoo.foundation.service.IUserConfigService;
import com.metoo.lucene.LuceneThread;
import com.metoo.lucene.LuceneVo;
import com.metoo.lucene.tools.LuceneVoTools;
import com.metoo.view.web.tools.GroupViewTools;
/**
*
* <p>
* Title: LuceneManageAction.java
* </p>
*
* <p>
* Description: 全文检索处理器
* </p>
*
* <p>
* Copyright: Copyright (c) 2015
* </p>
*
* <p>
* Company: 沈阳网之商科技有限公司 www.metoo.com
* </p>
*
* @author erikzhang
*
* @date 2014年5月27日
*
* @version metoo_b2b2c 2.0
*/
@Controller
public class LuceneManageAction {
@Autowired
private ISysConfigService configService;
@Autowired
private IUserConfigService userConfigService;
@Autowired
private IGoodsService goodsService;
@Autowired
private IStoreService storeService;
@Autowired
private IArticleService articleService;
@Autowired
private IGroupLifeGoodsService groupLifeGoodsService;
@Autowired
private GroupViewTools groupViewTools;
@Autowired
private IGroupGoodsService groupGoodsService;
@Autowired
private LuceneVoTools luceneVoTools;
@SecurityMapping(title = "全文检索设置", value = "/admin/lucene.htm*", rtype = "admin", rname = "全文检索", rcode = "luence_manage", rgroup = "工具")
@RequestMapping("/admin/lucene.htm")
public ModelAndView lucene(HttpServletRequest request,
HttpServletResponse response) {
ModelAndView mv = new JModelAndView("admin/blue/lucene.html",
configService.getSysConfig(),
this.userConfigService.getUserConfig(), 0, request, response);
String path = System.getProperty("metoob2b2c.root") + File.separator
+ "luence";
File file = new File(path);
if (!file.exists()) {
CommUtil.createFolder(path);
}
mv.addObject("lucene_disk_size", CommUtil.fileSize(file));
mv.addObject("lucene_disk_path", path);
return mv;
}
@SecurityMapping(title = "全文检索关键字保存", value = "/admin/lucene_hot_save.htm*", rtype = "admin", rname = "全文检索", rcode = "luence_manage", rgroup = "工具")
@RequestMapping("/admin/lucene_hot_save.htm")
public void lucene_hot_save(HttpServletRequest request,
HttpServletResponse response, String id, String hotSearch,String lucenen_queue) {
SysConfig obj = this.configService.getSysConfig();
boolean ret = true;
if (id.equals("")) {
obj.setHotSearch(hotSearch);
obj.setLucenen_queue(CommUtil.null2Int(lucenen_queue));
obj.setAddTime(new Date());
ret = this.configService.save(obj);
} else {
obj.setHotSearch(hotSearch);
obj.setLucenen_queue(CommUtil.null2Int(lucenen_queue));
ret = this.configService.update(obj);
}
response.setContentType("text/plain");
response.setHeader("Cache-Control", "no-cache");
response.setCharacterEncoding("UTF-8");
PrintWriter writer;
try {
writer = response.getWriter();
writer.print(ret);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@SecurityMapping(title = "全文检索更新", value = "/admin/lucene_update.htm*", rtype = "admin", rname = "全文检索", rcode = "luence_manage", rgroup = "工具")
@RequestMapping("/admin/lucene_update.htm")
public void lucene_update(HttpServletRequest request,
HttpServletResponse response, String id, String hotSearch) {
Map params = new HashMap();
params.put("goods_status", 0);
List<Goods> goods_list = this.goodsService
.query("select obj from Goods obj where obj.goods_status=:goods_status",
params, -1, -1);
params.clear();
params.put("store_status", 2);
List<Store> store_list = this.storeService
.query("select obj from Store obj where obj.store_status=:store_status",
params, -1, -1);
params.clear();
params.put("group_status", 1);
List<GroupLifeGoods> lifeGoods_list = this.groupLifeGoodsService
.query("select obj from GroupLifeGoods obj where obj.group_status=:group_status",
params, -1, -1);
List<GroupGoods> groupGoods_list = this.groupGoodsService
.query("select obj from GroupGoods obj where obj.gg_status=:group_status",
params, -1, -1);
params.clear();
params.put("display", true);
List<Article> article_list = this.articleService.query(
"select obj from Article obj where obj.display=:display",
params, -1, -1);
String goods_lucene_path = System.getProperty("metoob2b2c.root")
+ File.separator + "luence" + File.separator + "goods";
String grouplifegoods_lucene_path = System.getProperty("metoob2b2c.root")
+ File.separator + "luence" + File.separator + "grouplifegoods";
String groupgoods_lucene_path = System.getProperty("metoob2b2c.root")
+ File.separator + "luence" + File.separator + "groupgoods";
File file = new File(goods_lucene_path);
if (!file.exists()) {
CommUtil.createFolder(goods_lucene_path);
}
file = new File(grouplifegoods_lucene_path);
if (!file.exists()) {
CommUtil.createFolder(grouplifegoods_lucene_path);
}
file = new File(groupgoods_lucene_path);
if (!file.exists()) {
CommUtil.createFolder(groupgoods_lucene_path);
}
List<LuceneVo> goods_vo_list = new ArrayList<LuceneVo>();
for (Goods goods : goods_list) {
LuceneVo vo = this.luceneVoTools.updateGoodsIndex(goods);
goods_vo_list.add(vo);
}
List<LuceneVo> lifegoods_vo_list = new ArrayList<LuceneVo>();
for (GroupLifeGoods goods : lifeGoods_list) {
LuceneVo vo = new LuceneVo();
vo.setVo_id(goods.getId());
vo.setVo_title(goods.getGg_name());
vo.setVo_content(goods.getGroup_details());
vo.setVo_type("lifegoods");
vo.setVo_store_price(CommUtil.null2Double(goods.getGroup_price()));
vo.setVo_add_time(goods.getAddTime().getTime());
vo.setVo_goods_salenum(goods.getGroupInfos().size());
vo.setVo_cost_price(CommUtil.null2Double(goods.getCost_price()));
if (goods.getGroup_acc() != null) {
vo.setVo_main_photo_url(goods.getGroup_acc().getPath() + "/"
+ goods.getGroup_acc().getName());
}
vo.setVo_cat(goods.getGg_gc().getId().toString());
String rate = this.groupViewTools.getRate(
CommUtil.null2Double(goods.getGroup_price()),
CommUtil.null2Double(goods.getCost_price())).toString();
vo.setVo_rate(rate);
if (goods.getGg_ga() != null) {
vo.setVo_goods_area(goods.getGg_ga().getId().toString());
}
lifegoods_vo_list.add(vo);
}
List<LuceneVo> groupgoods_vo_list = new ArrayList<LuceneVo>();
for (GroupGoods goods : groupGoods_list) {
LuceneVo vo = new LuceneVo();
vo.setVo_id(goods.getId());
vo.setVo_title(goods.getGg_name());
vo.setVo_content(goods.getGg_content());
vo.setVo_type("lifegoods");
vo.setVo_store_price(CommUtil.null2Double(goods.getGg_price()));
vo.setVo_add_time(goods.getAddTime().getTime());
vo.setVo_goods_salenum(goods.getGg_selled_count());
vo.setVo_cost_price(CommUtil.null2Double(goods.getGg_goods()
.getGoods_price()));
if (goods.getGg_img() != null) {
vo.setVo_main_photo_url(goods.getGg_img().getPath() + "/"
+ goods.getGg_img().getName());
}
vo.setVo_cat(goods.getGg_gc().getId().toString());
vo.setVo_rate(CommUtil.null2String(goods.getGg_rebate()));
if (goods.getGg_ga() != null) {
vo.setVo_goods_area(goods.getGg_ga().getId().toString());
}
groupgoods_vo_list.add(vo);
}
LuceneThread goods_thread = new LuceneThread(goods_lucene_path,
goods_vo_list);
LuceneThread lifegoods_thread = new LuceneThread(
grouplifegoods_lucene_path, lifegoods_vo_list);
LuceneThread groupgoods_thread = new LuceneThread(
groupgoods_lucene_path, groupgoods_vo_list);
Date d1 = new Date();
goods_thread.run();
lifegoods_thread.run();
groupgoods_thread.run();
Date d2 = new Date();
String path = System.getProperty("metoob2b2c.root") + File.separator
+ "luence";
Map map = new HashMap();
map.put("run_time", d2.getTime() - d1.getTime());
map.put("file_size", CommUtil.fileSize(new File(path)));
map.put("update_time", CommUtil.formatLongDate(new Date()));
SysConfig config = this.configService.getSysConfig();
config.setLucene_update(new Date());
this.configService.update(config);
response.setContentType("text/plain");
response.setHeader("Cache-Control", "no-cache");
response.setCharacterEncoding("UTF-8");
PrintWriter writer;
try {
writer = response.getWriter();
writer.print(Json.toJson(map, JsonFormat.compact()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
package com.dong1990.test;
import org.apache.commons.lang.StringUtils;
public class Test_StringBuffer {
public static void main(String[] args) {
StringBuffer_test();
Test_gateway();
}
private static void Test_gateway() {
String spCode = "gateway:1-spcode:0401,gateway:2-spcode:12512141311," +
"gateway:2-spcode:123123123,gateway:1-spcode:12512141311,gateway:1-spcode:1111";
String[] s;
StringBuilder sbyd = new StringBuilder();
StringBuilder sblt = new StringBuilder();
StringBuilder sbdx = new StringBuilder();
s=spCode.split(",");
String yd="";
String lt="";
String dx="";
for (int i = 0; i < s.length; i++) {
//s[i]=s[i].replaceAll("gateway:,", "");
s[i]=s[i].replaceAll("spcode:", ",");
s[i]=s[i].replaceAll("gateway:1-", "Y");
s[i]=s[i].replaceAll("gateway:2-", "L");
s[i]=s[i].replaceAll("gateway:3-", "D");
if(s[i].startsWith("Y")){
sbyd.append(s[i].substring(2, s[i].length()) +",");
}
yd=sbyd+"";
//System.out.println(sbyd+"");
//System.out.println("sss "+new StringBuilder(yd).append(sbyd).toString());
if(s[i].startsWith("L")){
sblt.append(s[i].substring(2, s[i].length()) +",");
}
lt=sblt+"";
if(s[i].startsWith("D")){
sbdx.append(s[i].substring(2, s[i].length()) +",");
}
dx=sbdx+"";
}
String gateway_spcode="";
if(yd != "" && yd.length()>0){
gateway_spcode=gateway_spcode+"Y:"+yd;
}
if(lt != "" && lt.length()>0){
gateway_spcode=gateway_spcode+"L:"+lt;
}
if(dx != "" && dx.length()>0){
gateway_spcode=gateway_spcode+"D:"+dx;
}
if(gateway_spcode.length()>0){
gateway_spcode=gateway_spcode.substring(0, gateway_spcode.length()-1);
}
System.out.println(gateway_spcode);
}
private static void StringBuffer_test() {
String name = "gateway:1-name:李芳180通道产品,gateway:1-name:新产品-行业泰逗," +
"gateway:3-name:李芳180通道产品,gateway:2-name:李芳180通道产品";
StringBuilder sbyd=new StringBuilder();
StringBuilder sblt=new StringBuilder();
StringBuilder sbdx=new StringBuilder();
String[] stringArray;
stringArray = name.split(",");
String YD_product = "";
String LT_product = "";
String DX_product = "";
for(int i = 0; i < stringArray.length; i++){
stringArray[i] = stringArray[i].replaceAll("gateway:1-name","Y");
stringArray[i] = stringArray[i].replaceAll("gateway:2-name","L");
stringArray[i] = stringArray[i].replaceAll("gateway:3-name","D");
if(stringArray[i].startsWith("Y")){
sbyd.append(stringArray[i].substring(2,stringArray[i].length())+",");
}
YD_product = new StringBuilder(YD_product).append(sbyd).toString();
if(stringArray[i].startsWith("L")){
sblt.append(stringArray[i].substring(2,stringArray[i].length())+",");
}
LT_product = new StringBuilder(LT_product).append(sblt).toString();
if(stringArray[i].startsWith("D")){
sbdx.append(stringArray[i].substring(2,stringArray[i].length())+",");
}
DX_product = new StringBuilder(DX_product).append(sbdx).toString();
}
String name2 = "";
if(StringUtils.isNotBlank(YD_product)){
name2 = new StringBuilder(name2).append(new StringBuilder("移动通道产品:")).append(sbyd).toString();
}
if(StringUtils.isNotBlank(LT_product)){
name2 = new StringBuilder(name2).append(new StringBuilder("联通通道产品:")).append(sblt).toString();
}
if(StringUtils.isNotBlank(YD_product)){
name2 = new StringBuilder(name2).append(new StringBuilder("电信通道产品:")).append(sbdx).toString();
}
if(StringUtils.isNotBlank(name2)){
name2 = name2.substring(0,name2.length() - 1);
}
sbyd.delete(0, sbyd.length());
sblt.delete(0, sblt.length());
sbdx.delete(0, sbdx.length());
System.out.println(name2);
name2 = name2.replace(",联通",";联通");
name2 = name2.replace(",电信",";电信");
System.out.println("-------------------------");
System.out.println(name2);
}
}
|
package com.emg.projectsmanage.dao.projectsmanager;
import java.util.List;
import java.util.Map;
import com.emg.projectsmanage.pojo.UserRoleModel;
public interface UserRoleModelDao {
List<UserRoleModel> query(UserRoleModel record);
List<UserRoleModel> queryAll();
int queryCount();
int delEpleRole(UserRoleModel record);
int addEpleRole(UserRoleModel record);
List<Map<String, Object>> getEpleRoles(int userid);
}
|
package com.english.alin.learnenglish.persistance;
import android.os.AsyncTask;
import android.util.Log;
import com.english.alin.learnenglish.persistance.database.DatabaseConstants.CorrectAnswer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import static com.english.alin.learnenglish.MainActivity.databaseManager;
import static com.english.alin.learnenglish.persistance.FactoryMethods.getContent;
import static com.english.alin.learnenglish.persistance.JSON_URL.REQUEST_URL;
import static com.english.alin.learnenglish.persistance.database.DatabaseConstants.CorrectAnswer.*;
import static com.english.alin.learnenglish.persistance.database.DatabaseConstants.CorrectAnswer.FALSE;
import static com.english.alin.learnenglish.persistance.database.DatabaseConstants.PrimaryKeyColumns.QUESTIONS_ID;
import static com.english.alin.learnenglish.persistance.database.DatabaseConstants.PrimaryKeyColumns.QUIZ_ID;
import static com.english.alin.learnenglish.persistance.database.DatabaseConstants.PrimaryKeyColumns.READING_ID;
import static com.english.alin.learnenglish.persistance.database.DatabaseConstants.Tables.questions;
import static com.english.alin.learnenglish.persistance.database.DatabaseConstants.Tables.quiz;
import static com.english.alin.learnenglish.persistance.database.DatabaseConstants.Tables.reading;
/**
* Created by Alin on 3/19/2016.
*/
public class DownloadTask extends AsyncTask<String, Void, JSONObject> {
final static String DATE = "date";
final static String QUIZ_TITLE = "quizTitle";
final static String READING_TEXT = "reading";
final static String QUESTIONS = "questions";
final static String QUESTION = "question";
final static String ANSWERS = "answers";
final static String ANSWER = "answer";
final static String IS_CORRECT = "isCorrect";
String date;
@Override
protected JSONObject doInBackground(String[] params) {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(getContent(REQUEST_URL));
} catch (JSONException e) {
e.printStackTrace();
}
fillDatabase(jsonObject);
return jsonObject;
}
private void fillDatabase(JSONObject requestedJSON){
String title, readingText,quizTitle,dateInserted,readingTextInserted;
try {
readingTextInserted = databaseManager.getLastReadingText();
dateInserted = databaseManager.getLastDate();
date = requestedJSON.getString(DATE);
readingText = requestedJSON.getString(READING_TEXT);
if (!readingText.equals(readingTextInserted) || !date.equals(dateInserted)){
quizTitle = requestedJSON.getString(QUIZ_TITLE);
databaseManager.insertIntoReadingTable(readingText);
JSONArray questionsArray = requestedJSON.getJSONArray(QUESTIONS);
int numberOfQuestions = questionsArray.length();
JSONObject currentQuestion;
int maxIdReading = databaseManager.getMaxId(reading, READING_ID);
databaseManager.insertIntoQuizTable(date, quizTitle, maxIdReading);
int maxId = databaseManager.getMaxId(quiz, QUIZ_ID);
for (int i = 0; i < numberOfQuestions; i++) {
currentQuestion = questionsArray.getJSONObject(i);
title = currentQuestion.getString(QUESTION);
databaseManager.insertIntoQuestions(maxId, title);
int currentQuestionId = databaseManager.getMaxId(questions, QUESTIONS_ID);
fillAnswersTable(currentQuestion, currentQuestionId);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private void fillAnswersTable(JSONObject currentQuestion, int questionId){
try {
int numberOfAnswers = currentQuestion.getJSONArray(ANSWERS).length();
JSONArray questionsArray = currentQuestion.getJSONArray(ANSWERS);
for (int i = 0; i < numberOfAnswers ; i++) {
JSONObject answersArrayObject = questionsArray.getJSONObject(i);
String answer = answersArrayObject.getString(ANSWER);
CorrectAnswer correctAnswer = answersArrayObject.getString(IS_CORRECT).equals("true")? TRUE : FALSE;
databaseManager.insertIntoAnswers(answer,correctAnswer, questionId, i);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
|
/**
* Copyright 2014 零志愿工作室 (http://www.0will.com). All rights reserved.
* File Name: BaseEntity.java
* Author: chenlong
* Encoding UTF-8
* Version: 1.0
* Date: 2014年12月4日
* History:
*/
package com.Owill.web.base.tools;
/**
* @author chenlong(chenlongwill@163.com)
* @version Revision: 1.0.0 Date: 2014年12月4日
*/
public class ConstantValues {
public static final String USER = "currentUser";
public static final String EDIT_SUCC = "edit_success";
public static final String EDIT_FAILED = "edit_failed";
}
|
package com.itfacesystem.domain.front;
import java.io.Serializable;
import java.util.List;
/**
* Created by wangrongtao on 15/11/3.
*/
public class CaseProgress implements Serializable, Comparable{
private long id;
private long caseinfoid;
private int processnodeid;
private String processnodename;
private int processnodeindex;
private int parentprocessnodeid;
private String backColor;
private List<CaseProgressComment> caseProgressCommentList;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getCaseinfoid() {
return caseinfoid;
}
public void setCaseinfoid(long caseinfoid) {
this.caseinfoid = caseinfoid;
}
public int getProcessnodeid() {
return processnodeid;
}
public void setProcessnodeid(int processnodeid) {
this.processnodeid = processnodeid;
}
public List<CaseProgressComment> getCaseProgressCommentList() {
return caseProgressCommentList;
}
public void setCaseProgressCommentList(List<CaseProgressComment> caseProgressCommentList) {
this.caseProgressCommentList = caseProgressCommentList;
}
public String getProcessnodename() {
return processnodename;
}
public void setProcessnodename(String processnodename) {
this.processnodename = processnodename;
}
public int getProcessnodeindex() {
return processnodeindex;
}
public void setProcessnodeindex(int processnodeindex) {
this.processnodeindex = processnodeindex;
}
public int getParentprocessnodeid() {
return parentprocessnodeid;
}
public void setParentprocessnodeid(int parentprocessnodeid) {
this.parentprocessnodeid = parentprocessnodeid;
}
public String getBackColor() {
return backColor;
}
public void setBackColor(String backColor) {
this.backColor = backColor;
}
@Override
public int compareTo(Object o) {
if (o!=null) {
return (((CaseProgress) o).getProcessnodeindex())-this.processnodeindex;
}
return 0;
}
}
|
package com.khasikov.app.objectdata;
import java.io.Serializable;
public class ObjectToId implements Serializable
{
private String objectId;
private Integer srcObject;
private Integer regionKey;
private String objectType;
private String objectCn;
private String objectCon;
private String subjectId;
private String regionId;
private String settlementId;
private String street;
private String house;
private String addressNotes;
private String okato;
private String apartment;
private String nobjectCn;
private String nobjectCon;
private final static long serialVersionUID = 722603421976383220L;
public String getObjectId() {
return objectId;
}
public void setObjectId(String objectId) {
this.objectId = objectId;
}
public Integer getSrcObject() {
return srcObject;
}
public void setSrcObject(Integer srcObject) {
this.srcObject = srcObject;
}
public Integer getRegionKey() {
return regionKey;
}
public void setRegionKey(Integer regionKey) {
this.regionKey = regionKey;
}
public String getObjectType() {
return objectType;
}
public void setObjectType(String objectType) {
this.objectType = objectType;
}
public String getObjectCn() {
return objectCn;
}
public void setObjectCn(String objectCn) {
this.objectCn = objectCn;
}
public String getObjectCon() {
return objectCon;
}
public void setObjectCon(String objectCon) {
this.objectCon = objectCon;
}
public String getSubjectId() {
return subjectId;
}
public void setSubjectId(String subjectId) {
this.subjectId = subjectId;
}
public String getRegionId() {
return regionId;
}
public void setRegionId(String regionId) {
this.regionId = regionId;
}
public String getSettlementId() {
return settlementId;
}
public void setSettlementId(String settlementId) {
this.settlementId = settlementId;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getHouse() {
return house;
}
public void setHouse(String house) {
this.house = house;
}
public String getAddressNotes() {
return addressNotes;
}
public void setAddressNotes(String addressNotes) {
this.addressNotes = addressNotes;
}
public String getOkato() {
return okato;
}
public void setOkato(String okato) {
this.okato = okato;
}
public String getApartment() {
return apartment;
}
public void setApartment(String apartment) {
this.apartment = apartment;
}
public String getNobjectCn() {
return nobjectCn;
}
public void setNobjectCn(String nobjectCn) {
this.nobjectCn = nobjectCn;
}
public String getNobjectCon() {
return nobjectCon;
}
public void setNobjectCon(String nobjectCon) {
this.nobjectCon = nobjectCon;
}
}
|
package Utils;
import org.apache.http.Consts;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import sun.misc.BASE64Decoder;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ConnectionUtils {
/**
* 向服务端发送手机的sim卡信息
* @param imsi
* @param phone
* @param phone_nation_code
* @return
* @throws Exception
*/
public static boolean SendPhoneInfo(String imsi,String phone,String phone_nation_code) throws Exception {
RequestConfig config = RequestConfig.custom().setSocketTimeout(60000).build();
CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(config).build();
HttpPost post = new HttpPost("http://47.96.5.240:8989/ghost/getVerificationCode");
// HttpPost post = new HttpPost("http://192.168.17.232:8989/ghost/getVerificationCode");
ArrayList<NameValuePair> list = new ArrayList<NameValuePair>();
list.add(new BasicNameValuePair("imsi", imsi));
list.add(new BasicNameValuePair("phone", phone));
list.add(new BasicNameValuePair("phone_nation_code", phone_nation_code));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, Consts.UTF_8);
post.setEntity(entity);
CloseableHttpResponse response = client.execute(post);
String result = EntityUtils.toString(response.getEntity());
System.out.println(result);
return "ok".equals(result);
}
/**
* 查询服务端是否已获取到验证码
* @return
*/
public static int isReady() throws IOException {
RequestConfig config = RequestConfig.custom().setSocketTimeout(60000).build();
CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(config).build();
HttpPost post = new HttpPost("http://47.96.5.240:8989/ghost/getState");
// HttpPost post = new HttpPost("http://192.168.17.232:8989/ghost/getState");
CloseableHttpResponse response = client.execute(post);
String result = EntityUtils.toString(response.getEntity());
//正在运行
if ("1001".equals(result)){
return 0;
}
//拿到结果
if ("1003".equals(result)){
return 1;
}
//确认可以发短信
if ("1004".equals(result)){
return 2;
}
//不是以上两种结果说明出错
return -1;
}
/**
* 查询是否可以获取短信
* @return
*/
public static int getCodeStatus() throws Exception {
RequestConfig config = RequestConfig.custom().setSocketTimeout(60000).build();
CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(config).build();
HttpPost post = new HttpPost("http://47.96.5.240:8989/ghost/getCodeState");
// HttpPost post = new HttpPost("http://192.168.17.232:8989/ghost/getCodeState");
CloseableHttpResponse response = client.execute(post);
String result = EntityUtils.toString(response.getEntity());
if ("ok".equals(result)){
return 1;
}
return -1;
}
/**
* 获取短信验证码
* @return
*/
public static String getVerficationCode(int length) throws Exception {
RequestConfig config = RequestConfig.custom().setSocketTimeout(60000).build();
CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(config).build();
HttpPost post = new HttpPost("http://47.96.5.240:8989/ghost/getCodeContent");
// HttpPost post = new HttpPost("http://192.168.17.232:8989/ghost/getCodeContent");
CloseableHttpResponse response = client.execute(post);
String result = EntityUtils.toString(response.getEntity());
BASE64Decoder decoder = new BASE64Decoder();
byte[] buffer = decoder.decodeBuffer(result);
result=new String(buffer);
System.out.println(result);
if ("NotGet".equals(result)){
return null;
}
return getYzmFromSms(result,length);
}
/**
* 获取手机验证码
* @param smsBody
* @param length
* @return
*/
public static String getYzmFromSms(String smsBody,int length) {
Pattern pattern = Pattern.compile("\\d{"+length+"}");
Matcher matcher = pattern.matcher(smsBody);
if (matcher.find()) {
return matcher.group();
}
return null;
}
}
|
package com.pom.PageObjetModel;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import junit.framework.Assert;
public class SignInPage {
@FindBy(xpath="//a[@class='login']")
public WebElement signin;
@FindBy(xpath="//input[@id='email']")
public WebElement userEmail;
@FindBy(id="passwd")
public WebElement userPassword;
@FindBy(xpath="//p[@class='submit']//span[1]")
public WebElement submitlogin;
@FindBy(xpath="//li[contains(text(),'Authentication failed.')]")
public WebElement geterrorMessage;
public SignInPage(WebDriver driver) {
PageFactory.initElements(driver, this);
}
public void login() {
signin.click();
userEmail.sendKeys("galazy007@gamil.com");
userPassword.sendKeys("galaxy007");
submitlogin.click();
}
public String errorMessage() {
return geterrorMessage.getText();
}
/*
* public static void main(String[] args) { WebDriver driver;
* System.setProperty("webdriver.chrome.driver",
* "C:\\Users\\GOPALAKRISHNA\\Desktop\\Selenium Jars\\chromedriver_win32\\chromedriver.exe"
* );
*
* driver=new ChromeDriver();
* driver.get("http://automationpractice.com/index.php");
* driver.manage().window().maximize();
*
* driver.findElement(By.xpath("//a[@class='login']")).click();
*
*
* driver.findElement(By.xpath("//input[@id='email']")).sendKeys(
* "galazy007@gamil.com");;
*
* driver.findElement(By.id("passwd")).sendKeys("galaxy007");
* driver.findElement(By.xpath("//p[@class='submit']//span[1]")).click();
*
* String actualerror =
* driver.findElement(By.xpath("//li[contains(text(),'Authentication failed.')]"
* )).getText(); String expectederror="Authentication failed.";
* Assert.assertEquals(expectederror, actualerror);
*
* }
*/
}
|
package at.wea5.geocaching.webserviceproxy;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java-Klasse für anonymous complex type.
*
* <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="requestingUser" type="{http://GeoCaching.Services/}User" minOccurs="0"/>
* <element name="rating" type="{http://GeoCaching.Services/}Rating" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"requestingUser",
"rating"
})
@XmlRootElement(name = "AddRatingForCache")
public class AddRatingForCache {
protected User requestingUser;
protected Rating rating;
/**
* Ruft den Wert der requestingUser-Eigenschaft ab.
*
* @return
* possible object is
* {@link User }
*
*/
public User getRequestingUser() {
return requestingUser;
}
/**
* Legt den Wert der requestingUser-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link User }
*
*/
public void setRequestingUser(User value) {
this.requestingUser = value;
}
/**
* Ruft den Wert der rating-Eigenschaft ab.
*
* @return
* possible object is
* {@link Rating }
*
*/
public Rating getRating() {
return rating;
}
/**
* Legt den Wert der rating-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link Rating }
*
*/
public void setRating(Rating value) {
this.rating = value;
}
}
|
package core.client.game.operations;
import java.util.HashSet;
import cards.equipments.Equipment.EquipmentType;
import commands.server.ingame.InGameServerCommand;
import core.player.PlayerSimple;
import ui.game.interfaces.CardUI;
/**
* A generic card usage only reaction Operation. Such an Operation has a separate command
* to send when the player gives up reaction (by pressing CANCEL), and may or may not allow
* the CANCEL button to be pressed (i.e. inaction may not be an option, e.g. Show Card)
*
* @author Harry
*
*/
public abstract class AbstractMultiCardNoTargetReactionOperation extends AbstractMultiCardMultiTargetOperation {
public AbstractMultiCardNoTargetReactionOperation(int maxCards) {
super(maxCards, 0);
}
@Override
public final void onCanceled() {
if (this.cards.size() > 0) { // Unselect all cards
for (CardUI card : new HashSet<>(this.cards.keySet())) {
this.onCardClicked(card);
}
} else { // Give up card reaction
this.onUnloaded();
this.onDeactivated();
this.panel.sendResponse(getCommandOnInaction());
}
}
@Override
protected boolean isConfirmEnabled() {
return this.cards.size() == this.maxCards;
}
@Override
protected boolean isEquipmentTypeActivatable(EquipmentType type) {
return false;
}
@Override
protected final boolean isPlayerActivatable(PlayerSimple player) {
return false;
}
/**
* <p>The command to be sent when player gives up on reaction. If giving up
* is not allowed (i.e. {@link #isCancelEnabled()} does not always return true),
* this method may return null</p>
*
* @return command upon inaction, or null if inaction is not allowed
*/
protected abstract InGameServerCommand getCommandOnInaction();
}
|
package ru.payts.pool;
import ru.payts.base.SpritesPool;
import ru.payts.sprite.Bullet;
public class BulletPool extends SpritesPool<Bullet> {
@Override
protected Bullet newObject() {
return new Bullet();
}
}
|
package com.ngocdt.tttn.entity;
import lombok.Data;
import javax.persistence.*;
@Entity
@Table(name = "SkinType")
@Data
public class SkinType {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column
private int id;
@Column
private String type;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
|
package org.sayesaman.app2;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.widget.ImageView;
import android.widget.Toast;
import com.googlecode.androidannotations.annotations.App;
import com.googlecode.androidannotations.annotations.Click;
import com.googlecode.androidannotations.annotations.EActivity;
import com.googlecode.androidannotations.annotations.Fullscreen;
import com.googlecode.androidannotations.annotations.NoTitle;
import com.googlecode.androidannotations.annotations.ViewById;
import org.sayesaman.R;
import org.sayesaman.database.DatabaseHandler;
/**
* Created with IntelliJ IDEA.
* User: a_meysami
* Date: 11/26/12
* Time: 8:49 AM
* To change this template use File | Settings | File Templates.
*/
@EActivity(R.layout.app2)
@NoTitle
@Fullscreen
public class MainActivity extends Activity {
@App
DatabaseHandler handler;
@ViewById
ImageView app2_btn01;
@ViewById
ImageView app2_btn02;
@ViewById
ImageView app2_btn03;
@ViewById
ImageView app2_btn04;
@ViewById
ImageView app2_btn05;
@ViewById
ImageView app2_btn06;
@ViewById
ImageView app2_btn07;
@ViewById
ImageView app2_btn08;
@ViewById
ImageView app2_btn09;
@ViewById
ImageView app2_btn10;
@ViewById
ImageView app2_btn11;
@ViewById
ImageView app2_btn12;
@ViewById
ImageView app2_btn13;
@ViewById
ImageView app2_btn14;
@ViewById
ImageView app2_btn15;
@ViewById
ImageView app2_btn16;
@ViewById
ImageView app2_btn17;
@ViewById
ImageView app2_btn18;
@ViewById
ImageView app2_btn19;
@Click
void app2_btn01() {
if (handler.isConnected()) {
Toast.makeText(this, "1", Toast.LENGTH_SHORT).show();
Intent i = new Intent();
i.setClass(getApplicationContext(), org.sayesaman.app7.MyActivity_.class);
startActivity(i);
}
}
@Click
void app2_btn02() {
Toast.makeText(this, "2", Toast.LENGTH_SHORT).show();
final Intent intent = new Intent();
ComponentName cName = new ComponentName("org.mapsforge.applications.android.advancedmapviewer", "org.mapsforge.applications.android.advancedmapviewer.AdvancedMapViewer");
intent.setComponent(cName);
startActivity(intent);
}
@Click
void app2_btn03() {
if (handler.isConnected()) {
Toast.makeText(this, "3", Toast.LENGTH_SHORT).show();
Intent i = new Intent();
i.setClass(getApplicationContext(), org.sayesaman.bpp1.MyActivity_.class);
startActivity(i);
}
}
@Click
void app2_btn04() {
if (handler.isConnected()) {
Toast.makeText(this, "4", Toast.LENGTH_SHORT).show();
Intent i = new Intent();
i.setClass(getApplicationContext(), org.sayesaman.bpp2.MyActivity_.class);
startActivity(i);
}
}
@Click
void app2_btn05() {
if (handler.isConnected()) {
Toast.makeText(this, "5", Toast.LENGTH_SHORT).show();
Intent i = new Intent();
i.setClass(getApplicationContext(), org.sayesaman.app3.MyActivity1_.class);
startActivity(i);
}
}
@Click
void app2_btn06() {
if (handler.isConnected()) {
Toast.makeText(this, "6", Toast.LENGTH_SHORT).show();
Intent i = new Intent();
i.setClass(getApplicationContext(), org.sayesaman.bpp3.MyActivity_.class);
startActivity(i);
}
}
@Click
void app2_btn07() {
if (handler.isConnected()) {
Toast.makeText(this, "7", Toast.LENGTH_SHORT).show();
Intent i = new Intent();
i.setClass(getApplicationContext(), org.sayesaman.tut4.path.PageViewActivity_.class);
startActivity(i);
}
}
@Click
void app2_btn08() {
if (handler.isConnected()) {
Toast.makeText(this, "8", Toast.LENGTH_SHORT).show();
Intent i = new Intent();
i.setClass(getApplicationContext(), org.sayesaman.bpp8.MyActivity_.class);
startActivity(i);
}
}
@Click
void app2_btn09() {
Toast.makeText(this, "9", Toast.LENGTH_SHORT).show();
Intent i = new Intent();
i.setClass(getApplicationContext(), org.sayesaman.bpp4.updatechecker.UpdateActivity_.class);
startActivity(i);
}
@Click
void app2_btn10() {
Toast.makeText(this, "10", Toast.LENGTH_SHORT).show();
Intent i = new Intent();
i.setClass(getApplicationContext(), org.sayesaman.app9.config.MyActivity_.class);
startActivity(i);
}
@Click
void app2_btn11() {
Toast.makeText(this, "11", Toast.LENGTH_SHORT).show();
Intent i = new Intent();
i.setClass(getApplicationContext(), org.sayesaman.bpp5.info.MyActivity_.class);
startActivity(i);
}
@Click
void app2_btn12() {
Toast.makeText(this, "12", Toast.LENGTH_SHORT).show();
finish();
}
@Click
void app2_btn13() {
Toast.makeText(this, "13", Toast.LENGTH_SHORT).show();
final Intent intent = new Intent();
ComponentName cName = new ComponentName("net.cloud.computing", "net.cloud.computing.app1.Activity1");
intent.setComponent(cName);
startActivity(intent);
}
@Click
void app2_btn14() {
Toast.makeText(this, "14", Toast.LENGTH_SHORT).show();
final Intent intent = new Intent();
ComponentName cName = new ComponentName("net.cloud.computing.inventory", "net.cloud.computing.inventory.app1.Activity1");
intent.setComponent(cName);
startActivity(intent);
}
@Click
void app2_btn15() {
Toast.makeText(this, "15", Toast.LENGTH_SHORT).show();
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
// intent.putExtra("SCAN_MODE", "PRODUCT_MODE");
startActivityForResult(intent, 0);
}
@Click
void app2_btn16() {
Toast.makeText(this, "در حال آماده سازی", Toast.LENGTH_SHORT).show();
}
@Click
void app2_btn17() {
Toast.makeText(this, "در حال آماده سازی", Toast.LENGTH_SHORT).show();
}
@Click
void app2_btn18() {
Toast.makeText(this, "در حال آماده سازی", Toast.LENGTH_SHORT).show();
}
@Click
void app2_btn19() {
Toast.makeText(this, "در حال آماده سازی", Toast.LENGTH_SHORT).show();
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
String contents = intent.getStringExtra("SCAN_RESULT");
String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
// Handle successful scan
String msg = "بارکد " + contents + " با فرمت " + format + " شناسایی شد.";
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
} else if (resultCode == RESULT_CANCELED) {
// Handle cancel
}
}
}
}
|
package facades;
import DTO.MembersDTO;
import entities.Colour;
import utils.EMF_Creator;
import entities.Members;
import java.awt.Color;
import java.util.List;
import javassist.CtClass;
import javassist.bytecode.annotation.Annotation;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import utils.Settings;
import utils.EMF_Creator.DbSelector;
import utils.EMF_Creator.Strategy;
//Uncomment the line below, to temporarily disable this test
//@Disabled
public class MembersFacadeTest {
private static EntityManagerFactory emf;
private static MembersFacade facade;
Members memberUsedByIdTest = new Members("Bob", "bob@cphbusiness.dk", Colour.GREEN);
public MembersFacadeTest() {
}
//@BeforeAll
public static void setUpClass() {
emf = EMF_Creator.createEntityManagerFactory(
"pu",
"jdbc:mysql://localhost:3307/startcode_test",
"dev",
"ax2",
EMF_Creator.Strategy.CREATE);
facade = MembersFacade.getMembersFacade(emf);
}
/* **** HINT ****
A better way to handle configuration values, compared to the UNUSED example above, is to store those values
ONE COMMON place accessible from anywhere.
The file config.properties and the corresponding helper class utils.Settings is added just to do that.
See below for how to use these files. This is our RECOMENDED strategy
*/
@BeforeAll
public static void setUpClassV2() {
emf = EMF_Creator.createEntityManagerFactory(DbSelector.TEST,Strategy.DROP_AND_CREATE);
facade = MembersFacade.getMembersFacade(emf);
}
@AfterAll
public static void tearDownClass() {
// Clean up database after test is done or use a persistence unit with drop-and-create to start up clean on every test
}
// Setup the DataBase in a known state BEFORE EACH TEST
//TODO -- Make sure to change the script below to use YOUR OWN entity class
@BeforeEach
public void setUp() {
EntityManager em = emf.createEntityManager();
try {
em.getTransaction().begin();
em.createNamedQuery("Members.deleteAllRows").executeUpdate();
em.persist(new Members("Tom", "Tom@cphbusiness.dk", Colour.GREEN));
em.persist(new Members("Lone", "Lone@cphbusiness.dk", Colour.YELLOW));
em.persist(new Members("Sigurd", "Sigurd@cphbusiness.dk", Colour.RED));
em.persist(memberUsedByIdTest);
em.getTransaction().commit();
} finally {
em.close();
}
}
@AfterEach
public void tearDown() {
// Remove any data after each test was run
}
// TODO: Delete or change this method
@Test
public void testGetMembersCount() {
assertEquals(4, facade.getMembersCount(), "Expects two rows in the database");
}
@Test
public void testGetMemberById()
{
//Arrange
MembersDTO member;
//Act
member = facade.getMemberById( memberUsedByIdTest.getId());
//Arrange
assertEquals("Bob", member.getName());
assertEquals(Colour.GREEN, member.getColourLevelOfStudent());
}
@Test
public void testGetAllMembers()
{
//Arrange
List<MembersDTO> allMembers;
//Act
allMembers = facade.getAllMembers();
//Assert
assertEquals(4, allMembers.size());
}
@Test
public void testCreateMember()
{
//Arrange
Long count;
//Act
count = facade.getMembersCount();
facade.createMember(new Members("Sine", "sine@cphbusiness.dk", Colour.RED));
//Assert (if the member above got persisted, the members count should be equal to the count before it got persisted +1 )
assertEquals(count+1, facade.getMembersCount());
}
}
|
package jarjestaminen.algoritmit;
import java.util.Arrays;
import java.util.Random;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class QuickSortTest {
private int[] arr;
private int[] arr2;
@Before
public void setUp() throws Exception {
arr = new int[20];
Random generator = new Random();
for (int i = 0; i < arr.length; i++) {
arr[i] = generator.nextInt(100);
}
arr2 = new int[20000];
for (int i = 0; i < arr2.length; i++) {
arr2[i] = generator.nextInt(100);
}
}
/**
* Testataan toimiiko Quicksort-järjestäminen pienellä taulukolla.
*/
@Test
public void QuickSortJarjestaminenToimiiPienellaTaulukolla() {
QuickSort Quick = new QuickSort(arr);
Quick.sort(0, arr.length-1);
Arrays.sort(arr);
Assert.assertArrayEquals(Quick.getArr(), arr);
}
/**
* Testataan toimiiko Quicksort-järjestäminen suurella taulukolla.
*/
@Test
public void QuickSortJarjestaminenToimiiSuurellaTaulukolla() {
QuickSort Quick = new QuickSort(arr2);
Quick.sort(0, arr2.length-1);
Arrays.sort(arr2);
Assert.assertArrayEquals(Quick.getArr(), arr2);
}
/**
* Testataan toimiiko Quicksort-järjestäminen jos taulukko on tyhjä.
*/
@Test
public void QuickSortJarjestaminenToimiiTyhjallaTaulukolla() {
int[] arrEmpty = new int[0];
QuickSort Quick = new QuickSort(arrEmpty);
Quick.sort(0, arrEmpty.length-1);
Assert.assertArrayEquals(Quick.getArr(), arrEmpty);
}
/**
* Testataan toimiiko Quicksort-järjestäminen jos taulukossa on useampi sama
* arvo.
*/
@Test
public void QuickSortJarjestaminenToimiiJosTaulukossaSamojaArvoja() {
int[] arr3 = {0, 1, 7, 3, 9, 2, 2, 3, 4, 1, 1, 5};
QuickSort Quick = new QuickSort(arr3);
Quick.sort(0, arr3.length-1);
Arrays.sort(arr3);
Assert.assertArrayEquals(Quick.getArr(), arr3);
}
/**
* Testataan toimiiko Quicksort-järjestäminen jos taulukossa on vain yksi
* arvo.
*/
@Test
public void QuickSortJarjestaminenToimiiJosTaulukossaOnVainYksiArvo() {
int[] arr4 = {7};
QuickSort Quick = new QuickSort(arr4);
Quick.sort(0,arr4.length-1);
Arrays.sort(arr4);
Assert.assertArrayEquals(Quick.getArr(), arr4);
}
@After
public void tearDown() {
}
}
|
package com.github.service.impl;
import com.alibaba.fastjson.JSON;
import com.github.domain.webData;
import com.github.service.monitorService;
import org.junit.Test;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import static org.junit.Assert.*;
public class monitorServiceImplTest {
monitorService monitorService = new monitorServiceImpl();
@Test
public void view() {
//monitorService.view();
SimpleDateFormat format = new SimpleDateFormat("MM-dd");
Date date = new Date();
String format1 = format.format(date);
System.out.println(format1);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE,-1);
String yesterday = new SimpleDateFormat( "MM-dd ").format(cal.getTime());
System.out.println(yesterday);
}
@Test
public void getWebData() {
webData webData = monitorService.getWebData();
String s = JSON.toJSONString(webData);
System.out.println(s);
}
}
|
public class Arrays {
private int [] sc;
private int size = 0;
private int j=0;
public Arrays(int [] sc,int size)
{
this.sc =sc;
this.size = size;
}
public boolean isEmpty()
{
if(j==0)
{
return true;
}
else if(j>0 && j<size)
{
return true;
}
else
{
return false;
}
}
public void insert(int num)
{
if(isEmpty()==true)
{
sc[j] = num;
j = j +1;
}
else
{
System.out.println("Array full");
}
}
public void print()
{
if(j==0)
{
System.out.println("Array is Empty");
}
else
{
for(int i=0;i<j;i++)
{
System.out.println(sc[i]);
}
}
}
public void delete()
{
if(j ==0)
{
System.out.println("The Array is Empty");
}
else
{
j = j -1;
System.out.println("Deletion Succesful at position:- "+ j);
}
}
public void deleteall()
{
if(j==0)
{
System.out.println("Array is empty and Nothing to delete");
}
else
{
j = 0;
}
}
}
|
public class DisorderlyEscape {
}
|
package file;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.swing.JFileChooser;
import com.lowagie.text.BadElementException;
import com.lowagie.text.Cell;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Table;
import com.lowagie.text.rtf.RtfWriter2;
import gui.ComponentTools;
import gui.comp.FileChooser;
// iText-rtf-2.1.5.jar
public class RTFFile
{
private File file;
private com.lowagie.text.Document document;
private Table table;
public RTFFile (final String filename) throws IOException
{
document = new com.lowagie.text.Document();
RtfWriter2.getInstance (document, new FileOutputStream (filename));
document.open();
}
public RTFFile (final File file)
{
this.file = file;
}
public File getFile()
{
return file;
}
public String getText()
{
String text = null;
if (file.exists())
{
try
{
text = RtfToText.getPlainText (file);
}
catch (IOException x)
{
x.printStackTrace (System.err);
}
}
return text;
}
public static String getText (final File file)
{
return new RTFFile (file).getText();
}
// methods to create an RTF file
public void createTable (final int numColumns)
{
try
{
table = new Table (numColumns);
}
catch (BadElementException x)
{
x.printStackTrace();
}
}
public void addRow (final String[] contents)
{
for (String s : contents)
{
Paragraph p = new Paragraph (s);
Cell c = null;
try
{
c = new Cell (p);
}
catch (BadElementException x)
{
x.printStackTrace();
}
table.addCell (c);
}
}
public void close()
{
try
{
document.add (table);
}
catch (DocumentException x)
{
x.printStackTrace();
}
document.close();
}
public static void main (final String[] args)
{
ComponentTools.setDefaults();
String user = System.getProperty ("user.name");
String dir = "C:/Documents and Settings/" + user + "/Desktop/";
FileChooser fc = new FileChooser ("Select File", dir);
fc.setRegexFilter (".+[.]rtf", "Rich Text Format (*.rtf) files");
if (fc.showOpenDialog (null) == JFileChooser.APPROVE_OPTION)
{
File file = fc.getSelectedFile();
if (file != null)
{
RTFFile rtf = new RTFFile (file);
System.out.println (rtf.getText());
}
}
}
}
|
package com.staniul.teamspeak.security.clientaccesscheck;
import com.staniul.teamspeak.query.Client;
import java.util.Set;
/**
* Checks if client is in one of many a servergroups based on given groups.
*/
public class ClientServergroupAccessCheck extends ClientGroupAccessCheck {
public ClientServergroupAccessCheck(Set<Integer> groups) {
super(groups);
}
@Override
public Boolean apply(Client client) {
return client.isInServergroup(groups);
}
}
|
package com.trump.auction.back.rule.service;
import com.cf.common.util.page.PageUtils;
import com.cf.common.util.page.Paging;
import com.github.pagehelper.PageHelper;
import com.trump.auction.back.auctionProd.dao.read.AuctionProductInfoDao;
import com.trump.auction.back.product.vo.ParamVo;
import com.trump.auction.back.rule.dao.read.AuctionRuleDao;
import com.trump.auction.back.rule.model.AuctionRule;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 竞拍规则管理
*
* @author zhangliyan
* @create 2018-01-03 15:54
**/
@Slf4j
@Service
public class AuctionRuleServiceImpl implements AuctionRuleService {
@Autowired
private AuctionRuleDao auctionRuleDao;
@Autowired
private AuctionProductInfoDao auctionProductInfoDao;
/**
* 分页查询订单列表
* @param paramVo
* @return
*/
@Override
public Paging<AuctionRule> findAuctionRulePage(ParamVo paramVo) {
long startTime = System.currentTimeMillis();
log.info("findAuctionRulePage invoke,StartTime:{},params:{}", startTime, paramVo);
Paging<AuctionRule> result = null;
try {
result = new Paging<>();
PageHelper.startPage(paramVo.getPage(),paramVo.getLimit());
result = PageUtils.page(auctionRuleDao.findAuctionRuleList(paramVo));
if(CollectionUtils.isNotEmpty(result.getList())){
for (AuctionRule rule:result.getList()
) {
rule.setProductNum(auctionProductInfoDao.getProductNumByRuleId(rule.getId()));
}
}
} catch (NumberFormatException e) {
log.error("findAuctionRulePage error:", e);
}
long endTime = System.currentTimeMillis();
log.info("findAuctionRulePage end,duration:{}", endTime - startTime);
return result;
}
@Override
public List<AuctionRule> findAuctionRuleList() {
Map<String,Object> map=new HashMap<String,Object>();
map.put("status",1);
ParamVo paramVo = new ParamVo();
paramVo.setStatus(1);
return auctionRuleDao.findAuctionRuleList(paramVo);
}
@Override
public AuctionRule findAuctionRuleById(Integer id) {
long startTime = System.currentTimeMillis();
log.info("findAuctionRuleById invoke,StartTime:{},params:{}", startTime, id);
if (null == id) {
throw new IllegalArgumentException("findAuctionRuleById param orderId is null");
}
AuctionRule result = null;
try {
result = auctionRuleDao.findAuctionRuleById(id);
} catch (NumberFormatException e) {
log.error("findAuctionRuleById error:", e);
}
long endTime = System.currentTimeMillis();
log.info("findAuctionRuleById end,duration:{}", endTime - startTime);
return result;
}
@Override
public AuctionRule getAuctionRule(Integer id) {
AuctionRule rule = auctionRuleDao.getAuctionRule(id);
return rule;
}
@Override
public AuctionRule queryRuleById(int ruleId) {
return auctionRuleDao.getAuctionRule(ruleId);
}
}
|
package com.ecej.nove.base.po;
import org.apache.commons.lang3.StringUtils;
import java.io.Serializable;
import java.util.Date;
public class MonitorBase implements Serializable{
private static final long serialVersionUID = 8280094606296752962L;
/**
* 路由信息 db_column: protocal
*/
private String protocal;
/**
* 本地 db_column: host
*/
private String host;
/**
* 远程地址
*/
private String remoteHost;
/**
* 本地端口 consumer:0,provider:xxxx db_column: port
*/
private String port;
/**
* interface/method db_column: path
*/
private String path;
/**
* application db_column: application
*/
private String application;
/**
* interfaceName db_column: interfaceName
*/
private String interfaceName;
/**
* method db_column: method
*/
private String method;
/**
* rovider/consumer db_column: role
*/
private String role;
/**
* failure/success db_column: status
*/
private String status;
/**
* errorMsg db_column: errorMsg
*/
private String errorMsg;
/**
* elapsed db_column: elapsed
*/
private String elapsed;
/**
* concurrent db_column: concurrent
*/
private String concurrent;
/**
* input db_column: input
*/
private String input;
/**
* 输出 db_column: output
*/
private String output;
/**
* distributId db_column: distributId
*/
private String distributId;
/**
* step db_column: step
*/
private String step;
private Date startDate;
/**
* 应用端口
*/
private String appPort;
public String getAppPort() {
return appPort;
}
public void setAppPort(String appPort) {
this.appPort = appPort;
}
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
//columns END
public String getRemoteHost() {
return remoteHost;
}
public void setRemoteHost(String remoteHost) {
this.remoteHost = remoteHost;
}
public String getProtocal() {
return this.protocal;
}
public void setProtocal(String value) {
this.protocal = value;
}
public String getHost() {
return this.host;
}
public void setHost(String value) {
this.host = value;
}
public String getPort() {
return this.port;
}
public void setPort(String value) {
this.port = value;
}
public String getPath() {
return this.path;
}
public void setPath(String value) {
this.path = value;
}
public String getApplication() {
return this.application;
}
public void setApplication(String value) {
this.application = value;
}
public String getInterfaceName() {
return this.interfaceName;
}
public void setInterfaceName(String value) {
this.interfaceName = value;
}
public String getMethod() {
return this.method;
}
public void setMethod(String value) {
this.method = value;
}
public String getRole() {
return this.role;
}
public void setRole(String value) {
this.role = value;
}
public String getStatus() {
return this.status;
}
public void setStatus(String value) {
this.status = value;
}
public String getErrorMsg() {
return this.errorMsg;
}
public void setErrorMsg(String value) {
this.errorMsg = value;
}
public String getElapsed() {
return this.elapsed;
}
public void setElapsed(String value) {
this.elapsed = value;
}
public String getConcurrent() {
return this.concurrent;
}
public void setConcurrent(String value) {
this.concurrent = value;
}
public String getInput() {
return this.input;
}
public void setInput(String value) {
this.input = value;
}
public String getOutput() {
return this.output;
}
public void setOutput(String value) {
this.output = value;
}
public String getDistributId() {
return this.distributId;
}
public void setDistributId(String value) {
if(StringUtils.isNotEmpty(value)){
String[] idStep = value.split("-");
this.distributId = idStep[0];
this.step = idStep[1];
}
}
public String getStep() {
return this.step;
}
public void setStep(String value) {
this.step = value;
}
}
|
package com.github.gaoyangthu.esanalysis.hbase.service.impl;
import com.github.gaoyangthu.core.hbase.HbaseTemplate;
import com.github.gaoyangthu.core.hbase.HbaseTemplateFactory;
import com.github.gaoyangthu.esanalysis.hbase.bean.UserId;
import com.github.gaoyangthu.esanalysis.hbase.bean.UserIndex;
import com.github.gaoyangthu.esanalysis.hbase.constant.UserIdConst;
import com.github.gaoyangthu.esanalysis.hbase.dao.UserIdMapper;
import com.github.gaoyangthu.esanalysis.hbase.dao.UserIndexMapper;
import com.github.gaoyangthu.esanalysis.hbase.service.UserBehaviorService;
import com.github.gaoyangthu.esanalysis.hbase.service.UserChannelTagService;
import com.github.gaoyangthu.esanalysis.hbase.service.UserIdService;
import com.github.gaoyangthu.esanalysis.hbase.service.UserStatService;
import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.hbase.client.HTableInterface;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.util.Bytes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
/**
* Created with IntelliJ IDEA.
* Author: gaoyangthu
* Date: 14-3-13
* Time: 上午9:53
*/
public class UserIdServiceImpl implements UserIdService {
private static final Logger LOGGER = LoggerFactory.getLogger(UserIdServiceImpl.class);
private HbaseTemplate hbaseTemplate = HbaseTemplateFactory.getHbaseTemplate();
private UserBehaviorService userBehaviorService;
private UserChannelTagService userChannelTagService;
private UserStatService userStatService;
public UserIdServiceImpl() {
userBehaviorService = new UserBehaviorServiceImpl();
userChannelTagService = new UserChannelTagServiceImpl();
userStatService = new UserStatServiceImpl();
}
@Override
public List<UserId> findAllUserId() {
return hbaseTemplate.find(UserIdConst.USER_ID, new Scan(), new UserIdMapper());
}
@Override
public List<UserIndex> findAllUserIndex() {
return hbaseTemplate.find(UserIdConst.USER_INDEX, new Scan(), new UserIndexMapper());
}
@Override
public String getBdUserUuid(String uaId, String cookieId, String accountId) {
UserIndex uaIndex = getUserIndexById(uaId);
UserIndex cookieIndex = getUserIndexById(cookieId);
UserIndex accountIndex = getUserIndexById(accountId);
boolean flag = false;
String bdUserUuid = null;
if(accountIndex != null) {
// 存在accountIndex
// 更新其他的index的uuid到accountIndex
bdUserUuid = accountIndex.getBdUserUuid();
if (cookieIndex != null) {
if (!cookieIndex.getBdUserUuid().equals(bdUserUuid)) {
String oldUuid = cookieIndex.getBdUserUuid();
// TODO 更新tag对应的uuid,将oldUuid的tag赋值给新的bdUserUuid,删除oldUuid.
userBehaviorService.changeBdUser(oldUuid, bdUserUuid);
userChannelTagService.changeBdUser(oldUuid, bdUserUuid);
// 更新user_index
flag = addUserIndex(cookieId, bdUserUuid);
if(!flag) {
LOGGER.error(
"Update user_index error. cookieId={}, bdUserUuid={}",
cookieId, bdUserUuid);
}
}
} else if (StringUtils.isNotBlank(cookieId)) {
// cookieIndex == null && cookieId != null
flag = addUserIndex(cookieId, bdUserUuid);
if(!flag) {
LOGGER.error(
"Create user_index error. cookieId={}, bdUserUuid={}",
cookieId, bdUserUuid);
}
}
if (uaIndex != null) {
if (!uaIndex.getBdUserUuid().equals(bdUserUuid)) {
String oldUuid = uaIndex.getBdUserUuid();
// TODO 更新tag对应的uuid,将oldUuid的tag赋值给新的bdUserUuid,删除oldUuid.
userBehaviorService.changeBdUser(oldUuid, bdUserUuid);
userChannelTagService.changeBdUser(oldUuid, bdUserUuid);
// 更新user_index
flag = addUserIndex(uaId, bdUserUuid);
if(!flag) {
LOGGER.error(
"Update user_index error. uaId={}, bdUserUuid={}",
uaId, bdUserUuid);
}
}
} else if (StringUtils.isNotBlank(uaId)) {
// uaIndex == null && uaId != null
flag = addUserIndex(uaId, bdUserUuid);
if(!flag) {
LOGGER.error("Create user_index error. uaId={}, bdUserUuid={}",
uaId, bdUserUuid);
}
}
} else if(cookieIndex != null) {
bdUserUuid = cookieIndex.getBdUserUuid();
if (StringUtils.isNotBlank(accountId)) {
// accountIndex == null && accountId != null
flag = addUserIndex(accountId, bdUserUuid);
if (!flag) {
LOGGER.error(
"Create user_index error. accountId={}, bdUserUuid={}",
accountId, bdUserUuid);
}
}
if (uaIndex != null) {
if (!uaIndex.getBdUserUuid().equals(bdUserUuid)) {
String oldUuid = uaIndex.getBdUserUuid();
// TODO 更新tag对应的uuid,将oldUuid的tag赋值给新的bdUserUuid,删除oldUuid.
userBehaviorService.changeBdUser(oldUuid, bdUserUuid);
userChannelTagService.changeBdUser(oldUuid, bdUserUuid);
// 更新user_index
flag = addUserIndex(uaId, bdUserUuid);
if(!flag) {
LOGGER.error(
"Update user_index error. uaId={}, bdUserUuid={}",
uaId, bdUserUuid);
}
}
} else if (StringUtils.isNotBlank(uaId)) {
// uaIndex == null && uaId != null
flag = addUserIndex(uaId, bdUserUuid);
if(!flag) {
LOGGER.error("Create user_index error. uaId={}, bdUserUuid={}",
uaId, bdUserUuid);
}
}
} else if(uaIndex != null) {
bdUserUuid = uaIndex.getBdUserUuid();
if (StringUtils.isNotBlank(accountId)) {
// accountIndex == null && accountId != null
flag = addUserIndex(accountId, bdUserUuid);
if (!flag) {
LOGGER.error(
"Create user_index error. accountId={}, bdUserUuid={}",
accountId, bdUserUuid);
}
}
if (StringUtils.isNotBlank(cookieId)) {
flag = addUserIndex(cookieId, bdUserUuid);
if(!flag) {
LOGGER.error(
"Create user_index error. cookieId={}, bdUserUuid={}",
cookieId, bdUserUuid);
}
}
} else {
// bdUserUuid为空,表示没有生成过bdUserUuid
bdUserUuid = createBdUserUuid();
// 添加userIndex
if (StringUtils.isNotBlank(uaId)) {
flag = addUserIndex(uaId, bdUserUuid);
if(!flag) {
LOGGER.error("Create user_index error. uaId={}, bdUserUuid={}",
uaId, bdUserUuid);
}
}
if (StringUtils.isNotBlank(cookieId)) {
flag = addUserIndex(cookieId, bdUserUuid);
if(!flag) {
LOGGER.error(
"Create user_index error. cookieId={}, bdUserUuid={}",
cookieId, bdUserUuid);
}
}
if (StringUtils.isNotBlank(accountId)) {
flag = addUserIndex(accountId, bdUserUuid);
if(!flag) {
LOGGER.error(
"Create user_index error. accountId={}, bdUserUuid={}",
accountId, bdUserUuid);
}
}
}
// 添加userId
flag = addUserId(bdUserUuid, uaId, cookieId, accountId);
if (!flag) {
LOGGER.error(
"Create user_id error. bdUserUuid={}, uaId={}, cookieId={}, accountId={}",
bdUserUuid, uaId, cookieId, accountId);
}
return bdUserUuid;
}
public String getBdUuid(String uaId, String cookieId, String accountId) {
// TODO 代码可以优化,用hashmap<id, UserIndex>做后续的遍历和访问
UserIndex uaIndex = getUserIndexById(uaId);
UserIndex cookieIndex = getUserIndexById(cookieId);
UserIndex accountIndex = getUserIndexById(accountId);
String bdUserUuid = null;
Long timestamp = Long.MAX_VALUE;
if ((uaIndex != null) && (uaIndex.getTimestamp() < timestamp)) {
bdUserUuid = uaIndex.getBdUserUuid();
timestamp = uaIndex.getTimestamp();
}
if ((cookieIndex != null) && (cookieIndex.getTimestamp() < timestamp)) {
bdUserUuid = cookieIndex.getBdUserUuid();
timestamp = cookieIndex.getTimestamp();
}
if ((accountIndex != null) && (accountIndex.getTimestamp() < timestamp)) {
bdUserUuid = accountIndex.getBdUserUuid();
timestamp = accountIndex.getTimestamp();
}
boolean flag = false;
if (StringUtils.isBlank(bdUserUuid)) {
// bdUserUuid为空,表示没有生成过bdUserUuid
bdUserUuid = createBdUserUuid();
// 添加userId
flag = addUserId(bdUserUuid, uaId, cookieId, accountId);
if (!flag) {
LOGGER.error(
"Create user_id error. bdUserUuid={}, uaId={}, cookieId={}, accountId={}",
bdUserUuid, uaId, cookieId, accountId);
}
// 添加userIndex
if (StringUtils.isNotBlank(uaId)) {
flag = addUserIndex(uaId, bdUserUuid);
if(!flag) {
LOGGER.error("Create user_index error. uaId={}, bdUserUuid={}",
uaId, bdUserUuid);
}
}
if (StringUtils.isNotBlank(cookieId)) {
flag = addUserIndex(cookieId, bdUserUuid);
if(!flag) {
LOGGER.error(
"Create user_index error. cookieId={}, bdUserUuid={}",
cookieId, bdUserUuid);
}
}
if (StringUtils.isNotBlank(accountId)) {
flag = addUserIndex(accountId, bdUserUuid);
if(!flag) {
LOGGER.error(
"Create user_index error. accountId={}, bdUserUuid={}",
accountId, bdUserUuid);
}
}
return bdUserUuid;
} else {
// bdUserUuid != null, 存在一个创建时间最早的bdUserUuid
// 更新不一致的id(ua_id,cookie_id,account_id对应的bdUserUuid)
if (uaIndex != null) {
if (!uaIndex.getBdUserUuid().equals(bdUserUuid)) {
String oldUuid = uaIndex.getBdUserUuid();
// TODO 更新tag对应的uuid,将oldUuid的tag赋值给新的bdUserUuid,删除oldUuid.
userBehaviorService.changeBdUser(oldUuid, bdUserUuid);
userChannelTagService.changeBdUser(oldUuid, bdUserUuid);
userStatService.changeBdUser(oldUuid, bdUserUuid);
// 更新user_index
flag = addUserIndex(uaId, bdUserUuid);
if(!flag) {
LOGGER.error(
"Update user_index error. uaId={}, bdUserUuid={}",
uaId, bdUserUuid);
}
}
} else if (StringUtils.isNotBlank(uaId)) {
// uaIndex == null && uaId != null
flag = addUserIndex(uaId, bdUserUuid);
if(!flag) {
LOGGER.error("Create user_index error. uaId={}, bdUserUuid={}",
uaId, bdUserUuid);
}
}
if (cookieIndex != null) {
if (!cookieIndex.getBdUserUuid().equals(bdUserUuid)) {
String oldUuid = cookieIndex.getBdUserUuid();
// TODO 更新tag对应的uuid,将oldUuid的tag赋值给新的bdUserUuid,删除oldUuid.
userBehaviorService.changeBdUser(oldUuid, bdUserUuid);
userChannelTagService.changeBdUser(oldUuid, bdUserUuid);
userStatService.changeBdUser(oldUuid, bdUserUuid);
// 更新user_index
flag = addUserIndex(cookieId, bdUserUuid);
if(!flag) {
LOGGER.error(
"Update user_index error. cookieId={}, bdUserUuid={}",
cookieId, bdUserUuid);
}
}
} else if (StringUtils.isNotBlank(cookieId)) {
// cookieIndex == null && cookieId != null
flag = addUserIndex(cookieId, bdUserUuid);
if(!flag) {
LOGGER.error(
"Create user_index error. cookieId={}, bdUserUuid={}",
cookieId, bdUserUuid);
}
}
if (accountIndex != null) {
if (!accountIndex.getBdUserUuid().equals(bdUserUuid)) {
String oldUuid = accountIndex.getBdUserUuid();
// TODO 更新tag对应的uuid,将oldUuid的tag赋值给新的bdUserUuid,删除oldUuid.
userBehaviorService.changeBdUser(oldUuid, bdUserUuid);
userChannelTagService.changeBdUser(oldUuid, bdUserUuid);
userStatService.changeBdUser(oldUuid, bdUserUuid);
// 更新user_index
flag = addUserIndex(accountId, bdUserUuid);
if(!flag) {
LOGGER.error(
"Update user_index error. accountId={}, bdUserUuid={}",
accountId, bdUserUuid);
}
}
} else if (StringUtils.isNotBlank(accountId)) {
// accountIndex == null && accountId != null
flag = addUserIndex(accountId, bdUserUuid);
if(!flag) {
LOGGER.error(
"Create user_index error. accountId={}, bdUserUuid={}",
accountId, bdUserUuid);
}
}
// 更新userId
flag = addUserId(bdUserUuid, uaId, cookieId, accountId);
if (!flag) {
LOGGER.error(
"Update user_id error. bdUserUuid={}, uaId={}, cookieId={}, accountId={}",
bdUserUuid, uaId, cookieId, accountId);
}
}
return bdUserUuid;
}
private String createBdUserUuid() {
return UUID.randomUUID().toString();
}
public UserIndex getUserIndexById(String id) {
if (StringUtils.isBlank(id)) {
return null;
}
UserIndex userIndex = hbaseTemplate.get(UserIdConst.USER_INDEX, id,
new UserIndexMapper());
return userIndex;
}
public boolean addUserId(String bdUserUuid, String uaId, String cookieId,
String accountId) {
boolean flag = false;
HTableInterface userIdTable = hbaseTemplate.getTable(UserIdConst.USER_ID);
try {
Put put = new Put(Bytes.toBytes(bdUserUuid));
// id列族
// id:trade_id
if (StringUtils.isNotBlank(uaId)) {
put.add(Bytes.toBytes(UserIdConst.ID),
Bytes.toBytes(UserIdConst.UA_ID), Bytes.toBytes(uaId));
}
// id:cookie_id
if (StringUtils.isNotBlank(cookieId)) {
put.add(Bytes.toBytes(UserIdConst.ID),
Bytes.toBytes(UserIdConst.COOKIE_ID),
Bytes.toBytes(cookieId));
}
// id:account_id
if (StringUtils.isNotBlank(accountId)) {
put.add(Bytes.toBytes(UserIdConst.ID),
Bytes.toBytes(UserIdConst.ACCOUNT_ID),
Bytes.toBytes(accountId));
}
userIdTable.put(put);
flag = true;
} catch (IOException e) {
LOGGER.error("Add user id error", e);
} finally {
hbaseTemplate.releaseTable(UserIdConst.USER_ID, userIdTable);
}
return flag;
}
public boolean addUserIndex(String id, String bdUserUuid) {
boolean flag = false;
HTableInterface userIdTable = hbaseTemplate.getTable(UserIdConst.USER_INDEX);
try {
Put put = new Put(Bytes.toBytes(id));
// bd_user_uuid列族
// bd_user_uuid:bd_user_uuid
put.add(Bytes.toBytes(UserIdConst.BD_USER_UUID),
Bytes.toBytes(UserIdConst.BD_USER_UUID),
Bytes.toBytes(bdUserUuid));
userIdTable.put(put);
flag = true;
} catch (IOException e) {
LOGGER.error("Add user index error", e);
} finally {
hbaseTemplate.releaseTable(UserIdConst.USER_INDEX, userIdTable);
}
return flag;
}
}
|
package main.java.util.dto;
/**
* 书籍类
* @author libowen1
*
*/
public class BookDTO {
/**
* 名称
*/
private String name;
/**
* 路径
*/
private String url;
/**
* 读到了哪一章对应的行
*/
private int historyUnitLine;
/**
* 读到的章节名称
*/
private String historyUnitName;
/**
* 一共多少章
*/
private int unitAll;
/**
* 章节目录的第几页
*/
private int currentPage;
private long lastReaderTime;
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public int getHistoryUnitLine() {
return historyUnitLine;
}
public void setHistoryUnitLine(int historyUnitLine) {
this.historyUnitLine = historyUnitLine;
}
public String getHistoryUnitName() {
return historyUnitName;
}
public void setHistoryUnitName(String historyUnitName) {
this.historyUnitName = historyUnitName;
}
public int getUnitAll() {
return unitAll;
}
public void setUnitAll(int unitAll) {
this.unitAll = unitAll;
}
public long getLastReaderTime() {
return lastReaderTime;
}
public void setLastReaderTime(long lastReaderTime) {
this.lastReaderTime = lastReaderTime;
}
@Override
public String toString() {
return "BookDTO [name=" + name + ", url=" + url + ", historyUnitLine=" + historyUnitLine + ", historyUnitName=" + historyUnitName + ", unitAll=" + unitAll + ", lastReaderTime="
+ lastReaderTime + "]";
}
}
|
package presentation.customer;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.image.Image;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import presentation.customer.view.*;
import vo.CustomerVO;
import vo.HotelInfoVO;
import vo.OrderVO;
import vo.SearchInfoVO;
import java.io.IOException;
/**
* Created by 啊 on 2016/12/5.
*/
public class MainAPP extends Application{
private Stage primaryStage;
private BorderPane rootLayout;
@Override
public void start(Stage primaryStage) throws Exception {
this.primaryStage = primaryStage;
this.primaryStage.setTitle("顾客");
this.primaryStage.getIcons().add(new Image("/presentation/icon_title.png"));
showSignInView();
}
public void showRootView(CustomerVO customerVO) {
try {
// Load root layout from fxml file.
FXMLLoader loader = new FXMLLoader();
loader.setLocation(MainAPP.class.getResource("view/RootLayout.fxml"));
rootLayout = (BorderPane) loader.load();
Scene scene = new Scene(rootLayout);
primaryStage.setScene(scene);
primaryStage.show();
RootLayoutController controller = loader.getController();
controller.setCustomerVO(customerVO);
controller.setMainApp(this);
} catch (IOException e) {
e.printStackTrace();
}
}
public void showSearchView(CustomerVO customerVO) {
try {
// Load root layout from fxml file.
FXMLLoader loader = new FXMLLoader();
loader.setLocation(MainAPP.class.getResource("view/search.fxml"));
AnchorPane search=(AnchorPane)loader.load();
rootLayout.setCenter(search);
SearchController controller = loader.getController();
controller.setCustomerVO(customerVO);
controller.setMainApp(this);
} catch (IOException e) {
e.printStackTrace();
}
}
public void showSignUpView() {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(MainAPP.class.getResource("view/SignUp.fxml"));
Scene scene=new Scene( loader.load());
primaryStage.setScene(scene);
primaryStage.show();
SignUpController controller=loader.getController();
controller.setMainAPP(this);
} catch (IOException e) {
e.printStackTrace();
}
}
public void showSignUpBirthdayView(CustomerVO customerVO){
try{
FXMLLoader loader = new FXMLLoader();
loader.setLocation(MainAPP.class.getResource("view/SignUp_Birthday.fxml"));
Scene scene=new Scene(loader.load());
primaryStage.setScene(scene);
SignUp_BirthdayController controller=loader.getController();
controller.setCustomerVO(customerVO);
controller.setMainAPP(this);
primaryStage.show();
} catch (IOException e) {
e.printStackTrace();
}
}
public void showSignUpEnterpriseView(CustomerVO customerVO) {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(MainAPP.class.getResource("view/SignUp_Enterprise.fxml"));
Scene scene=new Scene( loader.load());
primaryStage.setScene(scene);
SignUp_EnterpriseController controller=loader.getController();
controller.setCustomerVO(customerVO);
controller.setMainAPP(this);
primaryStage.show();
} catch (IOException e) {
e.printStackTrace();
}
}
public void showSignInView() {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(MainAPP.class.getResource("view/SignIn.fxml"));
Scene scene=new Scene( loader.load());
primaryStage.setScene(scene);
primaryStage.show();
SignInController controller=loader.getController();
controller.setMainAPP(this);
} catch (IOException e) {
e.printStackTrace();
}
}
public void showOrderInfoView(CustomerVO customerVO) {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(MainAPP.class.getResource("view/OrderInfo.fxml"));
AnchorPane order=(AnchorPane)loader.load();
rootLayout.setCenter(order);
OrderInfoController controller=loader.getController();
controller.setCustomerVO(customerVO);
controller.setMainAPP(this);
} catch (IOException e) {
e.printStackTrace();
}
}
public void showOrderInfoView(CustomerVO customerVO, HotelInfoVO hotelInfoVO) {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(MainAPP.class.getResource("view/OrderInfo.fxml"));
AnchorPane order=(AnchorPane)loader.load();
rootLayout.setCenter(order);
OrderInfoController controller=loader.getController();
controller.setCustomerVO(customerVO);
controller.setHotelInfoVO(hotelInfoVO);
controller.setMainAPP(this);
} catch (IOException e) {
e.printStackTrace();
}
}
public void showDetailedCreditField(CustomerVO customerVO) {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(MainAPP.class.getResource("view/CustomerCreditInfo.fxml"));
AnchorPane credit=(AnchorPane)loader.load();
rootLayout.setCenter(credit);
CreditInfoController controller=loader.getController();
controller.setCustomerVO(customerVO);
controller.setMainAPP(this);
} catch (IOException e) {
e.printStackTrace();
}
}
public void showCustomerInfoModifyView(CustomerVO customerVO) {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(MainAPP.class.getResource("view/CustomerInfoModify.fxml"));
AnchorPane modify=(AnchorPane)loader.load();
rootLayout.setCenter(modify);
CustomerInfoModifyController controller=loader.getController();
controller.setCustomerVO(customerVO);
controller.setMainAPP(this);
} catch (IOException e) {
e.printStackTrace();
}
}
public void showDetailedSearchView(CustomerVO customerVO) {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(MainAPP.class.getResource("view/DetailedSearch.fxml"));
AnchorPane search=(AnchorPane)loader.load();
rootLayout.setCenter(search);
DetailedSearchController controller=loader.getController();
controller.setCustomerVO(customerVO);
controller.setMainAPP(this);
}catch (IOException e) {
e.printStackTrace();
}
}
public void showPersonalInformationView(CustomerVO customerVO) {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(MainAPP.class.getResource("view/CustomerInfo.fxml"));
AnchorPane information=(AnchorPane)loader.load();
rootLayout.setCenter(information);
CustomerInfoController controller=loader.getController();
controller.setCustomerVO(customerVO);
controller.setMainAPP(this);
} catch (IOException e) {
e.printStackTrace();
}
}
public void showOrderGeneratedView(CustomerVO customerVO,HotelInfoVO hotelInfoVO, SearchInfoVO searchInfoVO) {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(MainAPP.class.getResource("view/CustomerOrderGenerated1.fxml"));
AnchorPane generate=(AnchorPane)loader.load();
rootLayout.setCenter(generate);
OrderGeneratedController controller=loader.getController();
controller.setHotelVO(hotelInfoVO);
controller.setCustomerVO(customerVO);
controller.setSearchInfoVO(searchInfoVO);
controller.setMainAPP(this);
} catch (IOException e) {
e.printStackTrace();
}
}
public void showSearchHotelView(CustomerVO customerVO, SearchInfoVO searchInfoVO) {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(MainAPP.class.getResource("view/SearchHotel.fxml"));
AnchorPane search=(AnchorPane)loader.load();
rootLayout.setCenter(search);
SearchHotelController controller=loader.getController();
controller.setCustomerVO(customerVO);
controller.setSearchInfoVO(searchInfoVO);
controller.setMainAPP(this);
} catch (IOException e) {
e.printStackTrace();
}
}
public void showOrderGenerated2ControllerView(CustomerVO customerVO, OrderVO orderVO, HotelInfoVO hotelInfoVO, SearchInfoVO searchInfoVO) {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(MainAPP.class.getResource("view/CustomerOrderGenerated.fxml"));
AnchorPane generate=(AnchorPane)loader.load();
rootLayout.setCenter(generate);
OrderGenerated2Controller controller=loader.getController();
controller.setOrderVO(orderVO);
controller.setCustomerVO(customerVO);
controller.setHotelVO(hotelInfoVO);
controller.setSearchInfoVO(searchInfoVO);
controller.setMainAPP(this);
} catch (IOException e) {
e.printStackTrace();
}
}
public void showHotelInfoView(CustomerVO customerVO,String hotelName, SearchInfoVO searchInfoVO) {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(MainAPP.class.getResource("view/HotelInfo.fxml"));
AnchorPane hotel=(AnchorPane)loader.load();
rootLayout.setCenter(hotel);
HotelInfoController controller=loader.getController();
controller.setCustomer(customerVO);
controller.setSearchInfoVO(searchInfoVO);
controller.setHotelInfoVO(hotelName);
controller.setMainAPP(this);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args){
launch();
}
public void showCustomerEvaluateView(CustomerVO customerVO, OrderVO orderVO,HotelInfoVO hotelInfoVO) {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(MainAPP.class.getResource("view/CustomerEvaluate.fxml"));
AnchorPane evaluate=(AnchorPane)loader.load();
rootLayout.setCenter(evaluate);
CustomerEvaluateController controller=loader.getController();
controller.setCustomerVO(customerVO);
controller.setOrderVO(orderVO);
controller.setHotelInfoVO(hotelInfoVO);
controller.setMainAPP(this);
} catch (IOException e) {
e.printStackTrace();
}
}
public void showLivedHotelView(CustomerVO customerVO) {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(MainAPP.class.getResource("view/livedHotel.fxml"));
AnchorPane lived=(AnchorPane)loader.load();
rootLayout.setCenter(lived);
LivedHotelController controller=loader.getController();
controller.setCustomerVO(customerVO);
controller.setMainAPP(this);
} catch (IOException e) {
e.printStackTrace();
}
}
public void informationAlert(String information) {
Alert alert;
alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Information");
alert.setHeaderText(null);
alert.setContentText(information);
alert.showAndWait();
}
public void errorAlert(String information){
Alert alert;
alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("错误");
alert.setHeaderText(null);
alert.setContentText(information);
alert.showAndWait();
}
public Boolean check(String str){
if(str.length()!=11) {
errorAlert("联系方式位数不正确");
return false;
}
return true;
}
}
|
package person;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
public class PersonHelper {
public static String getDetails(Person p) {
return p.getFullName() +", " + p.getGender() + ", "+ p.getAge() + ", "+ p.getSsn();
}
public static Person getOldestPerson(Person...persons){
Person oldestPerson = persons[0];
for(Person personInList: persons){
if(personInList.getAge() > oldestPerson.getAge()){
oldestPerson = personInList;
}
}
return oldestPerson;
}
public static List<Person> readPersonFile(String fileName) {
List<Person> list = new ArrayList<Person>();
try{
FileReader inputFile = new FileReader(fileName);
BufferedReader bufferReader = new BufferedReader(inputFile);
String line;
while ((line = bufferReader.readLine()) != null) {
String firstName = line.split(", ")[0];
String lastName = line.split(", ")[1];
char gender = (char) line.split(", ")[3].charAt(0);
int age = Integer.parseInt(line.split(", ")[2]);
String ssn = line.split(", ")[4];
list.add(new Person(ssn, firstName, lastName, gender, age));
}
bufferReader.close();
} catch(Exception e){
System.out.println("Error while reading "+fileName+" line by line: "
+ e.getMessage());
}
return list;
}
public static HashMap<String, Integer> countDuplicateLastNames(List<Person> pList){
HashMap<String, Integer> lastNameCount = new HashMap<String, Integer>();
for(Person person: pList){
if(lastNameCount.containsKey(person.getLastName())) {
lastNameCount.put(person.getLastName(), lastNameCount.get(person.getLastName()) + 1);
} else {
lastNameCount.put(person.getLastName(),1);
}
}
return lastNameCount;
}
public static ArrayList<String> getDuplicateLastNames(Map<String, Integer> lastNames) {
ArrayList<String> dupLastNames = new ArrayList<String>();
for (Map.Entry<String, Integer> entry : lastNames.entrySet()) {
if (entry.getValue() > 1) {
dupLastNames.add(entry.getKey());
}
}
return dupLastNames;
}
}
|
public class jubilacion{
int edad;
int antiguedad;
String clasificacion;
public void setEdad(int edad){
this.edad=edad;
}
public void setAntiguedad(int antiguedad){
this.antiguedad=antiguedad;
}
public String devolver(){
if(edad>60&&antiguedad<25){
clasificacion="EDAD";
}
if(edad<60&&antiguedad>25){
clasificacion="JOVEN";
}
if(edad>60&&antiguedad>25){
clasificacion="ADULTA";
}
return clasificacion;
}
}
|
package org.rs.core.service.impl;
import java.util.List;
import java.util.Map;
import org.rs.core.beans.RsDict;
import org.rs.core.beans.RsDictInfo;
import org.rs.core.key.RsKeyGenerator;
import org.rs.core.mapper.RsDictInfoMapper;
import org.rs.core.mapper.RsDictMapper;
import org.rs.core.service.RsDictService;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.rs.core.page.IPage;
@Service
public class RsDictServiceImpl implements RsDictService {
@Autowired
private RsDictMapper dictMapper;
@Autowired
private RsDictInfoMapper dictInfoMapper;
@Autowired
private RsKeyGenerator key;
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public String getDictKey() {
return "D"+key.getZipKey(DICT_KEY_NAME, 8);
}
@Override
public String getDictInfoKey() {
return "I"+key.getZipKey(DICT_KEY_NAME, 8);
}
@Override
public int insertBean( RsDict bean ) {
bean.setZdzj(getDictKey());
return dictMapper.insertBean( bean );
}
@Override
public int updateBean( RsDict bean ) {
RsDict dbBean = dictMapper.queryBeanById(bean.getZdzj());
if( dbBean != null ) {
String oldZdbh = dbBean.getZdbh();
dbBean.setZdmc(bean.getZdmc());
dbBean.setZdbh(bean.getZdbh());
dbBean.setZdlx(bean.getZdlx());
dbBean.setZdxh(bean.getZdxh());
dictMapper.updateBean( dbBean );
if( !oldZdbh.equals(dbBean.getZdbh())) {
jdbcTemplate.update("update rs_dict_info set zdbh=? where zdbh=?",new Object[] {dbBean.getZdbh(),oldZdbh});
}
}
return 0;
}
@Override
public int deleteBean( String zdzj ) {
RsDict dbBean = dictMapper.queryBeanById(zdzj);
dictInfoMapper.deleteBeanByWhereCause("zdbh='" + dbBean.getZdbh() + "'");
return dictMapper.deleteBeanById( zdzj );
}
@Override
public RsDict queryBean( String zdzj ) {
return dictMapper.queryBeanById( zdzj );
}
@Override
public List<RsDict> queryBeans( Map<String,Object> param, IPage paramPage ) {
return dictMapper.queryBeanList( param, paramPage );
}
@Override
public List<RsDictInfo> queryInfoBeans(Map<String,Object> param, IPage paramPage) {
return dictInfoMapper.queryBeanList( param, paramPage );
}
@Override
public int insertInfoBean(RsDictInfo bean) {
bean.setTmzj(getDictInfoKey());
return dictInfoMapper.insertBean( bean );
}
@Override
public int updateInfoBean(RsDictInfo bean) {
RsDictInfo dbBean = dictInfoMapper.queryBeanById(bean.getTmzj());
if( dbBean != null ) {
dbBean.setTmmc(bean.getTmmc());
dbBean.setTmbh(bean.getTmbh());
dbBean.setTmpbh(bean.getTmpbh());
dbBean.setTmxh(bean.getTmxh());
dictInfoMapper.updateBean( dbBean );
}
return 0;
}
@Override
public int deleteInfoBean(String tmzj) {
return dictInfoMapper.deleteBeanById(tmzj);
}
}
|
package pro.likada.dao.daoImpl;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pro.likada.dao.TelegramConversationDAO;
import pro.likada.model.TelegramBot;
import pro.likada.model.TelegramConversation;
import pro.likada.model.TelegramUser;
import pro.likada.util.HibernateUtil;
import javax.inject.Named;
import javax.transaction.Transactional;
import java.util.List;
/**
* Created by Yusupov on 4/2/2017.
*/
@SuppressWarnings("unchecked")
@Named("telegramConversationDAO")
@Transactional
public class TelegramConversationDAOImpl implements TelegramConversationDAO {
private static final Logger LOGGER = LoggerFactory.getLogger(TelegramConversationDAOImpl.class);
@Override
public TelegramConversation findById(Long id) throws HibernateException {
LOGGER.info("Get TelegramConversation with an ID: {}", id);
Session session = HibernateUtil.getSessionFactory().openSession();
Criteria criteria = session.createCriteria(TelegramConversation.class);
criteria.add(Restrictions.idEq(id));
criteria.setCacheable(true);
TelegramConversation telegramConversation = (TelegramConversation) criteria.uniqueResult();
session.close();
return telegramConversation;
}
@Override
public TelegramConversation findByChatId(Long chatId) throws HibernateException {
LOGGER.info("Get TelegramConversation with an chat ID: {}", chatId);
Session session = HibernateUtil.getSessionFactory().openSession();
Criteria criteria = session.createCriteria(TelegramConversation.class);
criteria.add(Restrictions.eq("chatId", chatId));
criteria.setCacheable(true);
TelegramConversation telegramConversation = (TelegramConversation) criteria.uniqueResult();
session.close();
return telegramConversation;
}
@Override
public List<TelegramConversation> findByTelegramUser(TelegramUser telegramUser) {
LOGGER.info("Get all TelegramConversations by telegramUser: {}", telegramUser);
Session session = HibernateUtil.getSessionFactory().openSession();
Criteria criteria = session.createCriteria(TelegramConversation.class);
criteria.add(Restrictions.eq("telegramUser", telegramUser));
criteria.setCacheable(true);
List<TelegramConversation> telegramConversations = (List<TelegramConversation>) criteria.list();
session.close();
return telegramConversations;
}
@Override
public List<TelegramConversation> findByTelegramBot(TelegramBot telegramBot) {
LOGGER.info("Get all TelegramConversations by telegramBot: {}", telegramBot);
Session session = HibernateUtil.getSessionFactory().openSession();
Criteria criteria = session.createCriteria(TelegramConversation.class);
criteria.add(Restrictions.eq("telegramBot", telegramBot));
criteria.setCacheable(true);
List<TelegramConversation> telegramConversations = (List<TelegramConversation>) criteria.list();
session.close();
return telegramConversations;
}
@Override
public TelegramConversation findByTelegramUserAndTelegramBot(TelegramUser telegramUser, TelegramBot telegramBot) throws HibernateException {
LOGGER.info("Get TelegramConversation by telegramUser: {} and telegramBot: {}", telegramUser, telegramBot);
Session session = HibernateUtil.getSessionFactory().openSession();
Criteria criteria = session.createCriteria(TelegramConversation.class);
criteria.add(Restrictions.eq("telegramUser", telegramUser));
criteria.add(Restrictions.eq("telegramBot", telegramBot));
criteria.setCacheable(true);
TelegramConversation telegramConversation = (TelegramConversation) criteria.uniqueResult();
session.close();
return telegramConversation;
}
@Override
public List<TelegramConversation> findAll() {
LOGGER.info("Get all TelegramConversations");
Session session = HibernateUtil.getSessionFactory().openSession();
List<TelegramConversation> telegramConversations = (List<TelegramConversation>) session.createCriteria(TelegramConversation.class).setCacheable(true).list();
session.close();
return telegramConversations;
}
@Override
public void save(TelegramConversation telegramConversation) throws HibernateException {
LOGGER.info("Save TelegramConversation: {}", telegramConversation);
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
session.saveOrUpdate(telegramConversation);
transaction.commit();
session.flush();
session.close();
}
@Override
public void delete(TelegramConversation telegramConversation) throws HibernateException {
LOGGER.info("Delete TelegramConversation: {}", telegramConversation);
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
session.delete(telegramConversation);
transaction.commit();
session.flush();
session.close();
}
@Override
public void deleteById(Long id) throws HibernateException {
LOGGER.info("Delete TelegramConversation with id: {}", id);
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
session.delete(findById(id));
transaction.commit();
session.flush();
session.close();
}
}
|
package com.github.felixgail.gplaymusic;
import com.github.felixgail.gplaymusic.api.GPlayMusic;
import com.github.felixgail.gplaymusic.util.TokenProvider;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import svarzee.gps.gpsoauth.AuthToken;
import svarzee.gps.gpsoauth.Gpsoauth;
//AuthToken{token='owfYC_fys9FPUgWfqursNFVpia48lF-DgUIuV0TwQBGZIEmbz-oqvYlmBcQvuiS_2RdyVw.', expiry=-1}
public class test {
private static String USERNAME = "x814850963@gmail.com";
private static String PASSWORD = "pwls6666";
private static String ANDROID_ID = "3d422fb1d1dc4a40";
public static GPlayMusic api;
public static AuthToken authToken = null;
public static GPlayMusic connect(){
try {
authToken = TokenProvider.provideToken(USERNAME,
PASSWORD, ANDROID_ID);
}catch (Gpsoauth.TokenRequestFailed tokenRequestFailed) {
tokenRequestFailed.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
api = new GPlayMusic.Builder().setAuthToken(authToken).build();
return api;
//AuthToken authToken = new AuthToken("aas_et/AKppINZm2jnntEgHZelwqSiwmqA3HM0uJDijY6kUcoj-RRrv6-bXm4Qb_U7of86t3z_H4DOqdeR0fKAA4zzwkKr0VvqCuhZYJPzy14CrnMsGZEz0qM0V_4iQltBrLzWhtA==",1000L);
}
public static void main(String[]args) throws InterruptedException {
api = test.connect();
int i=0;
while(true)
{
Thread.sleep(1000);
System.out.println(api.toString());
}
}
}
|
package com.sinodynamic.hkgta.service.fms;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import com.sinodynamic.hkgta.dao.fms.FacilityUtilizationRateTimeDao;
import com.sinodynamic.hkgta.dto.fms.FacilityUtilizationRateDateDto;
import com.sinodynamic.hkgta.dto.fms.FacilityUtilizationRateListDto;
import com.sinodynamic.hkgta.dto.fms.FacilityUtilizationRateTimeDto;
import com.sinodynamic.hkgta.dto.fms.FacilityUtilizationRateTimeListDto;
import com.sinodynamic.hkgta.entity.fms.FacilityUtilizationRateTime;
import com.sinodynamic.hkgta.service.ServiceBase;
import com.sinodynamic.hkgta.util.constant.Constant.RateType;
@Service
public class FacilityUtilizationRateTimeServiceImpl extends ServiceBase<FacilityUtilizationRateTime> implements FacilityUtilizationRateTimeService
{
@Autowired
private FacilityUtilizationRateTimeDao facilityUtilizationRateTimeDao;
@Override
@Transactional(propagation = Propagation.REQUIRED)
public void saveFacilityUtilizationRateTime(FacilityUtilizationRateListDto rateDto,String userId)
{
for (FacilityUtilizationRateTimeListDto rateTime : rateDto.getDayRateList())
{
if (StringUtils.isEmpty(rateDto.getSubType()))
facilityUtilizationRateTimeDao.removeFacilityUtilizationRateTime(rateDto.getFacilityType(), rateTime.getWeekDay());
else
facilityUtilizationRateTimeDao.removeFacilityUtilizationRateTime(rateDto.getFacilityType(), rateDto.getSubType(), rateTime.getWeekDay());
saveRateTime(rateTime,rateDto.getFacilityType(),rateDto.getSubType(),userId);
}
}
private void saveRateTime(FacilityUtilizationRateTimeListDto rateTime,String facilityType,String subType,String userId)
{
for (FacilityUtilizationRateTimeDto rateTimeDto : rateTime.getRateList())
{
if (RateType.HI.name().equals(rateTimeDto.getRateType()))
{
FacilityUtilizationRateTime facilityUtilizationRateTime = new FacilityUtilizationRateTime();
facilityUtilizationRateTime.setCreateDate(new Timestamp(new Date().getTime()));
facilityUtilizationRateTime.setCreateBy(userId);
facilityUtilizationRateTime.setRateType(rateTimeDto.getRateType());
facilityUtilizationRateTime.setBeginTime(rateTimeDto.getBeginTime());
facilityUtilizationRateTime.setEndTime(rateTimeDto.getBeginTime() + 1);
facilityUtilizationRateTime.setFacilityType(facilityType);
facilityUtilizationRateTime.setFacilityDateId(null);
facilityUtilizationRateTime.setWeekDay(rateTime.getWeekDay());
if (!StringUtils.isEmpty(subType))
facilityUtilizationRateTime.setFacilitySubtypeId(subType);
facilityUtilizationRateTimeDao.save(facilityUtilizationRateTime);
}
}
}
@Override
@Transactional(propagation = Propagation.REQUIRED)
public List<FacilityUtilizationRateTime> getFacilityUtilizationRateTimeList(String facilityType, String weekDay, String subType)
{
return facilityUtilizationRateTimeDao.getFacilityUtilizationRateTimeList(facilityType, weekDay, subType);
}
@Override
@Transactional(propagation = Propagation.REQUIRED)
public List<FacilityUtilizationRateTime> getFacilityUtilizationRateTimeList(String facilityType)
{
return facilityUtilizationRateTimeDao.getFacilityUtilizationRateTimeList(facilityType);
}
@Override
@Transactional
public List<FacilityUtilizationRateTime> getFacilityUtilizationRateTimeListBySubType(String facilityType, String facilitySubtypeId)
{
return facilityUtilizationRateTimeDao.getFacilityUtilizationRateTimeListBySubType(facilityType, facilitySubtypeId);
}
}
|
package com.sai.one.algorithms.arrays.trees;
/**
* Created by white on 12/23/2016.
* http://www.programcreek.com/2012/12/check-if-two-trees-are-same-or-not/
*/
public class IsSameTree {
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p==null && q==null){
return true;
}else if(p==null || q==null){
return false;
}
if(p.value==q.value){
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}else{
return false;
}
}
}
|
package za.ac.cput;
import za.ac.cput.views.MainGUI;
public class RunApp {
public static void main(String[] args) {
new MainGUI().setGUI();
}
}
|
package com.heihei.model.msg.bean;
import org.json.JSONArray;
import org.json.JSONObject;
import com.heihei.logic.UserMgr;
import com.heihei.model.User;
import android.R.bool;
import android.util.Log;
public class ObServerMessage {
public static final String OB_SERVER_MESSAGE_TYPE_START_BELL_ANIM = "start_bell";
public static final String OB_SERVER_MESSAGE_TYPE_STOP_BELL_ANIM = "stop_bell";
public static final String OB_SERVER_MESSAGE_TYPE_MESSAGE_COUNT = "msg_count";
public static final String OB_SERVER_MESSAGE_TYPE_NOTIFY_DATA = "notify_data";
public static final String OB_SERVER_MESSAGE_TYPE_JOIN_ROOM = "join_room";
public static final String OB_SERVER_MESSAGE_TYPE_CHAT_USER_STATUS = "chat_user_status";
public static final String OB_SERVER_MESSAGE_TYPE_HIDE_MESSAGE_COUNT = "hide_msg_count";
public static final String OB_SERVER_MESSAGE_TYPE_PM_STOP_DUE = "pmfragment_stop_due";
public static final String OB_SERVER_MESSAGE_TYPE_NETWORK_OK = "network_status_ok";//网络已连接
public static final String OB_SERVER_MESSAGE_TYPE_NETWORK_OFF = "network_status_off";//网络已断开
public static final String OB_SERVER_MESSAGE_CANCEL_DUE_CHAT_NOTIFY = "cancel-due-chat";//网络已连接
public String type;
public int msgCount;
public chat chatInfo;
public qiniu qiniu;
public long chatId;
public ActionMessage chatUserStatusMessage;
public ObServerMessage() {
}
public ObServerMessage(String type) {
this.type = type;
}
public ObServerMessage(String type, int count) {
this.msgCount = count;
this.type = type;
}
public ObServerMessage(String type, ActionMessage actionMessage, long chatId) {
this.type = type;
this.chatId = chatId;
this.chatUserStatusMessage = actionMessage;
}
public ObServerMessage(String type, JSONObject object) {
try {
this.type = type;
User u = null;
JSONObject chatObj = object.optJSONObject("chat");
JSONObject qiniuObj = chatObj.optJSONObject("qiniu");
if (qiniuObj != null) {
qiniu = new qiniu(qiniuObj.optString("roomName"), qiniuObj.optString("roomToken"));
}
JSONArray array = chatObj.optJSONArray("users");
if (array != null && array.length() > 0) {
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.optJSONObject(i);
String id = o.optString("id");
if (!id.equals(UserMgr.getInstance().getUid())) {
u = new User(o);
}
}
}
chat c = new chat(chatObj.optLong("chatId"), chatObj.optLong("roomId"), chatObj.optInt("status"), u, chatObj.optString("initTopic"));
this.chatInfo = c;
this.chatId = c.chatId;
} catch (Exception e) {
e.printStackTrace();
}
}
public class qiniu {
public String roomName;
public String roomToken;
public qiniu(String roomName, String roomToken) {
this.roomName = roomName;
this.roomToken = roomToken;
}
}
public class chat {
public long chatId;
public long roomId;
public int chatStatus;
public User user;
public String initTopic;
public chat(long chatId, long roomId, int chatStatus, User user, String topic) {
this.chatId = chatId;
this.roomId = roomId;
this.chatStatus = chatStatus;
this.user = user;
this.initTopic = topic;
}
@Override
public String toString() {
return "chat [chatId=" + chatId + ", roomId=" + roomId + ", chatStatus=" + chatStatus + ", user=" + user.toString() + ", initTopic=" + initTopic + "]";
}
}
}
|
package caris.framework.handlers;
import caris.framework.basehandlers.GeneralHandler;
import caris.framework.basereactions.MultiReaction;
import caris.framework.basereactions.Reaction;
import caris.framework.library.Variables;
import caris.framework.reactions.ReactionEmbed;
import caris.framework.tokens.MessageBlock;
import sx.blah.discord.api.events.Event;
import sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent;
import sx.blah.discord.handle.obj.IChannel;
import sx.blah.discord.handle.obj.IGuild;
public class MessageTrackerHandler extends GeneralHandler {
public MessageTrackerHandler() {
super("MessageTracker", true);
}
@Override
protected boolean isTriggered(Event event) {
return event instanceof MessageReceivedEvent;
}
@Override
protected Reaction process(Event event) {
MessageReceivedEvent messageReceivedEvent = (MessageReceivedEvent) event;
MultiReaction track = new MultiReaction(-1);
for( IChannel outputChannel : Variables.trackerSets.keySet() ) {
for( IChannel inputChannel : Variables.trackerSets.get(outputChannel).channels ) {
if( messageReceivedEvent.getChannel().equals(inputChannel) ) {
track.reactions.add(new ReactionEmbed((new MessageBlock(messageReceivedEvent)).getEmbeds(), outputChannel));
}
}
for( IGuild inputGuild : Variables.trackerSets.get(outputChannel).guilds ) {
if( messageReceivedEvent.getGuild().equals(inputGuild) ) {
track.reactions.add(new ReactionEmbed((new MessageBlock(messageReceivedEvent).getEmbeds()), outputChannel));
}
}
}
return track;
}
@Override
public String getDescription() {
return "Tracks messages and sends them to tracking channels.";
}
}
|
package fabio.sicredi.evaluation.exception;
public class PollNotOpenException extends IllegalStateException {
}
|
import java.io.*;
public class TextFileReader{
private String passThis;
public String ReadFile(String fileName){
try{
File file = new File(fileName);
String s;
try{
BufferedReader in = new BufferedReader(new FileReader(file));
s=in.readLine();
passThis = s;
while(s!=null){
s = in.readLine();
passThis += s;
}
in.close();//Close buffered reader. This also closes the FileReader
}catch(FileNotFoundException e1){
passThis = "File not found: " + file;
}catch(IOException e2){
passThis = "IOException";
}//end inner try
}catch(ArrayIndexOutOfBoundsException e3){
passThis = "ArrayIndexOutOfBoundsException";
}//end catch(ArrayIndexOutOfBoundsException e3)
return passThis;
}//end ReadFile()
}//end TextFileReader
|
package mapx.util.filter;
public class LK implements SQLFilter {
LK() {}
public Entry filter(String realKey, Object value) {
return new Entry(realKey, " LIKE ", "%" + value + "%");
}
}
|
package com.example.cow.helpers;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.widget.Toast;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class NetworkManager {
static boolean isNetWorkAvailable;
public static boolean isAvailable(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
isNetWorkAvailable = activeNetworkInfo != null && activeNetworkInfo.isConnected();
if (isNetWorkAvailable) {
new Connected();
}
if (!isNetWorkAvailable) {
// UIHelper.showOkAlertDialog(context.getString(R.string.no_internet_title), context.getString(R.string.no_internet_message), context);
Toast.makeText(context, "No Connection", Toast.LENGTH_SHORT).show();
// UIHelper.showLongToast(context, context.getString(R.string.no_internet_message));
}
return isNetWorkAvailable;
}
private static class Connected extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... voids) {
try {
URL url = new URL("https://www.google.com/");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setConnectTimeout(1000);
httpURLConnection.connect();
if (httpURLConnection.getResponseCode() == 200) {
isNetWorkAvailable = true;
} else {
isNetWorkAvailable = false;
}
} catch (IOException e) {
e.printStackTrace();
isNetWorkAvailable = false;
}
return null;
}
}
}
|
package th.co.gosoft;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class OperandFactoryTest {
private static final int DUMMY_LEFT_OPERAND_VALUE = 7;
private static final int DUMMY_RIGHT_OPERAND_VALUE = 6;
@Test
public void firstPatternLeftOperandShouldBeInstanceOfStringOperand() {
OperandFactory operandFactory = new OperandFactory();
assertTrue(operandFactory.createLeftOperand(1, DUMMY_LEFT_OPERAND_VALUE) instanceof StringOperand);
}
@Test
public void firstPatternRightOperandShouldBeInstanceOfIntegerOperand() {
OperandFactory operandFactory = new OperandFactory();
assertTrue(operandFactory.createRightOperand(1, DUMMY_RIGHT_OPERAND_VALUE) instanceof IntegerOperand);
}
@Test
public void secondPatternLeftOperandShouldBeInstanceOfIntegerOperand() {
OperandFactory operandFactory = new OperandFactory();
assertTrue(operandFactory.createLeftOperand(2, DUMMY_LEFT_OPERAND_VALUE) instanceof IntegerOperand);
}
@Test
public void secondPatternRightOperandShouldBeInstanceOfStringOperand() {
OperandFactory operandFactory = new OperandFactory();
assertTrue(operandFactory.createRightOperand(2, DUMMY_RIGHT_OPERAND_VALUE) instanceof StringOperand);
}
}
|
package oath.server.controller;
import java.util.Collection;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import oath.server.model.Chicken;
import oath.server.repository.ChickenRepo;
@RestController
@RequestMapping("/chicken")
public class ChickenController {
ChickenRepo chickenRepo = new ChickenRepo();
@RequestMapping(value = "/list", method = RequestMethod.GET)
public ResponseEntity<Collection<Chicken>> getChickens() {
return new ResponseEntity<>(chickenRepo.findAll(), HttpStatus.OK);
}
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public ResponseEntity<Chicken> getChicken(@PathVariable int id) {
Chicken chicken = chickenRepo.findById(id);
if (chicken != null) {
return new ResponseEntity<>(chicken, HttpStatus.OK);
} else {
return new ResponseEntity<>(null, HttpStatus.NOT_FOUND);
}
}
}
|
package com.autenticacao;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Created by eduardo on 25/05/17.
*/
@SpringBootApplication
public class Configuracao {
public static void main(String[] args) {
SpringApplication.run(Configuracao.class, args);
}
}
|
import java.util.ArrayList;
/**
* Created by Daniel on 2/5/2017.
*/
public class LongestPrefix {
public String longestCommonPrefix(ArrayList<String> a) {
String prefix = a.get(0);
for (String s : a) {
while(!prefix.isEmpty() && !s.startsWith(prefix))
prefix = prefix.substring(0, prefix.length() - 1);
}
return prefix;
}
}
|
package part03.PartitionAndBacktrackingAlgorithm;
import java.util.TreeSet;
public class FullPermutation {
private static TreeSet<String> set = new TreeSet<>();
public static void main(String[] args) {
String s = "ABB";
char[] arr = s.toCharArray();
permutation(arr, 0, arr.length - 1);
for (String str : set) {
System.out.println(str);
}
}
private static void permutation(char[] arr, int from, int to) {
if (from == to) {
set.add(String.valueOf(arr));
}
for (int i = from; i <= to; i++) {
swap(arr, i, from);
permutation(arr, from + 1, to);
swap(arr, i, from);
}
}
private static void swap(char[] arr, int a, int b) {
char temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
}
|
package pro.likada.bean.backing;
import org.primefaces.model.TreeNode;
import pro.likada.model.*;
import pro.likada.service.ProductGroupService;
import javax.annotation.PostConstruct;
import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
/**
* Created by bumur on 13.02.2017.
*/
@Named
@ViewScoped
public class ProductBackingBean implements Serializable{
@Inject
private ProductGroupService productGroupService;
private TreeNode productRoot;
private TreeNode selectedProductNode;
private List<TreeNode> productGroupsNodeList;
private int treeNodeLevel;
private Product selectedProduct;
private ProductGroup AllProductGroup;
private List<Product> products;
private Product productChart;
private Product editProduct;
private List<ProductPrice> newProductPrices;
private ProductPrice selectedProductNewPrice;
private ProductPrice selectedProductPrice;
private ProductType popupDialogSelectedProductType;
private ShipmentBasis selectedProductDefaultShipmentBasis;
private ShipmentBasis selectedProductShipmentBasis;
private ShipmentBasis popupDialogSelectedShipmentBase;
private MeasureUnit measureUnit;
private Date newPriceData;
private Boolean newPriceNotify;
private Boolean productGroupSwitchOrder=false;
private int fieldNewPriceTabIndex = 1000;
private int fieldButtonPriceTabIndex = 0;
private int fieldNewBalanceTabIndex = 1000;
private int fieldButtonBalanceTabIndex = 0;
private String popupDialogSearchStringContractorByNameWork;
private String popupDialogSearchStringShipmentBaseByNameShort;
private List<ProductGroup> productGroups;
@PostConstruct
public void init(){
if(productGroups==null){
productGroups=productGroupService.getAllProductGroups();
}
this.newPriceNotify=false;
}
public List<ProductGroup> getProductGroups() {
return productGroups;
}
public void setProductGroups(List<ProductGroup> productGroups) {
this.productGroups = productGroups;
}
public TreeNode getProductRoot() {
return productRoot;
}
public void setProductRoot(TreeNode productRoot) {
this.productRoot = productRoot;
}
public Product getSelectedProduct() {
return selectedProduct;
}
public void setSelectedProduct(Product selectedProduct) {
this.selectedProduct = selectedProduct;
}
public List<ProductPrice> getNewProductPrices() {
return newProductPrices;
}
public void setNewProductPrices(List<ProductPrice> newProductPrices) {
this.newProductPrices = newProductPrices;
}
public ProductPrice getSelectedProductNewPrice() {
return selectedProductNewPrice;
}
public void setSelectedProductNewPrice(ProductPrice selectedProductNewPrice) {
this.selectedProductNewPrice = selectedProductNewPrice;
}
public ShipmentBasis getSelectedProductDefaultShipmentBasis() {
return selectedProductDefaultShipmentBasis;
}
public void setSelectedProductDefaultShipmentBasis(ShipmentBasis selectedProductDefaultShipmentBasis) {
this.selectedProductDefaultShipmentBasis = selectedProductDefaultShipmentBasis;
}
public ShipmentBasis getSelectedProductShipmentBasis() {
return selectedProductShipmentBasis;
}
public void setSelectedProductShipmentBasis(ShipmentBasis selectedProductShipmentBasis) {
this.selectedProductShipmentBasis = selectedProductShipmentBasis;
}
public int getFieldNewPriceTabIndex() {
return fieldNewPriceTabIndex;
}
public void setFieldNewPriceTabIndex(int fieldNewPriceTabIndex) {
this.fieldNewPriceTabIndex = fieldNewPriceTabIndex;
}
public int getFieldButtonPriceTabIndex() {
return fieldButtonPriceTabIndex;
}
public void setFieldButtonPriceTabIndex(int fieldButtonPriceTabIndex) {
this.fieldButtonPriceTabIndex = fieldButtonPriceTabIndex;
}
public int getFieldNewBalanceTabIndex() {
return fieldNewBalanceTabIndex;
}
public void setFieldNewBalanceTabIndex(int fieldNewBalanceTabIndex) {
this.fieldNewBalanceTabIndex = fieldNewBalanceTabIndex;
}
public int getFieldButtonBalanceTabIndex() {
return fieldButtonBalanceTabIndex;
}
public void setFieldButtonBalanceTabIndex(int fieldButtonBalanceTabIndex) {
this.fieldButtonBalanceTabIndex = fieldButtonBalanceTabIndex;
}
public MeasureUnit getMeasureUnit() {
return measureUnit;
}
public void setMeasureUnit(MeasureUnit measureUnit) {
this.measureUnit = measureUnit;
}
public ProductPrice getSelectedProductPrice() {
return selectedProductPrice;
}
public void setSelectedProductPrice(ProductPrice selectedProductPrice) {
this.selectedProductPrice = selectedProductPrice;
}
public Date getNewPriceData() {
return newPriceData;
}
public void setNewPriceData(Date newPriceData) {
this.newPriceData = newPriceData;
}
public Boolean getNewPriceNotify() {
return newPriceNotify;
}
public void setNewPriceNotify(Boolean newPriceNotify) {
this.newPriceNotify = newPriceNotify;
}
public ProductGroup getAllProductGroup() {
return AllProductGroup;
}
public void setAllProductGroup(ProductGroup allProductGroup) {
AllProductGroup = allProductGroup;
}
public int getTreeNodeLevel() {
return treeNodeLevel;
}
public void setTreeNodeLevel(int treeNodeLevel) {
this.treeNodeLevel = treeNodeLevel;
}
public TreeNode getSelectedProductNode() {
return selectedProductNode;
}
public void setSelectedProductNode(TreeNode selectedProductNode) {
this.selectedProductNode = selectedProductNode;
}
public List<Product> getProducts() {
return products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
public Boolean getProductGroupSwitchOrder() {
return productGroupSwitchOrder;
}
public void setProductGroupSwitchOrder(Boolean productGroupSwitchOrder) {
this.productGroupSwitchOrder = productGroupSwitchOrder;
}
public Product getProductChart() {
return productChart;
}
public void setProductChart(Product productChart) {
this.productChart = productChart;
}
public List<TreeNode> getProductGroupsNodeList() {
return productGroupsNodeList;
}
public void setProductGroupsNodeList(List<TreeNode> productGroupsNodeList) {
this.productGroupsNodeList = productGroupsNodeList;
}
public Product getEditProduct() {
return editProduct;
}
public void setEditProduct(Product editProduct) {
this.editProduct = editProduct;
}
public ProductType getPopupDialogSelectedProductType() {
return popupDialogSelectedProductType;
}
public void setPopupDialogSelectedProductType(ProductType popupDialogSelectedProductType) {
this.popupDialogSelectedProductType = popupDialogSelectedProductType;
}
public String getPopupDialogSearchStringContractorByNameWork() {
return popupDialogSearchStringContractorByNameWork;
}
public void setPopupDialogSearchStringContractorByNameWork(String popupDialogSearchStringContractorByNameWork) {
this.popupDialogSearchStringContractorByNameWork = popupDialogSearchStringContractorByNameWork;
}
public ShipmentBasis getPopupDialogSelectedShipmentBase() {
return popupDialogSelectedShipmentBase;
}
public void setPopupDialogSelectedShipmentBase(ShipmentBasis popupDialogSelectedShipmentBase) {
this.popupDialogSelectedShipmentBase = popupDialogSelectedShipmentBase;
}
public String getPopupDialogSearchStringShipmentBaseByNameShort() {
return popupDialogSearchStringShipmentBaseByNameShort;
}
public void setPopupDialogSearchStringShipmentBaseByNameShort(String popupDialogSearchStringShipmentBaseByNameShort) {
this.popupDialogSearchStringShipmentBaseByNameShort = popupDialogSearchStringShipmentBaseByNameShort;
}
}
|
package org.jphototagger.program.module.thumbnails;
import java.awt.Component;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.jphototagger.domain.thumbnails.ThumbnailCreator;
import org.jphototagger.lib.api.PositionProviderAscendingComparator;
import org.jphototagger.lib.swing.Dialog;
import org.jphototagger.lib.swing.util.ComponentUtil;
import org.openide.util.Lookup;
/**
* @author Elmar Baumann
*/
public class ThumbnailCreatorSettingsDialog extends Dialog {
private static final long serialVersionUID = 1L;
public ThumbnailCreatorSettingsDialog() {
super(ComponentUtil.findFrameWithIcon(), true);
initComponents();
postInitComponents();
}
private void postInitComponents() {
List<ThumbnailCreator> creators = new ArrayList<ThumbnailCreator>(Lookup.getDefault().lookupAll(ThumbnailCreator.class));
Collections.sort(creators, PositionProviderAscendingComparator.INSTANCE);
for (ThumbnailCreator creator : creators) {
Component settingsComponent = creator.getSettingsComponent();
if (settingsComponent != null) {
tabbedPane.add(creator.getDisplayName(), settingsComponent);
}
}
}
/**
* This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The
* content of this method is always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
private void initComponents() {//GEN-BEGIN:initComponents
tabbedPane = new javax.swing.JTabbedPane();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("org/jphototagger/program/module/thumbnails/Bundle"); // NOI18N
setTitle(bundle.getString("ThumbnailCreatorSettingsDialog.title")); // NOI18N
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(tabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 611, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(tabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 413, Short.MAX_VALUE)
.addContainerGap())
);
pack();
}//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTabbedPane tabbedPane;
// End of variables declaration//GEN-END:variables
}
|
package adapter;
public class TravelingByBoat implements AdvancedJourney {
@Override
public void travelOn(int pathLength) {
System.out.println("Journey to the boat " + pathLength + "Íž.");
}
}
|
<<<<<<< HEAD
package Mines_Weeper;
import java.lang.*;
import java.util.*;
public class ConsolApp extends MinesWeeper{
//Attributes
int x,y;
boolean isPointer;
//Methods
ConsolApp(int n,int m,int mines_num){
super(n,m,mines_num);
x=y=0;
isPointer =false;
}
public void GenerateBoard(){
board=new char[n][m];
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
board[i][j]='O';
} //done
public void ConvertInput(String s){
if(s.contains("-"))
isPointer =true;
else
isPointer =false;
for(int i=0;i<s.length();i++) {
if (Character.isLetter(s.charAt(i))) {
y = s.charAt(i) - 65;
} else if (Character.isDigit(s.charAt(i))) {
if (x == 0)
x = s.charAt(i) - 49;
else
x = (x * 10) + (s.charAt(i) - 49);
}
}
} //done
public void setMinesLocation(){
Random r=new Random();
for(int i=0;i<mines_num;i++)
{
mines_location[i][0]=r.nextInt(n);
mines_location[i][1]=r.nextInt(m);
}
/* //printing mines_location
for (int i = 0; i < mines_num; i++)
{
for(int j=0;j<2;j++)
System.out.print(mines_location[i][j]+ "\t");
System.out.println();
}*/
} //done
public void PrintBoard() {
//for Axis Coordinates
int[] row = new int[n];
char[] columen = new char[m];
for (int i = 0; i < n; i++)
row[i] = i + 1;
System.out.print(" ");
for(int j=0;j<m;j++)
{
columen[j]=(char)('A'+j);
System.out.print(" "+columen[j]);
}
System.out.println();
System.out.print(" ");
for(int i=0;i<n;i++)
System.out.print(" "+"_");
System.out.println();
for(int i=0;i<n;i++) {
if(i<9)
System.out.print(row[i]+ " | ");
else
System.out.print(row[i]+ "| ");
for (int j = 0; j < m; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}
} //done
// public int CheckAround(){}
public void EditBoard(){
//pointer situation
if(isPointer)
board[x][y]='P';
//TODO num situation
else
{
for(int i=0;i<mines_num;i++)
{
if(mines_location[i][0]==x && mines_location[i][1]==y) {
//TODO lose case & score check
}
}
}
}
public void LoseCase(){}
public void WinCase() {}
public void EditScore(){}
}
=======
package Mines_Weeper;
import java.lang.*;
import java.util.*;
public class ConsolApp extends MinesWeeper{
//Attributes
int x,y;
boolean isPointer;
//Methods
ConsolApp(int n,int m,int mines_num){
super(n,m,mines_num);
x=y=0;
isPointer =false;
}
public void GenerateBoard(){
board=new char[n][m];
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
board[i][j]='O';
} //done
public void ConvertInput(String s){
if(s.contains("-"))
isPointer =true;
else
isPointer =false;
for(int i=0;i<s.length();i++) {
if (Character.isLetter(s.charAt(i))) {
y = s.charAt(i) - 65;
} else if (Character.isDigit(s.charAt(i))) {
if (x == 0)
x = s.charAt(i) - 49;
else
x = (x * 10) + (s.charAt(i) - 49);
}
}
} //done
public void setMinesLocation(){
Random r=new Random();
for(int i=0;i<mines_num;i++)
{
mines_location[i][0]=r.nextInt(n);
mines_location[i][1]=r.nextInt(m);
}
/* //printing mines_location
for (int i = 0; i < mines_num; i++)
{
for(int j=0;j<2;j++)
System.out.print(mines_location[i][j]+ "\t");
System.out.println();
}*/
} //done
public void PrintBoard() {
//for Axis Coordinates
int[] row = new int[n];
char[] columen = new char[m];
for (int i = 0; i < n; i++)
row[i] = i + 1;
System.out.print(" ");
for(int j=0;j<m;j++)
{
columen[j]=(char)('A'+j);
System.out.print(" "+columen[j]);
}
System.out.println();
System.out.print(" ");
for(int i=0;i<n;i++)
System.out.print(" "+"_");
System.out.println();
for(int i=0;i<n;i++) {
if(i<9)
System.out.print(row[i]+ " | ");
else
System.out.print(row[i]+ "| ");
for (int j = 0; j < m; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}
} //done
// public int CheckAround(){}
public void EditBoard(){
//pointer situation
if(isPointer)
board[x][y]='P';
//TODO num situation
else
{
for(int i=0;i<mines_num;i++)
{
if(mines_location[i][0]==x && mines_location[i][1]==y) {
//TODO lose case & score check
}
}
}
}
public void LoseCase(){}
public void WinCase() {}
public void EditScore(){}
}
>>>>>>> origin/master
|
/*
* Copyright (c) 2016 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.db.generic.reg;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import pl.edu.icm.unity.db.DBAttributes;
import pl.edu.icm.unity.db.generic.DependencyChangeListener;
import pl.edu.icm.unity.exceptions.EngineException;
import pl.edu.icm.unity.exceptions.SchemaConsistencyException;
import pl.edu.icm.unity.types.basic.AttributeType;
import pl.edu.icm.unity.types.registration.AttributeRegistrationParam;
import pl.edu.icm.unity.types.registration.BaseForm;
public class AttributeTypeChangeListener implements DependencyChangeListener<AttributeType>
{
private FormsSupplier supplier;
public AttributeTypeChangeListener(FormsSupplier supplier)
{
this.supplier = supplier;
}
@Override
public String getDependencyObjectType()
{
return DBAttributes.ATTRIBUTE_TYPES_NOTIFICATION_ID;
}
@Override
public void preAdd(AttributeType newObject, SqlSession sql) throws EngineException { }
@Override
public void preUpdate(AttributeType oldObject,
AttributeType updatedObject, SqlSession sql) throws EngineException {}
@Override
public void preRemove(AttributeType removedObject, SqlSession sql)
throws EngineException
{
List<? extends BaseForm> forms = supplier.getForms(sql);
for (BaseForm form: forms)
{
for (AttributeRegistrationParam attr: form.getAttributeParams())
if (attr.getAttributeType().equals(removedObject.getName()))
throw new SchemaConsistencyException("The attribute type is used "
+ "by an attribute in a form " + form.getName());
}
}
}
|
package com.sunekaer.mods.toolkit.commands;
import com.mojang.brigadier.builder.ArgumentBuilder;
import com.sunekaer.mods.toolkit.utils.CommandUtils;
import net.minecraft.command.CommandSource;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.util.text.TranslationTextComponent;
import static net.minecraft.command.Commands.literal;
import static net.minecraft.realms.Realms.setClipboard;
public class CommandHotbar {
public static ArgumentBuilder<CommandSource, ?> register() {
return literal("hotbar")
.requires(cs -> cs.hasPermissionLevel(0)) //permission
.executes(ctx -> getHotbar(
ctx.getSource(),
ctx.getSource().asPlayer()
)
);
}
private static int getHotbar(CommandSource source, PlayerEntity player) {
String clipboard = "";
for (int slot = 0; slot < 9; slot++) {
ItemStack stack = player.inventory.mainInventory.get(slot);
if (stack.isEmpty()) {
continue;
}
String itemName = stack.getItem().getRegistryName().toString();
String withNBT = "";
CompoundNBT nbt = stack.serializeNBT();
if (nbt.contains("tag")) {
withNBT += nbt.get("tag");
}
clipboard += itemName + withNBT + CommandUtils.NEW_LINE;
}
source.sendFeedback(new TranslationTextComponent("commands.toolkit.clipboard.copied"), true);
setClipboard(clipboard);
return 1;
}
}
|
import java.util.Scanner;
public class PalindromeChecker {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String word;
do{
//New input
System.out.println("INPUT A WORD TO SEE IF IT IS A PALINDROME(quit to quit)");
word = sc.nextLine();
word = word.toLowerCase(); //normalize the word to all lower case letters
word = word.replaceAll("\\s", ""); //get rid of white space
word = word.replaceAll("\\.", "");
char[] chars = word.toCharArray();
if(word.equalsIgnoreCase("quit")){
continue;
}
if(isPalindrome(chars, chars.length - 1)){
System.out.println("This word is a palindrome");
}else{
System.out.println("This word is NOT a palindromes");
}
}while(!word.equalsIgnoreCase("quit"));
System.out.println("You have quit");
}
public static boolean isPalindrome(char[] a, int used){
for(int i = 0; i < used; i++){
if(a[i] != a[used - i]){
return false;
}
}
return true;
}
}
|
package ru.client;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class MyDataSource {
private static final String ORACLE_JDBC_DRIVER_ORACLE_DRIVER = "oracle.jdbc.driver.OracleDriver";
private static Connection connection;
public static Connection getConnetction() throws ClassNotFoundException, SQLException {
if (connection == null) {
Class.forName(ORACLE_JDBC_DRIVER_ORACLE_DRIVER);
connection = DriverManager.getConnection("jdbc:oracle:thin:@//10.4.0.119:1521/xe", "gladkikh13204", "gladkikh13204");
return connection;
} else {
return connection;
}
}
}
|
package network.nerve.dex.model.txData;
import io.nuls.base.basic.NulsByteBuffer;
import io.nuls.base.basic.NulsOutputStreamBuffer;
import io.nuls.base.data.BaseNulsData;
import io.nuls.core.exception.NulsException;
import io.nuls.core.parse.SerializeUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class TradingCancelTxData extends BaseNulsData {
private List<CancelDeal> cancelDealList;
@Override
public int size() {
int size = SerializeUtils.sizeOfVarInt(cancelDealList.size());
for (CancelDeal cancelDeal : cancelDealList) {
size += SerializeUtils.sizeOfNulsData(cancelDeal);
}
return size;
}
@Override
protected void serializeToStream(NulsOutputStreamBuffer stream) throws IOException {
stream.writeVarInt(cancelDealList.size());
for (int i = 0; i < cancelDealList.size(); i++) {
stream.writeNulsData(cancelDealList.get(i));
}
}
@Override
public void parse(NulsByteBuffer byteBuffer) throws NulsException {
int size = (int) byteBuffer.readVarInt();
List<CancelDeal> cancelDealList = new ArrayList<>();
for (int i = 0; i < size; i++) {
cancelDealList.add(byteBuffer.readNulsData(new CancelDeal()));
}
this.cancelDealList = cancelDealList;
}
public List<CancelDeal> getCancelDealList() {
return cancelDealList;
}
public void setCancelDealList(List<CancelDeal> cancelDealList) {
this.cancelDealList = cancelDealList;
}
}
|
package com.lynn.test;
import com.lynn.bean.UserBean;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import org.junit.Test;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Administrator
*/
public class ObjectTest {
@Test
public void init(){}
// @Test
public void equals(){
boolean a = Objects.equals("", "");
boolean b = Objects.equals(null, null);
boolean c = "".equals("");
System.out.println("【1】" + a + "_" + b + "_" + c);
String temp = null;
// boolean d = temp.equals(null);
// System.out.println("【2】" + d);
}
// @Test
public void equals1(){
boolean a = (null == null);
String temp1 = null;
String temp2 = null;
boolean b = (temp1 == temp2);
boolean c = temp1 instanceof String;
boolean d = null instanceof String;
System.out.println("【】" + a + "_" + b + "_" + c + "_" + d);
}
// @Test
public void equalsInteger(){
Integer a = 120;
Integer b = 120;
boolean isResult = (a == b);
boolean isResult1 = (1 == 1);
boolean isResult2 = ((1 + "").equals(1));//false
boolean isResult3 = ((1 + "").equals(1 + ""));
boolean isResult4 = (new Integer(1).equals(1));
System.out.println("【】" + isResult + "_" + isResult1 + "_" + isResult2 + "_" + isResult3 + "_" + isResult4);
}
// @Test
public void testObject(){
UserBean userBean = new UserBean();
userBean.setId(1);
set(userBean);
System.out.println("【】" + userBean.getPassword());
}
public void set(UserBean userBean){
userBean.setPassword("22");
}
// @Test
public void object(){
Map map;
map = null;
Map map1 = new HashMap();
map = map1;
}
}
|
package com.asm.view.controller.serviceOrders;
import com.asm.entities.order.Status;
import com.asm.interactors.OrderInteractor;
import com.asm.view.controller.properties.OrderProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.control.*;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.VBox;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
public class ServiceOrdersController implements Initializable{
private ObservableList<OrderProperty> ordersData;
private String currentUserID;
private OrderInteractor interactor;
private String baseURL = "http://localhost:8080";
private ScrollPane mainScrollPane;
// Anchor pane for forms
@FXML
private AnchorPane mainAnchorPane;
// Clients table items
@FXML private TableView<OrderProperty> ordersTable;
@FXML private TableColumn<OrderProperty, String> columnID;
@FXML private TableColumn<OrderProperty, String> columnClientName;
@FXML private TableColumn<OrderProperty, String> columnAutomobileName;
@FXML private TableColumn<OrderProperty, String> columnService;
@FXML private TableColumn<OrderProperty, String> columnEmployee;
@FXML private TableColumn<OrderProperty, String> columnRequiredTime;
@FXML private TableColumn<OrderProperty, String> columnPrice;
@FXML private TableColumn<OrderProperty, String> columnStatus;
// Client Details labels
@FXML private SplitPane clientDetailSplitPane;
@FXML private AnchorPane clientDetailsPane;
@FXML private VBox clientDetailsVBox;
@FXML private VBox carDetailsVBox;
@FXML private Label serviceTypeDetail;
@FXML private Label serviceDescriptionDetail;
@FXML private Label serviceClientDetail;
@FXML private Label serviceCarDetail;
@FXML private Label serviceEmployeeDetail;
@FXML private Label serviceStartDateDetail;
@FXML private Label serviceFinishDateDetail;
@FXML private Label servicePriceDetail;
private OrderProperty selectedOrder;
public ServiceOrdersController() {
this.interactor = new OrderInteractor();
try {
this.ordersData = FXCollections.observableArrayList(interactor.readAsOrderProperty());
} catch (IOException e) {
e.printStackTrace();
}
}
public ObservableList<OrderProperty> getOrdersData() {
return ordersData;
}
private void setUpTable() {
ordersTable.setItems(getOrdersData());
}
@Override
public void initialize(URL location, ResourceBundle resources) {
columnID.setCellValueFactory(cellData-> cellData.getValue().idProperty());
columnClientName.setCellValueFactory(cellData -> cellData.getValue().clientProperty());
columnAutomobileName.setCellValueFactory(cellData -> cellData.getValue().automobileProperty());
columnEmployee.setCellValueFactory(cellData -> cellData.getValue().mechanicProperty());
columnService.setCellValueFactory(cellData -> cellData.getValue().serviceProperty());
columnRequiredTime.setCellValueFactory(cellData-> cellData.getValue().hourlyRequiredTimeProperty());
columnPrice.setCellValueFactory(cellData-> cellData.getValue().priceProperty());
columnStatus.setCellValueFactory(cellData-> cellData.getValue().statusProperty());
showEmployeeDetails(null);
// columnNSS.setCellValueFactory(cellData-> cellData.getValue().nssProperty());
ordersTable.getSelectionModel().selectedItemProperty().addListener(
(observable, oldValue, newValue) -> showEmployeeDetails(newValue)
);
setUpTable();
}
private void showClientDetailsPane(boolean visible) {
clientDetailsPane.setVisible(visible);
clientDetailsPane.setManaged(visible);
}
public void showEmployeeDetails(OrderProperty OrderProperty) {
System.out.println("Here on earth");
if (OrderProperty != null) {
this.selectedOrder = OrderProperty;
showClientDetailsPane(true);
carDetailsVBox.getChildren().clear();
clientDetailSplitPane.setDividerPositions(new double[]{0.5});
serviceTypeDetail.setText( OrderProperty.getService());
serviceDescriptionDetail.setText(OrderProperty.getDescription());
serviceClientDetail.setText(OrderProperty.getClient());
serviceEmployeeDetail.setText(OrderProperty.getMechanic());
serviceCarDetail.setText(OrderProperty.getAutomobile());
serviceStartDateDetail.setText(OrderProperty.getStartDate());
servicePriceDetail.setText("$"+OrderProperty.getPrice());
} else {
showClientDetailsPane(false);
clientDetailSplitPane.setDividerPositions(new double[]{1});
serviceTypeDetail.setText("");
serviceDescriptionDetail.setText("");
serviceClientDetail.setText("");
serviceEmployeeDetail.setText("");
serviceCarDetail.setText("");
servicePriceDetail.setText("");
currentUserID = "";
}
}
public void closeClientDetails(MouseEvent mouseEvent) {
showClientDetailsPane(false);
clientDetailSplitPane.setDividerPositions(new double[]{1});
serviceTypeDetail.setText("");
serviceDescriptionDetail.setText("");
serviceClientDetail.setText("");
currentUserID = "";
}
public void newOrderClicked(MouseEvent mouseEvent) throws IOException {
FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/services_views/newServiceOrder.fxml"));
Parent root = loader.load();
NewServiceOrderController newServiceOrderController= loader.getController();
newServiceOrderController.init(mainScrollPane);
this.mainScrollPane.setContent(root);
mainScrollPane.setFitToWidth(true);
System.out.println("New Order");
}
public int initToGetCount() {
return getOrdersData().size();
}
public double getTotalIncome() {
double total = 0;
for (int i = 0; i < ordersData.size(); i++) {
OrderProperty order = ordersData.get(i);
String orderStatus = order.getStatus();
if (orderStatus.equals("FINISHED")) {
total += new Double(order.getPrice());
}
}
return total;
}
public void init(ScrollPane mainScrollPane) {
this.mainScrollPane = mainScrollPane;
}
public void initWithNewOrder(ScrollPane mainScrollPane, OrderProperty createdOrder) {
this.mainScrollPane = mainScrollPane;
this.ordersData.add(createdOrder);
}
public void finishOrder(MouseEvent mouseEvent) {
if (this.selectedOrder != null) {
selectedOrder.setStatus(Status.FINISHED.toString());
}
}
public void cancelOrder(MouseEvent mouseEvent) {
}
}
|
package com.programapprentice.app;
import com.programapprentice.util.Util;
import org.junit.Test;
import java.util.List;
/**
* User: program-apprentice
* Date: 9/6/15
* Time: 11:05 PM
*/
public class RestoreIPAddresses_Test {
RestoreIPAddresses_93 obj = new RestoreIPAddresses_93();
@Test
public void test1() {
String s = "25525511135";
List<String> output = obj.restoreIpAddresses(s);
Util.printListString(output);
}
@Test
public void test2() {
String s = "010010";
List<String> output = obj.restoreIpAddresses(s);
Util.printListString(output);
}
}
|
package in.anandm.oj.repository.impl;
import in.anandm.oj.model.EmailId;
import in.anandm.oj.model.User;
import in.anandm.oj.repository.UserRepository;
import com.googlecode.genericdao.search.Filter;
import com.googlecode.genericdao.search.Search;
public class JPAUserRepository extends JPABaseRepository<User, String> implements
UserRepository {
@Override
public User saveUser(User user) {
return super.save(user);
}
@Override
public User getUserByEmailId(EmailId emailId) {
Search search = new Search();
search.addFilter(Filter.equal("emailId", emailId));
search.setMaxResults(1);
return super.searchUnique(search);
}
}
|
package com.example.naleirbag.login;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import java.util.ArrayList;
public class LoginWithSharedPreferences extends AppCompatActivity implements View.OnClickListener {
private static EditText usernameEt;
private EditText passwordEt;
private Button btnLogin;
private CheckBox checkBox;
private SharedPreferences loginPref;
private SharedPreferences.Editor loginEditor;
private static String usr = "", pass = "";
private final static String USERNAME_KEY = "username";
private final static String PASSWORD_KEY = "password";
private final static String SAVED_KEY = "saved";
private Intent logIntent;
private boolean isSaved = false;
Button loginBtn;
boolean firstTime = false;
ArrayList<User> usersData = new ArrayList<>();
final String[] users = {"ana", "ion", "dan"};
final String[] passwords = {"123", "456", "789"};
Context ctx;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
isSaved = loginPref.getBoolean(SAVED_KEY, false);
if (isSaved) {
fillData();
} else {
clearFiels();
}
usr = loginPref.getString(USERNAME_KEY, "");
if (isSaved) {
fillData();
}
}
private void init() {
ctx = this.getApplicationContext();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
usernameEt = (EditText) findViewById(R.id.login_username_text);
passwordEt = (EditText) findViewById(R.id.login_password_text);
checkBox = (CheckBox) findViewById(R.id.checkBoxRemember);
loginBtn = (Button) findViewById(R.id.login_btn);
loginPref = getSharedPreferences("loginPrefs", MODE_PRIVATE);
loginEditor = loginPref.edit();
loginBtn.setOnClickListener(this);
usersData.add(new User("Ana Popescu", "begginer", "Romania"));
usersData.add(new User("Ion Popescu", "begginer", "Romania"));
usersData.add(new User("Dan Popescu", "advanced", "Romania"));
}
private void fillData() {
usr = loginPref.getString(USERNAME_KEY, "");
pass = loginPref.getString(PASSWORD_KEY, "");
passwordEt.setText(pass);
usernameEt.setText(usr);
checkBox.setChecked(isSaved);
}
private boolean checkSaveOption(String usr, String pass) {
if (checkBox.isChecked()) {
isSaved = true;
saveData(usr, pass);
} else {
loginEditor.clear();
loginEditor.commit();
isSaved = false;
}
return isSaved;
}
private void saveData(String usr, String pass) {
Toast.makeText(
ctx, "Username is saved",
Toast.LENGTH_LONG).show();
loginEditor.putString(USERNAME_KEY, usr);
loginEditor.putString(PASSWORD_KEY, pass);
loginEditor.putBoolean(SAVED_KEY, isSaved);
loginEditor.commit();
}
private void clearFiels() {
Toast.makeText(
ctx, "Username is not saved",
Toast.LENGTH_LONG).show();
passwordEt.setText("");
usernameEt.setText("");
}
private boolean checkUserValability(String usr, String pass) {
if (usr.trim().length() == 0) {
Toast.makeText(
ctx, getResources().getText(
R.string.insert_username),
Toast.LENGTH_LONG).show();
usernameEt.requestFocus();
return false;
} else {
if (pass.trim().length() == 0) {
Toast.makeText(
ctx, getResources().getText(
R.string.insert_password),
Toast.LENGTH_LONG).show();
passwordEt.requestFocus();
return false;
} else {
for (int i = 0; i < users.length; i++)
if ((usr.matches(users[i]) & pass.matches(passwords[i]))) {
logIntent = new Intent(LoginWithSharedPreferences.this, ProfileActivity.class);
logIntent.putExtra("username", usersData.get(i).name);
logIntent.putExtra("country", usersData.get(i).country);
logIntent.putExtra("usertype", usersData.get(i).usertype);
Intent intent = new Intent(ctx, ProfileActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
return true;
}else {
Toast.makeText(
ctx, "Invalid username or password",
Toast.LENGTH_LONG).show();
return false;
}
}
}
return true;
}
@Override
public void onClick(View view) {
int id=view.getId();
switch (id){
case(R.id.login_btn):
usr = usernameEt.getText().toString();
pass = passwordEt.getText().toString();
checkSaveOption(usr, pass);
if(checkUserValability(usr,pass)){
Intent inte =new Intent(getBaseContext(),LoginService.class);
startService(inte);
startActivity(logIntent);
finish();
}
break;
}
}
}
|
/*
* Copyright (c) 2008-2019 Haulmont.
*
* 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.haulmont.reports.entity.wizard;
import com.haulmont.chile.core.annotations.Composition;
import com.haulmont.chile.core.annotations.MetaClass;
import com.haulmont.chile.core.annotations.MetaProperty;
import com.haulmont.cuba.core.entity.BaseUuidEntity;
import com.haulmont.cuba.core.entity.annotation.SystemLevel;
import com.haulmont.reports.entity.*;
import com.haulmont.reports.entity.charts.ChartType;
import javax.persistence.OneToMany;
import javax.persistence.Transient;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
@MetaClass(name = "report$WizardReportData")
@SystemLevel
public class ReportData extends BaseUuidEntity {
private static final long serialVersionUID = -1649648403032678085L;
public static class Parameter implements Serializable {
public final String name;
public final Class javaClass;
public final ParameterType parameterType;
public final String defaultValue;
public final PredefinedTransformation predefinedTransformation;
public final Boolean hidden;
public Parameter(String name, Class javaClass, ParameterType parameterType, String defaultValue, Boolean hidden) {
this(name, javaClass, parameterType, defaultValue, null, hidden);
}
public Parameter(String name, Class javaClass, ParameterType parameterType, String defaultValue, PredefinedTransformation transformation,
Boolean hidden) {
this.name = name;
this.javaClass = javaClass;
this.parameterType = parameterType;
this.defaultValue = defaultValue;
this.predefinedTransformation = transformation;
this.hidden = hidden;
}
}
public enum ReportType {
SINGLE_ENTITY(false, true),
LIST_OF_ENTITIES(true, true),
LIST_OF_ENTITIES_WITH_QUERY(true, false);
private boolean list;
private boolean entity;
ReportType(boolean list, boolean entity) {
this.list = list;
this.entity = entity;
}
public boolean isList() {
return list;
}
public boolean isEntity() {
return entity;
}
}
@MetaProperty
@Transient
protected String name;
@MetaProperty
@Transient
protected EntityTreeNode entityTreeRootNode;
@MetaProperty
@Transient
protected Report generatedReport;
@MetaProperty
@Transient
protected ReportGroup group;
@MetaProperty
@Transient
protected ReportType reportType;
@MetaProperty
@Transient
protected String templateFileName;
@MetaProperty
@Transient
protected String outputNamePattern;
@MetaProperty
@Transient
protected ReportOutputType outputFileType;
@MetaProperty
@Composition
@Transient
@OneToMany(targetEntity = RegionProperty.class)
protected List<ReportRegion> reportRegions = new ArrayList<>();
@Transient
protected String query;
@Transient
protected List<Parameter> queryParameters;
@Transient
protected String dataStore;
@Transient
protected TemplateFileType templateFileType;
@Transient
protected byte[] templateContent;
@Transient
protected ChartType chartType = ChartType.SERIAL;
public Report getGeneratedReport() {
return generatedReport;
}
public void setGeneratedReport(Report generatedReport) {
this.generatedReport = generatedReport;
}
public ReportGroup getGroup() {
return group;
}
public void setGroup(ReportGroup group) {
this.group = group;
}
public ReportType getReportType() {
return reportType;
}
public void setReportType(ReportType reportType) {
this.reportType = reportType;
}
public String getTemplateFileName() {
return templateFileName;
}
public void setTemplateFileName(String templateFileName) {
this.templateFileName = templateFileName;
}
public ReportOutputType getOutputFileType() {
return outputFileType;
}
public void setOutputFileType(ReportOutputType outputFileType) {
this.outputFileType = outputFileType;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public EntityTreeNode getEntityTreeRootNode() {
return entityTreeRootNode;
}
public void setEntityTreeRootNode(EntityTreeNode entityTreeRootNode) {
this.entityTreeRootNode = entityTreeRootNode;
}
public List<ReportRegion> getReportRegions() {
return reportRegions;
}
public void setReportRegions(List<ReportRegion> reportRegions) {
this.reportRegions = reportRegions;
}
@Transient
public ReportData addRegion(ReportRegion region) {
reportRegions.add(region);
return this;
}
@Transient
public ReportData addRegion(int index, ReportRegion region) {
reportRegions.add(index, region);
return this;
}
public String getOutputNamePattern() {
return outputNamePattern;
}
public void setOutputNamePattern(String outputNamePattern) {
this.outputNamePattern = outputNamePattern;
}
@Transient
public void removeRegion(int index) {
reportRegions.remove(index);
}
@Transient
public void clearRegions() {
reportRegions.clear();
}
public String getQuery() {
return query;
}
public void setQuery(String query) {
this.query = query;
}
public String getDataStore() {
return dataStore;
}
public void setDataStore(String dataStore) {
this.dataStore = dataStore;
}
public List<Parameter> getQueryParameters() {
return queryParameters;
}
public void setQueryParameters(List<Parameter> queryParameters) {
this.queryParameters = queryParameters;
}
public TemplateFileType getTemplateFileType() {
return templateFileType;
}
public void setTemplateFileType(TemplateFileType templateFileType) {
this.templateFileType = templateFileType;
}
public byte[] getTemplateContent() {
return templateContent;
}
public void setTemplateContent(byte[] templateContent) {
this.templateContent = templateContent;
}
public ChartType getChartType() {
return chartType;
}
public void setChartType(ChartType chartType) {
this.chartType = chartType;
}
}
|
/*
* Copyright 2002-2018 the original author or authors.
*
* 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
*
* https://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 org.springframework.beans.factory.support;
import org.springframework.beans.factory.config.BeanPostProcessor;
/**
* Post-processor callback interface for <i>merged</i> bean definitions at runtime.
* {@link BeanPostProcessor} implementations may implement this sub-interface in order
* to post-process the merged bean definition (a processed copy of the original bean
* definition) that the Spring {@code BeanFactory} uses to create a bean instance.
*
* <p>The {@link #postProcessMergedBeanDefinition} method may for example introspect
* the bean definition in order to prepare some cached metadata before post-processing
* actual instances of a bean. It is also allowed to modify the bean definition but
* <i>only</i> for definition properties which are actually intended for concurrent
* modification. Essentially, this only applies to operations defined on the
* {@link RootBeanDefinition} itself but not to the properties of its base classes.
*
* @author Juergen Hoeller
* @since 2.5
* @see org.springframework.beans.factory.config.ConfigurableBeanFactory#getMergedBeanDefinition
*/
public interface MergedBeanDefinitionPostProcessor extends BeanPostProcessor {
/**
* Post-process the given merged bean definition for the specified bean.
* @param beanDefinition the merged bean definition for the bean
* @param beanType the actual type of the managed bean instance
* @param beanName the name of the bean
* @see AbstractAutowireCapableBeanFactory#applyMergedBeanDefinitionPostProcessors
*/
void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName);
/**
* A notification that the bean definition for the specified name has been reset,
* and that this post-processor should clear any metadata for the affected bean.
* <p>The default implementation is empty.
* @param beanName the name of the bean
* @since 5.1
* @see DefaultListableBeanFactory#resetBeanDefinition
*/
default void resetBeanDefinition(String beanName) {
}
}
|
package com.codingchili.instance.model.items;
import com.codingchili.instance.context.GameContext;
import com.codingchili.instance.model.dialog.InteractionOutOfRangeException;
import com.codingchili.instance.model.entity.*;
import com.codingchili.instance.model.entity.Vector;
import com.codingchili.instance.model.events.NotificationEvent;
import com.codingchili.instance.model.npc.LootableEntity;
import com.codingchili.instance.model.spells.SpellTarget;
import com.codingchili.instance.scripting.*;
import io.vertx.core.Future;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
import com.codingchili.core.context.CoreRuntimeException;
/**
* @author Robin Duda
* <p>
* Implements logic for modifying creature inventory.
*/
public class InventoryEngine {
private static final String TARGET = "target";
private static final int LOOT_RANGE = 164;
private static final int ITEM_USE_GCD = 1000;
private static final String ITEM = "item";
private static final String SPELLS = "spells";
private static final String SKILLS = "skills";
private static final String SUCCESS = "success";
private static final String FAIL = "fail";
private ItemDB items;
private GameContext game;
/**
* @param game the game context to run on.
*/
public InventoryEngine(GameContext game) {
this.game = game;
this.items = new ItemDB(game.instance());
}
/**
* Changes the amount of currency the given creature holds.
*
* @param target the target to modify the currency value of.
* @param amount the amount to modify with, can be negative.
* @return true if there was enough currency left to withdraw.
*/
public boolean currency(Creature target, int amount) {
Inventory inventory = target.getInventory();
int current = inventory.getCurrency();
if (current + amount < 0) {
return false;
} else {
inventory.setCurrency(current + amount);
target.handle(new InventoryUpdateEvent(target));
return true;
}
}
/**
* Adds the given item to the targets inventory if the item exists
* in the database.
*
* @param target the creature of which inventory to add the item to.
* @param itemId the id of the item to add.
* @param amount the quantity of the item to add.
* @return true if the item was found and added to the targets inventory.
*/
public boolean item(Creature target, String itemId, int amount) {
Optional<Item> item = this.items.getById(itemId);
item.ifPresent(found -> {
found.setQuantity(amount);
target.getInventory().add(found);
target.handle(new InventoryUpdateEvent(target));
});
return item.isPresent();
}
/**
* Adds the given item to the players inventory.
*
* @param target the target to add the item to.
* @param item the item to add.
*/
public void item(Creature target, Item item) {
target.getInventory().add(item);
target.handle(new InventoryUpdateEvent(target));
}
/**
* Removes an equipped item and places it into the creatures bag.
*
* @param source the creature to unequip an item..
* @param slot the slot of the item to unequip.
*/
public void unequip(Creature source, Slot slot) {
Inventory inventory = source.getInventory();
Item item = inventory.getEquipped().remove(slot);
if (item != null) {
inventory.getItems().add(item);
}
update(source);
game.publish(new StatsUpdateEvent(source));
game.publish(new UnequipItemEvent(source, slot));
}
/**
* equips the given item on the specified creature.
*
* @param source the creature to equip an item
* @param itemId the id of the item in the creatures inventory.
*/
public void equip(Creature source, String itemId) {
Inventory inventory = source.getInventory();
Item item = inventory.getById(itemId);
Slot slot = item.getSlot();
if (!item.getSlot().equals(Slot.none)) {
int position = inventory.getItems().indexOf(item);
inventory.getItems().remove(item);
if (inventory.getEquipped().containsKey(item.getSlot())) {
// if slot is weapon and offhand is free, equip to offhand.
if (Slot.weapon == item.getSlot() && !inventory.getEquipped().containsKey(Slot.offhand)) {
inventory.getEquipped().put(Slot.offhand, item);
slot = Slot.offhand;
} else {
inventory.getItems().add(position,
inventory.getEquipped().replace(item.getSlot(), item));
}
} else {
inventory.getEquipped().put(item.slot, item);
}
update(source);
game.publish(new StatsUpdateEvent(source));
game.publish(new EquipItemEvent(source, item, slot));
} else {
throw new CoreRuntimeException("Not able to equip item: " + item.getName());
}
}
/**
* Uses an item in the inventory, reducing its quantity by 1 and applying effects.
*
* @param source the creature that uses the item.
* @param target the target of the item use.
* @param itemId the id of the item in the sources inventory.
*/
public void use(Creature source, SpellTarget target, String itemId) {
Inventory inventory = source.getInventory();
Item item = inventory.getById(itemId);
if (source.getSpells().isOnGCD()) {
// notify client?
} else {
// trigger gcd first to prevent race conditions/multi-use.
source.getSpells().triggerGcd(ITEM_USE_GCD);
if (item.getOnUse() != null) {
Scripted scripted = new ScriptReference(item.onUse);
var failed = new AtomicBoolean(false);
var called = new AtomicBoolean(false);
// show notification banner on error.
var fail = (Consumer<String>) (message) -> {
source.handle(new NotificationEvent(message));
failed.set(true);
called.set(true);
};
// consume the item on success.
var success = (Runnable) () -> {
item.setQuantity(item.getQuantity() - 1);
if (item.getQuantity() < 1) {
inventory.getItems().remove(item);
}
called.set(true);
};
Bindings bindings = new Bindings();
bindings.setContext(game)
.set(ITEM, item)
.set(SUCCESS, success)
.set(FAIL, fail)
.set(SPELLS, game.spells())
.set(SKILLS, game.skills())
.setSource(source)
.set(TARGET, target);
scripted.apply(bindings);
if (!called.get()) {
// assume success if fail is not called - prefer to consume item without effects.
success.run();
}
update(source);
}
}
}
/**
* Drops an item out of the specified creatures inventory.
*
* @param source the specified creature to drop an item from.
* @param itemId the id of the item to drop.
*/
public void drop(Creature source, String itemId) {
Inventory inventory = source.getInventory();
Item item = inventory.getById(itemId);
inventory.getItems().remove(item);
update(source);
game.add(LootableEntity.dropped(source.getVector(), item));
}
/**
* Drops an item in the world at the given location.
*
* @param vector the target point to drop the item at.
* @param item the item to drop.
*/
public void drop(Vector vector, Item item) {
game.add(LootableEntity.dropped(vector, item));
}
/**
* Spawns loot from a creature upon death.
*
* @param source the creature to spawn loot from.
*/
public void spawnLoot(Creature source) {
Inventory inventory = source.getInventory();
ArrayList<Item> loot = new ArrayList<>();
loot.addAll(inventory.getItems());
loot.addAll(inventory.getEquipped().values());
// drop everything equipped and in inventory.
inventory.getEquipped().clear();
inventory.getItems().clear();
game.instance().save(source);
game.add(LootableEntity.fromCorpse(source, loot));
}
/**
* Takes an item out of the loot container as specified by its item id
* and moves it into the inventory of the looter. If the source entity
* is not already subscribed the action is ignored.
*
* @param source the creature performing the looting.
* @param targetId the id of the container that holds the loot.
* @param itemId the id of the item in the container to take.
*/
public void takeLoot(Creature source, String targetId, String itemId) {
LootableEntity entity = game.getById(targetId);
if (entity.subscribed(source)) {
Item item = entity.takeItem(itemId);
source.getInventory().add(item);
update(source);
}
}
/**
* Takes all items out of the loot container and moves it into the
* inventory of the looter. No subscription is required.
*
* @param source the creature performing the looting.
* @param targetId the if of the container that holds the loot.
*/
public void takeAll(Creature source, String targetId) {
LootableEntity entity = game.getById(targetId);
source.getInventory().addAll(entity.takeAll());
update(source);
}
/**
* Lists available loot in the given container.
*
* @param source the creature that is interested in the loot contents.
* @param targetId the target loot container.
* @return future
*/
public Future<Void> listLoot(Creature source, String targetId) {
LootableEntity entity = game.getById(targetId);
Future<Void> future = Future.future();
if (targetInRange(source, entity)) {
if (entity.getItems().isEmpty()) {
future.fail(new LootableEmptyException());
} else {
entity.subscribe(source);
future.complete();
game.movement().stop(source);
}
} else {
future.fail(new InteractionOutOfRangeException());
}
return future;
}
/**
* Called after subscribing to a loot container to not receive any more update events.
*
* @param target the unsubscribing entity.
* @param subscribed the lootable entity.
*/
public void unsubscribe(String target, String subscribed) {
LootableEntity entity = game.getById(subscribed);
entity.unsubscribe(target);
}
private boolean targetInRange(Entity source, Entity target) {
int distance = source.getVector().distance(target.getVector());
return distance < LOOT_RANGE;
}
private void update(Creature source) {
source.getInventory().update();
source.handle(new InventoryUpdateEvent(source));
}
public ItemDB items() {
return items;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.