blob_id stringlengths 40 40 | language stringclasses 1
value | repo_name stringlengths 5 132 | path stringlengths 2 382 | src_encoding stringclasses 34
values | length_bytes int64 9 3.8M | score float64 1.5 4.94 | int_score int64 2 5 | detected_licenses listlengths 0 142 | license_type stringclasses 2
values | text stringlengths 9 3.8M | download_success bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
298d3cdd5af5f59d29456e4807d6a5d2f39fb9e8 | Java | mattCPSC304/mattCPSC304 | /src/matt/ui/UIWindow.java | UTF-8 | 2,780 | 2.53125 | 3 | [] | no_license | package matt.ui;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
//main tutorial used: previous, plus:
// for the useful/horrifying gridbag layouts: http://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html
@SuppressWarnings("serial")
public class UIWindow extends JFrame {
ImportDeleteMenubar importDeleteMenubar;
JTabbedPane mainTabs;
JTabbedPane clerkTabs;
JPanel newBorrowerPanel;
JPanel checkoutPanel;
JPanel returnPanel;
JPanel checkOverduePanel;
JTabbedPane borrowerTabs;
JPanel searchPanel;
JPanel checkAccountPanel;
JPanel placeHoldPanel;
JTabbedPane librarianTabs;
JPanel addBookPanel;
JPanel checkedOutPanel;
JPanel mostPopularPanel;
JTextArea textArea;
public UIWindow() {
super("Main Class");
//initialize the menu
importDeleteMenubar = new ImportDeleteMenubar(this);
this.setJMenuBar(importDeleteMenubar);
// create the tab hierarchy. Leaf tabs are custom panels we define.
mainTabs = new JTabbedPane(); getContentPane().add(mainTabs, BorderLayout.CENTER);
clerkTabs = new JTabbedPane(); mainTabs.addTab("clerk", clerkTabs);
newBorrowerPanel = new NewBorrowerPanel(); clerkTabs.addTab("new borrower", newBorrowerPanel);
checkoutPanel = new CheckoutPanel(); clerkTabs.addTab("checkout", checkoutPanel);
returnPanel = new ReturnPanel(); clerkTabs.addTab("return", returnPanel);
checkOverduePanel = new CheckOverduePanel(); clerkTabs.addTab("check overdue", checkOverduePanel);
borrowerTabs = new JTabbedPane(); mainTabs.addTab("borrower", borrowerTabs);
searchPanel = new SearchPanel(); borrowerTabs.addTab("search", searchPanel);
checkAccountPanel = new CheckAccountPanel(); borrowerTabs.addTab("check account", checkAccountPanel);
placeHoldPanel = new PlaceHoldPanel(); borrowerTabs.addTab("place hold", placeHoldPanel);
librarianTabs = new JTabbedPane(); mainTabs.addTab("librarian", librarianTabs);
addBookPanel = new AddBookPanel(); librarianTabs.addTab("add book", addBookPanel);
checkedOutPanel = new CheckedOutPanel(); librarianTabs.addTab("checked out", checkedOutPanel);
mostPopularPanel = new MostPopularPanel(); librarianTabs.addTab("most popular", mostPopularPanel);
textArea = new JTextArea("", 10,10);
getContentPane().add(textArea, BorderLayout.EAST);
setTitle("CPSC 304 DB browser");
setSize(1024, 768);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void LogMessage(String message) {
textArea.append(message + "\n");
}
} | true |
d4f77a338fbc4bc3ce0acb983d225d004bd11e6e | Java | wangxp1988/kuaidi | /renren-admin/src/main/java/io/renren/common/utils/UploadAndExcelUtil.java | UTF-8 | 1,361 | 2.609375 | 3 | [
"Apache-2.0"
] | permissive | package io.renren.common.utils;
import java.io.File;
import java.io.IOException;
import java.util.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;
/**
* excle文件上传工具上传后返回路径
* @author Administrator
*
*/
public class UploadAndExcelUtil {
/**
* @param multipartFile
* @return
* @throws IOException
*/
public static String saveFile(MultipartFile multipartFile,String diskDirPath) throws IOException {
try {
String originalFilename = multipartFile.getOriginalFilename();
String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
String newFileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
/*if (suffix.equalsIgnoreCase("xls") || suffix.equalsIgnoreCase("xlsx")) {
diskDirPath = File.separator+"excle";
} */
File nf = new File(diskDirPath);
if (!nf.exists()) {
nf.mkdirs();
}
File newFile = new File(diskDirPath, newFileName);
multipartFile.transferTo(newFile);
if (suffix.equalsIgnoreCase("xls") || suffix.equalsIgnoreCase("xlsx")) {
return diskDirPath + File.separator + newFileName;
}
} catch (IllegalStateException | IOException e) {
e.printStackTrace();
}
return null;
}
}
| true |
2b04856456042fcef11cdf2e248f1e8c3e648dcc | Java | asaelr/TastyIdea | /app/src/main/java/com/example/asaelr/tastyidea/RecipesSearcher.java | UTF-8 | 2,729 | 2.328125 | 2 | [] | no_license | package com.example.asaelr.tastyidea;
import android.content.res.Resources;
import android.os.AsyncTask;
import com.example.asaelr.tastyidea.RecipesSupplier;
import com.google.api.client.json.GenericJson;
import com.google.api.client.util.Key;
import java.io.IOException;
import java.io.Serializable;
import networking.Networking;
import networking.RecipeMetadata;
/**
* Created by asael on 16/05/16.
*/
public class RecipesSearcher implements Serializable, RecipesSupplier {
public String[] ingredients;
public String[] excluded;
public boolean vegeterian = false;
public boolean vegan = false;
public boolean kosher = false;
public int maxPrepTime = 500;
public int minRating = 1;
public int maxDifficulty = 0;
public String category = ""; //empty string for "all categories"
@Override
public void supply(final Callback callback) {
new AsyncTask<Void,Void,RecipeMetadata[]>() {
@Override
protected RecipeMetadata[] doInBackground(Void... params) {
try {
SearchJSON search = new SearchJSON();
search.ingredients = ingredients;
search.vegeterian = vegeterian;
search.vegan = vegan;
search.kosher = kosher;
search.maxPrepTime = maxPrepTime;
search.minRating = minRating;
search.category = category;
search.exclude = excluded;
search.maxDifficulty = maxDifficulty;
return Networking.searchRecipes(search);
} catch (IOException e) {
e.printStackTrace();
return null;
} catch (RuntimeException e) {
e.printStackTrace();
return null;
}
}
@Override
protected void onPostExecute(RecipeMetadata[] result) {
if (result!=null) callback.onSuccess(result);
else callback.onFailure();
}
}.execute();
}
@Override
public String getTitle(Resources res) {
return res.getString(R.string.search_results);
}
public static class SearchJSON extends GenericJson {
@Key
public String[] ingredients;
@Key
public boolean vegeterian;
@Key
public boolean vegan;
@Key
public boolean kosher;
@Key
public int maxPrepTime;
@Key
public int minRating;
@Key
public String[] exclude;
@Key
public String category;
@Key
public int maxDifficulty;
}
}
| true |
13055282c3b152ae7b659366fec69912d383b2be | Java | JogiYo/Algorithm | /src/baek10000/BOJ_10773.java | UTF-8 | 711 | 3.234375 | 3 | [] | no_license | package baek10000;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Stack;
// BOJ 10773 : Zero
// using stack
public class BOJ_10773 {
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
int k = Integer.parseInt(br.readLine());
Stack<Integer> stk = new Stack<>();
int sum = 0;
while(k-- > 0) {
int num = Integer.parseInt(br.readLine());
if(num == 0) stk.pop();
else stk.push(num);
}
if(!stk.isEmpty()) {
while(!stk.isEmpty()) {
sum += stk.pop();
}
}
sb.append(sum + "");
System.out.print(sb);
}
} | true |
a68b1dcd723bdab23684cb6cd9d6409d7e760e21 | Java | alexeyev/trends | /TrendsSuite/src/test/java/ru/compscicenter/trends/SorterExecutor.java | UTF-8 | 2,722 | 2.546875 | 3 | [] | no_license | package ru.compscicenter.trends;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.compscicenter.trends.ner.EnglishNEExtractor;
import ru.compscicenter.trends.ner.model.NamedEntity;
import ru.compscicenter.trends.ner.model.Tag;
import ru.compscicenter.trends.util.CounterLogger;
import java.io.File;
import java.util.List;
import java.util.concurrent.BlockingQueue;
/**
* See SortingTool.
* @author alexeyev
*/
public class SorterExecutor implements Runnable {
private final Logger log = LoggerFactory.getLogger(this.toString());
private final BlockingQueue<File> queue;
private final CounterLogger cl;
SorterExecutor(BlockingQueue<File> q,
CounterLogger clog) {
queue = q;
cl = clog;
}
@Override
public void run() {
File destDirectory = new File("../new_gizmodo/corpus4/");
destDirectory.mkdirs();
while ((!queue.isEmpty())) {
try {
File year = queue.take();
log.info(year.getAbsolutePath());
// articles
for (File article : year.listFiles()) {
String text = FileUtils.readFileToString(article);
// NER
List<NamedEntity> nes = EnglishNEExtractor.getNamedEntities(text);
for (NamedEntity ne : nes) {
// filtering organizations
if (ne.getTag().equals(Tag.ORGANIZATION)) {
Long orgId = SortingTool.map.getMap().get(ne.getWords());
// only known organizations
if (orgId == null) {
//do nothing
// only companies that are mentioned often
} else if (SortingTool.interestingCompanies.contains(orgId)) {
File destYearDir = new File(
String.format(
"%s/%s/%s/",
destDirectory.getAbsolutePath(),
orgId.toString(),
year.getName()));
destYearDir.mkdirs();
FileUtils.copyFileToDirectory(article, destYearDir);
}
}
}
cl.tick();
}
} catch (Exception e) {
log.error("Problems getting stuff from queue.");
}
}
}
}
| true |
f6b5c62cd1b85c86305daa4c1f2999e83eb5d173 | Java | KM-88/JPlayer | /common-systems/src/main/java/datasource/BaseDAO.java | UTF-8 | 1,031 | 2.296875 | 2 | [] | no_license | /*
* 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 datasource;
import java.util.List;
/**
*
* @author kranti
*/
public class BaseDAO {
private static DataBaseInterface dataLink;
public static void setDataLink(DataBaseInterface dataLink){
BaseDAO.dataLink = dataLink;
}
public static void init(DataBaseInterface dataSource){
dataLink = dataSource;
}
public static Class<?> getById(Class clazz, Long id) {
return dataLink.getById(clazz, id);
}
public static synchronized List<?> getAll(Class clazz) {
return dataLink.getAll(clazz);
}
public static void save(Object object) {
dataLink.save(object);
}
public static synchronized void save(List<?> objects) {
dataLink.save(objects);
}
public static void deleteAll(Class clazz){
dataLink.deleteAll(clazz);
}
}
| true |
4d7d7e3fea321f6f422c2ad9a24cf6b18b368375 | Java | pixb/xc-chat | /XCAndroid/modules/XCServerLibrary/protobuf/out/com/pix/xcserverlibrary/protobuf/XCChatMsgBRO.java | UTF-8 | 5,051 | 2.109375 | 2 | [] | no_license | // Code generated by Wire protocol buffer compiler, do not edit.
// Source file: xc_protoc.proto at 63:1
package com.pix.xcserverlibrary.protobuf;
import com.squareup.wire.FieldEncoding;
import com.squareup.wire.Message;
import com.squareup.wire.ProtoAdapter;
import com.squareup.wire.ProtoReader;
import com.squareup.wire.ProtoWriter;
import com.squareup.wire.WireField;
import com.squareup.wire.internal.Internal;
import java.io.IOException;
import java.lang.Object;
import java.lang.Override;
import java.lang.String;
import java.lang.StringBuilder;
import okio.ByteString;
/**
* (公聊)消息返回
*/
public final class XCChatMsgBRO extends Message<XCChatMsgBRO, XCChatMsgBRO.Builder> {
public static final ProtoAdapter<XCChatMsgBRO> ADAPTER = new ProtoAdapter_XCChatMsgBRO();
private static final long serialVersionUID = 0L;
/**
* 发送者
*/
@WireField(
tag = 1,
adapter = "com.pix.xcserverlibrary.protobuf.ChatPlayer#ADAPTER"
)
public final ChatPlayer player;
@WireField(
tag = 2,
adapter = "com.pix.xcserverlibrary.protobuf.XCChatMsg#ADAPTER"
)
public final XCChatMsg chat;
public XCChatMsgBRO(ChatPlayer player, XCChatMsg chat) {
this(player, chat, ByteString.EMPTY);
}
public XCChatMsgBRO(ChatPlayer player, XCChatMsg chat, ByteString unknownFields) {
super(ADAPTER, unknownFields);
this.player = player;
this.chat = chat;
}
@Override
public Builder newBuilder() {
Builder builder = new Builder();
builder.player = player;
builder.chat = chat;
builder.addUnknownFields(unknownFields());
return builder;
}
@Override
public boolean equals(Object other) {
if (other == this) return true;
if (!(other instanceof XCChatMsgBRO)) return false;
XCChatMsgBRO o = (XCChatMsgBRO) other;
return Internal.equals(unknownFields(), o.unknownFields())
&& Internal.equals(player, o.player)
&& Internal.equals(chat, o.chat);
}
@Override
public int hashCode() {
int result = super.hashCode;
if (result == 0) {
result = unknownFields().hashCode();
result = result * 37 + (player != null ? player.hashCode() : 0);
result = result * 37 + (chat != null ? chat.hashCode() : 0);
super.hashCode = result;
}
return result;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
if (player != null) builder.append(", player=").append(player);
if (chat != null) builder.append(", chat=").append(chat);
return builder.replace(0, 2, "XCChatMsgBRO{").append('}').toString();
}
public static final class Builder extends Message.Builder<XCChatMsgBRO, Builder> {
public ChatPlayer player;
public XCChatMsg chat;
public Builder() {
}
/**
* 发送者
*/
public Builder player(ChatPlayer player) {
this.player = player;
return this;
}
public Builder chat(XCChatMsg chat) {
this.chat = chat;
return this;
}
@Override
public XCChatMsgBRO build() {
return new XCChatMsgBRO(player, chat, buildUnknownFields());
}
}
private static final class ProtoAdapter_XCChatMsgBRO extends ProtoAdapter<XCChatMsgBRO> {
ProtoAdapter_XCChatMsgBRO() {
super(FieldEncoding.LENGTH_DELIMITED, XCChatMsgBRO.class);
}
@Override
public int encodedSize(XCChatMsgBRO value) {
return (value.player != null ? ChatPlayer.ADAPTER.encodedSizeWithTag(1, value.player) : 0)
+ (value.chat != null ? XCChatMsg.ADAPTER.encodedSizeWithTag(2, value.chat) : 0)
+ value.unknownFields().size();
}
@Override
public void encode(ProtoWriter writer, XCChatMsgBRO value) throws IOException {
if (value.player != null) ChatPlayer.ADAPTER.encodeWithTag(writer, 1, value.player);
if (value.chat != null) XCChatMsg.ADAPTER.encodeWithTag(writer, 2, value.chat);
writer.writeBytes(value.unknownFields());
}
@Override
public XCChatMsgBRO decode(ProtoReader reader) throws IOException {
Builder builder = new Builder();
long token = reader.beginMessage();
for (int tag; (tag = reader.nextTag()) != -1;) {
switch (tag) {
case 1: builder.player(ChatPlayer.ADAPTER.decode(reader)); break;
case 2: builder.chat(XCChatMsg.ADAPTER.decode(reader)); break;
default: {
FieldEncoding fieldEncoding = reader.peekFieldEncoding();
Object value = fieldEncoding.rawProtoAdapter().decode(reader);
builder.addUnknownField(tag, fieldEncoding, value);
}
}
}
reader.endMessage(token);
return builder.build();
}
@Override
public XCChatMsgBRO redact(XCChatMsgBRO value) {
Builder builder = value.newBuilder();
if (builder.player != null) builder.player = ChatPlayer.ADAPTER.redact(builder.player);
if (builder.chat != null) builder.chat = XCChatMsg.ADAPTER.redact(builder.chat);
builder.clearUnknownFields();
return builder.build();
}
}
}
| true |
9e4978bead8b7001378543fd4883a94f51449f47 | Java | MrcRjs/soap-client-gui | /src/wsgui/ImageUtil.java | UTF-8 | 585 | 2.75 | 3 | [
"MIT"
] | permissive | package wsgui;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Display;
public class ImageUtil {
public Image resize(Image image, int width, int height) {
Image scaled = new Image(Display.getDefault(), width, height);
GC gc = new GC(scaled);
gc.setAntialias(SWT.ON);
gc.setInterpolation(SWT.HIGH);
gc.drawImage(image, 0, 0,
image.getBounds().width, image.getBounds().height,
0, 0, width, height);
gc.dispose();
image.dispose(); // don't forget about me!
return scaled;
}
}
| true |
d665ff41cda429e001501f8982ceedd2d27b30a5 | Java | sirinath/Terracotta | /dso/tags/2.7.0/code/base/deploy/src/com/tc/admin/sessions/SessionsProductWrapper.java | UTF-8 | 2,549 | 2.015625 | 2 | [] | no_license | /*
* All content copyright (c) 2003-2008 Terracotta, Inc., except as may otherwise be noted in a separate copyright
* notice. All rights reserved.
*/
package com.tc.admin.sessions;
import com.tc.management.exposed.SessionsProductMBean;
import com.tc.management.opentypes.adapters.ClassCreationCount;
import java.util.Arrays;
import javax.management.openmbean.TabularData;
public class SessionsProductWrapper {
private SessionsProductMBean bean;
private int requestCount;
private int requestCountPerSecond;
private int sessionWritePercentage;
private int sessionsCreatedPerMinute;
private int sessionsExpiredPerMinute;
private TabularData top10ClassesByObjectCreationCount;
private ClassCreationCount[] classCreationCount;
private static final ClassCreationCount[] EMPTY_COUNT = {};
public SessionsProductWrapper(SessionsProductMBean bean) {
this.bean = bean;
requestCount = bean.getRequestCount();
requestCountPerSecond = bean.getRequestCountPerSecond();
sessionWritePercentage = bean.getSessionWritePercentage();
sessionsCreatedPerMinute = bean.getSessionsCreatedPerMinute();
sessionsExpiredPerMinute = bean.getSessionsExpiredPerMinute();
try {
top10ClassesByObjectCreationCount = bean.getTop10ClassesByObjectCreationCount();
if (top10ClassesByObjectCreationCount != null) {
classCreationCount = ClassCreationCount.fromTabularData(top10ClassesByObjectCreationCount);
} else {
classCreationCount = new ClassCreationCount[0];
}
} catch (Exception e) {
classCreationCount = new ClassCreationCount[0];
}
}
public int getRequestCount() {
return requestCount;
}
public int getRequestCountPerSecond() {
return requestCountPerSecond;
}
public int getSessionWritePercentage() {
return sessionWritePercentage;
}
public int getSessionsCreatedPerMinute() {
return sessionsCreatedPerMinute;
}
public int getSessionsExpiredPerMinute() {
return sessionsExpiredPerMinute;
}
public TabularData getTop10ClassesByObjectCreationCount() {
return top10ClassesByObjectCreationCount;
}
public ClassCreationCount[] getClassCreationCount() {
return Arrays.asList(classCreationCount).toArray(EMPTY_COUNT);
}
public void expireSession(String sessionId) {
bean.expireSession(sessionId);
}
}
| true |
8c0935ebc67d731480f84d60bb37ea89b741f5de | Java | Amir-Khan-98/MThree | /src/Database/DatabaseRunMain.java | UTF-8 | 2,105 | 2.6875 | 3 | [] | no_license | package Database;
import java.sql.*;
import OrderManager.Order;
import Ref.Instrument;
import Ref.Ric;
public class DatabaseRunMain {
public static void main(String[] args) throws Exception {
// PREREQUISITE FOR CONNECTING TO THE DATABASE AND CONTROLLERS
DatabaseController dbc = new DatabaseController("com.mysql.jdbc.Driver","jdbc:mysql://localhost/marketdatabase","root","");
Connection databaseConnection = dbc.getConnection();
ClientsController clientsController = new ClientsController(databaseConnection);
OrderController orderController = new OrderController(databaseConnection);
FixController fixController = new FixController(databaseConnection);
// CREATE THE TABLES
//ClientsController.createClientsTable();
//OrderController.createOrderTable();
//FixController.createFixTable();
//CODE FOR TESTING CLIENT TABLE
//ClientsController.addClient(3,2020);
//ClientsController.addClient(1,2021);
//ClientsController.removeClientFromTable(0);
ResultSet rs = ClientsController.selectAll();
ClientsController.printResultSet(rs);
// CODE FOR TESTING ORDER TABLE
//Instrument testInstrument = new Instrument(new Ric("BT.L"));
//Order testOrder = new Order(3,2,testInstrument,5); //Random Order object 1
//Order testOrder2 = new Order(6,7,testInstrument,10); //Random Order object 1
//OrderController.addOrderToTable(testOrder);
//OrderController.addOrderToTable(testOrder2);
//OrderController.removeOrderFromTable(testOrder2);
ResultSet orderResults = OrderController.selectAll();
OrderController.printResultSet(orderResults);
// CODE FOR TESTING FIX TABLE
//String fix1 = "11=0;35=A;39=A";
//FixController.addFixMessageToTable(fix1);
//FixController.removeMessageFromTable(fix1);
//FixController.removeRowsFromTable();
ResultSet fixResults = FixController.selectAll();
FixController.printResultSet(fixResults);
}
}
| true |
d654ec5084bf8858f2089aa7b8ce6d0e0cf32866 | Java | realsightAPM/westworld | /tsp/src/main/java/com/realsight/westworld/tsp/lib/util/data/VolumeData.java | UTF-8 | 2,559 | 2.6875 | 3 | [] | no_license | package com.realsight.westworld.tsp.lib.util.data;
import java.io.IOException;
import java.nio.charset.Charset;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import com.realsight.westworld.tsp.lib.csv.CsvReader;
import com.realsight.westworld.tsp.lib.series.DoubleSeries;
import com.realsight.westworld.tsp.lib.series.TimeSeries;
public class VolumeData {
private char delimiter = ',';
private Charset charset = null;
private String csvFilePath = null;
public VolumeData(char delimiter, Charset charset, String path){
this.delimiter = delimiter;
this.charset = charset;
this.csvFilePath = path;
}
public VolumeData(String path){
this(',', Charset.forName("ISO-8859-1"), path);
}
public DoubleSeries getPropertySeries(String name, SimpleDateFormat sdf){
DoubleSeries res = new DoubleSeries(name);
try {
CsvReader cr = new CsvReader(csvFilePath, delimiter, charset);
cr.readHeaders();
if(cr.getIndex("start_time") == -1)
throw new IOException("File not exists start_time.");
if(!name.equals("hour") && cr.getIndex(name)==-1)
throw new IOException("File not exists " + name + ".");
Long idx = 0L;
while(cr.readRecord()){
String time = cr.get("start_time").trim();
Date date = null;
try {
date = sdf.parse(time);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Long timestamp = date.getTime();
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(timestamp);
double num = Double.parseDouble(cr.get(name));
res.add(new TimeSeries.Entry<Double>(num, idx));
idx = idx + 1L;
}
cr.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return res;
}
public DoubleSeries getPropertySeries(String name){
DoubleSeries res = new DoubleSeries(name);
try {
CsvReader cr = new CsvReader(csvFilePath, delimiter, charset);
cr.readHeaders();
if(cr.getIndex("timestamp") == -1)
throw new IOException("File not exists timestamp.");
if(cr.getIndex(name) == -1)
throw new IOException("File not exists " + name + ".");
while(cr.readRecord()){
String time = cr.get("timestamp");
Long timestamp = Long.valueOf(time);
double num = Double.parseDouble(cr.get(name));
res.add(new TimeSeries.Entry<Double>(num, timestamp));
}
cr.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return res;
}
}
| true |
43283a83729c08ef30076df452f969ae994be373 | Java | desadipas/lucas_app | /app/src/main/java/com/tibox/lucas/network/dto/AnularDTO.java | UTF-8 | 699 | 1.882813 | 2 | [] | no_license | package com.tibox.lucas.network.dto;
/**
* Created by desa02 on 21/06/2017.
*/
public class AnularDTO {
private String cUser;
private String cComentario;
private int nIdFlujoMaestro;
public String getcUser() {
return cUser;
}
public void setcUser(String cUser) {
this.cUser = cUser;
}
public String getcComentario() {
return cComentario;
}
public void setcComentario(String cComentario) {
this.cComentario = cComentario;
}
public int getnIdFlujoMaestro() {
return nIdFlujoMaestro;
}
public void setnIdFlujoMaestro(int nIdFlujoMaestro) {
this.nIdFlujoMaestro = nIdFlujoMaestro;
}
}
| true |
a3537f78f9636431ef288c9f5ac8679972446b5d | Java | raviish95/SPDevelopers | /app/src/main/java/com/awizom/spdeveloper/Adapter/NotificationListAdapter.java | UTF-8 | 4,549 | 1.929688 | 2 | [] | no_license | package com.awizom.spdeveloper.Adapter;
import java.lang.reflect.Type;
import java.util.List;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.awizom.spdeveloper.ClientHistory;
import com.awizom.spdeveloper.Helper.ClientHelper;
import com.awizom.spdeveloper.Model.NotificationModel;
import com.awizom.spdeveloper.R;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import uk.co.senab.photoview.PhotoViewAttacher;
public class NotificationListAdapter extends RecyclerView.Adapter<NotificationListAdapter.MyViewHolder> {
private List<NotificationModel> notificationModelList;
private Context mCtx;
String result = "";
private AlertDialog progressDialog;
public NotificationListAdapter(Context baseContext, List<NotificationModel> notificationModelList) {
this.notificationModelList = notificationModelList;
this.mCtx = baseContext;
}
/* for solve issue of item change on scroll this method is set*/
@Override
public long getItemId(int position) {
return position;
}
/* for solve issue of item change on scroll this method is set*/
@Override
public int getItemViewType(int position) {
return position;
}
@Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
NotificationModel c = notificationModelList.get(position);
holder.orderid.setText(String.valueOf(c.getEmployeeID()));
holder.notification_id.setText(String.valueOf(c.getClientLeadNotiId()));
if (c.getRead()) {
holder.cardView.setCardBackgroundColor(Color.parseColor("#FFFFFF"));
}
holder.notification_body.setText(c.getMSGBody().toString());
/* holder.notification_date.setText(String.valueOf(c.getDate().toString()).split("T")[0]);*/
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
readNotification(holder.notification_id.getText().toString());
Intent intent=new Intent(mCtx, ClientHistory.class);
intent.putExtra("Empid",holder.orderid.getText().toString());
mCtx.startActivity(intent);
}
});
}
private void readNotification(String noti_id) {
try {
result = new ClientHelper.PostReadNotification().execute(noti_id).get();
if (result.isEmpty()) {
Toast.makeText(mCtx, "Invalid request", Toast.LENGTH_SHORT).show();
result = new ClientHelper.PostReadNotification().execute(noti_id).get();
} else {
Gson gson = new Gson();
/* Type getType = new TypeToken<ResultModel>() {
}.getType();
ResultModel resultModel = new Gson().fromJson(result, getType);*/
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public int getItemCount() {
return notificationModelList.size();
}
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_notificationlist, parent, false);
return new MyViewHolder(v);
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView notification_body, notification_type, orderid, notification_id;
CardView cardView;
ImageView noti_typeimage;
@RequiresApi(api = Build.VERSION_CODES.M)
public MyViewHolder(View view) {
super(view);
notification_body = view.findViewById(R.id.noti_body);
notification_id = view.findViewById(R.id.noti_ID);
orderid = view.findViewById(R.id.noti_orderid);
cardView = view.findViewById(R.id.card_view);
notification_type = view.findViewById(R.id.noti_type);
noti_typeimage = view.findViewById(R.id.noti_typeImage);
}
}
} | true |
ff783fae5624208a4bd47804ee8297109f406690 | Java | desrogers/ascent-autos | /src/main/java/com/galvanize/autos/Automobiles.java | UTF-8 | 1,577 | 2.4375 | 2 | [] | no_license | package com.galvanize.autos;
import com.fasterxml.jackson.annotation.JsonFormat;
import javax.persistence.*;
import java.util.Date;
@Entity
@Table(name = "automobiles")
public class Automobiles {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "model_year")
private int year;
private String make;
private String model;
private String color;
@Column(name = "owner_name")
private String owner;
@JsonFormat(pattern = "MM/dd/yyyy")
private Date purchaseDate;
@Column(unique = true)
private String vin;
public int getYear() {
return year;
}
public String getMake() {
return make;
}
public String getModel() {
return model;
}
public String getColor() {
return color;
}
public String getOwner() {
return owner;
}
public String getVin() {
return vin;
}
public Date getPurchaseDate() {
return purchaseDate;
}
public void setPurchaseDate(Date purchaseDate) {
this.purchaseDate = purchaseDate;
}
public Automobiles() {
}
public Automobiles(int year, String make, String model, String color, String owner, String vin) {
this.year = year;
this.make = make;
this.model = model;
this.color = color;
this.owner = owner;
this.vin = vin;
}
public void setColor(String color) {
this.color = color;
}
public void setOwner(String owner) {
this.owner = owner;
}
}
| true |
54fb9524672326a16b9c8b90b8471df6a8da3f6e | Java | minwoo/TopicSeg | /src/topicseg/Runner.java | UTF-8 | 3,873 | 2.21875 | 2 | [] | no_license | /*
* Copyright (C) 2010 Cluster of Excellence, Univ. of Saarland
* Minwoo Jeong (minwoo.j@gmail.com) is a main developer.
* This file is part of "TopicSeg" package.
* This software is provided under the terms of LGPL.
*/
package topicseg;
import jargs.gnu.CmdLineParser;
import org.apache.log4j.*;
import topicseg.document.*;
import topicseg.segment.*;
import topicseg.utils.*;
/**
* unisaar.topicseg::Runner.java
* A command line running tool of topic segmentation
*
* @author minwoo
*/
public class Runner {
public static void main(String[] args) {
Logger logger = Logger.getLogger(Runner.class);
logger.info("===" + Runner.class.getName() + "===");
// command line parsing
CmdLineParser cmdParser = new CmdLineParser();
CmdLineParser.Option debug = cmdParser.addBooleanOption('d', "debug");
CmdLineParser.Option verbose = cmdParser.addBooleanOption('v', "verbose");
CmdLineParser.Option configfile = cmdParser.addStringOption('c', "config");
try {
cmdParser.parse(args);
}
catch (CmdLineParser.OptionException e) {
logger.error(e.getMessage());
logger.error("Usage: java -cp ${CLASSPATH} unisaar.topicseg.Runner " +
"[-c,--config] config_file [{-v,--verbose}] [{-d,--debug}]");
System.exit(2);
}
String configFileName = (String)cmdParser.getOptionValue(configfile);
Boolean isDebug = (Boolean)cmdParser.getOptionValue(debug, Boolean.TRUE);
Boolean isVerbose = (Boolean)cmdParser.getOptionValue(verbose, Boolean.TRUE);
// running
try {
Option config = new Option(configFileName);
if (config.contains("exp.log"))
Option.addFileLogger(logger, config.getString("exp.log"));
String classifierName = config.contains("model.class") ? config.getString("model.class") : "unisaar.topicseg.segment.MultiSeg";
// hyperparameters for DCM
double dcmGlobalPrior = config.contains("prior.dcm.global") ? config.getDouble("prior.dcm.global") : 0.1;
double dcmLocalPrior = config.contains("prior.dcm.local") ? config.getDouble("prior.dcm.local") : 0.1;
int nTrials = config.contains("exp.trial") ? config.getInteger("exp.trial") : 1;
String outputFilename = config.contains("exp.output") ? config.getString("exp.output") : "";
boolean usePerDocEval = config.contains("exp.perDocEval") ? config.getBoolean("exp.perDocEval") : false;
for (int n = 0; n < nTrials; n++) {
// segmenter
Segmenter segmenter = (Segmenter) Class.forName(classifierName).getConstructor(new Class[]{}).newInstance(new Object[]{});
segmenter.initialize(config);
segmenter.initializeRandom(n+1);
// corpus processing
if (config.contains("corpus.datasetDir")) {
// data loading
Corpus corpus = new Corpus(config.getString("corpus.datasetDir"), config);
// segmentation
segmenter.run(corpus, dcmGlobalPrior, dcmLocalPrior);
// write out
if (!outputFilename.equals("")) {
segmenter.writeResult(corpus, outputFilename + "." + n, usePerDocEval);
}
if (config.contains("output.outputDir") && config.contains("output.rawDataDir")) {
corpus.writeSegmentResult(config.getString("output.rawDataDir"), config.getString("output.outputDir"));
}
}
}
}
catch (Exception e) {
logger.error("error " + e.getMessage());
e.printStackTrace();
System.exit(2);
}
}
}
| true |
bed89e4a11a7c2dbe332cbd275b62f732ece1aea | Java | June-Boat/samplejava | /src/Test2.java | GB18030 | 1,862 | 3.40625 | 3 | [] | no_license | import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test2 {
public static void main(String[] args){
int rowCount = 0;
Scanner sc = new Scanner(System.in);
rowCount = sc.nextInt();
int i=0;
StringBuilder sb = new StringBuilder();
while(i<=rowCount){
sb.append(sc.nextLine()+" ");
i++;
}
//ƥ
Pattern pattern= Pattern.compile("[a-zA-Z]+");
Matcher matcher=pattern.matcher(sb.toString());
Map<String,Integer> words=new HashMap<String,Integer>();
String word="";
int wordCount;
while(matcher.find()){
word=matcher.group();
if(words.containsKey(word)){
wordCount=words.get(word);
words.put(word, wordCount+1);
}else{
words.put(word, 1);
}
}
List<Map.Entry<String,Integer>> list=new ArrayList<Map.Entry<String,Integer>>(words.entrySet());
//ԼϽ
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
if (o1.getValue() > o2.getValue()) {
return -1;
} else if (o1.getValue() == o2.getValue()) {
return o1.getKey().compareTo(o2.getKey());
} else {
return 1;
}
}
});
//
StringBuilder output = new StringBuilder();
for(Map.Entry<String,Integer> bean : list){
output.append(bean.getKey()).append(" ").append(bean.getValue()).append("\n");
}
System.out.println(output.toString());
}
} | true |
5f156ef4936c7f38a0997bafd74e986148ead8b5 | Java | PedroRomanoBarbosa/Distributed-Backup-Service | /src/sdis/DataSocket.java | UTF-8 | 1,574 | 2.84375 | 3 | [] | no_license | package sdis;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.util.Arrays;
public class DataSocket extends MulticastSocket {
public DataSocket(int port) throws IOException {
super(port);
}
@Deprecated
public String receive(int size) throws IOException {
byte[] buffer = new byte[size];
DatagramPacket packet = new DatagramPacket(buffer,buffer.length);
this.receive(packet);
return new String(packet.getData(),packet.getOffset(),packet.getLength());
}
public byte[] receiveData(int size) throws IOException {
byte[] buffer = new byte[size];
DatagramPacket packet = new DatagramPacket(buffer,buffer.length);
this.receive(packet);
return Arrays.copyOfRange(packet.getData(),packet.getOffset(),packet.getLength());
}
public DatagramPacket receivePacket(int size) throws IOException {
byte[] buffer = new byte[size];
DatagramPacket packet = new DatagramPacket(buffer,buffer.length);
this.receive(packet);
return packet;
}
public void send(String m, InetAddress ip, int port) throws IOException {
byte[] buffer = m.getBytes();
DatagramPacket packet = new DatagramPacket(buffer,buffer.length,ip,port);
this.send(packet);
}
public void sendPacket(byte[] m, InetAddress ip, int port) throws IOException {
DatagramPacket packet = new DatagramPacket(m,m.length,ip,port);
this.send(packet);
}
}
| true |
75320ac1849a28f70d741298a22bceff6f4be531 | Java | androidsxy/Mandroid | /baiduweishii/src/main/java/com/zzptc/sxy/baiduweishii/Uitls/MemoryCleanTools.java | UTF-8 | 8,377 | 2.21875 | 2 | [] | no_license | package com.zzptc.sxy.baiduweishii.Uitls;
import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import com.zzptc.sxy.baiduweishii.R;
import com.zzptc.sxy.baiduweishii.contant.AppProcessInfo;
import com.zzptc.sxy.baiduweishii.contant.Contant;
import java.util.ArrayList;
import java.util.List;
/**
* Created by SXY on 2016/5/26.
*/
import android.support.v4.content.ContextCompat;
import org.xutils.x;
/**
* Created by Administrator on 2016/5/25.
*/
public class MemoryCleanTools {
//因为我们昨天已经准备好了RecyclerView,因此我们今天需要准备数据集合
//因为我们做了是一个手机加速模块,因此我们需要扫描系统的进程,必须是用户进程,并且排除自己。
//因为有些用户安装的用户比较多,因此进行数量比较大,需要开启异步任务去执行扫描的任务
//得到进行集合?如何去获取进程?如何使用异步任务去执行这个获取的过程?
//http://www.cnblogs.com/crazypebble/archive/2011/04/09/2010196.html
private ActivityManager activityManager ;
private Context context;
private List<AppProcessInfo> list;
private PackageManager pck ;
public MemoryCleanTools(){
context = x.app().getApplicationContext();
activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
pck = context.getPackageManager();
}
public void scanProcess(){
new ScanProcess().execute();
}
//添加监听接口 三个
public interface OnProcessListener{
void onScanStartListener(Context context);
void onScanProcessLisener(Context context,int current,int total);
void onScanCompleteListener(Context context,List<AppProcessInfo> list);
void onCleanStarListener(Context context);
void onCleanCompleteListener(Context context,long cleanMemory);
}
private OnProcessListener onProcessListener;
public void setOnProcessListener(OnProcessListener onProcessListener){
this.onProcessListener = onProcessListener;
}
class ScanProcess extends AsyncTask<Void,Integer,List<AppProcessInfo>>{
@Override
protected void onPreExecute() {
super.onPreExecute();
if(onProcessListener != null){
onProcessListener.onScanStartListener(context);
}
}
@Override
protected List<AppProcessInfo> doInBackground(Void... params) {
list = new ArrayList<>();
int progress = 0;
List<ActivityManager.RunningAppProcessInfo> runningAppProcesses = activityManager.getRunningAppProcesses();
for(ActivityManager.RunningAppProcessInfo processInfo:runningAppProcesses){
//更新进度
publishProgress(++progress,runningAppProcesses.size());
AppProcessInfo contant = new AppProcessInfo();
//得到进程名
contant.setPakcageName(processInfo.processName);
try {
ApplicationInfo appInfo = pck.getApplicationInfo(processInfo.processName,0);
//图标
contant.setIcon(appInfo.loadIcon(pck));
//应用程序的名称
contant.setYinName(appInfo.loadLabel(pck).toString());
//判断是否为系统进程
if((appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0){
contant.isSystem = true;
}else{
contant.isSystem = false;
}
if(processInfo.processName.equals(context.getPackageName())){
contant.isCurrent = true;
}
} catch (PackageManager.NameNotFoundException e) {
//分析 : 第一个:系统进程它没有应用名称 第二种:远程服务 xxx.xxx.xxx:xxx
if(processInfo.processName.contains(":")){
ApplicationInfo applicationInfo = getApplication(processInfo.processName.split(":")[0]);
if(applicationInfo != null){
contant.setIcon(applicationInfo.loadIcon(pck));
}else{
contant.setIcon(ContextCompat.getDrawable(context, R.mipmap.ic_launcher));
}
}else{
contant.setIcon(ContextCompat.getDrawable(context, R.mipmap.ic_launcher));
}
contant.isSystem = true;
contant.setPakcageName(processInfo.processName);
}
//获取内存
contant.setDaxiao(1024*(activityManager.getProcessMemoryInfo(new int[]{processInfo.pid})[0].getTotalPrivateDirty()));
list.add(contant);
}
return list;
}
@Override
protected void onPostExecute(List<AppProcessInfo> list) {
super.onPostExecute(list);
if(onProcessListener != null){
onProcessListener.onScanCompleteListener(context,list);
}
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
if(onProcessListener != null){
onProcessListener.onScanProcessLisener(context,values[0],values[1]);
}
}
}
public class CleanAsyncTask extends AsyncTask<List<AppProcessInfo>,Void,Long>{
@Override
protected Long doInBackground(List<AppProcessInfo>... params) {
List<AppProcessInfo> contantList = params[0];
List<ActivityManager.RunningAppProcessInfo> runningAppProcessInfos = activityManager.getRunningAppProcesses();
long befo = getAvailMemory();
if(runningAppProcessInfos!=null){
for(ActivityManager.RunningAppProcessInfo runningAppProcessInfo:runningAppProcessInfos){
for(AppProcessInfo contant:contantList){
if(contant.isChecked && contant.getPakcageName().equals(runningAppProcessInfo.processName)){
killBackGroundProcess(contant.getPakcageName());
}
}
}
}
long after = getAvailMemory();
return after - befo;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
if(onProcessListener != null){
onProcessListener.onCleanStarListener(context);
}
}
@Override
protected void onPostExecute(Long aLong) {
super.onPostExecute(aLong);
if(onProcessListener != null){
onProcessListener.onCleanCompleteListener(context,aLong);
}
}
}
/**
* 获取ApplicationInfo
* @param processName
* @return
*/
private ApplicationInfo getApplication(String processName){
if(processName == null){
return null;
}
List<ApplicationInfo> allLists = pck.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES);
for(ApplicationInfo applicationInfo:allLists){
if(processName.equals(applicationInfo.processName)){
return applicationInfo;
}
}
return null;
}
//获取内存大小
private long getAvailMemory(){
//获取android 当前可用内存
ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
activityManager.getMemoryInfo(memoryInfo);
return memoryInfo.availMem;
}
public void startClean(List<AppProcessInfo> contantList){
new CleanAsyncTask().execute(contantList);
}
/**清除进程
*
* @param processName
*/
public void killBackGroundProcess(String processName){
String process = processName;
if(processName.contains(":")){
process = processName.split(":")[0];
}
activityManager.killBackgroundProcesses(process);
}
}
| true |
80053f022ba518102362387f6347b28b0398095a | Java | feelxing/TecDemo | /JackSonDemo/src/main/java/com/feel/pojo/Persion.java | UTF-8 | 240 | 1.53125 | 2 | [] | no_license | package com.feel.pojo;
/**
* Created by MEV on 2017/3/30.
*/
public class Persion {
private String name;
private String address;
private String tel;
private int age;
private String sex;
private Company company;
}
| true |
9e943e5137f0e060cfde6378c612ef537b77a368 | Java | aorellanad/datastructure | /src/esctructura_de_datos/Shell_sort.java | UTF-8 | 799 | 3.234375 | 3 | [] | no_license |
package esctructura_de_datos;
/**
*
* @author Joel Tito
*/
public class Shell_sort {
public int[] toSort(int rNumbers[]) {
OrdenamientoShell(rNumbers);
return rNumbers;
}
public void OrdenamientoShell(int[] a) {
int salto, aux, i;
boolean cambios;
for (salto = a.length / 2; salto != 0; salto /= 2) {
cambios = true;
while (cambios) {
cambios = false;
for (i = salto; i < a.length; i++) {
if (a[i - salto] > a[i]) {
aux = a[i];
a[i] = a[i - salto];
a[i - salto] = aux;
cambios = true;
}
}
}
}
}
}
| true |
0c62f34173f13d574a22a29b7f5783ce5ab93e54 | Java | AntonioSuarez/progexch1 | /Main.java | UTF-8 | 248 | 2.875 | 3 | [] | no_license |
public class Main {
public static void main(String[] args){
House house = new House();
Window window = new Window();
house.CreateHouse(2);
window.CreateWindow(2);
window.DisPlayWindow("Is this what it's supposed to look like?");
}
}
| true |
d78c0afd299b0042458e821858ba42ae92a65426 | Java | blissnmx/owner-code | /spring-nmx-code-2.0-aop/src/main/java/com/demo/aspect/LogAspect.java | UTF-8 | 608 | 2.625 | 3 | [] | no_license | package com.demo.aspect;/**
* @author ning_mx
* @date 19:52 2020/4/26
* @description
*/
import lombok.extern.slf4j.Slf4j;
/**
* @author ning_mx
* @date 2020/4/26
*/
@Slf4j
public class LogAspect {
//在调用一个方法之前,执行before方法
public void before(){
//这个方法中的逻辑,是由我们自己写的
log.info("Invoker Before Method!!!");
}
//在调用一个方法之后,执行after方法
public void after(){
log.info("Invoker After Method!!!");
}
public void afterThrowing(){
log.info("出现异常");
}
}
| true |
4d1d5a4499cae0d29ff3d93955981bf0be8e6af6 | Java | Emonsaemon/hotel.booking | /hotelbooking/src/main/java/com/hotel/hotelbooking/dto/Token.java | UTF-8 | 476 | 2.5 | 2 | [] | no_license | package com.hotel.hotelbooking.dto;
public class Token {
String token;
String prefix;
public Token(String token) {
this.token = token;
this.prefix = "Bearer ";
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getPrefix() {
return prefix;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
}
| true |
8cbbeab7ea0ddebbd92074cf346cc72e017065cb | Java | yangfanfinland/UncleWooShop | /src/com/unclewoo/service/book/OrderItemService.java | UTF-8 | 331 | 1.898438 | 2 | [] | no_license | package com.unclewoo.service.book;
import com.unclewoo.bean.book.OrderItem;
import com.unclewoo.service.base.DAO1;
public interface OrderItemService extends DAO1<OrderItem>{
/**
* 更新商品购买数量
* @param itemid 订单项
* @param amount 购买数量
*/
public void updateAmount(Integer itemid, int amount);
}
| true |
33f085006d2cdeea9271622d8f8860a0e99b1705 | Java | Heifarabuval/MaReu | /app/src/main/java/com/heifara/buval/mareu2/utils/Filters.java | UTF-8 | 1,001 | 2.546875 | 3 | [] | no_license | package com.heifara.buval.mareu2.utils;
import com.heifara.buval.mareu2.model.Meet;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;
import static com.heifara.buval.mareu2.utils.Calendar.sameDate;
public class Filters {
/*
Return List sort by date
*/
public static List<Meet> getMeetByDate(Calendar date, List<Meet> meetings) {
List<Meet> temp = new ArrayList<>();
for (Meet meet : meetings)
if (sameDate(meet.getStart(), date))
temp.add(meet);
Collections.sort(temp);
return temp;
}
/*
Return List sort by room name
*/
public static List<Meet> getMeetByRoomName(String roomName, List<Meet> meets) {
List<Meet> temp = new ArrayList<>();
for (Meet meet : meets)
if (meet.getRoomName().trim().equals(roomName.trim()))
temp.add(meet);
Collections.sort(temp);
return temp;
}
}
| true |
aff6de18a08c949c481fe7f35fbb14bac35edb8d | Java | FelMelo/TIS-II | /src/javaapplication1/Empresa.java | UTF-8 | 3,669 | 2.75 | 3 | [] | no_license | package javaapplication1;
/*
* 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 rajha
*/
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Empresa {
@Override
public String toString() {
return "Empresa [razaosocial=" + razaosocial + ", CNPJ=" + cnpj + "]";
}
private static final Map<String, Empresa> Cadastro = new HashMap<>();
public static Empresa pesquisar(String razaosocial) {
return Empresa.get(razaosocial);
}
private static Empresa get(String razaosocial) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
private final String razaosocial;
private final String cnpj;
public Empresa(String razaosocial, String cnpj) {
this.razaosocial = razaosocial;
this.cnpj = cnpj;
}
public static void salvarEmpresa(File file, Empresa Empresa) throws FileNotFoundException {
FileOutputStream saida = null;
OutputStreamWriter gravador = null;
BufferedWriter buffer_saida = null;
BufferedReader buffRead = new BufferedReader (new FileReader(file));
buffRead.lines().count();
try {
saida = new FileOutputStream(file, true);
gravador = new OutputStreamWriter(saida);
buffer_saida = new BufferedWriter(gravador);
buffRead.lines().count();
buffer_saida.write(Empresa.razaosocial + " ");
buffer_saida.write(Empresa.cnpj);
buffer_saida.newLine();
buffer_saida.flush();
}catch (Exception Exception) {
}
//
// // Le o arquivo
// FileReader ler1 = new FileReader("teste.txt");
// @SuppressWarnings("resource")
// BufferedReader reader = new BufferedReader(ler1);
// String linha;
//// while( (linha = reader.readLine()) != null ){
//// System.out.println(linha);
////
//// }
// // Prepara para escrever no arquivo
// //FileWriter fw = new FileWriter(file.getAbsoluteFile());
// // Escreve e fecha arquivo
// //try (BufferedWriter bw = new BufferedWriter(fw)) {
// // Escreve e fecha arquivo
//
// BufferedWriter bw = null;
// FileOutputStream ow = new FileOutputStream(file, false);
//
// bw = new BufferedWriter(ow);
// reader.lines().count();
//
// bw.write( funcionario.nome + "\n");
// bw.write(funcionario.cpf + "\n");
//
//
//
// //}
//
// // Imprime confirmacao
// System.out.println("Feito =D");
//
// } catch (IOException e)
}
// private static final Map<String, Empresa> Cadastro = new HashMap<>();
//
//
// public static Funcionario pesquisar(String nome) {
// return Empresa.get(nome);
// }
//
// private static Funcionario get(String nome) {
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
// }
//
// private final String nome;
// private final String cnpj;
//
//
// public Empresa(String nome, String cnpj) {
//
// this.nome = nome;
// this.cnpj = cnpj;
// }
} | true |
c614f7700543636a003e1f46383e90a698a2a264 | Java | tassoskonst/CinemaProject-Connect-with-Database-Java- | /CinemaProject-Connect with Database(Java-PostgreSql)/DYNWEBPROJECT/src/userspackage/Admins.java | UTF-8 | 4,004 | 2.703125 | 3 | [] | no_license | package userspackage;
import java.util.Scanner;
import java.util.HashSet;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class Admins extends Users
{
public Admins() {}
public Admins(String n,String u,String p,String p1)
{
super(n,u,p,p1);
}
public void AdminUser()
{
}
public void login() {
String line="";
boolean find=false;
BufferedReader br=null;
try {
br=new BufferedReader(new FileReader("AdminText.txt"));
while((line=br.readLine())!=null&&find==false) {
find=(line.equals(this.getUsername()+" "+this.getPass()));
}
if(find==true)
System.out.println("successful login");
else
System.out.println("not find this user");
br.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
public void createUser(String n,String u,String p)
{
super.UserInput(n,u,p);
}
public void updateUser()
{
System.out.println("Here you can update users!");
}
public void deleteUser()
{
System.out.println("Here you can delete users!");
}
public String getProperty()
{
return "admin";
}
public void searchUser(Users us)
{
System.out.println("Here you can search users!");
String name = us.getName();
String username =us.getUsername();
String password =us.getPass();
String property= us.getProperty();
String line="";
int count =0;
if (property=="admin")
{
BufferedReader b = null;
try {
b= new BufferedReader(new FileReader("AdminText.txt"));
while((line=b.readLine())!=null){
if(!line.isEmpty())
count++;
if (line.equals(name+ " "+username+" "+" "+password))
System.out.println("Found user" +name+ "in line"+count+1);
}
b.close();
}
catch(IOException e){
System.out.println(e);
}
}
else if (property=="contentadmin") {
BufferedReader b = null;
try {
b= new BufferedReader(new FileReader("ContAdmin.txt"));
while((line=b.readLine())!=null)
{
if(!line.isEmpty())
count++;
if (line.equals(name+ " "+username+" "+" "+password))
System.out.println("Found user" +name+ "in line"+count+1);
}
b.close();
}
catch(IOException e){
System.out.println(e);
}
}
else if (property=="customer") {
BufferedReader b = null;
try {
b= new BufferedReader(new FileReader("Customers.txt"));
while((line=b.readLine())!=null){
if(!line.isEmpty())
count++;
if (line.equals(name+ " "+username+" "+" "+password))
System.out.println("Found user" +name+ "in line"+count+1);
}
b.close();
}
catch(IOException e){
System.out.println(e);
}
}
}
// Users us = new Admins();
public void viewAllUsers()
{
System.out.println("Here you can view all users!");
}
public void registerAdmin()
{
System.out.println("Here you can register!");
try {
System.out.println("\n What you want to do :1)Create User 2)Update User 3) Delete User 4)Search User 5) View Users ");
Scanner input = new Scanner(System.in);
int choice = input.nextInt();
Users us = new Users();
switch(choice)
{
case 1: createUser(getName(),getUsername(),getPass());
break;
case 2: updateUser();
break;
case 3: deleteUser();
break;
case 4: searchUser(us);
break;
case 5: viewAllUsers();
break;
}
}
catch(ArithmeticException e) {
System.out.println("Arithmetic Exception!");
}
finally {
System.out.println("ok");
}
}
}
| true |
733549a0ab1aa521b871116c41f5c6add371c5d4 | Java | amitrai7/DelhiTourGuide | /app/src/main/java/com/example/android/tourguide/Information.java | UTF-8 | 3,252 | 2.4375 | 2 | [] | no_license | package com.example.android.tourguide;
import android.os.Parcel;
import android.os.Parcelable;
public class Information implements Parcelable {
private String placeName;
private String nearestMetro;
private String distanceFromMetro;
private int placeImageResourceID;
private String phoneNo;
private String address;
private String palaceDiscription;
public Information(String placeName, String nearestMetro, String distanceFromMetro, int placeImageResourceID,
String phoneNo, String address, String palaceDiscription) {
this.placeName = placeName;
this.nearestMetro = nearestMetro;
this.distanceFromMetro = distanceFromMetro;
this.placeImageResourceID = placeImageResourceID;
this.phoneNo = phoneNo;
this.address = address;
this.palaceDiscription = palaceDiscription;
}
protected Information(Parcel in) {
placeName = in.readString();
nearestMetro = in.readString();
distanceFromMetro = in.readString();
placeImageResourceID = in.readInt();
phoneNo = in.readString();
address = in.readString();
palaceDiscription = in.readString();
}
public static final Creator<Information> CREATOR = new Creator<Information>() {
@Override
public Information createFromParcel(Parcel in) {
return new Information(in);
}
@Override
public Information[] newArray(int size) {
return new Information[size];
}
};
public String getPlaceName() {
return placeName;
}
public String getNearestMetro() {
return nearestMetro;
}
public String getDistanceFromMetro() {
return distanceFromMetro;
}
public int getPlaceImageResourceID() {
return placeImageResourceID;
}
public String getPhoneNo() {
return phoneNo;
}
public String getAddress() {
return address;
}
public String getPalaceDiscription() {
return palaceDiscription;
}
public void setPlaceName(String placeName) {
this.placeName = placeName;
}
public void setNearestMetro(String nearestMetro) {
this.nearestMetro = nearestMetro;
}
public void setDistanceFromMetro(String distanceFromMetro) {
this.distanceFromMetro = distanceFromMetro;
}
public void setPlaceImageResourceID(int placeImageResourceID) {
this.placeImageResourceID = placeImageResourceID;
}
public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
public void setAddress(String address) {
this.address = address;
}
public void setPalaceDiscription(String palaceDiscription) {
this.palaceDiscription = palaceDiscription;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(placeName);
dest.writeString(nearestMetro);
dest.writeString(distanceFromMetro);
dest.writeInt(placeImageResourceID);
dest.writeString(phoneNo);
dest.writeString(address);
dest.writeString(palaceDiscription);
}
}
| true |
75f7b5268819e9606a11152095b9fd04165f02b1 | Java | arunma/YunaktiTestProject | /firstPackage/TestClass.java | UTF-8 | 1,107 | 2.859375 | 3 | [] | no_license | package firstPackage;
import java.util.Date;
import firstPackage.subFolder.MainClass;
@TC(classUnderTest = "firstPackage.subFolder.MainClass", helperClasses = "")
public class TestClass {
private String name;
private String address;
private int number;
MainClass main;
public TestClass(){
main=new MainClass();
}
public TestClass(String name){
this.name = name;
}
public TestClass(int number){
this.number = number;
}
@MUT(methodUnderTest = "mySecondMethod()")
public String testString(Date tmpDate){
Date current = new Date();
main.mySecondMethod();
//TestClass2 tmpClass2 = new TestClass2();
// String tmpString = tmpClass2.testString();
printLine(new String("Just for testing"));
double d = Math.PI;
for(int i = 0; i < Math.PI; i ++){
System.out.println("Test ====> " + i);
while(i >= 1){
switch(i){
case 1:
new Date();
case 2:
new Date();
default:
System.out.println("Default switch");
}
}
}
return "test";
}
private String printLine(String tmp){
return tmp;
}
}
| true |
f07200a99bf82fa9627a4b1c471e91092446d824 | Java | 2445896255/SoftwareTest | /softwareTest/test/com/unit/TestMyClass.java | UTF-8 | 3,808 | 3.1875 | 3 | [] | no_license | package com.unit;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
public class TestMyClass {
MyClass myClass;
@Before
public void init()
{
myClass=new MyClass();
}
/**
* int getGCD(int num1, int num2)
* 1.num1<0,num2>0
* 2.num1<0,num2<0
* 3.num1>0,num2>0
*/
@Test
public void testGCD1()
{
Assert.assertEquals(3,myClass.getGCD(-3,6));
}
@Test
public void testGCD2()
{
Assert.assertEquals(3,myClass.getGCD(-6,-3));
}
@Test
public void testGCD3()
{
Assert.assertEquals(1,myClass.getGCD(2,3));
}
/**
* lcm(int num1, int num2)
* num1>0,num2>0
*/
@Test
public void testLcm1()
{
Assert.assertEquals(24,myClass.lcm(8,6));
}
/**
* boolean isPrimeNum(int n)
* 是
* 不是
*/
@Test
public void testPrime1()
{
assertTrue(myClass.isPrimeNum(7));
}
@Test
public void testPrime2()
{
assertFalse(myClass.isPrimeNum(8));
}
/**
* boolean isLeapYear(int year)
* 是
* 不是
*/
@Test
public void testLeapYear1()
{
assertTrue(myClass.isLeapYear(2000));
}
@Test
public void testLeapYear2()
{
assertFalse(myClass.isLeapYear(2001));
}
/**
* boolean containsString(String father,String child)
* father null
* child null
* 包含
* 不包含
*/
@Test(expected = NullPointerException.class)
public void testContains1()
{
myClass.containsString(null,"child");
}
@Test(expected = NullPointerException.class)
public void testContains2()
{
myClass.containsString("father",null);
}
@Test
public void testContains3()
{
assertTrue(myClass.containsString("children","child"));
}
@Test
public void testContains4()
{
assertFalse(myClass.containsString("father","child"));
}
/**
* boolean IsPalindrome1(String A)
* null
* 是
* 不是
*/
@Test(expected = NullPointerException.class)
public void testPalindrome1()
{
myClass.IsPalindrome1(null);
}
@Test
public void testPalindrome2()
{
assertTrue(myClass.IsPalindrome1("abcba"));
}
@Test
public void testPalindrome3()
{
assertFalse(myClass.IsPalindrome1("abcb"));
}
/**
* String reverseString(String str)
*/
@Test
public void testReverse()
{
Assert.assertEquals("gnirts",myClass.reverseString("string"));
}
/**
* boolean selfDividing(int n)
* 是
* 不是
*/
@Test
public void testDivide1()
{
assertTrue(myClass.selfDividing(128));
}
@Test
public void testDivide2()
{
assertFalse(myClass.selfDividing(129));
}
/**
*int fib(int N)
* =1
* >1
*/
@Test
public void testFib1()
{
Assert.assertEquals(1,myClass.fib(1));
}
@Test
public void testFib2()
{
Assert.assertEquals(13,myClass.fib(7));
}
/**
* boolean isHappy(int n)
* 是
* 不是
*/
@Test
public void testHappy1()
{
assertTrue(myClass.isHappy(19));
}
@Test
public void testHappy2()
{
assertFalse(myClass.isHappy(21));
}
/**
* String addBinary(String a, String b)
* 有溢出
* 无溢出
*/
@Test
public void testBinary1()
{
Assert.assertEquals("111",myClass.addBinary("110","001"));
}
@Test
public void testBinary2()
{
Assert.assertEquals("1011",myClass.addBinary("110","101"));
}
}
| true |
a5e16acd3feb056f1a97be2800f41dec46f0d6c4 | Java | JorgeAlcarazKuv/EjerciciosAsignaturaProgramacion | /Tema3/Ejercicio02.java | UTF-8 | 530 | 3.390625 | 3 | [] | no_license | /*
Ejercicio 2 Tema 3
@author Jorge Alcaraz Bravo
*/
public class Ejercicio02 { //es readLine en realidad, y probando deberia ser mayus
public static void main(String[] args) {
double factorConversion = 166.386;
System.out.println("Introduce los euros a convertir: ");
double euros = Double.parseDouble(System.console().readLine());
System.out.printf("%.2f euros son %.0f pesetas", euros, (int)euros*factorConversion);
}
}
//Casting de Double a int:
//int variable = (int)(Integer.parseInt(euros*factorconversion);
| true |
c5ee7c0f434d2be1d2327512ba15b0ab361e0a64 | Java | ShiAnni/SE2 | /client/src/main/java/businesslogic/fundbl/BankAccount.java | UTF-8 | 4,035 | 2.453125 | 2 | [] | no_license | package businesslogic.fundbl;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* @author LIUXUANLIN
*/
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.ArrayList;
import businesslogic.CommonBusinessLogic;
import config.RMIConfig;
import dataservice.funddataservice.BankAccountDataService;
import po.BankAccountPO;
import state.ConfirmState;
import state.FindTypeAccount;
import state.ResultMessage;
import vo.BankAccountVO;
/**
*
* @author Ann
* @version 创建时间:2015年12月3日 下午3:34:01
*/
public class BankAccount implements CommonBusinessLogic<BankAccountPO>{
public final static String BLNAME="BankAccount";
private BankAccountDataService bankAccountData;
public BankAccount() throws MalformedURLException, RemoteException, NotBoundException {
bankAccountData = getData();
}
public BankAccountDataService getData() throws MalformedURLException, RemoteException, NotBoundException {
return (BankAccountDataService) Naming.lookup(RMIConfig.PREFIX + BankAccountDataService.NAME);
}
public ConfirmState confirmOperation() {
return ConfirmState.CONFIRM;
}
public String getID() throws RemoteException {
return bankAccountData.getID();
}
public ArrayList<BankAccountVO> show() throws RemoteException {
ArrayList<BankAccountPO> bankaccounts = bankAccountData.find();
return FundTrans.convertBankAccountPOstoVOs(bankaccounts);
}
public ResultMessage add(BankAccountPO po) throws RemoteException {
return bankAccountData.add(po);
}
public BankAccountPO delete(String ID) throws RemoteException {
return bankAccountData.delete(ID);
}
public BankAccountPO modify(BankAccountPO po) throws RemoteException {
return bankAccountData.modify(po);
}
/**
* 模糊查找账户
*
* @param keywords
* String型,关键字
* @param type
* FindTypeAccount型,查找类型
* @return ArrayList<BankAccountVO>型,符合条件的账户
* @throws RemoteException
* 远程异常
*/
public ArrayList<BankAccountVO> find(String keywords, FindTypeAccount type) throws RemoteException {
ArrayList<BankAccountPO> pos = this.findByType(keywords, type);
ArrayList<BankAccountVO> vos = FundTrans.convertBankAccountPOstoVOs(pos);
return vos;
}
/**
* 按照选择的类型查找关键字
*
* @author Ann
* @see FindTypeAccount#toMethodName(FindTypeAccount)
* @see BankAccountPO#toString()
* @see BankAccountPO#getID()
* @see BankAccountPO#getName()
* @see BankAccountPO#getMoneyString()
* @param keywords
* 关键字
* @param type
* 查找类型,包括ID,帐户名,余额 type为NULL时进行模糊查询
* @return 符合条件的BankAccountPO数组
* @throws RemoteException
*/
private ArrayList<BankAccountPO> findByType(String keywords, FindTypeAccount type) throws RemoteException {
ArrayList<BankAccountPO> pos = bankAccountData.find();
ArrayList<BankAccountPO> returnpos = new ArrayList<>();
try {
for (BankAccountPO bankAccountPO : pos) {
// 获得每个bankAccountPO的类
Class<?> bankAccountPOClass = bankAccountPO.getClass();
// 根据type类型获得方法
String methodName = FindTypeAccount.toMethodName(type);
Method method = bankAccountPOClass.getDeclaredMethod(methodName);
// 调用bankAccountPO的方法获得要查找的字段
String message = (String) method.invoke(bankAccountPO);
// 统一小写进行查询
if (message.toLowerCase().contains(keywords.toLowerCase()))
returnpos.add(bankAccountPO);
}
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
}
return returnpos;
}
}
| true |
647cead9ec7b29aa32649a4254b32778bafda637 | Java | HubertYoung/AcFun | /acfun5_7/src/main/java/io/reactivex/internal/operators/flowable/FlowableSingleMaybe.java | UTF-8 | 2,822 | 2.265625 | 2 | [] | no_license | package io.reactivex.internal.operators.flowable;
import io.reactivex.Flowable;
import io.reactivex.FlowableSubscriber;
import io.reactivex.Maybe;
import io.reactivex.MaybeObserver;
import io.reactivex.disposables.Disposable;
import io.reactivex.internal.fuseable.FuseToFlowable;
import io.reactivex.internal.subscriptions.SubscriptionHelper;
import io.reactivex.plugins.RxJavaPlugins;
import org.reactivestreams.Subscription;
public final class FlowableSingleMaybe<T> extends Maybe<T> implements FuseToFlowable<T> {
final Flowable<T> a;
static final class SingleElementSubscriber<T> implements FlowableSubscriber<T>, Disposable {
final MaybeObserver<? super T> a;
Subscription b;
boolean c;
T d;
SingleElementSubscriber(MaybeObserver<? super T> maybeObserver) {
this.a = maybeObserver;
}
public void onSubscribe(Subscription subscription) {
if (SubscriptionHelper.validate(this.b, subscription)) {
this.b = subscription;
this.a.onSubscribe(this);
subscription.request(Long.MAX_VALUE);
}
}
public void onNext(T t) {
if (!this.c) {
if (this.d != null) {
this.c = true;
this.b.cancel();
this.b = SubscriptionHelper.CANCELLED;
this.a.onError(new IllegalArgumentException("Sequence contains more than one element!"));
return;
}
this.d = t;
}
}
public void onError(Throwable th) {
if (this.c) {
RxJavaPlugins.a(th);
return;
}
this.c = true;
this.b = SubscriptionHelper.CANCELLED;
this.a.onError(th);
}
public void onComplete() {
if (!this.c) {
this.c = true;
this.b = SubscriptionHelper.CANCELLED;
Object obj = this.d;
this.d = null;
if (obj == null) {
this.a.onComplete();
} else {
this.a.onSuccess(obj);
}
}
}
public void dispose() {
this.b.cancel();
this.b = SubscriptionHelper.CANCELLED;
}
public boolean isDisposed() {
return this.b == SubscriptionHelper.CANCELLED;
}
}
public FlowableSingleMaybe(Flowable<T> flowable) {
this.a = flowable;
}
protected void b(MaybeObserver<? super T> maybeObserver) {
this.a.a(new SingleElementSubscriber(maybeObserver));
}
public Flowable<T> t_() {
return RxJavaPlugins.a(new FlowableSingle(this.a, null));
}
}
| true |
a66118920c27494f5b488c103799e0b66cc8734d | Java | gordo0195/Text--Finder | /src/arbolstring/LlamadaDocx.java | UTF-8 | 2,062 | 2.609375 | 3 | [] | no_license | /*
* 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 arbolstring;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import java.io.*;
/**
*
* @author Gordo_0195
*/
public class LlamadaDocx {
public static void main(String[] args) throws InvalidFormatException{
ArbolString Principal = new ArbolString();
File Archivo;
String referencia = "";
XWPFWordExtractor extractor;
XWPFDocument document;
String texto_extraido;
try{
Archivo = new File("C:\\Users\\Marco\\Dropbox\\documentos\\Indígena.docx");
referencia = Archivo.getName();
FileInputStream file = new FileInputStream(Archivo.getPath());
document = new XWPFDocument(OPCPackage.open(file));
extractor = new XWPFWordExtractor(document);
texto_extraido = extractor.getText();
String text = texto_extraido.toLowerCase();
System.out.println(text);
String[] words = text.split("\\s+");
for (int i = 0; i < words.length; i++) {
words[i] = words[i].replaceAll("[^\\w]", "");
}
for(int i = 0; i < (words.length)-1; i++){
words[i] = words[i].replaceAll("[^\\w]", "");
//System.out.println(words[i]);
Principal.addNode(words[i], referencia);
}
}catch(IOException e){
System.out.println(e);
}Principal.traverseInOrder();
}
}
| true |
509cf63ee410529d100dbe58c00075b8505cdc1e | Java | mnishom/OperatorAndMath | /src/contoh/kelasB/Penugasan.java | UTF-8 | 397 | 2.84375 | 3 | [] | no_license | package contoh.kelasB;
public class Penugasan {
static double sum(double... nilai){
double d = nilai[0];
for (int i = 1; i < nilai.length; i++) {
d += nilai[i];
}
return d;
}
public static void main(String[] args) {
double jumlah = sum(1,2,3,4,5,6,7,78.9,90.9,98);
System.out.println(""+jumlah);
}
}
| true |
cd9e2a3313e49198e8210263fa6dc065bb2f45f1 | Java | ClementBonnefoy/ChessMusic | /chessboard/src/sml/elements/Body.java | UTF-8 | 1,228 | 2.828125 | 3 | [] | no_license | package sml.elements;
import sml.interfaces.IInstruction;
import sml.interfaces.ISMLElement;
import sml.interfaces.IVisitor;
public class Body implements ISMLElement {
private IInstruction instruction;
private Body next;
public Body(IInstruction instruction, Body next) {
super();
this.instruction = instruction;
this.next = next;
}
public int getTime(Declarations environnement) {
int res=instruction.getTime(environnement);
res+=(next!=null)?next.getTime(environnement):0;
return res;
}
@Override
public void accept(IVisitor visitor) {
visitor.visit(this);
instruction.accept(visitor);
if(next!=null)
next.accept(visitor);
}
@Override
public String toString(){
StringBuilder bd=new StringBuilder();
bd.append(instruction.toString());
if(next!=null){
bd.append(";");
bd.append(next.toString());
}
return bd.toString();
}
public boolean isATempoInstruction(){
return instruction instanceof Tempo;
}
public IInstruction getInstruction() {
return instruction;
}
public Body getNext() {
return next;
}
public int size() {
if(instruction instanceof Play)
return 1+(next==null?0:next.size());
return (next==null?0:next.size());
}
}
| true |
4e9b3b6069d2b8a1355d421c14b5fa1a8d877770 | Java | casperenghuus/6878 | /Gene4x/ARACNE/src/org/geworkbench/util/associationdiscovery/clusterlogic/ClusterPanel.java | UTF-8 | 3,381 | 2.34375 | 2 | [] | no_license | package org.geworkbench.util.associationdiscovery.clusterlogic;
import javax.swing.*;
import java.awt.*;
/**
* <p>Title: Plug And Play</p>
* <p>Description: Dynamic Proxy Implementation of enGenious</p>
* <p>Copyright: Copyright (c) 2002</p>
* <p>Company: First Genetic Trust Inc.</p>
*
* @author Manjunath Kustagi
* @version 1.0
*/
public class ClusterPanel extends JPanel {
JLabel jLabel1 = new JLabel();
public JTextField jEntropyThr = new JTextField();
JLabel jLabel2 = new JLabel();
public JTextField jSigmaX = new JTextField();
GridBagLayout gridBagLayout1 = new GridBagLayout();
JScrollPane jScrollPane1 = new JScrollPane();
public DefaultListModel scoreList = new DefaultListModel();
JList jScores = new JList(scoreList);
JLabel jLabel3 = new JLabel();
public JTextField jPseudoX = new JTextField();
public ClusterPanel() {
this.setName(getComponentName());
try {
jbInit();
} catch (Exception ex) {
ex.printStackTrace();
}
}
void jbInit() throws Exception {
jLabel1.setText("Entropy Threshold:");
this.setLayout(gridBagLayout1);
jEntropyThr.setPreferredSize(new Dimension(63, 21));
jEntropyThr.setText("0.5");
jEntropyThr.setHorizontalAlignment(SwingConstants.TRAILING);
jLabel2.setHorizontalAlignment(SwingConstants.RIGHT);
jLabel2.setText("Sigma x:");
jSigmaX.setText("3.0");
jSigmaX.setHorizontalAlignment(SwingConstants.TRAILING);
jScrollPane1.setBorder(BorderFactory.createLoweredBevelBorder());
jLabel3.setText("Pseudo Count:");
jLabel3.setHorizontalAlignment(SwingConstants.RIGHT);
jPseudoX.setHorizontalAlignment(SwingConstants.TRAILING);
jPseudoX.setText("1.0");
this.add(jLabel1, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 5, 0, 5), 0, 0));
this.add(jEntropyThr, new GridBagConstraints(1, 0, 1, 1, 0.2, 0.0, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(4, 0, 0, 0), 0, 0));
this.add(jScrollPane1, new GridBagConstraints(2, 0, 1, 5, 0.5, 1.0, GridBagConstraints.NORTHEAST, GridBagConstraints.BOTH, new Insets(4, 4, 4, 4), 0, 0));
jScrollPane1.getViewport().add(jScores, null);
this.add(jLabel2, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.SOUTH, GridBagConstraints.BOTH, new Insets(0, 5, 0, 5), 0, 0));
this.add(jSigmaX, new GridBagConstraints(1, 1, 1, 1, 0.3, 0.0, GridBagConstraints.NORTHEAST, GridBagConstraints.BOTH, new Insets(2, 0, 2, 0), 0, 0));
this.add(jLabel3, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 4), 0, 0));
this.add(jPseudoX, new GridBagConstraints(1, 2, 1, 1, 0.2, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(2, 0, 2, 0), 41, 0));
}
public JComponent[] getVisualComponents(String areaName) {
JComponent[] panels = null;
if (areaName.equalsIgnoreCase("CommandArea")) {
panels = new JComponent[1];
panels[0] = this;
}
return panels;
}
public String getComponentName() {
return "Cluster Logic";
}
}
| true |
95c5af33dc82891b16204666218963eb3c5d6ffa | Java | BasRegi/CSFightClub | /src/test/TestCMD.java | UTF-8 | 13,183 | 2.65625 | 3 | [] | no_license | package test;
import java.util.ArrayList;
import java.util.Scanner;
import data.BattleData;
import data.Card;
import data.GameData;
import data.LobbyData;
import data.Minion;
import events.EventTrigger;
import events.EventUtil;
public class TestCMD extends Thread {
private GameData gameData;
private BattleData batData;
private EventTrigger eventTrigger;
private Scanner in = new Scanner(System.in);
private ArrayList<Card> oppoSelectableMinion = new ArrayList<Card>();
private ArrayList<Card> mySelectableMinion = new ArrayList<Card>();
private ArrayList<Card> mySelectableCard = new ArrayList<Card>();
private boolean registerReady = false;
private boolean loginReady = false;
public TestCMD(GameData gameData, EventTrigger eventTrigger){
this.gameData = gameData;
this.batData = gameData.getBattleData();
this.eventTrigger = eventTrigger;
}
public void run(){
System.out.println("test CMD running");
while (!gameData.sysGameEnd){
switch (gameData.currentScene) {
case GameData.WELCOME_PAGE:
welcome();
break;
case GameData.HOME_PAGE:
home();
break;
case GameData.BATTLE_PAGE:
battle();
break;
case GameData.LOBBY_PAGE:
lobby();
break;
case GameData.CANVAS_PAGE:
canvs();
break;
case GameData.COLLECTION_PAGE:
collection();
break;
case GameData.CHARACTOR_PAGE:
charactor();
break;
case GameData.STORE_PAGE:
store();
break;
}
if (gameData.sysGameEnd) System.out.println("Game should end!");
}
}
private void welcome() {
System.out.println("################################################");
System.out.println("# Welcome Page #");
System.out.println("################################################");
System.out.println("Input 'q' anytime if you wanna exit");
System.out.print("Username : ");
String username = in.nextLine();
if (username.equals("q")) eventTrigger.myInput("exit");
else eventTrigger.myInput("changeBoxUsername", username);
EventUtil.sleep(200);
System.out.print("Password : ");
String password = in.nextLine();
if (password.equals("q")) eventTrigger.myInput("exit");
else eventTrigger.myInput("changeBoxPassword", password);
EventUtil.sleep(200);
System.out.println("Press <Enter> to login (or input anything to register)");
String input = in.nextLine();
if (input.equals("q")) eventTrigger.myInput("exit");
else if (input.equals("")) eventTrigger.myInput("login", username, password);
else eventTrigger.myInput("register", username, password);
//System.out.println("Checking");
gameData.sysLockGUI = true;
while (gameData.sysLockGUI) {
EventUtil.sleep(500);
//System.out.print(".");
}
if (gameData.currentScene == GameData.WELCOME_PAGE){
System.out.println("The username or the password is incorrect");
}
}
private void home() {
System.out.println("################################################");
System.out.println("# Home Page #");
System.out.println("################################################");
System.out.println("# Input 'q' anytime if you wanna exit #");
System.out.println("# 0. Single Battle #");
System.out.println("# 1. Lobby #");
System.out.println("# 2. Collection #");
System.out.println("# 3. Canvas #");
System.out.println("# 4. Settings #");
System.out.println("# 5. Exit #");
System.out.println("################################################");
System.out.print("Input : ");
String input = in.nextLine();
if (input.equals("q") || input.equals("5")) {
eventTrigger.myInput("exit");
} else if (input.equals("1")){
System.out.print("HOST : ");
String host = in.nextLine();
if (host.equals("q")) {
eventTrigger.myInput("exit");
EventUtil.sleep(500);
return;
}
System.out.print("PORT : ");
String port = in.nextLine();
if (port.equals("q")) {
eventTrigger.myInput("exit");
EventUtil.sleep(500);
return;
}
eventTrigger.myInput("clickLobby", host, port);
} else if (input.equals("2")) {
eventTrigger.myInput("clickCollection" );
} else if (input.equals("3")) {
eventTrigger.myInput("clickCanvas" );
} else if (input.equals("4")) {
eventTrigger.myInput("clickSettings" );
} else if (input.equals("0")) {
eventTrigger.myInput("clickSingle");
}
EventUtil.sleep(500);
}
private void battle() {
System.out.println("########################################");
System.out.println("# Battle #");
System.out.println("########################################");
batData.battleEnd = false;
//wait for battle initialisation
System.out.print("Loading");
while (!batData.myTurn && !batData.oppoTurn) {
System.out.print(".");
EventUtil.sleep(500);
}
System.out.println("\nBattle Start!");
while (!batData.battleEnd) {
EventUtil.sleep(1000);
showBoardStatus();
while (!batData.battleEnd) {
EventUtil.sleep(1000);
if (batData.myTurn) {
while (batData.myTurn) {
showMyInfo();
showSelectableStuff();
showOptions();
String input;
switch (getNumberInput(5)){
case -1: // input==q
eventTrigger.myInput("giveUp");
eventTrigger.myInput("exit");
break;
case 0: // TODO select card
if (mySelectableCard.size()==0) System.out.println("No card available...");
int cardIndex = getNumberInput(mySelectableCard.size());
eventTrigger.myInput("selectCard", String.valueOf(
batData.myHand.indexOf(mySelectableCard.get(cardIndex))));
break;
case 1: // TODO select Minion
System.out.print("0.my / 1.oppo INPUT : ");
input = in.nextLine();
if (input.equals("0")){
if (mySelectableMinion.size()==0) {
System.out.println("No minion available...");
break;
}
int minionIndex = getNumberInput(mySelectableMinion.size());
eventTrigger.myInput("selectMinion", String.valueOf(
batData.myMinions.indexOf(mySelectableMinion.get(minionIndex))));
} else if (input.equals("1")){
if (oppoSelectableMinion.size()==0) {
System.out.println("No minion available...");
break;
}
int minionIndex = getNumberInput(oppoSelectableMinion.size());
eventTrigger.myInput("selectMinion", String.valueOf(
batData.oppoMinions.indexOf(oppoSelectableMinion.get(minionIndex))));
}
break;
case 2: // TODO select face
System.out.print("0.my / 1.oppo INPUT : ");
input = in.nextLine();
if (input.equals("0")){
if (!batData.myFaceSelectable) {
System.out.println("You can not touch your face");
break;
}
eventTrigger.myInput("selectMyFace");
} else if (input.equals("1")){
if (!batData.oppoFaceSelectable) {
System.out.println("You can not touch your opponent's face");
break;
}
eventTrigger.myInput("selectOppoFace");
}
break;
case 3: // TODO Pass
eventTrigger.myInput("nextRound");
break;
case 4: // TODO Surrender
eventTrigger.myInput("giveUp");
break;
}
EventUtil.sleep(1000);
}
break;
} else if (batData.oppoTurn ){
// TODO if AI is ready, just wait
if (gameData.sysAIReady){
EventUtil.sleep(50);
} else {
// TODO show some info of me
// TODO show all oppo info, cards on his hand, minions, and options
// TODO choose option, select card or minions to do something
// FUCK just nextRound...
eventTrigger.aiInput("nextRound");
break;
}
}
}
}
}
private void showBoardStatus(){
System.out.println("============= Board Status =============");
System.out.println("my deck opponent deck");
System.out.println(batData.myDeck.size()+" "+batData.oppoDeck.size());
System.out.println("\nmy minions opponent minions");
for (int i=0; i<Math.max(batData.myMinions.size(), batData.oppoMinions.size()); i++){
if (i<batData.myMinions.size()) System.out.print(batData.myMinions.get(i)+"\t\t\t");
else System.out.print("\t\t\t\t\t\t");
if (i<batData.oppoMinions.size()) System.out.print(batData.oppoMinions.get(i));
}
}
private void showMyInfo(){
System.out.println("\nOpponent Health:"+batData.oppoHP+"\tMana:"+batData.oppoMana);
System.out.println("\nPlayer Health:"+batData.myHP+"\tMana:"+batData.myMana);
for (int i=0; i<batData.myMinions.size(); i++){
System.out.println("Minion("+i+")\t"+batData.myHand.get(i)+"\n");
}
for (int i=0; i<batData.myHand.size(); i++){
System.out.println("Hand("+i+")\t"+batData.myHand.get(i)+"\n");
}
}
private void showSelectableStuff() {
oppoSelectableMinion.clear();
for (Card minionCard : batData.oppoMinions){
if (minionCard.selectable) oppoSelectableMinion.add(minionCard);
}
if (!oppoSelectableMinion.isEmpty()){
System.out.println("== Opponent Selectable Minions ==");
for (int i=0; i<oppoSelectableMinion.size(); i++){
System.out.println(i+"\t:\t"+oppoSelectableMinion.get(i));
}
}else{
System.out.println("No Selectable Opponent Minions");
}
mySelectableMinion.clear();
for (Card minionCard : batData.myMinions){
if (minionCard.selectable) mySelectableMinion.add(minionCard);
}
if (!mySelectableMinion.isEmpty()) {
System.out.println("== My Selectable Minions ==");
for (int i=0; i<mySelectableMinion.size(); i++){
System.out.println(i+"\t:\t"+mySelectableMinion.get(i));
}
} else {
System.out.println("No selectable Minion");
}
mySelectableCard.clear();
for (Card card : batData.myHand){
if (card.selectable) mySelectableCard.add(card);
}
if (!mySelectableCard.isEmpty()) {
System.out.println("== My Selectable Cards ==");
for (int i=0; i<mySelectableCard.size(); i++){
System.out.println(i+"\t:\t"+mySelectableCard.get(i));
}
} else {
System.out.println("No Selectable Card");
}
if (batData.myFaceSelectable) System.out.println("!! You may select your face");
if (batData.oppoFaceSelectable) System.out.println("!! You may select your opponent's face");
}
private void showOptions(){
System.out.println("==== Options ====");
System.out.println(" 0. Select Card");
System.out.println(" 1. Select Minion");
System.out.println(" 2. Select (My or opponent's)Face");
System.out.println(" 3. Pass");
System.out.println(" 4. Surrender");
}
private void lobby() {
System.out.println("########################################");
System.out.println("# Lobby #");
System.out.println("########################################");
LobbyData lobData = gameData.getLobbyData();
int msgTotal = lobData.messageHistory.size();
while (gameData.currentScene == GameData.LOBBY_PAGE) {
while (msgTotal < lobData.messageHistory.size()) {
int msgHistorySize = lobData.messageHistory.size();
for (int i=msgTotal; i<msgHistorySize; i++){
System.out.println(lobData.messageHistory.get(i));
}
msgTotal = lobData.messageHistory.size();
}
EventUtil.sleep(500);
System.out.print("MESSAGE : ");
String message = in.nextLine();
if (message.equals("q")) {
eventTrigger.myInput("back");
while (gameData.currentScene == GameData.LOBBY_PAGE) EventUtil.sleep(50);
break;
}
System.out.print("RECEIVE : ");
String receiver = in.nextLine();
if (receiver.equals("q")) {
eventTrigger.myInput("back");
while (gameData.currentScene == GameData.LOBBY_PAGE) EventUtil.sleep(50);
break;
}
if (receiver.equals("")) receiver = null;
eventTrigger.myInput("sendMessage", receiver, message);
}
}
private void canvs() {
// TODO Auto-generated method stub
}
private void collection() {
// TODO Auto-generated method stub
}
private void charactor() {
// TODO Auto-generated method stub
}
private void store() {
// TODO Auto-generated method stub
}
private int getNumberInput(int n) {
if (n<=0) return -1;
while (true){
System.out.print("INPUT (0.."+(n-1)+") : ");
String input = in.nextLine();
if (input == "q") return -1;
try{
int choice = Integer.valueOf(input);
if (choice>=0 && choice<n) return choice;
}catch (Exception e){
System.out.println(" INVALID INPUT!! ");
}
}
}
}
| true |
f93abfd6320f472acadd79c0da2eed1524cab6fe | Java | autumnharmony/oographplus | /openoffice-addon/src/main/java/ru/ssau/graphplus/PageHelper.java | UTF-8 | 8,991 | 1.835938 | 2 | [] | no_license | /*************************************************************************
*
* The Contents of this file are made available subject to the terms of
* the BSD license.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
* 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.
* 3. Neither the name of Sun Microsystems, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "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 THE
* COPYRIGHT OWNER 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.
*
*************************************************************************/
package ru.ssau.graphplus;
// __________ Imports __________
import com.sun.star.awt.Size;
import com.sun.star.beans.XPropertySet;
import com.sun.star.drawing.*;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.XServiceInfo;
import com.sun.star.presentation.XHandoutMasterSupplier;
import com.sun.star.presentation.XPresentationPage;
import com.sun.star.uno.UnoRuntime;
public class PageHelper {
// __________ static helper methods __________
// __________ draw pages __________
/**
* get the page count for standard pages
*/
static public int getDrawPageCount(XComponent xComponent) {
XDrawPagesSupplier xDrawPagesSupplier =
(XDrawPagesSupplier) UnoRuntime.queryInterface(
XDrawPagesSupplier.class, xComponent);
XDrawPages xDrawPages = xDrawPagesSupplier.getDrawPages();
return xDrawPages.getCount();
}
/**
* get draw page by index
*/
static public XDrawPage getDrawPageByIndex(XComponent xComponent, int nIndex)
throws com.sun.star.lang.IndexOutOfBoundsException,
com.sun.star.lang.WrappedTargetException {
XDrawPagesSupplier xDrawPagesSupplier =
(XDrawPagesSupplier) UnoRuntime.queryInterface(
XDrawPagesSupplier.class, xComponent);
XDrawPages xDrawPages = xDrawPagesSupplier.getDrawPages();
return (XDrawPage) UnoRuntime.queryInterface(XDrawPage.class, xDrawPages.getByIndex(nIndex));
}
/**
* creates and inserts a draw page into the giving position,
* the method returns the new created page
*/
static public XDrawPage insertNewDrawPageByIndex(XComponent xComponent, int nIndex)
throws Exception {
XDrawPagesSupplier xDrawPagesSupplier =
(XDrawPagesSupplier) UnoRuntime.queryInterface(
XDrawPagesSupplier.class, xComponent);
XDrawPages xDrawPages = xDrawPagesSupplier.getDrawPages();
return xDrawPages.insertNewByIndex(nIndex);
}
/**
* removes the given page
*/
static public void removeDrawPage(XComponent xComponent, XDrawPage xDrawPage) {
XDrawPagesSupplier xDrawPagesSupplier =
(XDrawPagesSupplier) UnoRuntime.queryInterface(
XDrawPagesSupplier.class, xComponent);
XDrawPages xDrawPages = xDrawPagesSupplier.getDrawPages();
xDrawPages.remove(xDrawPage);
}
/**
* get size of the given page
*/
static public Size getPageSize(XDrawPage xDrawPage)
throws com.sun.star.beans.UnknownPropertyException,
com.sun.star.lang.WrappedTargetException {
XPropertySet xPageProperties = (XPropertySet)
UnoRuntime.queryInterface(XPropertySet.class, xDrawPage);
return new Size(
((Integer) xPageProperties.getPropertyValue("Width")).intValue(),
((Integer) xPageProperties.getPropertyValue("Height")).intValue());
}
// __________ master pages __________
/**
* get the page count for master pages
*/
static public int getMasterPageCount(XComponent xComponent) {
XMasterPagesSupplier xMasterPagesSupplier =
(XMasterPagesSupplier) UnoRuntime.queryInterface(
XMasterPagesSupplier.class, xComponent);
XDrawPages xDrawPages = xMasterPagesSupplier.getMasterPages();
return xDrawPages.getCount();
}
/**
* get master page by index
*/
static public XDrawPage getMasterPageByIndex(XComponent xComponent, int nIndex)
throws com.sun.star.lang.IndexOutOfBoundsException,
com.sun.star.lang.WrappedTargetException {
XMasterPagesSupplier xMasterPagesSupplier =
(XMasterPagesSupplier) UnoRuntime.queryInterface(
XMasterPagesSupplier.class, xComponent);
XDrawPages xDrawPages = xMasterPagesSupplier.getMasterPages();
return (XDrawPage) UnoRuntime.queryInterface(XDrawPage.class, xDrawPages.getByIndex(nIndex));
}
/**
* creates and inserts a new master page into the giving position,
* the method returns the new created page
*/
static public XDrawPage insertNewMasterPageByIndex(XComponent xComponent, int nIndex) {
XMasterPagesSupplier xMasterPagesSupplier =
(XMasterPagesSupplier) UnoRuntime.queryInterface(
XMasterPagesSupplier.class, xComponent);
XDrawPages xDrawPages = xMasterPagesSupplier.getMasterPages();
return xDrawPages.insertNewByIndex(nIndex);
}
/**
* removes the given page
*/
static public void removeMasterPage(XComponent xComponent, XDrawPage xDrawPage) {
XMasterPagesSupplier xMasterPagesSupplier =
(XMasterPagesSupplier) UnoRuntime.queryInterface(
XMasterPagesSupplier.class, xComponent);
XDrawPages xDrawPages = xMasterPagesSupplier.getMasterPages();
xDrawPages.remove(xDrawPage);
}
/**
* return the corresponding masterpage for the giving drawpage
*/
static public XDrawPage getMasterPage(XDrawPage xDrawPage) {
XMasterPageTarget xMasterPageTarget =
(XMasterPageTarget) UnoRuntime.queryInterface(
XMasterPageTarget.class, xDrawPage);
return xMasterPageTarget.getMasterPage();
}
/**
* sets given masterpage at the drawpage
*/
static public void setMasterPage(XDrawPage xDrawPage, XDrawPage xMasterPage) {
XMasterPageTarget xMasterPageTarget =
(XMasterPageTarget) UnoRuntime.queryInterface(
XMasterPageTarget.class, xDrawPage);
xMasterPageTarget.setMasterPage(xMasterPage);
}
// __________ presentation pages __________
/**
* test if a Presentation Document is supported.
* This is important, because only presentation documents
* have notes and handout pages
*/
static public boolean isImpressDocument(XComponent xComponent) {
XServiceInfo xInfo = (XServiceInfo) UnoRuntime.queryInterface(
XServiceInfo.class, xComponent);
return xInfo.supportsService("com.sun.star.presentation.PresentationDocument");
}
/**
* in impress documents each normal draw page has a corresponding notes page
*/
static public XDrawPage getNotesPage(XDrawPage xDrawPage) {
XPresentationPage aPresentationPage =
(XPresentationPage) UnoRuntime.queryInterface(
XPresentationPage.class, xDrawPage);
return aPresentationPage.getNotesPage();
}
/**
* in impress each documents has one handout page
*/
static public XDrawPage getHandoutMasterPage(XComponent xComponent) {
XHandoutMasterSupplier aHandoutMasterSupplier =
(XHandoutMasterSupplier) UnoRuntime.queryInterface(
XHandoutMasterSupplier.class, xComponent);
return aHandoutMasterSupplier.getHandoutMasterPage();
}
}
| true |
ec1c7df9e1a18bfc4ba393bfad06ef4c1f8ee13f | Java | jelford/Please | /tests/test/gennedcode/PrimitiveArguments.java | UTF-8 | 1,935 | 2.328125 | 2 | [] | no_license | package test.gennedcode;
import gen.elford.james.please.Please;
import gen.elford.james.please.PleaseInterface;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
public class PrimitiveArguments {
private PleaseInterface please;
private test.candidates.PrimitiveArguments cut;
@Before
public void setUp() {
this.please = new Please();
cut = new test.candidates.PrimitiveArguments();
}
@After
public void tearDown() {
this.please = null;
cut = null;
}
@Test
public void testCanHandlePrimitiveByte() {
byte expected = 1;
byte ret = please.call(cut).buyte(expected);
assertThat(ret, is(equalTo(expected)));
}
@Test
public void testCanHandlePrimitiveShort() {
short expected = 1;
short ret = please.call(cut).suret(expected);
assertThat(ret, is(equalTo(expected)));
}
@Test
public void testCanHandlePrimitiveInt() {
int expected = 1;
int ret = please.call(cut).innt(expected);
assertThat(ret, is(equalTo(expected)));
}
@Test
public void testCanHandlePrimitiveLong() {
long expected = 1;
long ret = please.call(cut).lorng(expected);
assertThat(ret, is(equalTo(expected)));
}
@Test
public void testCanHandlePrimitiveFloat() {
float expected = 1.0f;
float ret = please.call(cut).flote(expected);
assertThat(ret, is(equalTo(expected)));
}
@Test
public void testCanHandlePrimitiveDouble() {
double expected = 1.0;
double ret = please.call(cut).dubul(expected);
assertThat(ret, is(equalTo(expected)));
}
@Test
public void testCanHandlePrimitiveBoolean() {
boolean expected = true;
boolean ret = please.call(cut).booleighan(expected);
assertThat(ret, is(equalTo(expected)));
}
@Test
public void testCanHandlePrimitiveChar() {
char expected = 'b';
char ret = please.call(cut).charr(expected);
assertThat(ret, is(equalTo(expected)));
}
}
| true |
f8f28f3b71a6e018fc2655e8a7a96e7861582e7c | Java | ajithmemana/My-Demo-Projects | /NewsReader/src/com/qburst/newsreader/api/GetNewsApi.java | UTF-8 | 1,936 | 2.015625 | 2 | [] | no_license | package com.qburst.newsreader.api;
import java.util.Map;
import android.util.Log;
import com.qburst.newsreader.api.beans.response.News_ParseResponseBean;
import com.qburst.newsreader.api.beans.request.News_ParseRequestBean;
import com.qburst.newsreader.interfaces.NRApiListener;
import com.qburst.newsreader.interfaces.NRExceptionApiListener;
import com.qburst.newsreader.interfaces.NewsListener;
public class GetNewsApi extends NRBaseApi implements NRApiListener {
private NewsListener _listener;
public GetNewsApi(NewsListener listener,
NRExceptionApiListener exceptionListener) {
this._listener = listener;
this._excptnListener = exceptionListener;
}
public void getMenuDetails(String sessionId) {
News_ParseRequestBean requestBean = new News_ParseRequestBean();
if (_listener != null) {
_listener.requestDidStart();
}
NRBaseWebService service = new NRBaseWebService(this,
requestBean.toJsonString(), News_ParseResponseBean.class,
baseUrl());
service.setAuthenticationParams("qburst", "qburst");
service.execute(baseUrl());
}
@Override
public String baseUrl() {
return super.baseUrl();
}
@Override
public void onResponseReceived(Map<String, Object> response) {
Log.i("RESPONSE", response.toString());
if (_listener != null) {
_listener.requestDidFinish();
}
if (response.containsKey(NRApiConstants.kSuccessMsgKey)) {
News_ParseResponseBean respBean = (News_ParseResponseBean) response
.get(NRApiConstants.kSuccessMsgKey);
if (respBean != null) {
Log.v("respbean", "" + respBean);
_listener.receivednewsapi(respBean);
}
} else if (response.containsKey(NRApiConstants.kApiFailedMsgKey)) {
if (response.containsKey("HttpStatus")) {
if (_listener != null) {
_listener.errorInResponse();
}
}
}
}
@Override
public void onFailedToGetResponse(Map<String, Object> errorResponse) {
// TODO Auto-generated method stub
}
}
| true |
9efa822ae4f7402f134a30818ccb0147484cd895 | Java | stevejhkang/algorithm-quiz | /project_folder/src/boj_may/BOJ_2636.java | UTF-8 | 4,293 | 2.9375 | 3 | [
"MIT"
] | permissive | package boj_may;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class BOJ_2636 {
private static int r;
private static int c;
private static int[][] map;
private static boolean[][] visit;
private static Queue<dot> static_queue = new LinkedList<>();
private static int time = 0;
private static int before = 0;
private static int[] dy = {0, 1, 0, -1};
private static int[] dx = {1, 0, -1, 0};
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer stringTokenizer =new StringTokenizer(bufferedReader.readLine());
r = Integer.parseInt(stringTokenizer.nextToken());
c = Integer.parseInt(stringTokenizer.nextToken());
map = new int[r + 1][c + 1];
for (int i = 1; i <= r; i++) {
stringTokenizer= new StringTokenizer(bufferedReader.readLine());
for (int j = 1; j <= c; j++) {
map[i][j] = Integer.parseInt(stringTokenizer.nextToken());
}
}
while (true) {
visit = new boolean[r + 1][c + 1];
init();
for (int i = 1; i <= r; i++) {
for (int j = 1; j <= c; j++) {
if (map[i][j] == 1 && Edge(i, j)) {
Queue<dot> queue = new LinkedList<>();
queue.add(new dot(i, j));
visit[i][j] = true;
while (!queue.isEmpty()) {
dot point = queue.poll();
if (Edge(point.y, point.x)) {
map[point.y][point.x] = 2;
static_queue.add(new dot(point.y, point.x));
}
for (int dir = 0; dir < 4; dir++) {
int ny = point.y + dy[dir];
int nx = point.x + dx[dir];
if(ny<=0||ny>r&&nx<=0||nx>c) continue;
if (map[ny][nx] == 1 && !visit[ny][nx]) {
queue.add(new dot(ny, nx));
visit[ny][nx] = true;
}
}
}
}
}
}
if (static_queue.isEmpty()) break;
before = static_queue.size();
while (!static_queue.isEmpty()) {
dot point = static_queue.poll();
map[point.y][point.x] = -1;
}
time++;
}
System.out.println(time + "\n" + before);
}
private static boolean Edge(int y, int x) {
for (int dir = 0; dir < 4; dir++) {
int ny = y + dy[dir];
int nx = x + dx[dir];
// if(ny<=0||ny>r||nx<=0||nx>c) return false;
if (map[ny][nx] == -1) {
return true;
}
}
return false;
}
private static void init() {
Queue<dot> queue = new LinkedList<>();
boolean[][] visited = new boolean[r + 1][c + 1];
queue.add(new dot(1, 1));
map[1][1] = -1;
visited[1][1] = true;
while (!queue.isEmpty()) {
dot point = queue.poll();
for (int i = 0; i < 4; i++) {
int ny = point.y + dy[i];
int nx = point.x + dx[i];
if(ny<=0||ny>r||nx<=0||nx>c) continue;
// System.out.println(ny+","+nx);
if (!visited[ny][nx]
&& map[ny][nx] <= 0) {
map[ny][nx] = -1;
visited[ny][nx] = true;
queue.add(new dot(ny, nx));
}
}
}
}
static class dot {
private int y;
private int x;
public dot(int y, int x) {
this.y = y;
this.x = x;
}
}
} | true |
16581833b6dd4198cab35afa2c12c90e9f425336 | Java | cpbentley/pasa_cbentley_swing | /src/pasa/cbentley/swing/widgets/b/BTextNote.java | UTF-8 | 1,313 | 2.046875 | 2 | [
"MIT"
] | permissive | package pasa.cbentley.swing.widgets.b;
import javax.swing.JTextArea;
import pasa.cbentley.core.src4.ctx.UCtx;
import pasa.cbentley.core.src4.logging.Dctx;
import pasa.cbentley.swing.ctx.SwingCtx;
import pasa.cbentley.swing.imytab.IMyGui;
public class BTextNote extends JTextArea implements IMyGui {
private String key;
private SwingCtx sc;
public BTextNote(SwingCtx sc, String key) {
super(2, 3);
this.sc = sc;
this.key = key;
setBackground(null);
setEditable(false);
setBorder(null);
setLineWrap(true);
setWrapStyleWord(true);
setFocusable(false);
}
public void guiUpdate() {
if (key != null) {
this.setText(sc.getResString(key));
}
}
//#mdebug
public String toString() {
return Dctx.toString(this);
}
public void toString(Dctx dc) {
dc.root(this, "BTextNote");
toStringPrivate(dc);
}
public String toString1Line() {
return Dctx.toString1Line(this);
}
private void toStringPrivate(Dctx dc) {
}
public void toString1Line(Dctx dc) {
dc.root1Line(this, "BTextNote");
toStringPrivate(dc);
}
public UCtx toStringGetUCtx() {
return sc.getUCtx();
}
//#enddebug
}
| true |
d04a43fbf78b2f451593032a35a99aab2c901835 | Java | iantal/AndroidPermissions | /apks/playstore_apps/com_ubercab/source/cmi.java | UTF-8 | 742 | 1.9375 | 2 | [
"GPL-1.0-or-later",
"Apache-2.0"
] | permissive | import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.View;
public abstract class cmi
{
private cmj a;
private int b;
private int c;
cmi() {}
abstract Surface a();
abstract void a(int paramInt);
void a(int paramInt1, int paramInt2) {}
void a(cmj paramCmj)
{
this.a = paramCmj;
}
abstract View b();
void b(int paramInt1, int paramInt2)
{
this.b = paramInt1;
this.c = paramInt2;
}
abstract Class c();
abstract boolean d();
protected void e()
{
this.a.a();
}
SurfaceHolder f()
{
return null;
}
Object g()
{
return null;
}
int h()
{
return this.b;
}
int i()
{
return this.c;
}
}
| true |
2917a4b539b901ad8ca350a36510783e754714f6 | Java | LuisMesquita/android-quantoprima | /app/src/main/java/br/com/mobiclub/quantoprima/ui/activity/AboutMobiClubActivity.java | UTF-8 | 2,992 | 2.09375 | 2 | [
"Apache-2.0"
] | permissive | package br.com.mobiclub.quantoprima.ui.activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.squareup.otto.Subscribe;
import br.com.mobiclub.quantoprima.R;
import br.com.mobiclub.quantoprima.events.NavItemSelectedEvent;
import br.com.mobiclub.quantoprima.domain.Constants;
import br.com.mobiclub.quantoprima.ui.factory.AlertDialogFactory;
public class AboutMobiClubActivity extends MenuActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
protected Fragment createFragment() {
return new AboutFragment();
}
@Subscribe
@Override
public void onNavigationItemSelected(NavItemSelectedEvent event) {
super.onNavigationItemSelectedImpl(event);
}
public void onSite(View view) {
navigateToUrl(Constants.URLMobiClub.SITE, getString(R.string.web_view_site_sao_braz_title));
}
@Override
protected void onDestroy() {
super.onDestroy();
}
private void navigateToUrl(String url, String title) {
if(!isConnected(true)) {
AlertDialog defaultError = AlertDialogFactory.createDefaultError(this, R.string.alert_title_attention,
R.string.alert_title_webview_no_connection);
defaultError.setCancelable(true);
defaultError.show();
return;
}
Intent browserIntent = new Intent(this, WebViewActivity.class);
browserIntent.putExtra(Constants.Extra.WEB_VIEW_URL, url);
browserIntent.putExtra(Constants.Extra.WEB_VIEW_TITLE, title);
startActivity(browserIntent);
}
public void onFacebook(View view) {
navigateToUrl(Constants.URLMobiClub.FANPAGE_FACEBOOK, getString(R.string.web_view_facebook_title));
}
public void onTwitter(View view) {
navigateToUrl(Constants.URLMobiClub.FANPAGE_TWITTER, getString(R.string.web_view_twitter_title));
}
public void onInstagram(View view) {
navigateToUrl(Constants.URLMobiClub.FANPAGE_INSTAGRAM, getString(R.string.web_view_instagram_title));
}
public void onEvaluate(View view) {
navigateToUrl(Constants.URLMobiClub.AVALIE_NA_PLAY_STORE, getString(R.string.web_view_avalie_na_play_store_title));
}
public void onIndicate(View view) {
navigateToUrl(Constants.URLMobiClub.INDIQUE_LOJA, getString(R.string.web_view_indique_loja_title));
}
public static class AboutFragment extends Fragment {
public AboutFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_about_mobiclub, container, false);
}
}
}
| true |
9ba13460ecfdf6a6456b44409ee3eea9807fb8bf | Java | JetBrains/intellij-community | /java/testFramework/src/com/intellij/testFramework/fixtures/impl/JavaTestFixtureFactoryImpl.java | UTF-8 | 1,871 | 2.015625 | 2 | [
"Apache-2.0"
] | permissive | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.testFramework.fixtures.impl;
import com.intellij.testFramework.LightProjectDescriptor;
import com.intellij.testFramework.builders.JavaModuleFixtureBuilder;
import com.intellij.testFramework.fixtures.*;
import org.jetbrains.annotations.NotNull;
public final class JavaTestFixtureFactoryImpl extends JavaTestFixtureFactory {
public JavaTestFixtureFactoryImpl() {
IdeaTestFixtureFactory.getFixtureFactory().registerFixtureBuilder(JavaModuleFixtureBuilder.class, MyJavaModuleFixtureBuilderImpl.class);
}
@Override
public JavaCodeInsightTestFixture createCodeInsightFixture(IdeaProjectTestFixture projectFixture) {
return new JavaCodeInsightTestFixtureImpl(projectFixture, new TempDirTestFixtureImpl());
}
@Override
public JavaCodeInsightTestFixture createCodeInsightFixture(IdeaProjectTestFixture projectFixture, TempDirTestFixture tempDirFixture) {
return new JavaCodeInsightTestFixtureImpl(projectFixture, tempDirFixture);
}
@Override
public TestFixtureBuilder<IdeaProjectTestFixture> createLightFixtureBuilder(@NotNull String name) {
return new LightTestFixtureBuilderImpl<>(new LightIdeaTestFixtureImpl(ourJavaProjectDescriptor, name));
}
public static class MyJavaModuleFixtureBuilderImpl extends JavaModuleFixtureBuilderImpl<ModuleFixture> {
public MyJavaModuleFixtureBuilderImpl(@NotNull TestFixtureBuilder<? extends IdeaProjectTestFixture> testFixtureBuilder) {
super(testFixtureBuilder);
}
@NotNull
@Override
protected ModuleFixture instantiateFixture() {
return new ModuleFixtureImpl(this);
}
}
private static final LightProjectDescriptor ourJavaProjectDescriptor = LightJavaCodeInsightFixtureTestCase.JAVA_1_6;
}
| true |
b85861212c98121e35f3d30c28954c981034dffc | Java | prodrigestivill/jmus | /src/ist/mus/comm/GameData.java | UTF-8 | 7,945 | 2.28125 | 2 | [] | no_license | /*
* Created on May 11, 2005
*
* Copyright 2005 Pau Rodriguez-Estivill <prodrigestivill@yahoo.es>
*
* This software is licensed under the GNU General Public License.
* See http://www.gnu.org/copyleft/gpl.html for details.
*/
package ist.mus.comm;
import ist.mus.baraja.Baraja40;
import ist.mus.baraja.Carta;
import ist.mus.baraja.Cartas;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
/**
* @author Pau Rodriguez-Estivill
*/
public class GameData {
public final static int ver = 1;
public static boolean isGameData(Packet pkt) {
if (pkt.getProperty("GameName") == null
|| pkt.getProperty("Version") == null)
return false;
if (pkt.getProperty("GameName").toString().equalsIgnoreCase("JMus")
&& (((Integer) pkt.getProperty("Version")).intValue() == ver))
return true;
else
return false;
}
int accion = 0; /* Manda boton pulsado junto con lo complementario */
boolean addme = false;
int aposta = 0;
int apostaval = 0;
Cartas cartas = null;
int evento = 0; /* Evento como vamos a pequenyas i demas */
JID from = null;
String idcartas = null; /* Destino de cartas: usar D para descartar */
String mano = null;
int puntospor = -1;
int puntos[] = { -1, -1 };
int senyas = 0; /* Manda senyas */
boolean wakeup = false;
/**
*
*/
public GameData() {
super();
clear();
}
public GameData(Packet p) {
this();
fillFromPacket(p);
}
public boolean isEmpty() {
return senyas == 0 && accion == 0 && aposta == 0 && apostaval == 0
&& !wakeup && cartas == null && idcartas == null
&& mano == null && evento == 0 && !addme && puntos[0] == -1
&& puntos[1] == -1;
}
public void clear() {
from = null;
senyas = 0;
accion = 0;
aposta = 0;
apostaval = 0;
wakeup = false;
cartas = null;
idcartas = null;
mano = null;
evento = 0;
addme = false;
puntospor = -1;
puntos[0] = -1;
puntos[1] = -1;
}
public void fillFromPacket(Packet pkt) {
Carta c = null;
int k;
clear();
from = new JID(pkt.getFrom());
//Comprueva Version
if (isGameData(pkt)) {
//Coje los datos
if (pkt.getProperty("Accion") != null)
accion = ((Integer) pkt.getProperty("Accion")).intValue();
if (pkt.getProperty("AddMe") != null)
addme = true;
if (pkt.getProperty("Aposta") != null)
aposta = ((Integer) pkt.getProperty("Aposta")).intValue();
if (pkt.getProperty("ApostaVal") != null)
apostaval = ((Integer) pkt.getProperty("ApostaVal")).intValue();
if (pkt.getProperty("Evento") != null)
evento = ((Integer) pkt.getProperty("Evento")).intValue();
if (pkt.getProperty("Mano") != null)
mano = ((String) pkt.getProperty("Mano"));
if (pkt.getProperty("Sena") != null)
senyas = ((Integer) pkt.getProperty("Sena")).intValue();
if (pkt.getProperty("WakeUp") != null)
wakeup = true;
if (pkt.getProperty("PuntosPor") != null)
puntospor = ((Integer) pkt.getProperty("PuntosPor")).intValue();
if (pkt.getProperty("Puntos0") != null
&& pkt.getProperty("Puntos1") != null) {
puntos[0] = ((Integer) pkt.getProperty("Puntos0")).intValue();
puntos[1] = ((Integer) pkt.getProperty("Puntos1")).intValue();
}
//Cartas
try {
if (pkt.getProperty("Cartas") != null
&& pkt.getProperty("IdCartas") != null) {
cartas = new Cartas();
idcartas = (String) pkt.getProperty("IdCartas");
for (k = 0; k < ((Integer) pkt.getProperty("Cartas"))
.intValue(); k++)
if (pkt.getProperty("Carta_" + k) != null) {
c = (Carta) Baraja40.getHM().get(
(String) pkt.getProperty("Carta_" + k));
if (c instanceof Carta)
cartas.add(c);
}
}
} catch (Exception e) {
cartas = null;
idcartas = null;
}
}
}
public Packet fillToPacket() {
return fillToPacket(Comunicacion.getComm().createPacket());
}
Packet fillToPacket(Packet pkt) {
int k;
/* Marca el paquete conforme es del juego */
pkt.setProperty("GameName", "JMus");
pkt.setProperty("Version", ver);
/* Copia solo las variables establecidas */
if (accion != 0)
pkt.setProperty("Accion", accion);
if (addme)
pkt.setProperty("AddMe", 1);
if (aposta != 0)
pkt.setProperty("Aposta", aposta);
if (apostaval != 0)
pkt.setProperty("ApostaVal", apostaval);
if (evento != 0)
pkt.setProperty("Evento", evento);
if (mano != null)
pkt.setProperty("Mano", mano);
if (senyas != 0)
pkt.setProperty("Sena", senyas);
if (wakeup)
pkt.setProperty("WakeUp", 1);
if (puntospor != -1)
pkt.setProperty("PuntosPor", puntospor);
if (puntos[0] != -1 && puntos[1] != -1) {
pkt.setProperty("Puntos0", puntos[0]);
pkt.setProperty("Puntos1", puntos[1]);
}
//Cartas
if (cartas != null && idcartas != null) {
pkt.setProperty("IdCartas", idcartas);
pkt.setProperty("Cartas", cartas.size());
for (k = 0; k < cartas.size(); k++)
pkt.setProperty("Carta_" + k, ((Carta) cartas.get(k))
.toString());
}
return pkt;
}
public Packet fillToPacket(String to) {
Packet pkt = new Message();
pkt.setTo(to);
return fillToPacket(pkt);
}
public int getAccion() {
return accion;
}
public boolean getAddMe() {
return addme;
}
public int getAposta() {
return aposta;
}
public int getApostaVal() {
return apostaval;
}
public Cartas getCartas() {
return cartas;
}
public int getEvento() {
return evento;
}
public JID getFrom() {
return from;
}
public String getIdCartas() {
return idcartas;
}
public String getMano() {
return mano;
}
public int[] getPuntos() {
if (puntos[0] == -1 || puntos[0] == -1)
return null;
return puntos;
}
public int getPuntosPor() {
return puntospor;
}
public int getSena() {
return senyas;
}
public boolean getWake() {
return wakeup;
}
public void setAccion(int a) {
accion = a;
}
public void setAddMe(boolean o) {
addme = o;
}
public void setAposta(int a, int val) {
aposta = a;
apostaval = val;
}
public void setCartas(Cartas c, String ic) {
cartas = c;
idcartas = ic;
}
public void setEvento(int e) {
evento = e;
}
public void setMano(String m) {
mano = m;
}
public void setPuntos(int p0, int p1) {
if (p0 == -1 || p1 == -1)
return;
puntos[0] = p0;
puntos[1] = p1;
}
public void setPuntosPor(int pp) {
puntospor = pp;
}
public void setSena(int s) {
senyas = s;
}
public void setWake(boolean w) {
wakeup = w;
}
}
| true |
3419fb4aa19be8eb814254973a5625f7d3204cf0 | Java | nikskonda/library-back-end | /service/src/main/java/by/bntu/fitr/converter/user/OrderDtoConverter.java | UTF-8 | 771 | 2.28125 | 2 | [] | no_license | package by.bntu.fitr.converter.user;
import by.bntu.fitr.converter.AbstractDtoConverter;
import by.bntu.fitr.dto.user.order.OrderDto;
import by.bntu.fitr.model.user.order.Order;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class OrderDtoConverter extends AbstractDtoConverter<Order, OrderDto> {
@Autowired
public OrderDtoConverter(ModelMapper modelMapper) {
super(modelMapper);
}
@Override
public OrderDto convertToDto(Order entity) {
return modelMapper.map(entity, OrderDto.class);
}
@Override
public Order convertFromDto(OrderDto dto) {
return modelMapper.map(dto, Order.class);
}
}
| true |
c0ea7c783d0b66b1c56afdc7782b86aca6ccb4f5 | Java | bellmit/mescep | /src/main/java/com/mes/old/meta/RTransportationTime.java | UTF-8 | 489 | 1.78125 | 2 | [] | no_license | package com.mes.old.meta;
// Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final
/**
* RTransportationTime generated by hbm2java
*/
public class RTransportationTime implements java.io.Serializable {
private RTransportationTimeId id;
public RTransportationTime() {
}
public RTransportationTime(RTransportationTimeId id) {
this.id = id;
}
public RTransportationTimeId getId() {
return this.id;
}
public void setId(RTransportationTimeId id) {
this.id = id;
}
}
| true |
45ac9a57b3a5c5b6bdc98dbcb0a344902e2b88cd | Java | PMalaniouk/JDBC | /src/jdbc/DatabaseConnection.java | UTF-8 | 7,396 | 2.390625 | 2 | [] | no_license | /*
* 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 JDBC;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author whb108
* @version 0.1
* @since Feb 17, 2020 3:09:49 PM
*
*/
/** MODIFICATION LOG
Feb 17, 2020 Initial file creation at 3:09:49 PM
*/
public abstract class DatabaseConnection
{
// SQL Statements
public static final String strSQLGETAllAUTHOR = "Select count(isbn) as 'Paul Dietal' from authorisbn where authorid = 2";
public static final String strSQLGETALLCOPYRIGHT = "Select Copyright, Count(Copyright) from Titles Group by Copyright";
public static final String strSQLGETJAVAPRICE = "Select * from Titles";
public static final String strSQLGETNEWINFO = "Insert into Titles(isbn, title, editionNumber, copyright, publisherID,imagefile) "
+ " Values ('9780786838653', 'The Lightning Thief', '1', '2006', '1', 'jh.jpg','200.95')";
private Connection myConnection;
public abstract Connection connectToDB(String strDriverName,
String strUserName, String strPassword,String strDatabaseLocation)
throws ClassNotFoundException, SQLException;
public void closeConnection()
{
try {
getMyConnection().close();
} catch (SQLException ex) {
Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, ex);
}
}
public Connection connectAndSave(String strDriverName,
String strUserName, String strPassword,String strDatabaseLocation) throws ClassNotFoundException, SQLException
{
setMyConnection(connectToDB(strDriverName,
strUserName,
strPassword,
strDatabaseLocation));
return getMyConnection();
}// connectAndSave
/*
public final ResultSet getAllAuthor()
{
ResultSet rsReturn = null;
try
{
Connection cTemp = getMyConnection();
if (cTemp != null)
{
Statement stmtGetAllAuthor = cTemp.createStatement();
rsReturn = stmtGetAllAuthor.executeQuery(strSQLGETAllAUTHOR);
}
}
catch (SQLException ex)
{
Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, ex);
}
return rsReturn;
}// getAllAuthors
public final ResultSet getAllCopyright()
{
ResultSet rsReturn = null;
try
{
Connection cTemp = getMyConnection();
if (cTemp != null)
{
Statement stmtGetAllCopyright = cTemp.createStatement();
rsReturn = stmtGetAllCopyright.executeQuery(strSQLGETALLCOPYRIGHT);
}
}
catch (SQLException ex)
{
Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, ex);
}
return rsReturn;
}// getAllcopyright count
*/
public final ResultSet getAllJavaPrice()
{
ResultSet rsReturn = null;
try
{
Connection cTemp = getMyConnection();
if (cTemp != null)
{
Statement stmtGetAllJavaPrice = cTemp.createStatement();
rsReturn = stmtGetAllJavaPrice.executeQuery(strSQLGETJAVAPRICE);
}
}
catch (SQLException ex)
{
Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, ex);
}
return rsReturn;
}// getpriceupdate
public final ResultSet getAllNewInfo()
{
ResultSet rsReturn = null;
try
{
Connection cTemp = getMyConnection();
if (cTemp != null)
{
Statement stmtGetAllCopyright = cTemp.createStatement();
rsReturn = stmtGetAllCopyright.executeQuery(strSQLGETNEWINFO);
}
}
catch (SQLException ex)
{
Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, ex);
}
return rsReturn;
}
public String getConnectionMetaData() throws SQLException
{
Connection cnTemp = getMyConnection();
StringBuilder sbOut = new StringBuilder();
DatabaseMetaData dmdTemp = cnTemp.getMetaData();
sbOut.append("Database MetaData:\n");
sbOut.append("Product Name = " + dmdTemp.getDatabaseProductName() + "\n");
sbOut.append("Product Version = " + dmdTemp.getDatabaseProductVersion());
return sbOut.toString();
} // getConnectionMetaData
/**
* @return the myConnection
*/
public Connection getMyConnection() {
return myConnection;
}
/**
* @param myConnection the myConnection to set
*/
public void setMyConnection(Connection myConnection) {
this.myConnection = myConnection;
}
public String getResultSetMetaData(ResultSet rsIn)
{
if (rsIn != null)
{
StringBuilder sbReturn = new StringBuilder();
ResultSetMetaData rsMD;
try
{
rsMD = rsIn.getMetaData();
if(rsMD != null)
{
sbReturn.append("The ResultSet has " + rsMD.getColumnCount() + " columns:\n");
int intNumCols = rsMD.getColumnCount();
for (int nLCV = 1; nLCV <= intNumCols; nLCV++)
{
// TODO: Add code to display column information
sbReturn.append("Class Name - " + rsMD.getColumnClassName(nLCV));
sbReturn.append("\n");
sbReturn.append("Column Label - " + rsMD.getColumnLabel(nLCV));
sbReturn.append("\n");
sbReturn.append("Column Name - " + rsMD.getColumnName(nLCV));
sbReturn.append("\n");
sbReturn.append("Column Type - " + rsMD.getColumnType(nLCV));
sbReturn.append("\n");
sbReturn.append("Column Type Name - " + rsMD.getColumnTypeName(nLCV));
sbReturn.append("\n\n");
} // for
while(rsIn.next() == true)
{
for (int nLCV = 1; nLCV <= intNumCols; nLCV++)
{
switch(rsMD.getColumnType(nLCV)) {
case 4:
sbReturn.append(rsMD.getColumnLabel(nLCV) +
" = " + rsIn.getInt(nLCV));
sbReturn.append("\n");
break;
case 12:
sbReturn.append(rsMD.getColumnLabel(nLCV) +
" = " + rsIn.getString(nLCV));
sbReturn.append("\n");
break;
default:
sbReturn.append("Column " + nLCV + "type number is " + rsMD.getColumnType(nLCV));
sbReturn.append("\n");
} // switch
} // for
sbReturn.append("\n\n");
} // while
}// if rsMD is not null
} catch (SQLException ex)
{
sbReturn.append(ex.getLocalizedMessage());
// Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, ex);
}
return sbReturn.toString();
}
return "";
}// getResultSetMetaData
}// class DatabaseConnection | true |
879a401467ce0e0ffc6159abd279cc11c00360b9 | Java | kr-pound/Weather-Android-Studio | /Weather/app/src/main/java/data/WeatherHttpClient.java | UTF-8 | 1,808 | 2.578125 | 3 | [] | no_license | package data;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import Util.Utils;
public class WeatherHttpClient {
public String getWeatherData(String place) {
HttpURLConnection connection = null;
InputStream inputStream = null;
try {
String id = Utils.BASE_URL + place + Utils.BASE_ID_CODE;
connection = (HttpURLConnection) (new URL(id)).openConnection(); //connect to API link
//connection = (HttpURLConnection) (new URL("https://api.openweathermap.org/data/2.5/weather?q=Bangkok&appid=0dc2282cddca5c4ae08e93149b576aa4")).openConnection();
//connection = (HttpURLConnection) (new URL("https://www.google.co.th/")).openConnection();
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.setDoInput(true);
connection.connect();
Log.d("myClient", "ID: " + Utils.BASE_ID_CODE);
//Read the response
StringBuffer stringBuffer = new StringBuffer();
inputStream = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = null;
Log.d("myClient", Utils.BASE_URL + place + Utils.BASE_ID_CODE);
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line + "\r\n");
}
inputStream.close();
connection.disconnect();
return stringBuffer.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
| true |
a5f8b90401d0f60c2f9cf1abba7db44c690512fe | Java | juldrixx/MangAnime_Desktop | /src/controlers/ControlerMediaUnit.java | UTF-8 | 7,493 | 2.203125 | 2 | [] | no_license | package controlers;
import java.awt.Color;
import java.awt.Desktop;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import javax.swing.AbstractAction;
import javax.swing.Icon;
import components.API;
import components.Media;
import i18n.Constants;
import i18n.Messages;
import jiconfont.icons.font_awesome.FontAwesome;
import jiconfont.swing.IconFontSwing;
import models.ModelMedia;
import utils.TypeMedia;
import views.ViewMediaUnit;
public class ControlerMediaUnit {
private API api;
private Media media;
private ModelMedia modelMedia;
public ViewMediaUnit view;
public ControlerMediaUnit(TypeMedia type, API api, Media media, ModelMedia modelMedia) {
this.api = api;
this.media = media;
this.modelMedia = modelMedia;
this.view = new ViewMediaUnit();
MouseListenerLastViewed mouseListenerLastViewed = new MouseListenerLastViewed();
this.view.labelLastViewed.addMouseListener(mouseListenerLastViewed);
ActionLastViewedEdition actionLastViewedEdition = new ActionLastViewedEdition();
this.view.buttonLastViewed.setAction(actionLastViewedEdition);
MouseListenerActionState mouseListenerActionState = new MouseListenerActionState();
this.view.actionState.addMouseListener(mouseListenerActionState);
MouseListenerActionURL mouseListenerActionURL = new MouseListenerActionURL();
this.view.actionURL.addMouseListener(mouseListenerActionURL);
MouseListenerActionUnfollow mouseListenerActionUnfollow = new MouseListenerActionUnfollow();
this.view.actionUnfollow.addMouseListener(mouseListenerActionUnfollow);
MouseListenerHoverUnit mouseListenerHoverUnit = new MouseListenerHoverUnit();
this.view.addMouseListener(mouseListenerHoverUnit);
}
public class MouseListenerHoverUnit implements MouseListener {
public MouseListenerHoverUnit() {
// TODO Auto-generated constructor stub
}
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent e) {
view.setBackground(new Color(50, 50, 50));
}
@Override
public void mouseExited(MouseEvent e) {
view.setBackground(Color.decode("#212529"));
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
}
public class MouseListenerActionUnfollow implements MouseListener {
public MouseListenerActionUnfollow() {
// TODO Auto-generated constructor stub
}
@Override
public void mouseClicked(MouseEvent e) {
if(api.unfollowMedia((media.getId()))) {
modelMedia.removeMedia(media);
}
}
@Override
public void mouseEntered(MouseEvent e) {
Icon icon = IconFontSwing.buildIcon(FontAwesome.TRASH, 25, Color.WHITE);
view.actionUnfollow.setIcon(icon);
}
@Override
public void mouseExited(MouseEvent e) {
Icon icon = IconFontSwing.buildIcon(FontAwesome.TRASH, 25, Color.decode("#554b4b"));
view.actionUnfollow.setIcon(icon);
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
}
public class MouseListenerActionURL implements MouseListener {
public MouseListenerActionURL() {
// TODO Auto-generated constructor stub
}
@Override
public void mouseClicked(MouseEvent e) {
String url = media.getUrl();
if(Desktop.isDesktopSupported()){
Desktop desktop = Desktop.getDesktop();
try {
desktop.browse(new URI(url));
} catch (IOException | URISyntaxException err) {
// TODO Auto-generated catch block
err.printStackTrace();
}
}else{
Runtime runtime = Runtime.getRuntime();
try {
runtime.exec("xdg-open " + url);
} catch (IOException err) {
// TODO Auto-generated catch block
err.printStackTrace();
}
}
}
@Override
public void mouseEntered(MouseEvent e) {
Icon icon = IconFontSwing.buildIcon(FontAwesome.LINK, 25, Color.WHITE);
view.actionURL.setIcon(icon);
}
@Override
public void mouseExited(MouseEvent e) {
Icon icon = IconFontSwing.buildIcon(FontAwesome.LINK, 25, Color.decode("#13a1ff"));
view.actionURL.setIcon(icon);
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
}
public class MouseListenerActionState implements MouseListener {
public MouseListenerActionState() {
// TODO Auto-generated constructor stub
}
@Override
public void mouseClicked(MouseEvent e) {
Media m = api.updateMedia(media.getMedia_id(), media.getRelease_number());
if(m != null) {
media = m;
modelMedia.updateMedia(media);
}
}
@Override
public void mouseEntered(MouseEvent e) {
IconFontSwing.register(FontAwesome.getIconFont());
if (!media.isCompleted()) {
Icon icon = IconFontSwing.buildIcon(FontAwesome.TIMES, 25, new Color(255, 255, 255));
view.actionState.setIcon(icon);
}
else {
Icon icon = IconFontSwing.buildIcon(FontAwesome.CHECK, 25, new Color(255, 255, 255));
view.actionState.setIcon(icon);
}
}
@Override
public void mouseExited(MouseEvent e) {
IconFontSwing.register(FontAwesome.getIconFont());
if (!media.isCompleted()) {
Icon icon = IconFontSwing.buildIcon(FontAwesome.TIMES, 25, Color.decode("#d10531"));
view.actionState.setIcon(icon);
}
else {
Icon icon = IconFontSwing.buildIcon(FontAwesome.CHECK, 25, Color.decode("#0dab76"));
view.actionState.setIcon(icon);
}
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
}
@SuppressWarnings("serial")
public class ActionLastViewedEdition extends AbstractAction {
public ActionLastViewedEdition() {
this.putValue(NAME, Messages.RESOURCE_BUNDLE.getString(Constants.OK));
}
@Override
public void actionPerformed(ActionEvent e) {
Media m = api.updateMedia(media.getMedia_id(), Double.parseDouble((view.ftfLastViewed.getText())));
if(m != null) {
media = m;
modelMedia.updateMedia(media);
}
view.panelLastViewed.remove(view.panelLastViewedEdition);
view.panelLastViewed.add(view.labelLastViewed);
view.repaint();
view.revalidate();
}
}
public class MouseListenerLastViewed implements MouseListener {
public MouseListenerLastViewed() {
// TODO Auto-generated constructor stub
}
@Override
public void mouseClicked(MouseEvent e) {
view.panelLastViewed.remove(view.labelLastViewed);
view.panelLastViewed.add(view.panelLastViewedEdition);
view.repaint();
view.revalidate();
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
}
}
| true |
8fa67ec5700435938c4ca80067b9a6c1b72d8765 | Java | PadraoiX/QWCFPEnvDependencies | /QWCFPxWalli/Fontes/qwcfp_view-master/src/br/com/pix/qware/qwcfp/beans/OpenDownloadBean.java | UTF-8 | 2,683 | 1.867188 | 2 | [] | no_license | package br.com.pix.qware.qwcfp.beans;
import java.io.IOException;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import br.com.pix.qware.qwcfp.error.MsgTitleEnum;
import br.com.pix.qware.qwcfp.lazy.ListArquivosBean;
import br.com.pix.qware.qwcfp.service.DownloadLinkService;
import br.com.pix.qware.qwcfp.util.FacesMessages;
import br.com.pix.qware.qwcfp.wrappers.MyGroupsWrapper;
import br.com.pix.qwcfp.ws.client.erro.ViewError;
import br.com.qwcss.ws.dto.DownloadLinkDTO;
import br.com.qwcss.ws.dto.DownloadLinkParsDTO;
import br.com.qwcss.ws.dto.FileAndFileVersionWrapper;
import br.com.qwcss.ws.dto.FileListDTO;
//@Named("rulesBean")
@ManagedBean(name = "openDownload")
@ViewScoped
public class OpenDownloadBean extends AbstractBean {
private static final String MAIL_SEPARATOR = ";";
private static final long serialVersionUID = 8281391451977305172L;
@Inject
private FacesMessages messages;
@Inject
private DownloadLinkService downloadService;
private DownloadLinkParsDTO info;
private boolean tokenOk;
@PostConstruct
public void init() {
HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext()
.getRequest();
String token = request.getParameter("token");
if (token == null) {
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
try {
ec.redirect(ec.getRequestContextPath() + "/index.faces");
} catch (IOException e) {
e.printStackTrace();
}
}else if(token.isEmpty()) {
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
try {
ec.redirect(ec.getRequestContextPath() + "/index.faces");
} catch (IOException e) {
e.printStackTrace();
}
}else {
DownloadLinkParsDTO value = downloadService.start(token);
if (value.getErrorCode() != ViewError.OK.getCode()) {
messages.error(value.getErrorMsg());
setTokenOk(false);
info= new DownloadLinkParsDTO();
}else {
info = value;
setTokenOk(true);
}
}
}
public void doDownload() {
// TODO Auto-generated method stub
}
public DownloadLinkParsDTO getInfo() {
return info;
}
public void setInfo(DownloadLinkParsDTO info) {
this.info = info;
}
public boolean isTokenOk() {
return tokenOk;
}
public void setTokenOk(boolean tokenOk) {
this.tokenOk = tokenOk;
}
}
| true |
a1fc194a2d3ceeee7faa2c947a09bbf200705ba4 | Java | adonis2014/weixinradio | /src/main/java/com/qianmi/mq/ShadinessProducer.java | UTF-8 | 968 | 2.140625 | 2 | [] | no_license | package com.qianmi.mq;
import com.qianmi.domain.Pair;
import com.qianmi.domain.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Component;
import javax.jms.Queue;
import java.util.Map;
/**
* Created by aqlu on 15/8/21.
*/
@Component
public class ShadinessProducer {
@Autowired
private JmsMessagingTemplate jmsMessagingTemplate;
@javax.annotation.Resource
private Queue shadinessQueue;
@Value("${shadinessQueue.retry.period}")
private Long period;
public void send(Pair resourcePair) {
if(resourcePair == null){
return;
}
// jmsMessagingTemplate.getJmsTemplate().setDeliveryDelay(period * (resourcePair.getRetryCnt() + 1));
this.jmsMessagingTemplate.convertAndSend(this.shadinessQueue, resourcePair);
}
}
| true |
c7edae7f5e804c96c7da1ebca1f835f874dbc8ae | Java | 1187717503/BoutiquePortal | /intramirror-root/intramirror-vendor-web/src/main/java/com/intramirror/web/controller/order/OrderShipController.java | UTF-8 | 99,665 | 1.5625 | 2 | [] | no_license | package com.intramirror.web.controller.order;
import com.google.gson.Gson;
import com.intramirror.common.help.ResultMessage;
import com.intramirror.logistics.api.model.Invoice;
import com.intramirror.logistics.api.model.VendorShipment;
import com.intramirror.logistics.api.service.IInvoiceService;
import com.intramirror.main.api.model.AddressCountry;
import com.intramirror.main.api.model.Geography;
import com.intramirror.main.api.model.StockLocation;
import com.intramirror.main.api.model.Tax;
import com.intramirror.main.api.service.AddressCountryService;
import com.intramirror.main.api.service.GeographyService;
import com.intramirror.main.api.service.StockLocationService;
import com.intramirror.main.api.service.TaxService;
import com.intramirror.order.api.common.OrderStatusType;
import com.intramirror.order.api.model.Shipment;
import com.intramirror.order.api.model.ShippingProvider;
import com.intramirror.order.api.model.SubShipment;
import com.intramirror.order.api.service.IContainerService;
import com.intramirror.order.api.service.IOrderService;
import com.intramirror.order.api.service.IShipmentService;
import com.intramirror.order.api.service.IShippingProviderService;
import com.intramirror.order.api.service.ISubShipmentService;
import com.intramirror.order.api.util.HttpClientUtil;
import com.intramirror.order.api.vo.LogisticsProductVO;
import com.intramirror.product.api.model.Shop;
import com.intramirror.product.api.service.IShopService;
import com.intramirror.user.api.model.User;
import com.intramirror.user.api.model.Vendor;
import com.intramirror.user.api.service.VendorService;
import com.intramirror.utils.transform.JsonTransformUtil;
import com.intramirror.web.VO.DHLInputVO;
import com.intramirror.web.VO.InvoiceVO;
import com.intramirror.web.VO.RecipientVO;
import com.intramirror.web.VO.ShipperVO;
import com.intramirror.web.VO.TransitWarehouseInvoiceVO;
import com.intramirror.web.common.BarcodeUtil;
import com.intramirror.web.controller.BaseController;
import com.intramirror.web.util.ExcelUtil;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import pk.shoplus.common.utils.StringUtil;
@CrossOrigin
@Controller
@RequestMapping("/orderShip")
public class OrderShipController extends BaseController {
private static Logger logger = LoggerFactory.getLogger(OrderShipController.class);
@Autowired
private IOrderService orderService;
@Autowired
private VendorService vendorService;
@Autowired
private IShipmentService iShipmentService;
@Autowired
private IContainerService containerService;
@Autowired
private GeographyService geographyService;
@Autowired
private IInvoiceService invoiceService;
@Autowired
private IShopService shopService;
@Autowired
private IShippingProviderService shippingProviderService;
@Autowired
private ISubShipmentService subShipmentService;
@Autowired
private TaxService taxService;
@Autowired
private StockLocationService stockLocationService;
@Autowired
private AddressCountryService addressCountryService;
/**
* 获取所有箱子信息
*
* @param map
* @param httpRequest
* @return
*/
@RequestMapping(value = "/getReadyToShipCartonList", method = RequestMethod.POST)
@ResponseBody
public ResultMessage getPackOrderList(@RequestBody Map<String, Object> map, HttpServletRequest httpRequest) {
logger.info("order getReadyToShipCartonList 入参:" + new Gson().toJson(map));
ResultMessage result = new ResultMessage();
result.errorStatus();
// if(map == null || map.size() == 0 || map.get("status") == null){
// result.setMsg("Parameter cannot be empty");
// return result;
// }
User user = this.getUser(httpRequest);
if (user == null) {
result.setMsg("Please log in again");
return result;
}
List<Vendor> vendors = null;
try {
vendors = vendorService.getVendorsByUserId(user.getUserId());
} catch (Exception e) {
e.printStackTrace();
}
if (vendors == null) {
result.setMsg("Please log in again");
return result;
}
Boolean showShipe = false;
if(vendors.get(0).getAddressCountryId() == 2 || vendors.get(0).getAddressCountryId() == 3){
showShipe = true;
}
List<Long> vendorIds = vendors.stream().map(Vendor::getVendorId).collect(Collectors.toList());
try {
Map<String, Object> paramtMap = new HashMap<String, Object>();
if (map.get("sortByName") != null && StringUtils.isNoneBlank(map.get("sortByName").toString())) {
paramtMap.put("sortByName", map.get("sortByName").toString());
}
if (map.get("shipmentStatus") != null && StringUtils.isNoneBlank(map.get("shipmentStatus").toString())) {
paramtMap.put("shipmentStatus", Integer.parseInt(map.get("shipmentStatus").toString()));
}
if (map.get("locationId") != null && StringUtils.isNoneBlank(map.get("locationId").toString())) {
paramtMap.put("locationId", Integer.parseInt(map.get("locationId").toString()));
}
if (map.get("ship_to_geography") != null && StringUtils.isNoneBlank(map.get("ship_to_geography").toString())) {
paramtMap.put("ship_to_geography", map.get("ship_to_geography").toString());
}
if (map.get("locationId") != null && StringUtils.isNoneBlank(map.get("locationId").toString())) {
paramtMap.put("locationId", map.get("locationId").toString());
}
if (map.get("vendorId") != null && StringUtils.isNoneBlank(map.get("vendorId").toString())) {
vendorIds= Arrays.asList(Long.parseLong(map.get("vendorId").toString()));
}
paramtMap.put("vendorIds", vendorIds);
//获取箱子列表信息
logger.info("order getReadyToShipCartonList 获取container 列表信息 调用接口containerService.getContainerList 入参:" + new Gson().toJson(paramtMap));
List<Map<String, Object>> containerList = containerService.getContainerList(paramtMap);
List<Shipment> shipmentListSort = null;
if(paramtMap.get("sortByName")!=null){
//查询出有序的shipment的列表
shipmentListSort = iShipmentService.getShipmentList(paramtMap);
}
Map<String, List<Map<String, Object>>> shipMentCartonList = new HashMap<String, List<Map<String, Object>>>();
List<Map<String, Object>> shipMentList = new ArrayList<Map<String, Object>>();
if (containerList != null && containerList.size() > 0) {
logger.info("order getReadyToShipCartonList 解析container 列表信息 ");
//获取product列表
Set<Long> shipmentIds = new HashSet<>();
for (Map<String, Object> container:containerList){
shipmentIds.add(Long.parseLong(container.get("shipment_id").toString()));
}
paramtMap.put("shipmentIds",shipmentIds);
paramtMap.put("status", OrderStatusType.READYTOSHIP);
List<Map<String, Object>> orderList = orderService.getOrderListByShipmentId(paramtMap);
for (Map<String, Object> container : containerList) {
List<Map<String,Object>> orderListContain = new LinkedList<>();
String containerId = container.get("container_id").toString();
if(orderList!=null&&orderList.size()>0){
for (Map<String, Object> order :orderList){
String price = order.get("price")!=null?order.get("price").toString():"0";
order.put("price",(new BigDecimal(price).setScale(2, BigDecimal.ROUND_HALF_UP)).toString());
String in_price = order.get("in_price")!=null?order.get("in_price").toString():"0";
order.put("in_price",(new BigDecimal(in_price).setScale(2, BigDecimal.ROUND_HALF_UP)).toString());
if(containerId.equals(order.get("container_id").toString())){
orderListContain.add(order);
}
}
}
container.put("orderList",orderListContain);
//根据shipment_id 分组
if (shipMentCartonList.containsKey(container.get("shipment_id").toString())) {
List<Map<String, Object>> cons = shipMentCartonList.get(container.get("shipment_id").toString());
cons.add(container);
} else {
List<Map<String, Object>> cons = new ArrayList<Map<String, Object>>();
cons.add(container);
shipMentCartonList.put(container.get("shipment_id").toString(), cons);
//获取shipMent信息
Map<String, Object> shipMent = new HashMap<String, Object>();
shipMent.put("shipment_id", container.get("shipment_id").toString());
shipMent.put("shipment_no", container.get("shipment_no").toString());
shipMent.put("shipment_status", container.get("shipment_status").toString());
String shipToGeography = container.get("ship_to_geography").toString();
shipMent.put("ship_to_geography", shipToGeography);
shipMentList.add(shipMent);
}
}
if (shipMentList != null && shipMentList.size() > 0) {
//将cartonList 存入shipMent详情
for (Map<String, Object> shipMent : shipMentList) {
shipMent.put("cartonList", shipMentCartonList.get(shipMent.get("shipment_id").toString()));
shipMent.put("carton_qty", shipMentCartonList.get(shipMent.get("shipment_id").toString()).size());
}
}
for (Map<String, Object> shipItem : shipMentList) {
List<Map<String, Object>> cartonList = (List<Map<String, Object>>)shipItem.get("cartonList");
int product_qty_total = 0;
for(Map<String,Object> cartonItem: cartonList){
if(cartonItem.get("product_qty") != null){
product_qty_total = product_qty_total + Integer.parseInt(cartonItem.get("product_qty").toString());
}
}
shipItem.put("product_qty", product_qty_total);
}
}
//shipment排序
List<Map<String, Object>> shipmentListMapSort = new ArrayList<>();
if(shipmentListSort!=null&&shipmentListSort.size()>0){
for (Shipment shipment:shipmentListSort){
Long shipmentId = shipment.getShipmentId();
for (Map<String, Object> shipmentMap:shipMentList){
if(shipmentId.equals(Long.parseLong(shipmentMap.get("shipment_id").toString()))){
shipmentMap.put("stockLocation",shipment.getStockLocation());
shipmentMap.put("vendorName",shipment.getVendorName());
shipmentListMapSort.add(shipmentMap);
break;
}
}
}
}else {
shipmentListMapSort = shipMentList;
}
Boolean finalShowShipe = showShipe;
shipmentListMapSort.forEach(s ->{
if(s != null){
s.put("showShipe", finalShowShipe);
}
});
result.successStatus();
result.setData(shipmentListMapSort);
} catch (Exception e) {
e.printStackTrace();
result.setMsg("Query container list fail,Check parameters, please ");
return result;
}
return result;
}
@RequestMapping(value = "/updateStep",method = RequestMethod.POST)
@ResponseBody
public ResultMessage updateStep(@RequestBody Map<String, Object> map, HttpServletRequest httpRequest){
logger.info(" order update step 入参:"+new Gson().toJson(map));
ResultMessage result = new ResultMessage();
result.errorStatus();
Long shipmentId = Long.parseLong(map.get("shipment_id").toString());
if (map == null || map.size() == 0 || map.get("print_step") == null || map.get("shipment_id") == null) {
result.setMsg("Parameter cannot be empty");
return result;
}
User user = this.getUser(httpRequest);
if (user == null) {
result.setMsg("Please log in again");
return result;
}
Integer printStep = Integer.valueOf(map.get("print_step").toString());
Map<String, Object> getShipment = new HashMap<>();
getShipment.put("shipmentId", shipmentId);
//根据shipmentId 获取shipment
Shipment shipment = iShipmentService.selectShipmentById(getShipment);
if(printStep - shipment.getPrintStep() > 1){
result.setMsg("Print step is incorrect");
return result;
}
Map<String, Object> updateStepMap = new HashMap<>();
updateStepMap.put("print_step",printStep);
updateStepMap.put("shipment_id",shipmentId);
int re = iShipmentService.updatePrintStep(updateStepMap);
if(re >0){
result.successStatus();
result.setMsg("update step success");
}
return result;
}
/**
* 获取shipment 详细信息 以及关联的carton 及关联的订单信息
*
* @param map
* @param httpRequest
* @return
*/
@RequestMapping(value = "/getShipmentInfo", method = RequestMethod.POST)
@ResponseBody
public ResultMessage getShipmentInfo(@RequestBody Map<String, Object> map, HttpServletRequest httpRequest) {
logger.info("order getShipmentInfo 入参:" + new Gson().toJson(map));
ResultMessage result = new ResultMessage();
result.errorStatus();
Long shipmentId = Long.parseLong(map.get("shipment_id").toString());
if (map == null || map.size() == 0 || map.get("status") == null || map.get("shipment_id") == null) {
result.setMsg("Parameter cannot be empty");
return result;
}
User user = this.getUser(httpRequest);
if (user == null) {
result.setMsg("Please log in again");
return result;
}
List<Vendor> vendors = new ArrayList<>();
try {
vendors = vendorService.getVendorsByUserId(user.getUserId());
} catch (Exception e) {
e.printStackTrace();
}
if (CollectionUtils.isEmpty(vendors)) {
result.setMsg("Please log in again");
return result;
}
List<Long> vendorIds = vendors.stream().map(Vendor::getVendorId).collect(Collectors.toList());
try {
//map.put("vendorId", vendor.getVendorId());
map.put("vendorIds", vendorIds);
Map<String, Object> getShipment = new HashMap<>();
getShipment.put("shipmentId", Long.parseLong(map.get("shipment_id").toString()));
//根据shipmentId 获取shipment 相关信息及物流第一段类型
Map<String, Object> shipmentMap = iShipmentService.getShipmentInfoById(getShipment);
if (shipmentMap == null || shipmentMap.size() == 0) {
result.setMsg("Query Shipment fail,Check parameters, please ");
return result;
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat sdf2 = new SimpleDateFormat("dd/MM/yyyy");
if (shipmentMap.get("invoice_date") != null && StringUtils.isNotBlank(shipmentMap.get("invoice_date").toString())) {
shipmentMap.put("invoice_date", sdf2.format(sdf.parse(shipmentMap.get("invoice_date").toString())));
shipmentMap.put("invoice_num",shipmentMap.get("invoiceNum"));
}
//shipmentMap.put("vendor_name",vendor.getVendorName());
Integer print_step = Integer.valueOf(shipmentMap.get("print_step").toString());
// 添加invoice url
if(print_step >= 3){
VendorShipment vendorShipment = invoiceService.queryVendorShipmentByShipmentId(shipmentId);
if(vendorShipment!=null){
shipmentMap.put("invoice_url",vendorShipment.getInvoiceUrl());
}
// 添加awb url
if(shipmentMap.get("awb_num")!=null){
String awb_num = shipmentMap.get("awb_num").toString();
if(org.apache.commons.lang.StringUtils.isNotBlank(awb_num)){
String docUrl = iShipmentService.queryAwbUrlByAwbNum(awb_num);
if(org.apache.commons.lang.StringUtils.isNotBlank(docUrl)) {
shipmentMap.put("awbUrl", docUrl);
}
}
}
}
//获取carton列表
Set<Long> shipmentIds = new HashSet<>();
shipmentIds.add(Long.parseLong(map.get("shipment_id").toString()));
map.put("shipmentIds", shipmentIds);
List<Map<String, Object>> containerList = orderService.getOrderListByShipmentId(map);
Map<String, Object> resultMap = new HashMap<String, Object>();
Map<String, List<Map<String, Object>>> orderList = new HashMap<String, List<Map<String, Object>>>();
List<Map<String, Object>> shipMentCartonList = new ArrayList<Map<String, Object>>();
if (containerList != null && containerList.size() > 0) {
for (Map<String, Object> container : containerList) {
String priceStr = container.get("price").toString();
String inPriceStr = container.get("in_price").toString();
//四舍五入金额
container.put("price",new BigDecimal(priceStr).setScale(2,BigDecimal.ROUND_HALF_UP).toString());
container.put("in_price",new BigDecimal(inPriceStr).setScale(2,BigDecimal.ROUND_HALF_UP).toString());
//根据shipment_id 分组
if (orderList.containsKey(container.get("container_id").toString())) {
List<Map<String, Object>> cons = orderList.get(container.get("container_id").toString());
cons.add(container);
} else {
List<Map<String, Object>> cons = new ArrayList<Map<String, Object>>();
cons.add(container);
orderList.put(container.get("container_id").toString(), cons);
//获取container信息
Map<String, Object> cartonInfo = new HashMap<String, Object>();
cartonInfo.put("container_id", container.get("container_id").toString());
cartonInfo.put("barcode", container.get("barcode").toString());
cartonInfo.put("height", container.get("height").toString());
cartonInfo.put("width", container.get("width").toString());
cartonInfo.put("length", container.get("length").toString());
String weight = container.get("weight").toString();
BigDecimal decimal = new BigDecimal(weight);
cartonInfo.put("weight",decimal.setScale(2,BigDecimal.ROUND_HALF_UP).toString());
shipMentCartonList.add(cartonInfo);
}
}
if (shipMentCartonList != null && shipMentCartonList.size() > 0) {
//将orderList 存入container详情
for (Map<String, Object> carton : shipMentCartonList) {
carton.put("orderList", orderList.get(carton.get("container_id").toString()));
carton.put("order_qty", orderList.get(carton.get("container_id").toString()).size());
}
}
}
VendorShipment vendorShipment = invoiceService.queryVendorShipmentByShipmentId(Long.parseLong(map.get("shipment_id").toString()));
shipmentMap.put("carton_qty", shipMentCartonList == null ? 0 : shipMentCartonList.size());
resultMap.put("cartonList", shipMentCartonList);
resultMap.put("shipmentInfo", shipmentMap);
if(vendorShipment!=null){
resultMap.put("vendorShipment",vendorShipment);
}
// 获取收货人信息
Map<String, Object> dhlMap = new HashMap<>();
dhlMap.put("shipmentId",shipmentId);
dhlMap.put("sequence","1");
SubShipment dhlShipment = subShipmentService.getDHLShipment(dhlMap);
RecipientVO recipientVO = new RecipientVO();
recipientVO.setCity(dhlShipment.getShipToCity());
recipientVO.setCompanyName(dhlShipment.getConsignee());
recipientVO.setPersonName(dhlShipment.getPersonName());
recipientVO.setPhoneNumber(dhlShipment.getContact());
recipientVO.setEmailAddress(dhlShipment.getShipToEamilAddr());
String shipToAddr = dhlShipment.getShipToAddr();
if (shipToAddr.length()>35){
shipToAddr = shipToAddr.substring(0,34);
}
recipientVO.setStreetLines(shipToAddr);
if (StringUtil.isNotEmpty(dhlShipment.getShipToAddr2())
&&!"0".equals(dhlShipment.getShipToAddr2())){
recipientVO.setStreetLines2(dhlShipment.getShipToAddr2());
}
if (StringUtil.isNotEmpty(dhlShipment.getShipToAddr3())
&&!"0".equals(dhlShipment.getShipToAddr3())){
recipientVO.setStreetLines3(dhlShipment.getShipToAddr3());
}
if(dhlShipment.getPostalCode()!=null){
recipientVO.setPostalCode(dhlShipment.getPostalCode());
}else {
recipientVO.setPostalCode("101731");
}
recipientVO.setCountryCode(dhlShipment.getShipToCountryCode());
shipmentMap.put("recipient",recipientVO);
result.successStatus();
result.setData(resultMap);
} catch (Exception e) {
e.printStackTrace();
result.setMsg("Query container list fail,Check parameters, please ");
return result;
}
return result;
}
@RequestMapping(value = "/getGeography", method = RequestMethod.POST)
@ResponseBody
public ResultMessage getGeography() {
ResultMessage result = new ResultMessage();
result.errorStatus();
try {
List<Geography> geographyList = geographyService.getGeographyGroupList();
result.successStatus();
result.setData(geographyList);
} catch (Exception e) {
e.printStackTrace();
result.setMsg("Query geography list fail,Check parameters, please ");
return result;
}
return result;
}
@RequestMapping(value = "/getStockLocation", method = RequestMethod.GET)
@ResponseBody
public ResultMessage getStockLocation(Long userId,Long vendorId) {
ResultMessage result = new ResultMessage();
result.errorStatus();
if ((userId == null || userId == 0)&&(vendorId == null || vendorId == 0)){
result.setMsg("parameters vendorId is null ");
return result;
}
try {
if (userId != null) {
Vendor vendor = vendorService.getVendorByUserId(userId);
if (vendor != null){
List<StockLocation> stockLocationList = stockLocationService.getStockLocations(vendor.getVendorId());
result.successStatus();
result.setData(stockLocationList);
}else {
result.setMsg("此用户未注册买手店");
return result;
}
}else if(vendorId>0){
List<StockLocation> stockLocationList = stockLocationService.getStockLocations(vendorId);
result.successStatus();
result.setData(stockLocationList);
}else {
result.setMsg("Parameter error.");
return result;
}
} catch (Exception e) {
e.printStackTrace();
result.setMsg("Query StockLocation list fail,Check parameters, please ");
return result;
}
return result;
}
@RequestMapping(value = "/getVendors", method = RequestMethod.GET)
@ResponseBody
public ResultMessage getVendors(Long userId) {
ResultMessage result = new ResultMessage();
result.errorStatus();
if (userId == null || userId == 0){
result.setMsg("parameters vendorId is null ");
return result;
}
try {
List<Vendor> vendors=vendorService.getVendorsByUserId(userId);
result.successStatus();
result.setData(vendors);
} catch (Exception e) {
e.printStackTrace();
result.setMsg("Query StockLocation list fail,Check parameters, please ");
return result;
}
return result;
}
private ResultMessage printExcelShipmentInfo(HttpServletResponse response, Object obj) throws IOException {
String fileName = new Date().getTime() + ".xls";
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
if (obj instanceof TransitWarehouseInvoiceVO){
ExcelUtil.createWorkBook((TransitWarehouseInvoiceVO)obj).write(os);
}else if (obj instanceof Map){
ExcelUtil.createWorkBook((Map<String, Object>) obj).write(os);
}
} catch (IOException e) {
e.printStackTrace();
}
byte[] content = os.toByteArray();
InputStream is = new ByteArrayInputStream(content);
// 设置response参数,可以打开下载页面
response.reset();
response.setHeader("Access-Control-Allow-Origin", "*");
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(), "iso-8859-1"));
ServletOutputStream out = response.getOutputStream();
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(is);
bos = new BufferedOutputStream(out);
byte[] buff = new byte[2048];
int bytesRead;
// Simple read/write loop.
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
} catch (final IOException e) {
throw e;
} finally {
if (bis != null)
bis.close();
if (bos != null)
bos.close();
}
return null;
}
/***
* 打印shipment 详细信息 以及关联的carton 及关联的订单信息
* @param httpRequest
* @return
*/
@RequestMapping(value = "/printShipmentInfo", method = RequestMethod.POST)
@ResponseBody
public ResultMessage printShipmentInfo(@RequestBody Map<String, Object> map, HttpServletRequest httpRequest,HttpServletResponse response) {
Map<String, Object> resultMap = new HashMap<String, Object>();
ResultMessage result = new ResultMessage();
result.errorStatus();
if (map == null || map.size() == 0 || map.get("status") == null
|| map.get("shipment_id") == null
|| map.get("vendorId") == null) {
result.setMsg("Parameter cannot be empty");
return result;
}
User user = this.getUser(httpRequest);
if (user == null) {
result.setMsg("Please log in again");
return result;
}
Vendor vendor = null;
try {
vendor = vendorService.getVendorByUserId(user.getUserId());
} catch (Exception e) {
e.printStackTrace();
}
if (vendor == null) {
result.setMsg("Please log in again");
return result;
}
Long vendorId = Long.valueOf(map.get("vendorId").toString());
if (map.get("shipment_id") == null) {
result.setMsg("Parameter cannot be empty");
return result;
}
vendor = getVendor(vendor, vendorId);
//List<Long> vendorIds = vendors.stream().map(Vendor::getVendorId).collect(Collectors.toList());
//获取ddt number
long shipment_id = Long.parseLong(map.get("shipment_id").toString());
//获取Invoice 信息
logger.info("打印Invoice----获取Invoice信息");
Invoice invoice = invoiceService.getInvoiceByShipmentId(shipment_id);
if(map.get("shipmentCategory")!=null&&"1".equals(map.get("shipmentCategory").toString())){
if (invoice==null){
Map<String, Object> ddtNo = invoiceService.getMaxDdtNo();
int maxDdtNo = ddtNo.get("maxddtNum")!=null?Integer.parseInt(ddtNo.get("maxddtNum").toString()):0;
long s = ddtNo.get("shipment_id") != null ? Long.parseLong(ddtNo.get("shipment_id").toString()) : 0;
if (s!=shipment_id){
Invoice newInvoice = new Invoice();
if(maxDdtNo<10000){
maxDdtNo = 10000;
}else {
maxDdtNo++;
}
newInvoice.setEnabled(true);
newInvoice.setDdtNum(maxDdtNo);
newInvoice.setInvoiceNum("");
newInvoice.setShipmentId(shipment_id);
newInvoice.setVendorId(vendorId);
newInvoice.setInvoiceDate(new Date());
newInvoice.setVatNum("");
invoiceService.insertSelective(newInvoice);
invoice = newInvoice;
}
}
}else {
//获取Invoice To信息
logger.info("打印Invoice----获取Invoice To信息");
Shop shop = shopService.selectByPrimaryKey(65l);
resultMap.put("InvoiceTo", shop.getBusinessLicenseLocation());
resultMap.put("InvoiceName", shop.getShopName());
}
try {
map.put("vendorIds", Arrays.asList(vendorId));
Map<String, Object> getShipment = new HashMap<>();
getShipment.put("shipmentId", shipment_id);
//根据shipmentId 获取shipment 相关信息及物流第一段类型
logger.info("打印Invoice----根据shipmentId 获取shipment 相关信息及物流第一段类型,开始获取");
Map<String, Object> shipmentMap = iShipmentService.getShipmentTypeById(getShipment);
if (shipmentMap == null || shipmentMap.size() == 0) {
logger.info("获取失败");
result.setMsg("Query Shipment fail,Check parameters, please ");
return result;
}
resultMap.put("shipmentNo",shipmentMap.get("shipment_no"));
logger.info("打印Invoice----获取shipment相关信息及物流第一段类型成功");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat sdf2 = new SimpleDateFormat("dd/MM/yyyy");
if(map.get("shipmentCategory")!=null&&"1".equals(map.get("shipmentCategory").toString())){
resultMap.put("InvoiceNumber", invoice.getDdtNum());
}else {
resultMap.put("InvoiceNumber", invoice.getInvoiceNum());
}
if (invoice.getInvoiceDate() != null) {
String invoiceDate = sdf.format(invoice.getInvoiceDate());
resultMap.put("InvoiceDate", sdf2.format(sdf.parse(invoiceDate)));
} else {
result.setMsg("invoiceDate is null ");
return result;
}
//获取Ship From信息
StockLocation location = stockLocationService.getShipFromLocation(shipment_id);
AddressCountry country = addressCountryService.getAddressCountryByCountryCode(location.getAddressCountryCode());
String countryName = "Italy";
if (country != null){
countryName = country.getEnglishName();
}
// 获取invoice from
resultMap.put("companyName",location.getContactCompanyName());
resultMap.put("personName",location.getContactPersonName());
resultMap.put("contact",location.getContactPhoneNumber());
resultMap.put("address",location.getAddressStreetlines());
resultMap.put("city",location.getAddressCity());
resultMap.put("country",countryName);
resultMap.put("invoiceCompanyName",vendor.getCompanyName());
resultMap.put("invoicePersonName",vendor.getRegisteredPerson());
resultMap.put("invoiceAddress",vendor.getBusinessLicenseLocation());
resultMap.put("VATNumber", vendor.getBusinessLicenseNumber());
//resultMap.put("invoiceCity",location.getAddressCity());
resultMap.put("invoiceCountry",countryName);
logger.info("打印Invoice----获取Deliver To信息");
List<SubShipment> subShipmentList = subShipmentService.getSubShipmentByShipmentId(shipment_id);
if (subShipmentList!=null&&subShipmentList.size()>0){
resultMap.put("DeliverTo", subShipmentList.get(0));
//发往质检仓的取DHL税号
if(map.get("shipmentCategory")!=null&&"1".equals(map.get("shipmentCategory").toString())){
resultMap.put("VATNumber",subShipmentList.get(0).getPiva());
}
}else {
result.setMsg("DeliverTo is null ");
return result;
}
/*if (subShipmentList.size() > 1) {
ShippingProvider shippingProvider = shippingProviderService.getShippingProviderByShipmentId(shipment_id);
resultMap.put("DeliverTo", shippingProvider);
} else if (subShipmentList.size() == 1) {
resultMap.put("DeliverTo", subShipmentList.get(0));
//发往质检仓的取DHL税号
if(map.get("shipmentCategory")!=null&&"1".equals(map.get("shipmentCategory").toString())){
resultMap.put("VATNumber",subShipmentList.get(0).getPiva());
}
} else {
result.setMsg("DeliverTo is null ");
return result;
}*/
//获取carton列表
Set<Long> shipmentIds = new HashSet<>();
shipmentIds.add(shipment_id);
map.put("shipmentIds",shipmentIds);
List<Map<String, Object>> containerList = orderService.getOrderListByShipmentId(map);
BigDecimal allTotal = new BigDecimal(0);
BigDecimal VAT = new BigDecimal(0);
BigDecimal totalWeight = new BigDecimal(0);
Map<String,BigDecimal> decimalMap = new HashMap<>();
if (containerList != null && containerList.size() > 0) {
for (Map<String, Object> container : containerList) {
decimalMap.put(container.get("container_id").toString(),new BigDecimal(container.get("weight").toString()));
BigDecimal total = new BigDecimal(Double.parseDouble(container.get("in_price").toString()) * Double.parseDouble(container.get("amount").toString())).setScale(2,BigDecimal.ROUND_HALF_UP);
container.put("in_price",new BigDecimal(container.get("in_price").toString()).setScale(2,BigDecimal.ROUND_HALF_UP).toString());
//获取欧盟的信息
/*Geography geography = geographyService.getGeographyById(3l);
logger.info("打印Invoice----获取VAT信息");
//获取当前shipment的信息
Map<String, Object> shipmentPramMap = new HashMap<>();
shipmentPramMap.put("shipmentId", shipment_id);
Shipment shipment = iShipmentService.selectShipmentById(shipmentPramMap);
if (geography != null && shipment != null && geography.getGeographyId().toString().equals(container.get("geography_id").toString())) {
if (geography.getEnglishName().equals(shipment.getShipToGeography())) {
logger.info("打印Invoice----查询当前订单的到货国家");
//查询当前订单的到货国家
AddressCountry addressCountry = addressCountryService.getAddressCountryByName(container.get("countryName").toString());
logger.info("打印Invoice----查询当前到货国家的tax_rate");
//查询当前到货国家的tax_rate
Tax tax = taxService.getTaxByAddressCountryId(addressCountry.getAddressCountryId());
if (tax.getTaxRate() != null) {
logger.info("打印Invoice----计算VAT的值");
VAT = VAT.add(new BigDecimal(Double.parseDouble(container.get("in_price").toString())).multiply(tax.getTaxRate())).setScale(2,BigDecimal.ROUND_HALF_UP);
}
}
}*/
String orderLineNum = container.get("order_line_num").toString();
BigDecimal tax = taxService.calculateTax(orderLineNum);
if (tax != null) {
logger.info("打印Invoice----计算VAT的值");
VAT = VAT.add(new BigDecimal(Double.parseDouble(container.get("in_price").toString())).multiply(tax)).setScale(2,BigDecimal.ROUND_HALF_UP);
}
allTotal = allTotal.add(total);
container.put("Total", total);
}
}
if(decimalMap.size()>0){
Set<String> strings = decimalMap.keySet();
for (String key:strings){
totalWeight = totalWeight.add(decimalMap.get(key));
}
}
resultMap.put("totalWeight",totalWeight.setScale(2,BigDecimal.ROUND_HALF_UP).toString());
resultMap.put("cartonQty",decimalMap.size());
shipmentMap.put("all_qty", containerList == null ? 0 : containerList.size());
resultMap.put("all_qty", containerList == null ? 0 : containerList.size());
resultMap.put("cartonList", containerList);
resultMap.put("shipmentInfo", shipmentMap);
//金额四舍五入
resultMap.put("allTotal", allTotal.setScale(2,BigDecimal.ROUND_HALF_UP).toString());
resultMap.put("VAT", VAT.setScale(2,BigDecimal.ROUND_HALF_UP).toString());
resultMap.put("GrandTotal", (VAT.add(allTotal)).setScale(2,BigDecimal.ROUND_HALF_UP).toString());
String isExcel = map.get("isExcel")!=null?map.get("isExcel").toString():null;
if(isExcel!=null&&"1".equals(isExcel)){
printExcelShipmentInfo(response,resultMap);
}
result.successStatus();
result.setData(resultMap);
} catch (Exception e) {
e.printStackTrace();
result.setMsg("Query container list fail,Check parameters, please ");
return result;
}
return result;
}
/***
* 打印去transit warehouse的发票
* @param httpRequest
* @return
*/
@RequestMapping(value = "/printInvoice", method = RequestMethod.POST)
@ResponseBody
public ResultMessage printInvoice(@RequestBody Map<String, Object> map, HttpServletRequest httpRequest,HttpServletResponse response) {
Map<String, Object> resultMap = new HashMap<>();
ResultMessage result = new ResultMessage();
result.errorStatus();
if (map == null || map.size() == 0 || map.get("status") == null
|| map.get("shipment_id") == null) {
result.setMsg("Parameter cannot be empty");
return result;
}
User user = this.getUser(httpRequest);
if (user == null) {
result.setMsg("Please log in again");
return result;
}
Vendor vendor = null;
try {
vendor = vendorService.getVendorByUserId(user.getUserId());
} catch (Exception e) {
e.printStackTrace();
}
if (vendor == null) {
result.setMsg("Please log in again");
return result;
}
long shipment_id = Long.parseLong(map.get("shipment_id").toString());
//根据shipmentId 获取shipment 相关信息及物流第一段类型
logger.info("打印Invoice----根据shipmentId 获取shipment 相关信息及物流第一段类型,开始获取");
Map<String, Object> getShipment = new HashMap<>();
getShipment.put("shipmentId", shipment_id);
Map<String, Object> shipmentMap = iShipmentService.getShipmentTypeById(getShipment);
if (shipmentMap == null || shipmentMap.size() == 0) {
logger.info("获取失败");
result.setMsg("Query Shipment fail,Check parameters, please ");
return result;
}
Long vendorId = Long.valueOf(shipmentMap.get("vendor_id").toString());
vendor = getVendor(vendor, vendorId);
TransitWarehouseInvoiceVO transitWarehouseInvoiceVO = new TransitWarehouseInvoiceVO();
//获取Ship From信息
StockLocation location = stockLocationService.getShipFromLocation(shipment_id);
AddressCountry addressCountry = addressCountryService.getAddressCountryByCountryCode(location.getAddressCountryCode());
String countryName = "Italy";
if (addressCountry != null){
countryName = addressCountry.getEnglishName();
}
ShipperVO shipperVO = new ShipperVO();
shipperVO.setCompanyName(location.getContactCompanyName());
shipperVO.setPersonName(location.getContactPersonName());
shipperVO.setPhoneNumber(location.getContactPhoneNumber());
shipperVO.setStreetLines(location.getAddressStreetlines());
shipperVO.setStreetLines2(location.getAddressStreetlines2());
shipperVO.setStreetLines3(location.getAddressStreetlines3());
shipperVO.setCity(location.getAddressCity());
shipperVO.setCountry(countryName);
ShipperVO invoiceForm = new ShipperVO();
invoiceForm.setCompanyName(vendor.getCompanyName());
invoiceForm.setPersonName(vendor.getRegisteredPerson());
invoiceForm.setStreetLines(vendor.getBusinessLicenseLocation());
invoiceForm.setCountry(countryName);
boolean isDDt = false;
if(map.get("ddtFlag")!=null&&"1".equals(map.get("ddtFlag").toString())){
isDDt = true;
}
//获取Invoice 信息
logger.info("打印Invoice----获取Invoice信息");
Map<String, Object> invoiceMap = new HashMap<>();
if(map.get("ddtFlag")!=null&&"1".equals(map.get("ddtFlag").toString())){
invoiceMap.put("type", 2);
}else{
invoiceMap.put("type", 1);
}
invoiceMap.put("shipmentId", shipment_id);
Invoice invoice = invoiceService.getInvoiceByMap(invoiceMap);
if (invoice==null){
Map<String, Object> ddtNo = invoiceService.getMaxDdtNo();
int maxDdtNo = ddtNo.get("maxddtNum")!=null?Integer.parseInt(ddtNo.get("maxddtNum").toString()):0;
Invoice newInvoice = new Invoice();
if(maxDdtNo<10000){
maxDdtNo = 10000;
}else {
maxDdtNo++;
}
newInvoice.setEnabled(true);
newInvoice.setDdtNum(maxDdtNo);
newInvoice.setInvoiceNum("");
newInvoice.setShipmentId(shipment_id);
newInvoice.setVendorId(vendorId);
newInvoice.setInvoiceDate(new Date());
newInvoice.setVatNum("");
newInvoice.setType(2);
invoiceService.insertSelective(newInvoice);
invoice = newInvoice;
}else {
if(map.get("ddtFlag")!=null&&"1".equals(map.get("ddtFlag").toString())){
if(invoice.getDdtNum() == null){
Map<String, Object> ddtNo = invoiceService.getMaxDdtNo();
int maxDdtNo = ddtNo.get("maxddtNum")!=null?Integer.parseInt(ddtNo.get("maxddtNum").toString()):0;
if(maxDdtNo<10000){
maxDdtNo = 10000;
}else {
maxDdtNo++;
}
invoice.setDdtNum(maxDdtNo);
invoiceService.updateByPrimaryKey(invoice);
}
}
//获取Invoice To信息
logger.info("打印Invoice----获取Invoice To信息");
Shop shop = shopService.selectByPrimaryKey(65l);
resultMap.put("InvoiceTo", shop.getBusinessLicenseLocation());
resultMap.put("InvoiceName", shop.getShopName());
resultMap.put("contactPersonName", shop.getContactPersonName());
}
map.put("vendorIds", Arrays.asList(vendorId));
resultMap.put("shipmentNo",shipmentMap.get("shipment_no"));
logger.info("打印Invoice----获取shipment相关信息及物流第一段类型成功");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat sdf2 = new SimpleDateFormat("dd/MM/yyyy");
if(map.get("ddtFlag")!=null&&"1".equals(map.get("ddtFlag").toString())){
resultMap.put("InvoiceNumber", String.valueOf(invoice.getDdtNum()));
}else {
resultMap.put("InvoiceNumber", invoice.getInvoiceNum());
}
if (invoice.getInvoiceDate() != null) {
String invoiceDate = sdf.format(invoice.getInvoiceDate());
try {
resultMap.put("InvoiceDate", sdf2.format(sdf.parse(invoiceDate)));
} catch (ParseException e) {
logger.error("Query container list fail invoiceDate="+invoiceDate, e);
result.setMsg("Query container list fail,Check parameters, please ");
return result;
}
} else {
result.setMsg("invoiceDate is null ");
return result;
}
resultMap.put("VATNumber", invoice.getVatNum());
//ddt的invoice
InvoiceVO ddtInvoice = new InvoiceVO();
List<Map<String,Object>> ddtOrderList = new ArrayList<>();
BigDecimal ddtVAT = new BigDecimal(0);
BigDecimal ddtAllTotal = new BigDecimal(0);
BigDecimal ddtGrandTotal = new BigDecimal(0);
Integer ddtAllQty = 0;
if(isDDt){
ddtInvoice.setShipperVO(shipperVO);
RecipientVO recipientVO = new RecipientVO();
ShippingProvider shippingProvider = shippingProviderService.getShippingProviderById(5L);// 质检仓地址
if(shippingProvider == null){
shippingProvider = new ShippingProvider();
}
recipientVO.setCity(shippingProvider.getAddrCity());
recipientVO.setCompanyName(shippingProvider.getTransferConsignee());
recipientVO.setPersonName(shippingProvider.getPersonName());
recipientVO.setStreetLines(shippingProvider.getTransferAddr());
recipientVO.setStreetLines2(shippingProvider.getTransferAddr2());
recipientVO.setStreetLines3(shippingProvider.getTransferAddr3());
recipientVO.setPostalCode(shippingProvider.getZipCode());
recipientVO.setPhoneNumber(shippingProvider.getTransferContact());
recipientVO.setCountry(shippingProvider.getAddrCountry());
ddtInvoice.setRecipientVO(recipientVO);
ddtInvoice.setList(ddtOrderList);
ddtInvoice.setInvoiceTo((String) resultMap.get("InvoiceTo"));
ddtInvoice.setInvoiceName((String) resultMap.get("InvoiceName"));
ddtInvoice.setInvoicePersonName((String)resultMap.get("contactPersonName"));
ddtInvoice.setVatNum((String) resultMap.get("VATNumber"));
ddtInvoice.setInvoiceDate((String) resultMap.get("InvoiceDate"));
ddtInvoice.setInvoiceNum((String) resultMap.get("InvoiceNumber"));
ddtInvoice.setShipmentNo((String) resultMap.get("shipmentNo"));
}
//获取发往中国大陆,香港,澳门的订单列表
Set<Long> shipmentIds = new HashSet<>();
shipmentIds.add(shipment_id);
Map<String, Object> conditionMap = new HashMap<>();
conditionMap.put("status", map.get("status"));
conditionMap.put("vendorIds", Arrays.asList(vendorId));
conditionMap.put("shipmentIds", shipmentIds);
conditionMap.put("packGroup", 1);
List<Map<String, Object>> chinaList = orderService.getOrderListByShipmentId(conditionMap);
if( chinaList != null && chinaList.size() > 0 ){
InvoiceVO chinaInovice = new InvoiceVO();
RecipientVO recipientVO = new RecipientVO();
if(!isDDt){
transitWarehouseInvoiceVO.setChinaInvoice(chinaInovice);
}
//2018-6-28改回ZSY地址
ShippingProvider shippingProvider = shippingProviderService.getShippingProviderById(4L);//zsy地址
//2018-6-26修改发票ship to地址为物流第一段供应商地址
//ShippingProvider shippingProvider = shippingProviderService.getShippingProviderByVendorId(vendor.getVendorId());
if(shippingProvider == null){
shippingProvider = new ShippingProvider();
}
recipientVO.setCity(shippingProvider.getAddrCity());
recipientVO.setCompanyName(shippingProvider.getTransferConsignee());
recipientVO.setPersonName(shippingProvider.getPersonName());
recipientVO.setStreetLines(shippingProvider.getTransferAddr());
recipientVO.setStreetLines2(shippingProvider.getTransferAddr2());
recipientVO.setStreetLines3(shippingProvider.getTransferAddr3());
recipientVO.setPostalCode(shippingProvider.getZipCode());
recipientVO.setPhoneNumber(shippingProvider.getTransferContact());
recipientVO.setCountry(shippingProvider.getAddrCountry());
//获取shipTo地址信息
BigDecimal allTotal = new BigDecimal("0");
BigDecimal VAT = new BigDecimal("0");
for(Map<String, Object> chinaOrder : chinaList){
/*Object countryName = chinaOrder.get("countryName").equals("中国大陆") ? "中国" : chinaOrder.get("countryName");
AddressCountry addressCountry = addressCountryService.getAddressCountryByName(countryName.toString());
Tax tax = taxService.getTaxByAddressCountryId(addressCountry.getAddressCountryId());
BigDecimal taxRate = tax.getTaxRate() == null ? new BigDecimal("0") : tax.getTaxRate();*/
String orderLineNum = chinaOrder.get("order_line_num").toString();
BigDecimal taxRate = taxService.calculateTax(orderLineNum);
BigDecimal total = new BigDecimal(Double.parseDouble(chinaOrder.get("in_price").toString()) * Double.parseDouble(chinaOrder.get("amount").toString())).setScale(2, BigDecimal.ROUND_HALF_UP);
VAT = VAT.add(total.multiply(taxRate).setScale(2, BigDecimal.ROUND_HALF_UP));
allTotal = allTotal.add(total);
String inPrice = chinaOrder.get("in_price")!=null?chinaOrder.get("in_price").toString():"";
String retailPrice = chinaOrder.get("price")!=null?chinaOrder.get("price").toString():"";
double discountTax = getDiscountTax(orderLineNum);
BigDecimal discount = (new BigDecimal(1)).subtract((new BigDecimal(inPrice)).multiply(new BigDecimal(discountTax)).divide(new BigDecimal(retailPrice), 2, RoundingMode.HALF_UP));
chinaOrder.put("discount", discount.multiply(new BigDecimal("100")).setScale(0, BigDecimal.ROUND_HALF_UP).toString() + "%");
chinaOrder.put("in_price", (new BigDecimal(inPrice).setScale(2, BigDecimal.ROUND_HALF_UP).toString()));
chinaOrder.put("price", (new BigDecimal(retailPrice).setScale(2, BigDecimal.ROUND_HALF_UP).toString()));
}
BigDecimal grandTotal = (VAT.add(allTotal)).setScale(2,BigDecimal.ROUND_HALF_UP);
if(isDDt){
if(CollectionUtils.isNotEmpty(chinaList)){
ddtInvoice.getList().addAll(chinaList);
}
ddtGrandTotal = ddtGrandTotal.add(grandTotal);
ddtAllTotal = ddtAllTotal.add(allTotal);
ddtVAT = ddtVAT.add(VAT);
ddtAllQty = chinaList.size()+ddtAllQty;
}
chinaInovice.setList(chinaList);
chinaInovice.setRecipientVO(recipientVO);
chinaInovice.setShipperVO(shipperVO);
chinaInovice.setInvoiceFromVO(invoiceForm);
chinaInovice.setInvoiceTo((String) resultMap.get("InvoiceTo"));
chinaInovice.setInvoiceName((String) resultMap.get("InvoiceName"));
chinaInovice.setInvoicePersonName((String)resultMap.get("contactPersonName"));
chinaInovice.setVatNum((String) resultMap.get("VATNumber"));
chinaInovice.setInvoiceDate((String) resultMap.get("InvoiceDate"));
chinaInovice.setInvoiceNum((String) resultMap.get("InvoiceNumber"));
chinaInovice.setShipmentNo((String) resultMap.get("shipmentNo"));
chinaInovice.setGrandTotal(grandTotal.toString());
chinaInovice.setAllTotal(allTotal.toString());
chinaInovice.setVat(VAT.toString());
chinaInovice.setAllQty(String.valueOf(chinaList.size()));
}
//获取欧盟国家的订单
conditionMap.put("shipmentIds",shipmentIds);
conditionMap.put("packGroup",2);
List<Map<String, Object>> UNlist = orderService.getOrderListByShipmentId(conditionMap);
if (UNlist != null && UNlist.size() > 0){
List<InvoiceVO> UNInvoiceList = new ArrayList<>();
if(!isDDt){
transitWarehouseInvoiceVO.setUNInvoices(UNInvoiceList);
}
for (Map<String,Object> UNOrder: UNlist){
RecipientVO recipientVO = new RecipientVO();
InvoiceVO UNInvoiceVO = new InvoiceVO();
//欧盟的不显示remake
UNInvoiceVO.setRemark(null);
String country = UNOrder.get("user_rec_country") != null ? UNOrder.get("user_rec_country").toString() : "";
recipientVO.setCountry(country);
String personName = UNOrder.get("user_rec_name") != null ? UNOrder.get("user_rec_name").toString() : "";
recipientVO.setPersonName(personName);
String province = UNOrder.get("user_rec_province") != null ? UNOrder.get("user_rec_province").toString() : "";
recipientVO.setProvince(province);
String city = UNOrder.get("user_rec_city") != null ? UNOrder.get("user_rec_city").toString() : "";
recipientVO.setCity(city);
String addr = UNOrder.get("user_rec_addr") != null ? UNOrder.get("user_rec_addr").toString() : "";
recipientVO.setStreetLines(addr);
String mobile = UNOrder.get("user_rec_mobile") != null ? UNOrder.get("user_rec_mobile").toString() : "";
recipientVO.setPhoneNumber(mobile);
String postalCode = UNOrder.get("user_rec_code") != null ? UNOrder.get("user_rec_code").toString() : "";
recipientVO.setPostalCode(postalCode);
String area = UNOrder.get("user_rec_area") != null ? UNOrder.get("user_rec_area").toString() : "";
recipientVO.setArea(area);
String inPrice = UNOrder.get("in_price")!=null?UNOrder.get("in_price").toString():"";
String retailPrice = UNOrder.get("price")!=null?UNOrder.get("price").toString():"";
String orderLineNum = UNOrder.get("order_line_num").toString();
double discountTax = getDiscountTax(orderLineNum);
BigDecimal discount = (new BigDecimal(1)).subtract((new BigDecimal(inPrice)).multiply(new BigDecimal(discountTax)).divide(new BigDecimal(retailPrice), 2, RoundingMode.HALF_UP));
UNOrder.put("discount", discount.multiply(new BigDecimal("100")).setScale(0, BigDecimal.ROUND_HALF_UP).toString() + "%");
UNOrder.put("in_price", (new BigDecimal(inPrice).setScale(2, BigDecimal.ROUND_HALF_UP).toString()));
UNOrder.put("price", (new BigDecimal(retailPrice).setScale(2, BigDecimal.ROUND_HALF_UP).toString()));
/*AddressCountry addressCountry = addressCountryService.getAddressCountryByName(UNOrder.get("countryName").toString());
Tax tax = taxService.getTaxByAddressCountryId(addressCountry.getAddressCountryId());
BigDecimal taxRate = tax.getTaxRate() == null ? new BigDecimal("0") : tax.getTaxRate();*/
BigDecimal taxRate = taxService.calculateTax(orderLineNum);
BigDecimal total = new BigDecimal(Double.parseDouble(UNOrder.get("in_price").toString()) * Double.parseDouble(UNOrder.get("amount").toString())).setScale(2, BigDecimal.ROUND_HALF_UP);
BigDecimal VAT = total.multiply(taxRate).setScale(2, BigDecimal.ROUND_HALF_UP);
BigDecimal grandTotal = (VAT.add(total)).setScale(2,BigDecimal.ROUND_HALF_UP);
List<Map<String, Object>> list = new ArrayList<>();
list.add(UNOrder);
if(isDDt){
ddtInvoice.getList().addAll(list);
ddtAllTotal = ddtAllTotal.add(total);
ddtGrandTotal = ddtGrandTotal.add(grandTotal);
ddtVAT = ddtVAT.add(VAT);
ddtAllQty++;
}
UNInvoiceVO.setList(list);
UNInvoiceVO.setShipperVO(shipperVO);
UNInvoiceVO.setInvoiceFromVO(invoiceForm);
UNInvoiceVO.setRecipientVO(recipientVO);
UNInvoiceVO.setInvoiceTo((String) resultMap.get("InvoiceTo"));
UNInvoiceVO.setInvoiceName((String) resultMap.get("InvoiceName"));
UNInvoiceVO.setInvoicePersonName((String) resultMap.get("contactPersonName"));
UNInvoiceVO.setVatNum((String) resultMap.get("VATNumber"));
UNInvoiceVO.setInvoiceDate((String) resultMap.get("InvoiceDate"));
UNInvoiceVO.setInvoiceNum((String) resultMap.get("InvoiceNumber"));
UNInvoiceVO.setShipmentNo((String) resultMap.get("shipmentNo"));
UNInvoiceVO.setGrandTotal(grandTotal.toString());
UNInvoiceVO.setAllTotal(total.toString());
UNInvoiceVO.setVat(VAT.toString());
UNInvoiceVO.setAllQty(String.valueOf(list.size()));
UNInvoiceList.add(UNInvoiceVO);
}
}
// 获取到其他国家的数据
conditionMap.put("shipmentIds",shipmentIds);
conditionMap.put("packGroup", 4);
List<Map<String, Object>> elselist = orderService.getOrderListByShipmentId(conditionMap);
if (elselist != null && elselist.size() > 0) {
List<InvoiceVO> elseInvoiceList = new ArrayList<>();
if(!isDDt){
transitWarehouseInvoiceVO.setOtherInvoices(elseInvoiceList);
}
for (Map<String,Object> elseOrder: elselist){
InvoiceVO elseInvoiceVO = new InvoiceVO();
RecipientVO recipientVO = new RecipientVO();
String country = elseOrder.get("user_rec_country") != null ? elseOrder.get("user_rec_country").toString() : "";
recipientVO.setCountry(country);
String personName = elseOrder.get("user_rec_name") != null ? elseOrder.get("user_rec_name").toString() : "";
recipientVO.setPersonName(personName);
String province = elseOrder.get("user_rec_province") != null ? elseOrder.get("user_rec_province").toString() : "";
recipientVO.setProvince(province);
String city = elseOrder.get("user_rec_city") != null ? elseOrder.get("user_rec_city").toString() : "";
recipientVO.setCity(city);
String addr = elseOrder.get("user_rec_addr") != null ? elseOrder.get("user_rec_addr").toString() : "";
recipientVO.setStreetLines(addr);
String mobile = elseOrder.get("user_rec_mobile") != null ? elseOrder.get("user_rec_mobile").toString() : "";
recipientVO.setPhoneNumber(mobile);
String postalCode = elseOrder.get("user_rec_code") != null ? elseOrder.get("user_rec_code").toString() : "";
recipientVO.setPostalCode(postalCode);
String area = elseOrder.get("user_rec_area") != null ? elseOrder.get("user_rec_area").toString() : "";
recipientVO.setArea(area);
String inPrice = elseOrder.get("in_price")!=null?elseOrder.get("in_price").toString():"";
String retailPrice = elseOrder.get("price")!=null?elseOrder.get("price").toString():"";
String orderLineNum = elseOrder.get("order_line_num").toString();
double discountTax = getDiscountTax(orderLineNum);
BigDecimal discount = (new BigDecimal(1)).subtract((new BigDecimal(inPrice)).multiply(new BigDecimal(discountTax)).divide(new BigDecimal(retailPrice), 2, RoundingMode.HALF_UP));
elseOrder.put("discount", discount.multiply(new BigDecimal("100")).setScale(0, BigDecimal.ROUND_HALF_UP).toString() + "%");
elseOrder.put("in_price", (new BigDecimal(inPrice).setScale(2, BigDecimal.ROUND_HALF_UP).toString()));
elseOrder.put("price", (new BigDecimal(retailPrice).setScale(2, BigDecimal.ROUND_HALF_UP).toString()));
/*AddressCountry addressCountry = addressCountryService.getAddressCountryByName(elseOrder.get("countryName").toString());
Tax tax = taxService.getTaxByAddressCountryId(addressCountry.getAddressCountryId());
BigDecimal taxRate = tax.getTaxRate() == null ? new BigDecimal("0") : tax.getTaxRate();*/
BigDecimal taxRate = taxService.calculateTax(orderLineNum);
BigDecimal total = new BigDecimal(Double.parseDouble(elseOrder.get("in_price").toString()) * Double.parseDouble(elseOrder.get("amount").toString())).setScale(2, BigDecimal.ROUND_HALF_UP);
BigDecimal VAT = total.multiply(taxRate).setScale(2, BigDecimal.ROUND_HALF_UP);
BigDecimal grandTotal = (VAT.add(total)).setScale(2,BigDecimal.ROUND_HALF_UP);
List<Map<String, Object>> list = new ArrayList<>();
list.add(elseOrder);
if(isDDt){
ddtInvoice.getList().addAll(list);
ddtAllTotal = ddtAllTotal.add(total);
ddtGrandTotal = ddtGrandTotal.add(grandTotal);
ddtVAT = ddtVAT.add(VAT);
ddtAllQty++;
}
elseInvoiceVO.setList(list);
elseInvoiceVO.setShipperVO(shipperVO);
elseInvoiceVO.setInvoiceFromVO(invoiceForm);
elseInvoiceVO.setRecipientVO(recipientVO);
elseInvoiceVO.setInvoiceTo((String) resultMap.get("InvoiceTo"));
elseInvoiceVO.setInvoiceName((String) resultMap.get("InvoiceName"));
elseInvoiceVO.setInvoicePersonName((String) resultMap.get("contactPersonName"));
elseInvoiceVO.setVatNum((String) resultMap.get("VATNumber"));
elseInvoiceVO.setInvoiceDate((String) resultMap.get("InvoiceDate"));
elseInvoiceVO.setInvoiceNum((String) resultMap.get("InvoiceNumber"));
elseInvoiceVO.setShipmentNo((String) resultMap.get("shipmentNo"));
elseInvoiceVO.setGrandTotal(grandTotal.toString());
elseInvoiceVO.setAllTotal(total.toString());
elseInvoiceVO.setVat(VAT.toString());
elseInvoiceVO.setAllQty(String.valueOf(elseOrder.size()));
elseInvoiceList.add(elseInvoiceVO);
}
}
if(isDDt){
List<InvoiceVO> ddtInvoices = new ArrayList<>();
ddtInvoice.setGrandTotal(ddtGrandTotal.toString());
ddtInvoice.setAllTotal(ddtAllTotal.setScale(2,BigDecimal.ROUND_HALF_UP).toString());
ddtInvoice.setVat(ddtVAT.toString());
ddtInvoice.setAllQty(ddtAllQty.toString());
ddtInvoices.add(ddtInvoice);
transitWarehouseInvoiceVO.setUNInvoices(ddtInvoices);
}
try {
String isExcel = map.get("isExcel")!=null?map.get("isExcel").toString():null;
if(isExcel!=null&&"1".equals(isExcel)){
printExcelShipmentInfo(response, transitWarehouseInvoiceVO);
}
result.successStatus();
result.setData(transitWarehouseInvoiceVO);
} catch (Exception e) {
e.printStackTrace();
result.setMsg("Query container list fail,Check parameters, please ");
return result;
}
return result;
}
private double getDiscountTax(String orderLineNum) {
Tax tax = taxService.calculateDiscountTax(orderLineNum);
double discountTax;
if (tax != null){
discountTax = tax.getTaxRate().doubleValue() + 1;
}else {
discountTax = 1;
}
return discountTax;
}
/**
* 发往COMO的发票
* @param map
* @param httpRequest
* @param response
* @return
*/
@RequestMapping(value = "/printComoInvoice", method = RequestMethod.POST)
@ResponseBody
public ResultMessage printComoInvoice(@RequestBody Map<String,Object> map, HttpServletRequest httpRequest,HttpServletResponse response) {
Map<String, Object> resultMap = new HashMap<>();
ResultMessage result = new ResultMessage();
result.errorStatus();
if (map == null || map.size() == 0 || map.get("status") == null
|| map.get("shipment_id") == null) {
result.setMsg("Parameter cannot be empty");
return result;
}
User user = this.getUser(httpRequest);
if (user == null) {
result.setMsg("Please log in again");
return result;
}
Vendor vendor = null;
try {
vendor = vendorService.getVendorByUserId(user.getUserId());
} catch (Exception e) {
e.printStackTrace();
}
if (vendor == null) {
result.setMsg("Please log in again");
return result;
}
long shipment_id = Long.parseLong(map.get("shipment_id").toString());
//根据shipmentId 获取shipment 相关信息及物流第一段类型
logger.info("打印Invoice----根据shipmentId 获取shipment 相关信息及物流第一段类型,开始获取");
Map<String, Object> getShipment = new HashMap<>();
getShipment.put("shipmentId", shipment_id);
Map<String, Object> shipmentMap = iShipmentService.getShipmentTypeById(getShipment);
if (shipmentMap == null || shipmentMap.size() == 0) {
logger.info("获取失败");
result.setMsg("Query Shipment fail,Check parameters, please ");
return result;
}
Long vendorId = Long.valueOf(shipmentMap.get("vendor_id").toString());
vendor = getVendor(vendor, vendorId);
TransitWarehouseInvoiceVO transitWarehouseInvoiceVO = new TransitWarehouseInvoiceVO();
//获取Ship From信息
StockLocation location = stockLocationService.getShipFromLocation(shipment_id);
AddressCountry addressCountry = addressCountryService.getAddressCountryByCountryCode(location.getAddressCountryCode());
String countryName = "Italy";
if (addressCountry != null){
countryName = addressCountry.getEnglishName();
}
ShipperVO shipperVO = new ShipperVO();
shipperVO.setCompanyName(location.getContactCompanyName());
shipperVO.setPersonName(location.getContactPersonName());
shipperVO.setPhoneNumber(location.getContactPhoneNumber());
shipperVO.setStreetLines(location.getAddressStreetlines());
shipperVO.setStreetLines2(location.getAddressStreetlines2());
shipperVO.setStreetLines3(location.getAddressStreetlines3());
shipperVO.setCity(location.getAddressCity());
shipperVO.setCountry(countryName);
ShipperVO invoiceForm = new ShipperVO();
invoiceForm.setCompanyName(vendor.getCompanyName());
invoiceForm.setPersonName(vendor.getRegisteredPerson());
invoiceForm.setStreetLines(vendor.getBusinessLicenseLocation());
invoiceForm.setCountry(countryName);
//获取Invoice 信息
logger.info("打印Invoice----获取Invoice信息");
Map<String, Object> invoiceMap = new HashMap<>();
invoiceMap.put("type", 1);
invoiceMap.put("shipmentId", shipment_id);
Invoice invoice = invoiceService.getInvoiceByMap(invoiceMap);
if (invoice!=null){
//获取Invoice To信息
logger.info("打印Invoice----获取Invoice To信息");
Shop shop = shopService.selectByPrimaryKey(65l);
resultMap.put("InvoiceTo", shop.getBusinessLicenseLocation());
resultMap.put("InvoiceName", shop.getShopName());
resultMap.put("contactPersonName", shop.getContactPersonName());
}
map.put("vendorIds", Arrays.asList(vendorId));
resultMap.put("shipmentNo",shipmentMap.get("shipment_no"));
logger.info("打印Invoice----获取shipment相关信息及物流第一段类型成功");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat sdf2 = new SimpleDateFormat("dd/MM/yyyy");
resultMap.put("InvoiceNumber", invoice.getInvoiceNum());
if (invoice.getInvoiceDate() != null) {
String invoiceDate = sdf.format(invoice.getInvoiceDate());
try {
resultMap.put("InvoiceDate", sdf2.format(sdf.parse(invoiceDate)));
} catch (ParseException e) {
logger.error("Query container list fail invoiceDate="+invoiceDate, e);
result.setMsg("Query container list fail,Check parameters, please ");
return result;
}
} else {
result.setMsg("invoiceDate is null ");
return result;
}
resultMap.put("VATNumber", invoice.getVatNum());
//获取发往中国大陆,香港,澳门的订单列表
RecipientVO recipientVO = new RecipientVO();
recipientVO.setCountry("Via Manzoni 19 Montano Lucino, 22070, Como,Italy");
Set<Long> shipmentIds = new HashSet<>();
shipmentIds.add(shipment_id);
Map<String, Object> conditionMap = new HashMap<>();
conditionMap.put("status", map.get("status"));
conditionMap.put("vendorIds", Arrays.asList(vendorId));
conditionMap.put("shipmentIds", shipmentIds);
List<Map<String, Object>> orderList = orderService.getOrderListByShipmentId(conditionMap);
if( orderList != null && orderList.size() > 0 ){
InvoiceVO invoiceVO = new InvoiceVO();
transitWarehouseInvoiceVO.setChinaInvoice(invoiceVO);
//获取shipTo地址信息
BigDecimal VAT = new BigDecimal(0);
BigDecimal allTotal = new BigDecimal(0);
for(Map<String, Object> order : orderList){
String orderLineNum = order.get("order_line_num").toString();
BigDecimal taxRate = taxService.calculateTax(orderLineNum);
BigDecimal total = new BigDecimal(Double.parseDouble(order.get("in_price").toString()) * Double.parseDouble(order.get("amount").toString())).setScale(2, BigDecimal.ROUND_HALF_UP);
VAT = VAT.add(total.multiply(taxRate).setScale(2, BigDecimal.ROUND_HALF_UP));
allTotal = allTotal.add(total);
String inPrice = order.get("in_price")!=null?order.get("in_price").toString():"";
String retailPrice = order.get("price")!=null?order.get("price").toString():"";
double discountTax = getDiscountTax(orderLineNum);
BigDecimal discount = (new BigDecimal(1)).subtract((new BigDecimal(inPrice)).multiply(new BigDecimal(discountTax)).divide(new BigDecimal(retailPrice), 2, RoundingMode.HALF_UP));
order.put("discount", discount.multiply(new BigDecimal("100")).setScale(0, BigDecimal.ROUND_HALF_UP).toString() + "%");
order.put("in_price", (new BigDecimal(inPrice).setScale(2, BigDecimal.ROUND_HALF_UP).toString()));
order.put("price", (new BigDecimal(retailPrice).setScale(2, BigDecimal.ROUND_HALF_UP).toString()));
}
BigDecimal grandTotal = (VAT.add(allTotal)).setScale(2,BigDecimal.ROUND_HALF_UP);
invoiceVO.setList(orderList);
invoiceVO.setRecipientVO(recipientVO);
invoiceVO.setShipperVO(shipperVO);
invoiceVO.setInvoiceFromVO(invoiceForm);
invoiceVO.setInvoiceTo((String) resultMap.get("InvoiceTo"));
invoiceVO.setInvoiceName((String) resultMap.get("InvoiceName"));
invoiceVO.setInvoicePersonName((String)resultMap.get("contactPersonName"));
invoiceVO.setVatNum((String) resultMap.get("VATNumber"));
invoiceVO.setInvoiceDate((String) resultMap.get("InvoiceDate"));
invoiceVO.setInvoiceNum((String) resultMap.get("InvoiceNumber"));
invoiceVO.setShipmentNo((String) resultMap.get("shipmentNo"));
invoiceVO.setGrandTotal(grandTotal.toString());
invoiceVO.setAllTotal(allTotal.toString());
invoiceVO.setVat(VAT.toString());
invoiceVO.setAllQty(String.valueOf(orderList.size()));
invoiceVO.setRemark("Shipment exempt from VAT - IVA non imponibile Art. 8 1°C L/A DPR 633/72");
}
try {
printExcelShipmentInfo(response, transitWarehouseInvoiceVO);
result.successStatus();
result.setData(transitWarehouseInvoiceVO);
} catch (Exception e) {
e.printStackTrace();
result.setMsg("Query container list fail,Check parameters, please ");
return result;
}
return result;
}
private Vendor getVendor(Vendor vendor, Long vendorId) {
if (!vendorId.equals(vendor.getVendorId())){
//取子买手店信息
Map<String,Object> params = new HashMap<>();
params.put("vendor_id",vendorId);
Vendor vendorByVendorId = vendorService.getVendorByVendorId(params);
if (vendorByVendorId!=null){
vendor = vendorByVendorId;
}
}
return vendor;
}
/**
* packingList
*
* @param map
* @param httpRequest
* @return
*/
@RequestMapping(value = "/printPackingList", method = RequestMethod.POST)
@ResponseBody
public ResultMessage printPackingList(@RequestBody Map<String, Object> map, HttpServletRequest httpRequest) {
ResultMessage result = new ResultMessage();
result.errorStatus();
if (map == null || map.size() == 0 || map.get("status") == null
|| map.get("shipment_id") == null) {
result.setMsg("Parameter cannot be empty");
return result;
}
User user = this.getUser(httpRequest);
if (user == null) {
result.setMsg("Please log in again");
return result;
}
List<Vendor> vendors = null;
try {
vendors = vendorService.getVendorsByUserId(user.getUserId());
} catch (Exception e) {
e.printStackTrace();
}
if (CollectionUtils.isEmpty(vendors)) {
result.setMsg("Please log in again");
return result;
}
List<Long> vendorIds = vendors.stream().map(Vendor::getVendorId).collect(Collectors.toList());
try {
map.put("vendorIds", vendorIds);
Map<String, Object> getShipment = new HashMap<String, Object>();
getShipment.put("shipmentId", Long.parseLong(map.get("shipment_id").toString()));
logger.info("打印PackList----根据shipmentId 获取shipment相关信息及物流第一段类型");
//根据shipmentId 获取shipment 相关信息及物流第一段类型
Map<String, Object> shipmentMap = iShipmentService.getShipmentTypeById(getShipment);
if (shipmentMap == null || shipmentMap.size() == 0) {
result.setMsg("Query Shipment fail,Check parameters, please ");
return result;
}
//获取carton列表
logger.info("打印PackList----获取carton列表");
Set<Long> shipmentIds = new HashSet<>();
shipmentIds.add(Long.parseLong(map.get("shipment_id").toString()));
map.put("shipmentIds",shipmentIds);
List<Map<String, Object>> containerList = orderService.getOrderListByShipmentId(map);
Map<String, Object> resultMap = new HashMap<String, Object>();
Map<String, List<Map<String, Object>>> orderList = new HashMap<>();
List<Map<String, Object>> shipMentCartonList = new ArrayList<>();
if (containerList != null && containerList.size() > 0) {
for (Map<String, Object> container : containerList) {
//根据shipment_id 分组
if (orderList.containsKey(container.get("container_id").toString())) {
List<Map<String, Object>> cons = orderList.get(container.get("container_id").toString());
cons.add(container);
} else {
List<Map<String, Object>> cons = new ArrayList<Map<String, Object>>();
cons.add(container);
orderList.put(container.get("container_id").toString(), cons);
//获取container信息
Map<String, Object> cartonInfo = new HashMap<String, Object>();
cartonInfo.put("container_id", container.get("container_id").toString());
cartonInfo.put("ship_to_geography", container.get("ship_to_geography").toString());
cartonInfo.put("barcode", container.get("barcode").toString());
//生成条形码
String cartonNumUrl = "Barcode-" + container.get("barcode").toString() + ".png";
cartonNumUrl = BarcodeUtil.generateFile(container.get("barcode").toString(), cartonNumUrl, false);
cartonInfo.put("cartonNumUrl", cartonNumUrl);
cartonInfo.put("height", container.get("height").toString());
cartonInfo.put("width", container.get("width").toString());
cartonInfo.put("length", container.get("length").toString());
String weight = container.get("weight").toString();
BigDecimal decimal = new BigDecimal(weight);
cartonInfo.put("weight",decimal.setScale(2,BigDecimal.ROUND_HALF_UP).toString());
shipMentCartonList.add(cartonInfo);
}
}
if (shipMentCartonList != null && shipMentCartonList.size() > 0) {
//将orderList 存入container详情
for (Map<String, Object> carton : shipMentCartonList) {
List<Map<String, Object>> list = orderList.get(carton.get("container_id").toString());
carton.put("orderList", list);
double allTotal = 0;
for (Map<String, Object> conInfo : list) {
double total = Double.parseDouble(conInfo.get("in_price").toString()) * Double.parseDouble(conInfo.get("amount").toString());
allTotal = allTotal + total;
conInfo.put("Total", total);
carton.put("allTotal", list == null ? 0 : list.size());
carton.put("allTotalNum", allTotal);
}
carton.put("order_qty", orderList.get(carton.get("container_id").toString()).size());
}
}
}
shipmentMap.put("carton_qty", shipMentCartonList == null ? 0 : shipMentCartonList.size());
resultMap.put("cartonList", shipMentCartonList);
resultMap.put("shipmentInfo", shipmentMap);
result.successStatus();
result.setData(resultMap);
} catch (Exception e) {
e.printStackTrace();
result.setMsg("Query container list fail,Check parameters, please ");
return result;
}
return result;
}
@RequestMapping(value = "/printAWBNum", method = RequestMethod.POST)
@ResponseBody
public ResultMessage printAWBNum(@RequestBody Map<String, Object> map, HttpServletRequest httpRequest){
ResultMessage result = new ResultMessage();
result.errorStatus();
if (map == null || map.get("shipment_id") == null) {
result.setMsg("shipment_id cannot be empty");
return result;
}
User user = this.getUser(httpRequest);
if (user == null) {
result.setMsg("Please log in again");
return result;
}
Vendor vendor = null;
try {
vendor = vendorService.getVendorByUserId(user.getUserId());
} catch (Exception e) {
e.printStackTrace();
}
if (vendor == null) {
result.setMsg("Please log in again");
return result;
}
DHLInputVO inputVO = new DHLInputVO();
Long shipmentId = Long.parseLong(map.get("shipment_id").toString());
// 校验invoice
/*VendorShipment vendorShipment = invoiceService.queryVendorShipmentByShipmentId(shipmentId);
if(vendorShipment == null){
result.setMsg("Please upload invoice");
return result;
}*/
if (map.get("shipmentDate")!=null){
Long shipmentDate = Long.parseLong(map.get("shipmentDate").toString());
inputVO.setShipmentDate(shipmentDate);
}
if (map.get("specialPickupInstruction")!=null){
inputVO.setSpecialPickupInstruction(map.get("specialPickupInstruction").toString());
}
if (map.get("pickupLocation")!=null){
inputVO.setPickupLocation(map.get("pickupLocation").toString());
}
Map<String,Object> params = new HashMap<>();
//查询close状态纸箱
//params.put("status",2);
params.put("shipmentId",shipmentId);
//查询第一段
params.put("sequence",1);
SubShipment dhlShipment = subShipmentService.getDHLShipment(params);
List<Map<String, Object>> containerList = containerService.getListByShipmentId(params);
Shipment shipment = iShipmentService.selectShipmentById(params);
String oldAwbNo = null;
if(dhlShipment!=null){
if(StringUtil.isNotEmpty(dhlShipment.getAwbNum())){
/*String s;
try {
//获取awb文档
s = HttpClientUtil.httpGet(HttpClientUtil.queryAWBUrl + dhlShipment.getAwbNum());
}catch (Exception e){
result.addMsg("DHL service invocation failed");
logger.error("request fail,params={},url={}",JsonTransformUtil.toJson(inputVO),HttpClientUtil.createAWBUrl);
return result;
}
if(StringUtil.isNotEmpty(s)){
JSONObject jo = JSONObject.fromObject(s);
result.successStatus();
jo.put("shipmentNo",shipment.getShipmentNo());
result.setData(jo);
return result;
}*/
//删除awb
/*Map<String,Object> deleteParams = new HashMap<>();
deleteParams.put("awbNo",dhlShipment.getAwbNum());
deleteParams.put("requestorName",user.getUsername());
deleteParams.put("reason","001");
String s;
try{
s = HttpClientUtil.httpPost(JsonTransformUtil.toJson(deleteParams), HttpClientUtil.deleteAWBUrl);
}catch (Exception e){
logger.error("request fail,params={},url={}",JsonTransformUtil.toJson(deleteParams),HttpClientUtil.deleteAWBUrl);
result.setMsg("DHL service invocation failed");
return result;
}
if (StringUtil.isEmpty(s)){
logger.error("deleteAWB fail");
result.errorStatus().putMsg("Info", "deleteAWB fail");
return result;
}*/
//deleteParams.put("shipmentId",map.get("shipmentId"));
//deleteParams.put("awbNo","");
//subShipmentService.updateSubShipment(deleteParams);
oldAwbNo = dhlShipment.getAwbNum();
}
StockLocation fromLocation = stockLocationService.getShipFromLocation(shipmentId);
String countryCode = "IT";
if (fromLocation != null){
countryCode = fromLocation.getAddressCountryCode();
}
if ("IT".equalsIgnoreCase(countryCode)){
inputVO.setPickupType("pickup");
}else {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_YEAR, 1);
Date currentTime = calendar.getTime();
//获取意大利时间,再往后延一天
inputVO.setShipmentDate(currentTime.getTime());
}
if (shipment!=null){
String shipToGeography = shipment.getShipToGeography();
/*if ("European Union".equals(shipToGeography)){
if (countryCode.equalsIgnoreCase(dhlShipment.getShipToCountryCode())){
inputVO.setServiceType("N");
}else {
inputVO.setServiceType("U");
}
}else*/
if ("Transit Warehouse".equals(shipToGeography)){
if ("IT".equalsIgnoreCase(countryCode)){
inputVO.setServiceType("N");
}else {
inputVO.setServiceType("P");
}
}else if ("Other".equalsIgnoreCase(shipToGeography)){
if (countryCode.equalsIgnoreCase(dhlShipment.getShipToCountryCode())){
inputVO.setServiceType("N");
}else {
inputVO.setServiceType("P");
}
} else {
inputVO.setServiceType("P");
}
}
if ("P".equalsIgnoreCase(inputVO.getServiceType())){
//只有类型ServiceType=P时才需要customsValue
BigDecimal customValue = iShipmentService.getCustomValue(params);
if (customValue!=null){
inputVO.setCustomsValue(customValue.setScale(2,BigDecimal.ROUND_HALF_UP));
}
}
addParams(inputVO,dhlShipment,fromLocation,containerList,shipment);
String resultStr;
try{
logger.info("shipmentRequest,params={},url={}",JsonTransformUtil.toJson(inputVO), HttpClientUtil.createAWBUrl);
resultStr = HttpClientUtil.httpPost(JsonTransformUtil.toJson(inputVO), HttpClientUtil.createAWBUrl);
}catch (Exception e){
result.addMsg("DHL service invocation failed");
logger.error("request fail,params={},url={}",JsonTransformUtil.toJson(inputVO), HttpClientUtil.createAWBUrl);
return result;
}
if(StringUtil.isNotEmpty(resultStr)){
JSONObject object = JSONObject.fromObject(resultStr);
if(object.optInt("status")!=1) {
//获取DHL报错信息
String msg = object.optString("msg");
/*JSONObject jsonObject = JSONObject.fromObject(msg);
JSONObject shipmentResponse = jsonObject.optJSONObject("ShipmentResponse");
JSONArray notification = shipmentResponse.optJSONArray("Notification");
msg = notification.get(0).toString();
String message = JSONObject.fromObject(msg).optString("Message");
if (message.contains("[")&&message.contains("]")&&message.contains(":")){
message = convertMsg(message);
}
message = message + ". Please contact customer to adjust! ";*/
result.addMsg(msg);
return result;
}
JSONObject jo = JSONObject.fromObject(resultStr);
String awbNo = jo.optString("awbNo");
//保存到subShipment
params.put("awbNo",awbNo);
subShipmentService.updateSubShipment(params);
result.successStatus();
jo.put("shipmentNo",shipment.getShipmentNo());
jo.put("recipient",inputVO.getRecipient());
jo.remove("status");
result.setData(jo);
// if awbAdvance = 1 提前生成的 更新shipment信息
Map<String,Object> awbAdvanceMap = new HashMap<>();
awbAdvanceMap.put("shipment_id",shipmentId);
if(map.containsKey("awbAdvance") && map.get("awbAdvance").toString().equals("1")){
awbAdvanceMap.put("awbAdvance",1);
}else {
awbAdvanceMap.put("awbAdvance",0);
}
iShipmentService.updateShipmentAwbAdvance(awbAdvanceMap);
//保存awb单号
List<LogisticsProductVO> productVOList = iShipmentService.getlogisticsMilestone(shipmentId);
if (productVOList!=null&&productVOList.size()>0){
for (LogisticsProductVO vo:productVOList){
vo.setAwb(awbNo);
vo.setIsComplete(0);
vo.setShipmentType(3);
vo.setType(4);
iShipmentService.saveMilestone(vo);
}
}
logger.info("shipmentNo:{},新生成awb为{},并同步到物流数据中",shipment.getShipmentNo(),awbNo);
if (oldAwbNo != null){
//删除物流表中旧的awb单号
iShipmentService.deleteMilestone(oldAwbNo);
logger.info("awb:{}已从物流数据中删除",oldAwbNo);
}
return result;
}
}
return result;
}
public static String convertMsg(String message) {
String msg = "";
if (StringUtil.isNotEmpty(message)){
int i1 = message.indexOf("]");
int i2 = message.indexOf(":");
int i = message.indexOf("-");
boolean maximum = message.contains("maximum");
String substring = message.substring(i1 + 1, i);
String s = message.substring(i2+1);
String[] split = s.split("/");
String filed = "";
if (split.length>=3){
filed = split[split.length-3]+"."+split[split.length-2]+"."+split[split.length-1];
}else {
filed = s;
}
if (maximum){
msg = substring.trim() + "(35 characters) ";
}else {
msg = substring.trim() + " ";
}
msg += "Filed: "+filed;
}
return msg;
}
private void addParams(DHLInputVO inputVO, SubShipment dhlShipment,StockLocation fromLocation, List<Map<String, Object>> containerList,Shipment shipment) {
SimpleDateFormat f1 = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat f2 = new SimpleDateFormat("HH:mm:ssz");
//Calendar calendar = Calendar.getInstance();
//calendar.add(Calendar.DAY_OF_YEAR, 1);
//Date currentTime = calendar.getTime();
Date currentTime = new Date(inputVO.getShipmentDate());
inputVO.setShipmentDate(null);
try {
//System.out.println(f1.parse("2015-12-12"));
f1.setTimeZone(TimeZone.getTimeZone("GMT+01:00"));
f2.setTimeZone(TimeZone.getTimeZone("GMT+01:00"));
} catch (Exception e) {
e.printStackTrace();
}
//更换账号2018-08-02
inputVO.setAccount("106841512");
inputVO.setShipmentTime(f1.format(currentTime)+"T"+f2.format(currentTime));
inputVO.setDescription("clothing");
inputVO.setLabelType("PDF");
inputVO.setLabelTemplate("ECOM26_A4_001");
if (fromLocation!=null){
ShipperVO shipperVO = new ShipperVO();
shipperVO.setCity(fromLocation.getAddressCity());
shipperVO.setCompanyName(fromLocation.getContactCompanyName());
shipperVO.setPersonName(fromLocation.getContactPersonName());
shipperVO.setPhoneNumber(fromLocation.getContactPhoneNumber());
shipperVO.setEmailAddress(fromLocation.getContactEmailAddress());
shipperVO.setStreetLines(fromLocation.getAddressStreetlines());
if (StringUtil.isNotEmpty(fromLocation.getAddressStreetlines2())){
shipperVO.setStreetLines2(fromLocation.getAddressStreetlines2());
}
if (StringUtil.isNotEmpty(fromLocation.getAddressStreetlines3())){
shipperVO.setStreetLines3(fromLocation.getAddressStreetlines3());
}
shipperVO.setPostalCode(fromLocation.getAddressPostalCode());
shipperVO.setCountryCode(fromLocation.getAddressCountryCode());
inputVO.setShipper(shipperVO);
}
if (dhlShipment!=null){
RecipientVO recipientVO = new RecipientVO();
recipientVO.setCity(dhlShipment.getShipToCity());
recipientVO.setCompanyName(dhlShipment.getConsignee());
recipientVO.setPersonName(dhlShipment.getPersonName());
recipientVO.setPhoneNumber(dhlShipment.getContact());
recipientVO.setEmailAddress(dhlShipment.getShipToEamilAddr());
String shipToAddr = dhlShipment.getShipToAddr();
if (shipToAddr.length()>35){
shipToAddr = shipToAddr.substring(0,34);
}
recipientVO.setStreetLines(shipToAddr);
if (StringUtil.isNotEmpty(dhlShipment.getShipToAddr2())
&&!"0".equals(dhlShipment.getShipToAddr2())){
recipientVO.setStreetLines2(dhlShipment.getShipToAddr2());
}
if (StringUtil.isNotEmpty(dhlShipment.getShipToAddr3())
&&!"0".equals(dhlShipment.getShipToAddr3())){
recipientVO.setStreetLines3(dhlShipment.getShipToAddr3());
}
if(dhlShipment.getPostalCode()!=null){
recipientVO.setPostalCode(dhlShipment.getPostalCode());
}else {
recipientVO.setPostalCode("101731");
}
recipientVO.setCountryCode(dhlShipment.getShipToCountryCode());
inputVO.setRecipient(recipientVO);
}
if(containerList!=null&&containerList.size()>0){
List<Map<String,Object>> list = new ArrayList<>();
for (Map<String,Object> map:containerList){
Map<String,Object> container = new HashMap<>();
container.put("barcode",shipment.getShipmentNo()+"/"+map.get("barcode"));
container.put("length",map.get("length"));
container.put("width",map.get("width"));
container.put("height",map.get("height"));
container.put("weight",new BigDecimal(map.get("weight").toString()).setScale(2,BigDecimal.ROUND_HALF_UP).toString());
list.add(container);
}
inputVO.setPackageInfos(list);
}
}
}
| true |
80cca1c7e305c4a68235fdae0e975bdb12b7baeb | Java | michal257/day_schedule_android | /app/src/main/java/com/project/dayshedule/dayshedule/Groceries/GroceriesCategoryListActivity.java | UTF-8 | 3,123 | 2.125 | 2 | [] | no_license | package com.project.dayshedule.dayshedule.Groceries;
import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.ListView;
import com.project.dayshedule.dayshedule.Enum.RequestType;
import com.project.dayshedule.dayshedule.Enum.ResultType;
import com.project.dayshedule.dayshedule.Interface.OnTaskCompleted;
import com.project.dayshedule.dayshedule.Models.GroceriesCategoryModel;
import com.project.dayshedule.dayshedule.R;
import com.project.dayshedule.dayshedule.RequestData;
import com.project.dayshedule.dayshedule.RequestDataParameters;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class GroceriesCategoryListActivity extends AppCompatActivity {
private ListView lvGroceriesCategory;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_groceries_category);
setStatusBar();
lvGroceriesCategory = (ListView) findViewById(R.id.listView_groceries_category);
getGroceriesCategory();
}
@TargetApi(Build.VERSION_CODES.M)
private void setStatusBar(){
Window window = getWindow();
window.setStatusBarColor(getColor(R.color.colorPrimaryDark));
}
private void getGroceriesCategory(){
new RequestData(createGetGroceriesCategoryParam(), ResultType.ARRAY, new OnTaskCompleted() {
@Override
public void onTaskCompleted(Object obj) throws JSONException {
JSONArray jArray = (JSONArray) obj;
ArrayList<GroceriesCategoryModel> ArrayGroceriesCategory = new ArrayList<>();
for (int i = 0; i < jArray.length(); i++)
{
JSONObject g = (JSONObject) jArray.get(i);
ArrayGroceriesCategory.add(new GroceriesCategoryModel(Integer.parseInt(g.get("GID").toString()), g.get("Name").toString()));
}
GroceriesCategoryListAdapter adapter = new GroceriesCategoryListAdapter(GroceriesCategoryListActivity.this, ArrayGroceriesCategory);
lvGroceriesCategory.setAdapter(adapter);
}
}).execute();
}
private RequestDataParameters createGetGroceriesCategoryParam(){
RequestDataParameters param = new RequestDataParameters();
param.setmContext(GroceriesCategoryListActivity.this);
param.setMessage("Trwa pobieranie danych...");
param.setUrl("GroceriesCategoryController.php");
param.setReqType(RequestType.GET);
return param;
}
public void openAddCategory(View v){
Intent addCategory = new Intent(GroceriesCategoryListActivity.this, GroceriesCategoryAddActivity.class);
Bundle type = new Bundle();
type.putString("type", "add");
addCategory.putExtras(type);
startActivity(addCategory);
finish();
}
}
| true |
71f1f906e240db148cde75bd37047642971bf4c8 | Java | shivampathak94/otp-app-Angular | /Java-Code/rest/LoginController.java | UTF-8 | 1,221 | 2.3125 | 2 | [] | no_license | package com.prac1.springdemo.rest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class LoginController {
@ResponseBody
@GetMapping("/loginemployee")
public String loginEmp(String username, String password) {
if(username=="emp" && password=="1234") {
return "Employee Login Successfull";
}
else
return "Login failed";
}
@ResponseBody
@GetMapping("/loginadmin")
public String loginAdmin(String username, String password) {
if(username=="admin" && password=="1234") {
return "Admin Login Successfull";
}
else
return "Login failed";
}
@SuppressWarnings("unused")
@ResponseBody
@GetMapping("/registerlogin")
public String registerLogin(String name, String empId, String email, String projectCode, String projectName) {
name="Shivam";
empId="2323";
email="xyz@gmail.com";
projectCode="O4JT";
projectName="OneJava";
String username = null,password = null;
if(username=="register" && password=="1234") {
return "Registration";
}
else {
return "Registration Successfull";
}
}
}
| true |
9fd5b3f266ad8e004a695261a6a97e971c9bbd2e | Java | marcos8154/Persistor | /src/br/com/persistor/sessionManager/SessionFactory.java | UTF-8 | 2,984 | 2.421875 | 2 | [] | no_license | /*
* 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 br.com.persistor.sessionManager;
import br.com.persistor.connectionManager.DataSource;
import br.com.persistor.generalClasses.DBConfig;
import br.com.persistor.interfaces.Session;
/**
*
* @author Marcos Vinícius
*/
public class SessionFactory
{
private DataSource mainDataSource = null;
private DBConfig mainConfig = null;
private PersistenceContext persistenceContext;
public SessionFactory buildSession(DBConfig config)
{
try
{
this.persistenceContext = new PersistenceContext();
this.mainConfig = config;
mainDataSource = DataSource.getInstance(config);
return this;
}
catch (Exception ex)
{
System.err.println("Persistor: build SessionFactory error at: \n");
ex.printStackTrace();
}
return null;
}
public PersistenceContext getPersistenceContext()
{
return persistenceContext;
}
public void reset() throws Exception
{
mainDataSource.reset();
mainDataSource = null;
}
public DBConfig getConfig()
{
return this.mainConfig;
}
public Session getSession()
{
SessionImpl returnSessonImpl = null;
try
{
returnSessonImpl = new SessionImpl(mainDataSource.getConnection(), mainConfig);
if (persistenceContext.initialized)
returnSessonImpl.setSLContext(persistenceContext);
}
catch (Exception ex)
{
System.err.println("Persistor: create session error at: \n");
ex.printStackTrace();
}
return returnSessonImpl;
}
public Session getSession(DBConfig config) throws Exception
{
SessionImpl returnSessonImpl = null;
try
{
if (mainDataSource == null)
buildSession(config);
returnSessonImpl = new SessionImpl(mainDataSource.getConnection(), mainConfig);
if (mainConfig.getSlPersistenceContext() != null)
{
if (!persistenceContext.initialized)
{
System.err.println("Persistor: Initializing SL Persistence context...");
persistenceContext.Initialize(mainConfig.getSlPersistenceContext());
if (persistenceContext.initialized)
returnSessonImpl.setSLContext(persistenceContext);
}
else
returnSessonImpl.setSLContext(persistenceContext);
}
}
catch (Exception ex)
{
System.err.println("Persistor: create session error at: \n");
throw new Exception(ex.getMessage());
}
return returnSessonImpl;
}
}
| true |
84b84be8f3fee18c303a06fca73c45410237de3d | Java | eden9209/pokemons-game | /src/gameClient/myGui.java | UTF-8 | 8,223 | 2.65625 | 3 | [] | no_license | package gameClient;
import gameClient.CL_Pokemon;
import gameClient.CL_Agent;
import api.edge_data;
import api.game_service;
import api.directed_weighted_graph;
import api.node_data;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import org.json.JSONException;
import org.json.JSONObject;
import Server.Game_Server_Ex2;
import api.DWGraph_Algo;
import api.DWGraph_DS;
import api.Node;
import gameClient.util.Point3D;
import gameClient.util.StdDraw;
import api.game_service;
/*
* This class draw graphs using stdDraw
*/
public class myGui {
public DWGraph_Algo ga;
public HashMap<Integer, CL_Agent> agents;
public HashMap<Point3D, CL_Pokemon> pokemons;
public game_service game;
final double xMax = 35.216;
final double xMin = 35.1835;
final double yMax = 32.11;
final double yMin = 32.1;
/*
* Default constructor
*/
public myGui() {
ga = new DWGraph_Algo();
this.agents = new HashMap<>();
this.pokemons = new HashMap<>();
}
/*
* Copy constructor using the init function from Graph_Algo class
*/
public myGui(directed_weighted_graph g) {
this.ga = new DWGraph_Algo();
ga.init(g);
}
/*
* Add a node to the drawing using addNode function from DGraph
*/
public void addNode(Node a) {
ga.dg.addNode(a);
}
/*
* Draw the nodes
* @param x = the x of the node location (point)
* @param y = the y of the node location (point)
* @param abs = the number of the node
*/
public void drawNodes() {
try {
Collection<node_data> n=ga.dg.getV();
if(n != null && n.size() > 0) {
for (node_data a:n) {
double x=a.getLocation().x();
double y=a.getLocation().y();
StdDraw.setPenRadius(0.03);
StdDraw.setPenColor(StdDraw.BLUE);//nodes in blue
StdDraw.point(x,y);
StdDraw.setPenColor(StdDraw.BLACK);
String abs = a.getKey()+"";
StdDraw.text(x,y,abs);
}
}
}catch(Exception e) {
System.err.println("No nodes to draw");
}
}
/*
* Draw the edges
* @param allNodes = A collection of all the nodes
* @param allEdgesOfNode = A collection of all the edges that came out of the parameter's node
* @param Sx = the x of the source location
* @param Sy = the y of the source location
* @param Dx = the x of the destination location
* @param Dy = the y of the destination location
* @param arrowX = the x of the "arrow" point location
* @param arrowY = the y of the "arrow" point location
* @param te = the string of the weight number
*/
public void drawEdges() {
try {
Collection<node_data> allNodes = ga.dg.getV();
if(allNodes != null && allNodes.size() > 0) {
for(node_data n:allNodes) {
Collection<edge_data> allEdgesOfNode = ga.dg.getE(n.getKey());
if(allEdgesOfNode != null && allEdgesOfNode.size() > 0) {
for(edge_data edges:allEdgesOfNode) {
double Sx = ga.dg.getNode(edges.getSrc()).getLocation().x();
double Sy = ga.dg.getNode(edges.getSrc()).getLocation().y();
double Dx = ga.dg.getNode(edges.getDest()).getLocation().x();
double Dy = ga.dg.getNode(edges.getDest()).getLocation().y();
StdDraw.setPenRadius(0.005);
StdDraw.setPenColor(StdDraw.ORANGE);//paint the line between the nodes in orange
StdDraw.line(Sx,Sy,Dx,Dy);
StdDraw.setPenRadius(0.01);
StdDraw.setPenColor(StdDraw.RED);
double arrowX= (Dx*8+Sx)/9;
double arrowY= (Dy*8+Sy)/9;
StdDraw.point(arrowX,arrowY);
double tmp = edges.getWeight();
String dou = String.format("%.4g%n", tmp);
String te = dou+"";
StdDraw.setPenRadius(0.1);
StdDraw.setPenColor(Color.BLACK);
double newX= (Dx*4+Sx)/5;
double newY= (Dy*4+Sy)/5;
StdDraw.text(newX, newY, te);
}
}
}
}
}catch(Exception e) {
System.err.println("No edges to Draw");
}
}
/*
* This function open a window and calls to drawNode and drawEdge
*/
public void drawDGraph() {
try {
if(ga.dg.getV() != null) {
StdDraw.setGui(this);
setPageSize();
drawEdges();
drawNodes();
}
}catch(Exception e){
System.err.println("Nothing to draw");
}
}
/**
* set the page size
*/
private void setPageSize() {
final double fixScale = 0.0015;
StdDraw.setCanvasSize(1200 , 600 );
StdDraw.setXscale(xMin - fixScale, xMax + fixScale);
StdDraw.setYscale(yMin - fixScale, yMax + fixScale);
}
/**
* refresh > Draw graph
*/
public void refreshDraw() {
StdDraw.clear();
drawEdges();
drawNodes();
}
/**
* draw the pokemons in the HashMap
* @param game
*/
public void draw_pokemons(game_service game) {
Collection<CL_Pokemon> P_list = pokemons.values();
for (CL_Pokemon P : P_list) {
int type = P.getType();
Point3D pos = new Point3D(P.getLocation());
if(type == -1) {
StdDraw.picture(pos.x(), pos.y(), "yellowPok.png", 0.0007, 0.0007);
}else if(type == 1) {
StdDraw.picture(pos.x(), pos.y(), "greenPok.jpg", 0.0007, 0.0007);
}
}
}
/**
* draw the agents in the HashMap
* @param game
*/
public void drawAgent(game_service game) {
Collection<CL_Agent> A_list = agents.values();
for (CL_Agent ag : A_list) {
Point3D pos = new Point3D(ag.getLocation());
String file = "redAgent.png";
try {
StdDraw.picture(pos.x(), pos.y(), file, 0.0007, 0.0007);
}catch (Exception e) {
StdDraw.circle(pos.x(), pos.y(), .0015 * 0.3);
}
}
}
/**
* while the game is running, it shows the current score on the game window
* @param game
*/
public void printScore(game_service game) {
String results = game.toString();
long t = game.timeToEnd();
try {
int scoreInt = 0;
int movesInt = 0;
JSONObject score = new JSONObject(results);
JSONObject ttt = score.getJSONObject("GameServer");
scoreInt = ttt.getInt("grade");
movesInt = ttt.getInt("moves");
String countDown = "Time: " + t / 1000;
String scoreStr = "Score: " + scoreInt;
String movesStr = "Moves: " + movesInt;
double tmp1 = xMax - xMin;
double tmp2 = yMax - yMin;
StdDraw.setPenRadius(0.05);
StdDraw.setPenColor(Color.BLACK);
StdDraw.text(xMin+tmp1 / 1.05 , yMin + tmp2 / 0.90, countDown);
StdDraw.text(xMin+tmp1 / 1.05 , yMin + tmp2 / 0.95, movesStr);
StdDraw.text(xMin+tmp1 / 1.05 , yMin + tmp2, scoreStr);
}catch (Exception e) {
System.err.println("Failed to print score");
}
}
/**
* update the pokemons and agents in the list
* @param game
*/
public void refreshElements(game_service game, directed_weighted_graph g) {
initpokemons(game,g);
initAgents(game,g);
}
/**
* when game over, prints the final score
* @param game
*/
public void displayFinalScore(game_service game){
int scoreInt = 0;
int movesInt = 0;
try {
String results = game.toString();
System.out.println("Game Over: " + results);
JSONObject score = new JSONObject(results);
JSONObject ttt = score.getJSONObject("GameServer");
scoreInt = ttt.getInt("grade");
movesInt = ttt.getInt("moves");
String endGame = "Youre score is: " + scoreInt + "\n"
+ "Amount of moves: " + movesInt ;
JOptionPane.showMessageDialog(null, endGame);
}
catch (Exception e) {
e.getMessage();
}
}
/**
* initialize the pokemons of the game
* @param game
*/
public void initpokemons(game_service game, directed_weighted_graph g) {
String f_list = game.getPokemons();
ArrayList<CL_Pokemon> cl_fs = Arena.json2Pokemons(f_list);
if(pokemons != null)
{
pokemons.clear();
}
else pokemons = new HashMap<>();
for(int a = 0;a<cl_fs.size();a++) {
cl_fs.get(a).init(g);
edge_data e = cl_fs.get(a).getEdgePok();
if(e != null) {
cl_fs.get(a).set_edge(cl_fs.get(a).getEdgePok());
pokemons.put(cl_fs.get(a). getLocation(),cl_fs.get(a));
}
else
{
System.out.println("could not find edge to pokemon");
}
}
}
/**
* initialize the agents of the game
* @param game
*/
public void initAgents(game_service game, directed_weighted_graph gg) {
String a_list =game.getAgents();
List<CL_Agent> cl_as =Arena.getAgents(a_list, gg);
if(agents != null)
{
agents.clear();
}
else agents = new HashMap<>();
for(int a = 0;a<cl_as.size();a++) {
cl_as.get(a).init(gg);
agents.put(cl_as.get(a).getID(),cl_as.get(a));
}
}
}
| true |
ead5923b43a6ea9d52a57b719bb4606000c6d3f2 | Java | zhongxingyu/Seer | /Diff-Raw-Data/5/5_2c82119b048064bd47612ec63890e594f18df9c9/GroovyRepl/5_2c82119b048064bd47612ec63890e594f18df9c9_GroovyRepl_t.java | UTF-8 | 613 | 2.34375 | 2 | [] | no_license | package br.com.tecsinapse.glimpse.server.groovy;
import groovy.lang.GroovyShell;
import br.com.tecsinapse.glimpse.server.Repl;
public class GroovyRepl implements Repl {
private GroovyShell groovyShell = new GroovyShell();
public GroovyRepl(VarProducer varProducer) {
varProducer.fill(groovyShell);
}
public String eval(String expression) {
try {
Object result = groovyShell.evaluate(expression);
if (result == null)
return "null";
else
return result.toString();
} catch (RuntimeException e) {
return e.getMessage();
}
}
public void close() {
}
}
| true |
8e160dc422d7d551eba3c66274991c975d920fe4 | Java | aaroncheung123/EI-Robotics | /app/src/main/java/com/aaroncheung/prototype4/MainActivity.java | UTF-8 | 1,745 | 2.328125 | 2 | [] | no_license | package com.aaroncheung.prototype4;
import android.app.Activity;
import android.content.Intent;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import com.aaroncheung.prototype4.robot.RobotFacade;
import com.aaroncheung.prototype4.states.RobotState;
public class MainActivity extends Activity {
public final static String TAG = "debug_main6";
private UsbManager usbManager;
private RobotFacade robotFacade;
private RobotState robotState;
ImageView faceView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//This makes it fullscreen mode!!!!
//--------------------------------------------------
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
//--------------------------------------------------
Log.d(TAG, "onCreate was created ");
faceView = findViewById(R.id.multiFace);
UsbManager usbManager = (UsbManager) this.getSystemService(this.USB_SERVICE);
robotState = RobotState.getInstance();
usbManager = (UsbManager) getSystemService(USB_SERVICE);
Log.d(TAG, "1");
robotFacade = RobotFacade.getInstance();
robotFacade.init(this, usbManager);
}
public void faceClick(View view){
Intent myIntent = new Intent(this, HappyStateActivity.class);
this.startActivity(myIntent);
}
}
| true |
0733744dfb44d978bf5748bef7eb4288203d8f6b | Java | tomaszbawor/agro | /src/main/java/com/tbawor/agro/items/armor/body/BodyArmor.java | UTF-8 | 273 | 2.171875 | 2 | [] | no_license | package com.tbawor.agro.items.armor.body;
import com.tbawor.agro.items.ItemType;
import com.tbawor.agro.items.armor.Armor;
public class BodyArmor extends Armor {
public BodyArmor(String name, int defence) {
super(name, defence, ItemType.BODY_ARMOR);
}
}
| true |
546018ca322b80ab9cff6470f41b67c53fd597f8 | Java | lazuta/oaip-labs-1 | /src/lab10/Task2/iHealth.java | UTF-8 | 238 | 2.25 | 2 | [] | no_license | package lab10.Task2;
public interface iHealth {
String nameOrg = "";
String adress = "";
double budget = 0;
int countPeople = 0;
String getNameOrg();
String setNameOrg(String nameOrg);
String message();
}
| true |
66643f983f9f4cb13f945ae23347ca0865c06a37 | Java | bghorpade/SeleniumAutomation | /MavenProjects/FirstMavenProject/src/test/java/SamplePackage/SecondMavenClass.java | UTF-8 | 498 | 2.21875 | 2 | [] | no_license | package SamplePackage;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
public class SecondMavenClass {
@Test
public void launch()
{
WebDriver dr;
System.out.println("Launch Chrome Browser");
System.setProperty("webdriver.chrome.driver", "D:\\SeleniumAutomation\\Drivers\\chromedriver.exe");
dr = new ChromeDriver();
dr.manage().window().maximize();
dr.get("http://www.gmail.com/");
}
}
| true |
c7c71f2602fb9700f7dbb40cc5b0814d7de82ce5 | Java | karannkumar/data-structures | /src/com/leetcode/year_2020/MaximumLengthofRepeatedSubarray.java | UTF-8 | 4,196 | 2.96875 | 3 | [] | no_license | package com.leetcode.year_2020;
import static java.lang.Math.max;
/**
* @author neeraj on 03/05/20
* Copyright (c) 2019, data-structures.
* All rights reserved.
*/
@SuppressWarnings("DuplicatedCode")
public class MaximumLengthofRepeatedSubarray {
public static void main(String[] args) {
System.out.println(findLength(new int[]{1, 2, 3, 2, 1}, new int[]{3, 2, 1, 4, 7}));
System.out.println(findLength(new int[]{0, 0, 0, 0, 0, 0, 1, 0, 0, 0}, new int[]{0, 0, 0, 0, 0, 0, 0, 1, 0, 0}));
System.out.println(findLength(new int[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
new int[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}));
}
static int MAX_LENGTH = Integer.MIN_VALUE;
public static int findLength(int[] A, int[] B) {
// /**
// * This can be solved using longest common substring pattern.
// */
// if (B.length > A.length) {
// return findLength(B, A);
// }
// return repeatedSubArray(A, B);
// return repeatedSubArrayRecursive(A, B, A.length - 1, B.length - 1, 0);
Integer[][][] dp = new Integer[A.length + 1][B.length + 1][Math.max(A.length, B.length) + 1];
return repeatedSubArrayWithMemorization(A, B, A.length, B.length, 0, dp);
}
public static int repeatedSubArrayWithMemorization(int[] X, int[] Y, int m, int n, int lcsCount, Integer[][][] dp) {
if (m <= 0 || n <= 0)
return lcsCount;
if (dp[m][n][lcsCount] != null)
return dp[m][n][lcsCount];
int lcsCount1 = lcsCount;
if (X[m - 1] == Y[n - 1])
lcsCount1 = repeatedSubArrayWithMemorization(X, Y, m - 1, n - 1, lcsCount + 1, dp);
int lcsCount2 = repeatedSubArrayWithMemorization(X, Y, m, n - 1, 0, dp);
int lcsCount3 = repeatedSubArrayWithMemorization(X, Y, m - 1, n, 0, dp);
return dp[m][n][lcsCount] = Math.max(lcsCount1, Math.max(lcsCount2, lcsCount3));
}
public static int repeatedSubArrayRecursive(int[] A,
int[] B,
int A_indexToCompare,
int B_indexToCompare,
int result) {
// Base Case....... If any of the String is empty there is nothing common.
if (A_indexToCompare < 0 || B_indexToCompare < 0) {
return result;
}
if (A[A_indexToCompare] == B[B_indexToCompare]) {
result = repeatedSubArrayRecursive(A, B, A_indexToCompare - 1,
B_indexToCompare - 1, result + 1); // Increasing the result variable by 1.
}
return max(result, max(repeatedSubArrayRecursive(A, B, A_indexToCompare - 1, B_indexToCompare, 0),
repeatedSubArrayRecursive(A, B, A_indexToCompare, B_indexToCompare - 1, 0)));
}
public static int repeatedSubArray(int[] A, int[] B) {
int[][] LCS = new int[A.length + 1][B.length + 1];
int maxRepeatedLength = Integer.MIN_VALUE;
for (int i = 1; i < LCS.length; i++) {
for (int j = 1; j < LCS.length; j++) {
if (A[i - 1] == B[j - 1]) {
LCS[i][j] = 1 + LCS[i - 1][j - 1];
maxRepeatedLength = max(maxRepeatedLength, LCS[i][j]);
} else {
// Not common and since we are looking for continuous
// hence let's break the longest chain
LCS[i][j] = 0;
}
}
}
return maxRepeatedLength == Integer.MIN_VALUE ? 0 : maxRepeatedLength;
}
}
| true |
f585925b3b3a587561937b944a6d157174034e8b | Java | priyankagoel25/axelerant | /src/test/java/models/billPay.java | UTF-8 | 393 | 2.453125 | 2 | [] | no_license | package models;
public class billPay {
private static address address;
private static String name;
private static String phoneNumber;
private static String accountNumber;
public billPay(address address, String name, String phoneNumber, String accountNumber)
{
this.address = address;
this.name = name;
this.phoneNumber = phoneNumber;
this.accountNumber = accountNumber;
}
}
| true |
d0726e12fc562a4651835d4de03c9e4be14d783c | Java | callELPSYCONGROO/aurora | /utils/src/main/java/com/wuhenjian/aurora/utils/entity/zimg/ZimgResult.java | UTF-8 | 2,098 | 2.34375 | 2 | [] | no_license | package com.wuhenjian.aurora.utils.entity.zimg;
/**
* zimg服务器请求返回的结果
* @author 無痕剑
* @date 2018/1/3 16:59
*/
public class ZimgResult {
private Boolean ret;
private info info;
private error error;
public Boolean getRet() {
return ret;
}
public void setRet(Boolean ret) {
this.ret = ret;
}
public ZimgResult.info getInfo() {
return info;
}
public void setInfo(ZimgResult.info info) {
this.info = info;
}
public ZimgResult.error getError() {
return error;
}
public void setError(ZimgResult.error error) {
this.error = error;
}
/**
* 上传、删除、查询返回的字段
*/
class info {
//公用字段,上传返回的字段
private String md5;
private Long size;
//查询信息返回的字段
private Integer width;
private Integer height;
private Integer quality;
private String format;
//删除返回的字段
private Integer t;
public String getMd5() {
return md5;
}
public void setMd5(String md5) {
this.md5 = md5;
}
public Long getSize() {
return size;
}
public void setSize(Long size) {
this.size = size;
}
public Integer getWidth() {
return width;
}
public void setWidth(Integer width) {
this.width = width;
}
public Integer getHeight() {
return height;
}
public void setHeight(Integer height) {
this.height = height;
}
public Integer getQuality() {
return quality;
}
public void setQuality(Integer quality) {
this.quality = quality;
}
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
public Integer getT() {
return t;
}
public void setT(Integer t) {
this.t = t;
}
}
/**
* 发生错误返回的字段
*/
class error {
private Integer code;
private String message;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
}
| true |
18b825efd167318365133cca2ccd78d5ac6c9522 | Java | MobiusReactor/CS308 | /prototypes/collisions/model/SquareBumper.java | UTF-8 | 1,691 | 3.421875 | 3 | [] | no_license | package collisions.model;
import physics.LineSegment;
import physics.Vect;
import physics.Circle;
import java.util.ArrayList;
public class SquareBumper {
private int x1,x2,y1,y2,size; // x1 & y1 -> top left, x2 & y2 -> top right, x3 & y3 -> bottom right, x4 & y4 -> bottom left,
private LineSegment a,b,c,d;
private Circle ab,bc,cd,da; //named to show which circle is situated between which 2 sides of the square
ArrayList<Circle> circles;
ArrayList<LineSegment> lines;
public SquareBumper(int x, int y, int size){
this.x1 = x;
this.x2 = x + size;
this.y1 = y;
this.y2 = y + size;
this.size = size;
a = new LineSegment(x, y, x + size, y);
b = new LineSegment(x + size, y, x + size, y + size);
c = new LineSegment(x + size, y + size, x, y + size);
d = new LineSegment(x, y + size, x, y);
lines = new ArrayList<LineSegment>();
lines.add(a);
lines.add(b);
lines.add(c);
lines.add(d);
ab = new Circle(x,y,0);
bc = new Circle(x + size,y,0);
cd = new Circle(x + size,y + size,0);
da = new Circle(x,y + size,0);
circles = new ArrayList<Circle>();
circles.add(ab);
circles.add(bc);
circles.add(cd);
circles.add(da);
}
public ArrayList<LineSegment> getSides(){
return lines;
}
public ArrayList<Circle> getEdges(){
return circles;
}
public Vect getTopLeftCorner(){
return (new Vect(x1,y1));
}
public Vect getTopRightCorner(){
return (new Vect(x2,y1));
}
public Vect getBottomRightCorner(){
return (new Vect(x2,y2));
}
public Vect getBottomLeftCorner(){
return (new Vect(x1,y2));
}
public int getX() {
return x1;
}
public int getY() {
return y1;
}
public int getSize(){
return size;
}
}
| true |
9ecae0f5223a345811b669d897830e23cb06d290 | Java | andanhm/FoodApp | /app/src/main/java/app/andanhm/foodworld/database/client/table/CartTable.java | UTF-8 | 1,256 | 2.28125 | 2 | [] | no_license | package app.andanhm.foodworld.database.client.table;
/**
* --------------------------CART table--------------------------
*/
public class CartTable {
public static final String CART_TABLE = "tblCart";
public static final String PRODUCT_ID = "pro_id";
public static final String PRODUCT_NAME = "pro_name";
public static final String PRODUCT_DESCRIPTION = "pro_description";
public static final String PRODUCT_IMG_URL = "img_url";
public static final String PRODUCT_TYPE = "pro_type";
public static final String PRODUCT_PRICE = "pro_price";
public static final String PRODUCT_QUANTITY = "pro_quantity";
public static final String CART_ADD_TIME = "add_time";
public static String getCartTableQuery() {
return String.format("CREATE TABLE %s (%s TEXT, %s TEXT NOT NULL, %s TEXT,%s TEXT,%s TEXT,%s REAL TEXT NOT TEXT,%s INT NOT NULL,%s TEXT",
CART_TABLE,
PRODUCT_ID,
PRODUCT_NAME,
PRODUCT_DESCRIPTION,
PRODUCT_IMG_URL,
PRODUCT_TYPE,
PRODUCT_PRICE,
PRODUCT_QUANTITY,
CART_ADD_TIME);
}
}
| true |
87c7b28fad0081186d42cebdc369f7033672c9e8 | Java | zhaozhu365/PractiseCustomView | /app/src/main/java/com/example/zhaozhu/practisecustomview/pathanimationdemo/MainActivity.java | UTF-8 | 1,337 | 2.296875 | 2 | [] | no_license | //package com.example.zhaozhu.practisecustomview.pathanimationdemo;
//
//import android.app.Activity;
//import android.os.Bundle;
//import android.view.View;
//import android.view.View.OnClickListener;
//import android.widget.Button;
//import android.widget.RelativeLayout;
//
//public class MainActivity extends Activity {
//
// private Button run;
// private RelativeLayout rlt_animation_layout;
// private FllowerAnimation fllowerAnimation;
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main_pathmeasure);
//
// run = (Button) findViewById(R.id.but_run);
// rlt_animation_layout = (RelativeLayout) findViewById(R.id.rlt_animation_layout);
//
//
// rlt_animation_layout.setVisibility(View.VISIBLE);
//
// fllowerAnimation = new FllowerAnimation(this);
// RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
// fllowerAnimation.setLayoutParams(params);
// rlt_animation_layout.addView(fllowerAnimation);
//
//
// run.setOnClickListener(new OnClickListener() {
// @Override
// public void onClick(View v) {
// fllowerAnimation.startAnimation();
// }
// });
//
// }
//
//
//}
| true |
63dc3f057716d5299add7d382063125457ee434e | Java | louren1234/Weeting_front | /app/src/main/java/com/example/again/MyMoim.java | UTF-8 | 5,708 | 2 | 2 | [] | no_license | package com.example.again;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class MyMoim extends AppCompatActivity implements RecyclerAdapter.OnDataDetailClickListener {
private MoimCategoryResultData.serviceApi serviceApi;
private MoimCategoryResultData.MoimCategoryResultDataResponse dataList;
private List<MoimCategoryResultData> dataInfo;
RecyclerView myMoimRecyclerView;
RecyclerAdapter myMoimRecyclerAdapter;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.my_moim);
ImageView main = findViewById(R.id.mainpage);
ImageButton search = findViewById(R.id.search);
ImageButton chat = findViewById(R.id.chat);
ImageButton toHome = findViewById(R.id.toHome);
ImageButton toList = findViewById(R.id.toList);
ImageButton toMypage = findViewById(R.id.toMypage);
myMoimRecyclerView = findViewById(R.id.myMoim);
myMoimRecyclerView.setLayoutManager(new LinearLayoutManager(this));
serviceApi = RetrofitClient.getClient().create(MoimCategoryResultData.serviceApi.class);
serviceApi.getMyMoim().enqueue(new Callback<MoimCategoryResultData.MoimCategoryResultDataResponse>() {
@Override
public void onResponse(Call<MoimCategoryResultData.MoimCategoryResultDataResponse> call, Response<MoimCategoryResultData.MoimCategoryResultDataResponse> response) {
dataList = response.body();
dataInfo = dataList.data;
myMoimRecyclerAdapter = new RecyclerAdapter(getApplicationContext(), dataInfo);
myMoimRecyclerAdapterinit(myMoimRecyclerAdapter);
}
@Override
public void onFailure(Call<MoimCategoryResultData.MoimCategoryResultDataResponse> call, Throwable t) {
}
});
main.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), After_have_group.class);
startActivity(intent);
}
});
search.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), SearchList.class);
startActivity(intent);
}
});
toHome.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), After_have_group.class);
startActivity(intent);
}
});
toList.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), MoimList.class);
intent.putExtra("category", "all");
startActivity(intent);
}
});
chat.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), Create.class);
startActivity(intent);
}
});
toMypage.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), Mypage.class);
startActivity(intent);
}
});
}
public void myMoimRecyclerAdapterinit(RecyclerAdapter myMoimRecyclerAdapter){
myMoimRecyclerAdapter.setOnItemClicklistener(this); // onItemClick 함수 만들면 this 빨간줄 사라짐
myMoimRecyclerView.setAdapter(myMoimRecyclerAdapter);
}
@Override
public void onItemClick(View view, MoimCategoryResultData moimCategoryResultData){
// MoimCategoryResultData data = moimRecyclerAdapter.getItem(position);
Intent intent = new Intent(getApplicationContext(), MoimDetail.class);
intent.putExtra("meetingId", moimCategoryResultData.getMeeting_id());
startActivity(intent);
Log.e("RecyclerVIew :: ", moimCategoryResultData.toString());
}
@Override
protected void onResume(){
super.onResume();
serviceApi = RetrofitClient.getClient().create(MoimCategoryResultData.serviceApi.class);
serviceApi.getMyMoim().enqueue(new Callback<MoimCategoryResultData.MoimCategoryResultDataResponse>() {
@Override
public void onResponse(Call<MoimCategoryResultData.MoimCategoryResultDataResponse> call, Response<MoimCategoryResultData.MoimCategoryResultDataResponse> response) {
dataList = response.body();
dataInfo = dataList.data;
myMoimRecyclerAdapter = new RecyclerAdapter(getApplicationContext(), dataInfo);
myMoimRecyclerAdapterinit(myMoimRecyclerAdapter);
}
@Override
public void onFailure(Call<MoimCategoryResultData.MoimCategoryResultDataResponse> call, Throwable t) {
}
});
}
}
| true |
d6991203160118481f7b2b810c06897e5042c677 | Java | luiz158/sports-equipment | /src/main/java/ui/login/view/ClosableFrame.java | UTF-8 | 89 | 1.921875 | 2 | [] | no_license | package ui.login.view;
public interface ClosableFrame {
public void closeFrame();
}
| true |
8f5f179215e3db91c502cb5a710e99d3fa4151a4 | Java | KennethLieu/TicTacToe | /CounterClient.java | UTF-8 | 571 | 3.21875 | 3 | [] | no_license |
/**
* Write a description of class CounterClient here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class CounterClient
{
public static void main(String[] args)
{
Counter c = new Counter(5);
c.setCount(17);
c.increaseCount();
c.increaseCount();
c.decreaseCount();
System.out.println("Number of counts: " + c.getCount());
if(c.equalsZero()==true)
{
System.out.println("No counts remaining!");
}
System.out.println(c.toString());
}
}
| true |
684887f8bf53a9bcdd3fe69088c94df22d691a28 | Java | cyproto/stqa | /Project-1/selenium/src/selenium/DefaultSuiteTest.java | UTF-8 | 4,222 | 2.125 | 2 | [] | no_license | package selenium;
import org.junit.Test;
import org.junit.Before;
import org.junit.After;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.core.IsNot.not;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Alert;
import org.openqa.selenium.Keys;
import java.util.*;
public class DefaultSuiteTest {
private WebDriver driver;
private Map<String, Object> vars;
JavascriptExecutor js;
@Before
public void setUp() {
driver = new ChromeDriver();
js = (JavascriptExecutor) driver;
vars = new HashMap<String, Object>();
}
@After
public void tearDown() {
driver.quit();
}
@Test
public void a() throws Exception {
Random r = new Random();
String a = "ABCDEFGHIJKLMNOPQRSTUWXYZ";
int len = a.length();
String repo = "";
for(int i = 0;i<10;i++){
repo = repo + a.charAt(r.nextInt(len));
}
repo = repo.toLowerCase();
driver.get("https://github.com/");
driver.manage().window().setSize(new Dimension(1024, 736));
driver.findElement(By.linkText("Sign in")).click();
driver.findElement(By.id("login_field")).click();
driver.findElement(By.id("login_field")).sendKeys("seleniumtest-123");
driver.findElement(By.id("password")).click();
driver.findElement(By.id("password")).sendKeys("");
driver.findElement(By.name("commit")).click();
Thread.sleep(2000);
driver.findElement(By.cssSelector(".Header-link > .dropdown-caret:nth-child(2)")).click();
driver.findElement(By.linkText("New repository")).click();
Thread.sleep(2000);
driver.findElement(By.id("repository_name")).click();
Thread.sleep(2000);
driver.findElement(By.id("repository_name")).sendKeys(repo);
Thread.sleep(2000);
driver.findElement(By.cssSelector(".first-in-line")).click();
driver.findElement(By.linkText("creating a new file")).click();
driver.findElement(By.name("filename")).click();
driver.findElement(By.name("filename")).sendKeys("hello.py");
driver.findElement(By.cssSelector(".CodeMirror-line")).click();
{
WebElement element = driver.findElement(By.cssSelector(".CodeMirror-code"));
js.executeScript("if(arguments[0].contentEditable === 'true') {arguments[0].innerText = '<div style=\"position: relative;\"><div class=\"CodeMirror-gutter-wrapper\" contenteditable=\"false\" style=\"left: -53px;\"><div class=\"CodeMirror-linenumber CodeMirror-gutter-elt\" style=\"left: 0px; width: 21px;\">1</div></div><pre class=\" CodeMirror-line \" role=\"presentation\"><span role=\"presentation\" style=\"padding-right: 0.1px;\">print(\"hello\")</span></pre></div>'}", element);
}
driver.findElement(By.id("commit-summary-input")).click();
driver.findElement(By.id("commit-summary-input")).sendKeys("Create hello.py");
Thread.sleep(2000);
driver.findElement(By.id("submit-file")).click();
Thread.sleep(2000);
driver.findElement(By.linkText(repo)).click();
Thread.sleep(2000);
driver.findElement(By.linkText("hello.py")).click();
Thread.sleep(2000);
driver.findElement(By.linkText("Settings")).click();
Thread.sleep(2000);
driver.findElement(By.cssSelector(".Box-row:nth-child(4) > .details-reset > .btn")).click();
driver.findElement(By.cssSelector("p:nth-child(4) > .form-control")).click();
driver.findElement(By.cssSelector("p:nth-child(4) > .form-control")).click();
Thread.sleep(2000);
driver.findElement(By.cssSelector("p:nth-child(4) > .form-control")).sendKeys(repo);
driver.findElement(By.cssSelector("p:nth-child(4) > .form-control")).sendKeys(Keys.ENTER);
Thread.sleep(2000);
driver.findElement(By.cssSelector(".Header-item:nth-child(7)")).click();
Thread.sleep(2000);
driver.findElement(By.cssSelector(".dropdown-signout")).click();
}
}
| true |
0f11f280cfad18b9007a09363af19338c54bf640 | Java | JimaryX/LeetCode | /src/leet_code03/LeetCode445.java | UTF-8 | 1,664 | 3.5625 | 4 | [] | no_license | package leet_code03;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Stack;
public class LeetCode445 {
public static void main(String[] args) {
int[] num1 = { 1, 2, 3, 4 };
int[] num2 = { 8, 3, 4 };
System.out.println(Arrays.toString(listToInt(createList(num1))));
System.out.println(Arrays.toString(listToInt(createList(num2))));
System.out.println(Arrays.toString(listToInt(addTwoNumbers(createList(num1), createList(num2)))));
}
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode ans = null;
ListNode pre = null;
int curr = 0;
Stack stack1 = new Stack<Integer>();
Stack stack2 = new Stack<Integer>();
while (l1 != null || l2 != null) {
if (l1 != null) {
stack1.push(l1.val);
l1 = l1.next;
}
if (l2 != null) {
stack2.push(l2.val);
l2 = l2.next;
}
}
while (!stack1.empty() || !stack2.empty()) {
int sum = (stack1.empty() ? 0 : (int) stack1.pop()) + (stack2.empty() ? 0 : (int) stack2.pop());
pre = new ListNode((sum + curr) % 10);
curr = (sum + curr) / 10;
pre.next = ans;
ans = pre;
}
if (curr != 0) {
pre = new ListNode(1);
pre.next = ans;
}
return pre;
}
public static ListNode createList(int[] nums) {
ListNode list = new ListNode(0);
ListNode curr = list;
for (int i : nums) {
curr.next = new ListNode(i);
curr = curr.next;
}
curr = null;
return list.next;
}
public static int[] listToInt(ListNode list) {
ArrayList<Integer> array = new ArrayList<>();
while (list != null) {
array.add(list.val);
list = list.next;
}
return array.stream().mapToInt(Integer::valueOf).toArray();
}
}
| true |
c097ea3dce4cef76a56be09cc8fd0325277fcd96 | Java | RaniaBOUSSANDEL/AlphaGroupe | /ProjetGestiBanck/GestiBankBack/src/main/java/com/wha/springmvc/model/CompteBancaire.java | UTF-8 | 2,874 | 2.125 | 2 | [] | no_license | package com.wha.springmvc.model;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;
import com.fasterxml.jackson.annotation.JsonIgnore;
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "typeCompte")
@DiscriminatorValue("CB")
@Table(name = "CompteBancaire")
public class CompteBancaire implements Serializable {
/**
*
*/
private static final long serialVersionUID = -5642039818092510654L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private long numCompte;
private Date dateCreation;
private float solde;
//ok
@ManyToOne
@JoinColumn(name = "client_id") // le nom de la colonne cree dans la base de donnee
private Client client;
//ok
@JsonIgnore
@LazyCollection(LazyCollectionOption.FALSE)
@OneToMany(mappedBy = "compteB", fetch = FetchType.LAZY, cascade= {CascadeType.ALL})
private List<Transaction> transactions;
public CompteBancaire() {
id = 0;
}
public CompteBancaire(int id, long numCompte, Date dateCreation, float solde) {
this.id = id;
this.numCompte = numCompte;
this.dateCreation = dateCreation;
this.solde = solde;
}
public Client getClient() {
return client;
}
public void setClient(Client client) {
this.client = client;
}
public List<Transaction> getTransactions() {
return transactions;
}
public void setTransactions(List<Transaction> transactions) {
this.transactions = transactions;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public long getNumCompte() {
return numCompte;
}
public void setNumCompte(long numCompte) {
this.numCompte = numCompte;
}
public Date getDateCreation() {
return dateCreation;
}
public void setDateCreation(Date dateCreation) {
this.dateCreation = dateCreation;
}
public float getSolde() {
return solde;
}
public void setSolde(float solde) {
this.solde = solde;
}
@Override
public String toString() {
return "CompteBancaire [id=" + id + ", numCompte=" + numCompte + ", dateCreation=" + dateCreation + ", solde="
+ solde + "]";
}
} | true |
917dd9bf03d3add7837f5a8e9a236ff6b1b0a6be | Java | pylrichard/web_service_study | /roncoo_pay/pay_facade_bank/src/main/java/com/bd/roncoo/pay/facade/bank/entity/BankAccount.java | UTF-8 | 2,359 | 2.078125 | 2 | [] | no_license | package com.bd.roncoo.pay.facade.bank.entity;
import lombok.Getter;
import lombok.Setter;
import java.util.Date;
/**
* 银行账户信息表参数实体
*/
@Getter
@Setter
public class BankAccount extends BaseEntity {
private static final long serialVersionUID = 1L;
/**
* 开户银行名称
*/
private String openBank;
/**
* 开户支行地址
*/
private String openBankAddress;
/**
* 账户开户日期
*/
private Date opendate;
/**
* 银行账号
*/
private String bankAccount;
/**
* 银行支行行号,与银联系统数据相同
*/
private String bankNo;
/**
* 银行账户名称
*/
private String userName;
/**
* 开户经办人
*/
private String operator;
/**
* 合作方式:1 存管银行 2 合作银行
*/
private Integer cooperationWay;
/**
* 账户性质:1 备付金存管账户 2 自有资金账户 3 备付金收付账户 4 备付金汇缴账户
*/
private Integer accountNature;
/**
* 账户状态:1 正常 2 待销户 3 已销户
*/
private Integer accountStatus;
/**
* 账户类型:1 活期 2 定期 3 通支
*/
private Integer accountType;
/**
* 网银管理费
*/
private Double onlineBankFee;
/**
* 账户管理费
*/
private Double accountMngFee;
/**
* 是否有网银:1 是 2 否
*/
private Integer isOnlineBank;
/**
* 回单形式:1 邮寄 2 自取 3 打印
*/
private Integer receiptForm;
/**
* 预留印鉴记录
*/
private String reserveSeal;
/**
* 申请人
*/
private String proposer;
/**
* 银行联系方式:姓名、类型、电话、邮箱 长文本存放
*/
private String linkMan;
/**
* 开户信息预留人
*/
private String openAccountObligate;
/**
* 网银验证码预留人
*/
private String onlineBankObligate;
/**
* 大额转款确定预留人
*/
private String bigAmounttransferObligate;
/**
* 质押保证金
*/
private Double pledgefDeposits;
/**
* 备注
*/
private String comments;
/**
* 初始化金额
*/
private Double balance;
}
| true |
2f18466d72cb74070140f6facf2c2f5e93ed7a33 | Java | so72/iTend | /src/com/noesgoes/itend/db/OrderDbAdapter.java | UTF-8 | 3,168 | 2.9375 | 3 | [] | no_license | package com.noesgoes.itend.db;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class OrderDbAdapter {
private static final String TAG = "OrderDbAdapter";
private OrderDbHelper mDbHelper;
private SQLiteDatabase mDb;
private final Context mContext;
private static final String DB_NAME = "orderdata";
private static final String ORDER_TABLE = "orders";
private static final int DB_VERSION = 2;
public static final String KEY_ID = "_id";
public static final String KEY_DRINK_NAME = "drink_name";
public static final String KEY_DRINK_DESCRIPTION = "drink_description";
public static final String KEY_COST = "cost";
private static final String DB_CREATE =
"CREATE TABLE " + ORDER_TABLE
+ " (" + KEY_ID + " integer primary key autoincrement, "
+ KEY_DRINK_NAME + " text not null, "
+ KEY_DRINK_DESCRIPTION + " text not null, "
+ KEY_COST + " text not null);";
private static class OrderDbHelper extends SQLiteOpenHelper {
OrderDbHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DB_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS drinks");
onCreate(db);
}
}
/**
* Constructor - stores context for DB creation
*
* @param context the context in which to create the DB
*/
public OrderDbAdapter(Context context) {
this.mContext = context;
}
/**
* Open or create the drink database.
*
* @return a reference to itself, to allow chaining
* @throws SQLException if database couldn't be opened or created
*/
public OrderDbAdapter open() throws SQLException {
mDbHelper = new OrderDbHelper(mContext);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
mDbHelper.close();
}
/**
* Add a drink to order
*
* @param name the drink name
* @param cost the cost of the drink
* @return the ID or -1 if the insert failed
*/
public long addDrinkToOrder(String name, String description, String cost) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_DRINK_NAME, name);
initialValues.put(KEY_DRINK_DESCRIPTION, description);
initialValues.put(KEY_COST, cost);
return mDb.insert(ORDER_TABLE, null, initialValues);
}
/**
* Returns a list of drinks of type type
*
* @param type the type of drink
* @return cursor over all drinks of type type
*/
public Cursor getAllDrinks() {
String[] columns = {KEY_ID, KEY_DRINK_NAME, KEY_DRINK_DESCRIPTION, KEY_COST};
return mDb.query(ORDER_TABLE, columns, null, null, null, null, null);
}
public double getTabTotal() {
Cursor cursor = mDb.rawQuery("SELECT SUM("+KEY_COST+") FROM " + ORDER_TABLE, null);
cursor.moveToFirst();
double cnt = cursor.getDouble(0);
cursor.close();
return cnt;
}
public void clearAllDrinks() {
mDb.delete(ORDER_TABLE, null, null);
}
}
| true |
946ba98aaaf3fbe88ca650aadca0093aa698f2d5 | Java | neilwithdata/BBSmart-Alarms-Pro | /src/com/bbsmart/pda/blackberry/bbtime/util/BBLogger.java | UTF-8 | 424 | 1.953125 | 2 | [] | no_license | package com.bbsmart.pda.blackberry.bbtime.util;
import com.bbsmart.pda.blackberry.bbtime.AppInfo;
import net.rim.device.api.system.EventLogger;
public final class BBLogger {
public static void initialize() {
EventLogger.register(AppInfo.APP_KEY, "BBSmart Alarms Pro",
EventLogger.VIEWER_STRING);
}
public static void logEvent(String eventMsg) {
EventLogger.logEvent(AppInfo.APP_KEY, eventMsg.getBytes());
}
} | true |
cfd5a4a73b2426fde3e4eb4d82769d37b7299045 | Java | DavidSilvaAlves/androidStudioProject | /app/src/main/java/com/example/cartaofidelidade/Uteis/Uteis.java | UTF-8 | 485 | 1.914063 | 2 | [] | no_license | package com.example.cartaofidelidade.Uteis;
import android.app.AlertDialog;
import android.content.Context;
import com.example.cartaofidelidade.R;
public class Uteis {
public static void Alert(Context context, String mensagem){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("SISTEMA");
alertDialog.setMessage(mensagem);
alertDialog.setPositiveButton("OK",null);
alertDialog.show();
}
}
| true |
c8dbc7247258187ce9665906cdd1d914362f7339 | Java | caxapexac/StronglyConnectedComponentsPractice | /src/ru/eltech/view/GraphPopupMenuEdge.java | UTF-8 | 985 | 2.484375 | 2 | [
"MIT"
] | permissive | package ru.eltech.view;
import javax.swing.*;
/**
* Контекстное меню при клике ПКМ*2 на {@link ru.eltech.logic.Edge}
*/
public final class GraphPopupMenuEdge extends JPopupMenu {
public GraphPopupMenuEdge(GraphEditor graphEditor, Integer id) {
JMenuItem removeEdgeMenuItem = new JMenuItem("Удалить дугу");
removeEdgeMenuItem.addActionListener((action) -> graphEditor.destroyEdge(id));
add(removeEdgeMenuItem);
addSeparator();
JMenuItem changeEdgeStrokeMenuItem = new JMenuItem("Изменить толщину дуги");
changeEdgeStrokeMenuItem.addActionListener((action) -> graphEditor.changeEdgeStroke(id));
add(changeEdgeStrokeMenuItem);
JMenuItem changeEdgeColorMenuItem = new JMenuItem("Изменить цвет дуги");
changeEdgeColorMenuItem.addActionListener((action) -> graphEditor.changeEdgeColor(id));
add(changeEdgeColorMenuItem);
}
}
| true |
1298604fe13a8dc79769d945921b34c0d670e689 | Java | ecmnet/MAVGCL | /MAVGCL/src/main/java/me/drton/jmavlib/log/px4/PX4LogReader.java | UTF-8 | 12,809 | 2.171875 | 2 | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | package me.drton.jmavlib.log.px4;
import java.io.EOFException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import me.drton.jmavlib.log.BinaryLogReader;
import me.drton.jmavlib.log.FormatErrorException;
/**
* User: ton Date: 03.06.13 Time: 14:18
*/
public class PX4LogReader extends BinaryLogReader {
private static final int HEADER_LEN = 3;
private static final byte HEADER_HEAD1 = (byte) 0xA3;
private static final byte HEADER_HEAD2 = (byte) 0x95;
private long dataStart = 0;
private boolean formatPX4 = false;
private Map<Integer, PX4LogMessageDescription> messageDescriptions
= new HashMap<Integer, PX4LogMessageDescription>();
private Map<String, String> fieldsList = null;
private long time = 0;
private PX4LogMessage lastMsg = null;
private long sizeUpdates = -1;
private long sizeMicroseconds = -1;
private long startMicroseconds = -1;
private long utcTimeReference = -1;
private Map<String, Object> version = new HashMap<String, Object>();
private Map<String, Object> parameters = new HashMap<String, Object>();
private List<Exception> errors = new ArrayList<Exception>();
private String tsName = null;
private boolean tsMicros;
private static Set<String> hideMsgs = new HashSet<String>();
private static Map<String, String> formatNames = new HashMap<String, String>();
static {
hideMsgs.add("PARM");
hideMsgs.add("FMT");
hideMsgs.add("TIME");
hideMsgs.add("VER");
formatNames.put("b", "int8");
formatNames.put("B", "uint8");
formatNames.put("L", "int32 * 1e-7 (lat/lon)");
formatNames.put("i", "int32");
formatNames.put("I", "uint32");
formatNames.put("q", "int64");
formatNames.put("Q", "uint64");
formatNames.put("f", "float");
formatNames.put("c", "int16 * 1e-2");
formatNames.put("C", "uint16 * 1e-2");
formatNames.put("e", "int32 * 1e-2");
formatNames.put("E", "uint32 * 1e-2");
formatNames.put("n", "char[4]");
formatNames.put("N", "char[16]");
formatNames.put("Z", "char[64]");
formatNames.put("M", "uint8 (mode)");
}
public PX4LogReader(String fileName) throws IOException, FormatErrorException {
super(fileName);
readFormats();
updateStatistics();
}
@Override
public String getFormat() {
return formatPX4 ? "PX4" : "APM";
}
@Override
public String getSystemName() {
return getFormat();
}
@Override
public long getSizeUpdates() {
return sizeUpdates;
}
@Override
public long getStartMicroseconds() {
return startMicroseconds;
}
@Override
public long getSizeMicroseconds() {
return sizeMicroseconds;
}
@Override
public long getUTCTimeReferenceMicroseconds() {
return utcTimeReference;
}
@Override
public Map<String, Object> getVersion() {
return version;
}
@Override
public Map<String, Object> getParameters() {
return parameters;
}
private void updateStatistics() throws IOException, FormatErrorException {
seek(0);
long packetsNum = 0;
long timeStart = -1;
long timeEnd = -1;
boolean parseVersion = true;
StringBuilder versionStr = new StringBuilder();
while (true) {
PX4LogMessage msg;
try {
msg = readMessage();
} catch (EOFException e) {
break;
}
// Time range
if (formatPX4) {
if ("TIME".equals(msg.description.name)) {
long t = msg.getLong(0);
time = t;
if (timeStart < 0) {
timeStart = t;
}
timeEnd = t;
}
} else {
long t = getAPMTimestamp(msg);
if (t > 0) {
if (timeStart < 0) {
timeStart = t;
}
timeEnd = t;
}
}
packetsNum++;
// Version
if (formatPX4) {
if ("VER".equals(msg.description.name)) {
String fw = (String) msg.get("FwGit");
if (fw != null) {
version.put("FW", fw);
}
String hw = (String) msg.get("Arch");
if (hw != null) {
version.put("HW", hw);
}
}
} else {
if ("MSG".equals(msg.description.name)) {
String s = (String) msg.get("Message");
if (parseVersion && (s.startsWith("Ardu") || s.startsWith("PX4"))) {
if (versionStr.length() > 0) {
versionStr.append("; ");
}
versionStr.append(s);
} else {
parseVersion = false;
}
}
}
// Parameters
if ("PARM".equals(msg.description.name)) {
parameters.put((String) msg.get("Name"), msg.get("Value"));
}
if ("GPS".equals(msg.description.name)) {
if (utcTimeReference < 0) {
try {
if (formatPX4) {
int fix = ((Number) msg.get("Fix")).intValue();
long gpsT = ((Number) msg.get("GPSTime")).longValue();
if (fix >= 3 && gpsT > 0) {
utcTimeReference = gpsT - timeEnd;
}
} else {
int fix = ((Number) msg.get("Status")).intValue();
int week = ((Number) msg.get("Week")).intValue();
long ms = ((Number) msg.get(tsName)).longValue();
if (tsMicros) {
ms = ms / 1000;
}
if (fix >= 3 && (week > 0 || ms > 0)) {
long leapSeconds = 16;
long gpsT = ((315964800L + week * 7L * 24L * 3600L - leapSeconds) * 1000 + ms) * 1000L;
utcTimeReference = gpsT - timeEnd;
}
}
} catch (Exception ignored) {
}
}
}
}
startMicroseconds = timeStart;
sizeUpdates = packetsNum;
sizeMicroseconds = timeEnd - timeStart;
if (!formatPX4) {
version.put("FW", versionStr.toString());
}
seek(0);
}
@Override
public boolean seek(long seekTime) throws IOException {
position(dataStart);
lastMsg = null;
if (seekTime == 0) { // Seek to start of log
time = 0;
return true;
}
// Seek to specified timestamp without parsing all messages
try {
while (true) {
long pos = position();
int msgType = readHeader();
PX4LogMessageDescription messageDescription = messageDescriptions.get(msgType);
if (messageDescription == null) {
errors.add(new FormatErrorException(pos, "Unknown message type: " + msgType));
continue;
}
int bodyLen = messageDescription.length - HEADER_LEN;
try {
fillBuffer(bodyLen);
} catch (EOFException e) {
errors.add(new FormatErrorException(pos, "Unexpected end of file"));
return false;
}
if (formatPX4) {
if ("TIME".equals(messageDescription.name)) {
PX4LogMessage msg = messageDescription.parseMessage(buffer);
long t = msg.getLong(0);
if (t > seekTime) {
// Time found
time = t;
position(pos);
return true;
}
} else {
// Skip the message
buffer.position(buffer.position() + bodyLen);
}
} else {
Integer idx = messageDescription.fieldsMap.get(tsName);
if (idx != null && idx == 0) {
PX4LogMessage msg = messageDescription.parseMessage(buffer);
long t = msg.getLong(idx);
if (!tsMicros) {
t *= 1000;
}
if (t > seekTime) {
// Time found
time = t;
position(pos);
return true;
}
} else {
// Skip the message
buffer.position(buffer.position() + bodyLen);
}
}
}
} catch (EOFException e) {
return false;
}
}
// return ts in micros
private long getAPMTimestamp(PX4LogMessage msg) {
if (null == tsName) {
// detect APM's timestamp format on first timestamp seen
if (null != msg.description.fieldsMap.get("TimeUS")) {
// new format, timestamps in micros
tsMicros = true;
tsName = "TimeUS";
} else if (null != msg.description.fieldsMap.get("TimeMS")) {
// old format, timestamps in millis
tsMicros = false;
tsName = "TimeMS";
} else {
return 0;
}
}
Integer idx = msg.description.fieldsMap.get(tsName);
if (idx != null && idx == 0) {
return tsMicros ? msg.getLong(idx) : (msg.getLong(idx) * 1000);
}
return 0;
}
private void applyMsg(Map<String, Object> update, PX4LogMessage msg) {
String[] fields = msg.description.fields;
for (int i = 0; i < fields.length; i++) {
String field = fields[i];
if (!formatPX4) {
if (i == 0 && tsName.equals(field)) {
continue; // Don't apply timestamp field
}
}
update.put(msg.description.name + "." + field, msg.get(i));
}
}
@Override
public long readUpdate(Map<String, Object> update) throws IOException, FormatErrorException {
long t = time;
if (lastMsg != null) {
applyMsg(update, lastMsg);
lastMsg = null;
}
while (true) {
PX4LogMessage msg = readMessage();
if (null == msg) {
continue;
}
if (formatPX4) {
// PX4 log has TIME message
if ("TIME".equals(msg.description.name)) {
time = msg.getLong(0);
if (t == 0) {
// The first TIME message
t = time;
continue;
}
break;
}
} else {
// APM log doesn't have TIME message
long ts = getAPMTimestamp(msg);
if (ts > 0) {
time = ts;
if (t == 0) {
// The first message with timestamp
t = time;
} else {
if (time > t) {
// Timestamp changed, leave the message for future
lastMsg = msg;
break;
}
}
}
}
applyMsg(update, msg);
}
return t;
}
@Override
public Map<String, String> getFields() {
return fieldsList;
}
private void readFormats() throws IOException, FormatErrorException {
fieldsList = new HashMap<String, String>();
try {
while (true) {
if (fillBuffer() < 0) {
break;
}
while (true) {
if (buffer.remaining() < PX4LogMessageDescription.FORMAT.length) {
break;
}
buffer.mark();
int msgType = readHeader(); // Don't try to handle errors in formats
if (msgType == PX4LogMessageDescription.FORMAT.type) {
// Message description
PX4LogMessageDescription msgDescr = new PX4LogMessageDescription(buffer);
messageDescriptions.put(msgDescr.type, msgDescr);
if ("TIME".equals(msgDescr.name)) {
formatPX4 = true;
}
if (!hideMsgs.contains(msgDescr.name)) {
for (int i = 0; i < msgDescr.fields.length; i++) {
String field = msgDescr.fields[i];
String format = formatNames.get(Character.toString(msgDescr.format.charAt(i)));
if (i != 0 || !("TimeMS".equals(field) || "TimeUS".equals(field))) {
fieldsList.put(msgDescr.name + "." + field, format);
}
}
}
} else {
// Data message
if (formatPX4) {
// If it's PX4 log then all formats are read
buffer.clear();
dataStart = position();
return;
} else {
// APM may have format messages in the middle of log
// Skip the message
PX4LogMessageDescription messageDescription = messageDescriptions.get(msgType);
if (messageDescription == null) {
buffer.clear();
return;
//throw new RuntimeException("Unknown message type: " + msgType);
}
int bodyLen = messageDescription.length - HEADER_LEN;
buffer.position(buffer.position() + bodyLen);
}
}
}
}
} catch (EOFException ignored) {
}
}
private int readHeader() throws IOException {
long syncErr = -1;
while (true) {
fillBuffer(3);
int p = buffer.position();
if (buffer.get() != HEADER_HEAD1 || buffer.get() != HEADER_HEAD2) {
buffer.position(p + 1);
if (syncErr < 0) {
syncErr = position() - 1;
}
continue;
}
if (syncErr >= 0) {
errors.add(new FormatErrorException(syncErr, "Bad message header"));
}
return buffer.get() & 0xFF;
}
}
/**
* Read next message from log
*
* @return log message
* @throws IOException on IO error
* @throws EOFException on end of stream
*/
public PX4LogMessage readMessage() throws IOException {
while (true) {
int msgType = readHeader();
long pos = position();
PX4LogMessageDescription messageDescription = messageDescriptions.get(msgType);
if (messageDescription == null) {
errors.add(new FormatErrorException(pos, "Unknown message type: " + msgType));
continue;
}
try {
fillBuffer(messageDescription.length - HEADER_LEN);
} catch (EOFException e) {
errors.add(new FormatErrorException(pos, "Unexpected end of file"));
throw e;
}
return messageDescription.parseMessage(buffer);
}
}
@Override
public List<Exception> getErrors() {
return errors;
}
public void clearErrors() {
errors.clear();
}
public static void main(String[] args) throws Exception {
PX4LogReader reader = new PX4LogReader("test.bin");
long tStart = System.currentTimeMillis();
while (true) {
try {
PX4LogMessage msg = reader.readMessage();
} catch (EOFException e) {
break;
}
}
long tEnd = System.currentTimeMillis();
System.out.println(tEnd - tStart);
for (Exception e : reader.getErrors()) {
System.out.println(e.getMessage());
}
reader.close();
}
}
| true |
f69bd40c43d0a027dfe47f7f244531a6445dc989 | Java | alexyekymov/cvdb | /src/com/github/alexyekymov/cvdb/MainFile.java | UTF-8 | 1,786 | 3.125 | 3 | [
"Apache-2.0"
] | permissive | package com.github.alexyekymov.cvdb;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class MainFile {
public static void main(String[] args) {
String filePath = "./.gitignore";
File file = new File(filePath);
try {
System.out.println(file.getCanonicalPath());
} catch (IOException e) {
throw new RuntimeException("Error", e);
}
File dir = new File("./src/com/github/alexyekymov/cvdb");
System.out.println(dir.isDirectory());
String[] list = dir.list();
if (list != null) {
for (String name : list) {
System.out.println(name);
}
}
try (FileInputStream fis = new FileInputStream(filePath)) {
System.out.println(fis.read());
} catch (IOException e) {
throw new RuntimeException(e);
}
printDirectoryDeeply(dir);
}
static StringBuilder tab = new StringBuilder("");
public static void printDirectoryDeeply(File dir) {
File[] files = dir.listFiles();
List<File> dirs = new ArrayList<>();
System.out.println(tab + dir.getName());
tab.append("\t");
if (files != null) {
for (File file : files) {
if (file.isFile()) {
System.out.println(tab.toString() + file.getName());
}
if (file.isDirectory()) {
dirs.add(file);
}
}
}
for (File file : dirs) {
printDirectoryDeeply(file);
// tab.delete(tab.length() - 2, tab.length() -1);
tab.delete(1,2);
}
}
}
| true |
1ec1f75f0d1f8e3339b8b9846c69fc742e20ffa1 | Java | ArjanO/KenIkJouNietErgensVan | /spring-ws/src/main/java/com/dare2date/domein/lastfm/LastfmData.java | UTF-8 | 2,400 | 2.53125 | 3 | [
"MIT"
] | permissive | /**
* Copyright (c) 2013 HAN University of Applied Sciences
* Arjan Oortgiese
* Joëll Portier
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
package com.dare2date.domein.lastfm;
import java.util.ArrayList;
import java.util.TreeSet;
public class LastfmData {
private TreeSet<LastfmEvent> events;
public LastfmData() {
events = new TreeSet<LastfmEvent>();
}
public void addEvent(LastfmEvent event) {
events.add(event);
}
public TreeSet<LastfmEvent> getEvents() {
return events;
}
public void setEvents(TreeSet<LastfmEvent> events) {
this.events = events;
}
/**
* Compares two lastfm data objects and returns matching lastfm events.
* @param eventsToCompare Events to Compare
* @return Matching events
*/
public LastfmData getMatchingEvents(LastfmData eventsToCompare) {
LastfmData matchingEvents = new LastfmData();
for(LastfmEvent event : events) {
if(eventsToCompare.getEvents().contains(event)) {
matchingEvents.getEvents().add(event);
}
}
return matchingEvents;
}
public ArrayList<String> toStringList() {
ArrayList<String> data = new ArrayList<String>();
for(LastfmEvent event : events) {
data.add(event.getTitle());
}
return data;
}
}
| true |
641dc66fcdcac826dc3f9826145d3afb2c5da632 | Java | pkkann/his | /his_v2/src/webcam/WebcamTool.java | UTF-8 | 11,413 | 2.359375 | 2 | [] | no_license | /*
* 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 webcam;
import com.github.sarxos.webcam.Webcam;
import com.github.sarxos.webcam.WebcamPanel;
import com.github.sarxos.webcam.WebcamPicker;
import com.github.sarxos.webcam.WebcamResolution;
import configuration.PropertiesTool;
import file.FileTool;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import view.CreateGuestDIA;
import view.CreatePersonDIA;
import view.EditPersonDIA;
/**
*
* @author Patrick
*/
public class WebcamTool {
//Webcam frame
private static JFrame frame;
private static JPanel frameButtonPanel;
private static JButton cancelButton;
private static JButton captureButton;
//Picture dialog
private static JDialog dialog;
private static JPanel dialogButtonPanel;
private static JPanel dialogPicturePanel;
private static JButton yesButton;
private static JButton noButton;
//Webcam stuff
private static Webcam webcam;
private static WebcamPanel webPanel;
private static Thread webThread;
private static BufferedImage capturedImage;
private static final String defaultCapturePath = "webcam/capture.jpg";
public WebcamTool() {
}
public static void spawnWebcamFrame(final CreatePersonDIA dia) throws InterruptedException {
//Clean
FileTool.deleteFile(new File(defaultCapturePath));
try {
//Init gui stuff
frame = new JFrame();
frame.setLayout(new BorderLayout());
frameButtonPanel = new JPanel();
frame.add(frameButtonPanel, BorderLayout.SOUTH);
cancelButton = new JButton("Annuller");
cancelButton.setEnabled(false);
frameButtonPanel.add(cancelButton);
captureButton = new JButton("Tag billed");
captureButton.setEnabled(false);
frameButtonPanel.add(captureButton);
//Add action listeners
cancelButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
frame.dispose();
webPanel.stop();
webThread = null;
}
});
captureButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
capturedImage = webcam.getImage();
try {
ImageIO.write(capturedImage, "jpg", new FileOutputStream(new File(defaultCapturePath)));
} catch (IOException ex) {
Logger.getLogger(WebcamTool.class.getName()).log(Level.SEVERE, null, ex);
}
dia.setPicturePath(defaultCapturePath);
dia.setPicturePanel();
frame.dispose();
webPanel.stop();
webThread = null;
}
});
//Init webcam stuff
webcam = getDefaultWebcam();
webcam.setViewSize(WebcamResolution.VGA.getSize());
webPanel = new WebcamPanel(webcam, false);
frame.add(webPanel, BorderLayout.CENTER);
webThread = new Thread() {
@Override
public void run() {
webPanel.start();
cancelButton.setEnabled(true);
captureButton.setEnabled(true);
}
};
//start
frame.setUndecorated(true);
frame.pack();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setAlwaysOnTop(true);
webThread.start();
frame.setVisible(true);
} catch (IllegalArgumentException | NullPointerException ex) {
dia.setAlwaysOnTop(false);
JOptionPane.showMessageDialog(frame,
"Webcamet ser ikke ud til at være tilsluttet.\nKontakt en administrator for at få hjælp",
"Webcam fejl",
JOptionPane.ERROR_MESSAGE);
dia.setAlwaysOnTop(true);
}
}
public static void spawnWebcamFrame(final EditPersonDIA dia) throws InterruptedException {
//Clean
FileTool.deleteFile(new File(defaultCapturePath));
try {
//Init gui stuff
frame = new JFrame();
frame.setLayout(new BorderLayout());
frameButtonPanel = new JPanel();
frame.add(frameButtonPanel, BorderLayout.SOUTH);
cancelButton = new JButton("Annuller");
cancelButton.setEnabled(false);
frameButtonPanel.add(cancelButton);
captureButton = new JButton("Tag billed");
captureButton.setEnabled(false);
frameButtonPanel.add(captureButton);
//Add action listeners
cancelButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
frame.dispose();
webPanel.stop();
webThread = null;
}
});
captureButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
capturedImage = webcam.getImage();
try {
ImageIO.write(capturedImage, "jpg", new FileOutputStream(new File(defaultCapturePath)));
} catch (IOException ex) {
Logger.getLogger(WebcamTool.class.getName()).log(Level.SEVERE, null, ex);
}
dia.setPicturePath(defaultCapturePath);
dia.setPicturePanel();
frame.dispose();
webPanel.stop();
webThread = null;
}
});
//Init webcam stuff
webcam = getDefaultWebcam();
webcam.setViewSize(WebcamResolution.VGA.getSize());
webPanel = new WebcamPanel(webcam, false);
frame.add(webPanel, BorderLayout.CENTER);
webThread = new Thread() {
@Override
public void run() {
webPanel.start();
cancelButton.setEnabled(true);
captureButton.setEnabled(true);
}
};
//start
frame.setUndecorated(true);
frame.pack();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setAlwaysOnTop(true);
webThread.start();
frame.setVisible(true);
} catch (IllegalArgumentException | NullPointerException ex) {
dia.setAlwaysOnTop(false);
JOptionPane.showMessageDialog(frame,
"Webcamet ser ikke ud til at være tilsluttet.\nKontakt en administrator for at få hjælp",
"Webcam fejl",
JOptionPane.ERROR_MESSAGE);
dia.setAlwaysOnTop(true);
}
}
public static void spawnWebcamFrame(final CreateGuestDIA dia) throws InterruptedException {
//Clean
FileTool.deleteFile(new File(defaultCapturePath));
try {
//Init gui stuff
frame = new JFrame();
frame.setLayout(new BorderLayout());
frameButtonPanel = new JPanel();
frame.add(frameButtonPanel, BorderLayout.SOUTH);
cancelButton = new JButton("Annuller");
cancelButton.setEnabled(false);
frameButtonPanel.add(cancelButton);
captureButton = new JButton("Tag billed");
captureButton.setEnabled(false);
frameButtonPanel.add(captureButton);
//Add action listeners
cancelButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
frame.dispose();
webPanel.stop();
webThread = null;
}
});
captureButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
capturedImage = webcam.getImage();
try {
ImageIO.write(capturedImage, "jpg", new FileOutputStream(new File(defaultCapturePath)));
} catch (IOException ex) {
Logger.getLogger(WebcamTool.class.getName()).log(Level.SEVERE, null, ex);
}
dia.setPicturePath(defaultCapturePath);
dia.setPicturePanel();
frame.dispose();
webPanel.stop();
webThread = null;
}
});
//Init webcam stuff
webcam = getDefaultWebcam();
webcam.setViewSize(WebcamResolution.VGA.getSize());
webPanel = new WebcamPanel(webcam, false);
frame.add(webPanel, BorderLayout.CENTER);
webThread = new Thread() {
@Override
public void run() {
webPanel.start();
cancelButton.setEnabled(true);
captureButton.setEnabled(true);
}
};
//start
frame.setUndecorated(true);
frame.pack();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setAlwaysOnTop(true);
webThread.start();
frame.setVisible(true);
} catch (IllegalArgumentException | NullPointerException ex) {
dia.setAlwaysOnTop(false);
JOptionPane.showMessageDialog(frame,
"Webcamet ser ikke ud til at være tilsluttet.\nKontakt en administrator for at få hjælp",
"Webcam fejl",
JOptionPane.ERROR_MESSAGE);
dia.setAlwaysOnTop(true);
}
}
private static Webcam getDefaultWebcam() {
String camName = PropertiesTool.getInstance().getProperty("defaultcam");
List<Webcam> cams = Webcam.getWebcams();
for (Webcam w : cams) {
if (w.getName().equals(camName)) {
return w;
}
}
return null;
}
}
| true |
b6d6b0ff1c08ef9a7e97589e5382f4738fea4eca | Java | FatBallFish/Muses | /app/src/main/java/com/victorxu/muses/search/presenter/SearchResultPresenter.java | UTF-8 | 5,066 | 2.28125 | 2 | [] | no_license | package com.victorxu.muses.search.presenter;
import android.content.Context;
import android.util.Log;
import android.view.View;
import com.google.gson.Gson;
import com.victorxu.muses.R;
import com.victorxu.muses.gson.PageCommodity;
import com.victorxu.muses.search.contract.SearchResultContract;
import com.victorxu.muses.search.model.SearchResultModel;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
@SuppressWarnings({"NullableProblems", "ConstantConditions"})
public class SearchResultPresenter implements SearchResultContract.Presenter {
private static final String TAG = "SearchResultPresenter";
private SearchResultContract.View mView;
private SearchResultContract.Model mModel;
public SearchResultPresenter(int index, String keyword, SearchResultContract.View mView, Context context) {
this.mView = mView;
mModel = new SearchResultModel(context);
mModel.setIndex(index);
mModel.setKeyword(keyword);
}
@Override
public void loadRootView(View view) {
mView.initView(view);
}
@Override
public void loadProductToView() {
mView.showLoading();
mModel.getProductData(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.e(TAG, "onFailure: getProductData");
if (!e.getMessage().equals("Socket closed")) {
mView.hideLoading();
mView.showToast(R.string.network_error_please_try_again);
if (!mModel.checkDataStatus()) {
mView.showFailPage();
}
}
}
@Override
public void onResponse(Call call, Response response) {
try {
PageCommodity commodity = new Gson().fromJson(response.body().string(), PageCommodity.class);
if (commodity != null && commodity.getCode().equals("OK") && commodity.getPageData().getTotalNum() != 0) {
List<PageCommodity> pages = new ArrayList<>();
pages.add(commodity);
mModel.setPageList(pages);
mModel.setAllPages(commodity.getPageData().getPageCount());
mView.showProductList(commodity.getPageData().getCommodityList());
// Log.d(TAG, "onResponse: getProductData");
}
} catch (Exception e) {
mView.showToast(R.string.data_error_please_try_again);
e.printStackTrace();
} finally {
if (!mModel.checkDataStatus()) {
mView.showEmptyPage();
}
mView.hideLoading();
}
}
});
}
@Override
public void loadMoreProductToView() {
mView.showLoadingMore();
if (mModel.checkPageStatus()) {
mModel.getMoreProductData(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.e(TAG, "onFailure: getMoreProductData");
if (!e.getMessage().equals("Socket closed")) {
mView.hideLoadingMore(false, false);
mView.showToast(R.string.network_error_please_try_again);
}
}
@Override
public void onResponse(Call call, Response response) {
try {
PageCommodity commodity = new Gson().fromJson(response.body().string(), PageCommodity.class);
if (commodity != null && commodity.getCode().equals("OK") && commodity.getPageData().getTotalNum() != 0) {
mModel.addPage(commodity);
mModel.setAllPages(commodity.getPageData().getPageCount());
mView.showMoreProduct(commodity.getPageData().getCommodityList());
mView.hideLoadingMore(true, false);
Log.d(TAG, "onResponse: getMoreProductData");
} else {
mView.hideLoadingMore(false, false);
Log.w(TAG, "onResponse: getProductData DATA ERROR");
}
} catch (Exception e) {
mView.showToast(R.string.data_error_please_try_again);
e.printStackTrace();
}
}
});
} else {
mView.hideLoadingMore(true, true);
}
}
@Override
public void reloadProductToView() {
loadProductToView();
}
@Override
public void destroy() {
mView = null;
if (mModel != null) {
mModel.cancelTask();
mModel = null;
}
}
}
| true |
0b9ec7dff2db0abb724568abaa16feda9d7ad55a | Java | JeffWoo2019/aliyun-openapi-java-sdk | /aliyun-java-sdk-ecsops/src/main/java/com/aliyuncs/ecsops/model/v20160401/OpsSlsDescribeDashBoardResponse.java | UTF-8 | 3,312 | 1.851563 | 2 | [
"Apache-2.0"
] | permissive | /*
* 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.aliyuncs.ecsops.model.v20160401;
import java.util.List;
import com.aliyuncs.AcsResponse;
import com.aliyuncs.ecsops.transform.v20160401.OpsSlsDescribeDashBoardResponseUnmarshaller;
import com.aliyuncs.transform.UnmarshallerContext;
/**
* @author auto create
* @version
*/
public class OpsSlsDescribeDashBoardResponse extends AcsResponse {
private String requestId;
private String message;
private String code;
private String success;
private Long pageSize;
private Long pageNo;
private Long total;
private List<DashBoards> data;
public String getRequestId() {
return this.requestId;
}
public void setRequestId(String requestId) {
this.requestId = requestId;
}
public String getMessage() {
return this.message;
}
public void setMessage(String message) {
this.message = message;
}
public String getCode() {
return this.code;
}
public void setCode(String code) {
this.code = code;
}
public String getSuccess() {
return this.success;
}
public void setSuccess(String success) {
this.success = success;
}
public Long getPageSize() {
return this.pageSize;
}
public void setPageSize(Long pageSize) {
this.pageSize = pageSize;
}
public Long getPageNo() {
return this.pageNo;
}
public void setPageNo(Long pageNo) {
this.pageNo = pageNo;
}
public Long getTotal() {
return this.total;
}
public void setTotal(Long total) {
this.total = total;
}
public List<DashBoards> getData() {
return this.data;
}
public void setData(List<DashBoards> data) {
this.data = data;
}
public static class DashBoards {
private String dashboardName;
private String description;
private String displayName;
private String attribute;
public String getDashboardName() {
return this.dashboardName;
}
public void setDashboardName(String dashboardName) {
this.dashboardName = dashboardName;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDisplayName() {
return this.displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getAttribute() {
return this.attribute;
}
public void setAttribute(String attribute) {
this.attribute = attribute;
}
}
@Override
public OpsSlsDescribeDashBoardResponse getInstance(UnmarshallerContext context) {
return OpsSlsDescribeDashBoardResponseUnmarshaller.unmarshall(this, context);
}
@Override
public boolean checkShowJsonItemName() {
return false;
}
}
| true |
ed8c3126e8aef363b769e810be31be35c758269d | Java | vianhazman/dagger | /dagger-core/src/main/java/io/odpf/dagger/core/exception/HttpFailureException.java | UTF-8 | 350 | 2.171875 | 2 | [
"Apache-2.0"
] | permissive | package io.odpf.dagger.core.exception;
/**
* The class Exception if there is failure in Http.
*/
public class HttpFailureException extends RuntimeException {
/**
* Instantiates a new Http failure exception.
*
* @param message the message
*/
public HttpFailureException(String message) {
super(message);
}
}
| true |
fd154bb64edc25acbc2ae168792a071e0f7ded07 | Java | zulus128/aMTrade | /MTrade/src/com/vkassin/mtrade/Quote.java | UTF-8 | 1,915 | 2.671875 | 3 | [] | no_license | package com.vkassin.mtrade;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class Quote implements Comparable<Quote> {
// private static final long serialVersionUID = 24L;
private static final String TAG = "MTrade.Quote";
public String id = "";
private static DecimalFormat twoDForm = new DecimalFormat("#0.00");
static {
DecimalFormatSymbols dfs = new DecimalFormatSymbols();
dfs.setDecimalSeparator('.');
twoDForm.setDecimalFormatSymbols(dfs);
}
private Double price = Double.valueOf(0);
public Long qtySell = Long.valueOf(0);
public Long qtyBuy = Long.valueOf(0);
public Long instrId = Long.valueOf(0);
public int compareTo(Quote arg0) {
if(this.price < arg0.price)
{
/* текущее меньше полученного */
return 1;
}
else if(this.price > arg0.price)
{
/* текущее больше полученного */
return -1;
}
/* текущее равно полученному */
return 0;
}
public Quote(String i, JSONObject obj) {
this.id = i;
set(obj);
Log.i(TAG, " --/ Quote created id:" + i + ", price = " + price);
}
public void update(JSONObject obj) {
set(obj);
Log.i(TAG, "quote " + id + ", price = " + price + " updated.");
}
private void set(JSONObject obj){
try{ this.price = Double.parseDouble(obj.getString("price")); }catch(JSONException e){ }
try{ this.qtyBuy = obj.getLong("qtyBuy"); }catch(JSONException e){ }
try{ this.qtySell = obj.getLong("qtySell"); }catch(JSONException e){ }
try{ this.instrId = obj.getLong("instrId"); }catch(JSONException e){ }
}
public String getPriceS() {
return twoDForm.format(price);
}
}
| true |
fa17e3a4a9c612fc9746ff3d548a8114c34f9765 | Java | margaritis/genlab | /genlab.core/src/genlab/core/exec/ICleanableTask.java | UTF-8 | 187 | 1.726563 | 2 | [] | no_license | package genlab.core.exec;
/**
*
* Tags the tasks which, by construction, can be cleaned once finished.
*
* @author Samuel Thiriot
*
*/
public interface ICleanableTask extends ITask {
}
| true |
977b8ab087f8fa43ad4eeac99a4a5205fdc81f5a | Java | krudolph/jade4j | /src/main/java/de/neuland/jade4j/expression/JexlExpressionHandler.java | UTF-8 | 3,302 | 2.421875 | 2 | [
"MIT"
] | permissive | package de.neuland.jade4j.expression;
import org.apache.commons.jexl3.JexlExpression;
import org.apache.commons.jexl3.JexlScript;
import org.apache.commons.jexl3.internal.JadeJexlEngine;
import org.apache.commons.jexl3.JexlEngine;
import org.apache.commons.jexl3.MapContext;
import de.neuland.jade4j.exceptions.ExpressionException;
import de.neuland.jade4j.model.JadeModel;
import org.apache.commons.jexl3.JexlScript;
import org.apache.commons.jexl3.MapContext;
import org.apache.commons.jexl3.internal.Script;
import org.apache.commons.lang3.StringUtils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class JexlExpressionHandler implements ExpressionHandler {
private static final int MAX_ENTRIES = 5000;
public static Pattern plusplus = Pattern.compile("([a-zA-Z0-9-_]*[a-zA-Z0-9])\\+\\+\\s*;{0,1}\\s*$");
public static Pattern isplusplus = Pattern.compile("\\+\\+\\s*;{0,1}\\s*$");
public static Pattern minusminus = Pattern.compile("([a-zA-Z0-9-_]*[a-zA-Z0-9])--\\s*;{0,1}\\s*$");
public static Pattern isminusminus = Pattern.compile("--\\s*;{0,1}\\s*$");
private JexlEngine jexl;
public JexlExpressionHandler() {
jexl = new JadeJexlEngine(MAX_ENTRIES);
}
public Boolean evaluateBooleanExpression(String expression, JadeModel model) throws ExpressionException {
return BooleanUtil.convert(evaluateExpression(expression, model));
}
public Object evaluateExpression(String expression, JadeModel model) throws ExpressionException {
try {
expression = removeVar(expression);
if (isplusplus.matcher(expression).find()) {
expression = convertPlusPlusExpression(expression);
}
if (isminusminus.matcher(expression).find()) {
expression = convertMinusMinusExpression(expression);
}
JexlScript e = jexl.createScript(expression);
MapContext jexlContext = new MapContext(model);
Object evaluate = e.execute(jexlContext);
return evaluate;
} catch (Exception e) {
throw new ExpressionException(expression, e);
}
}
private String convertMinusMinusExpression(String expression) {
Matcher matcher = minusminus.matcher(expression);
if (matcher.find(0) && matcher.groupCount() == 1) {
String a = matcher.group(1);
expression = a + " = " + a + " - 1";
}
return expression;
}
private String convertPlusPlusExpression(String expression) {
Matcher matcher = plusplus.matcher(expression);
if (matcher.find(0) && matcher.groupCount() == 1) {
String a = matcher.group(1);
expression = a + " = " + a + " + 1";
}
return expression;
}
private String removeVar(String expression) {
expression = expression.replace("var ",";");
return expression;
}
public void assertExpression(String expression) throws ExpressionException {
try {
jexl.createExpression(expression);
} catch (Exception e) {
throw new ExpressionException(expression, e);
}
}
public String evaluateStringExpression(String expression, JadeModel model) throws ExpressionException {
Object result = evaluateExpression(expression, model);
return result == null ? "" : result.toString();
}
public void setCache(boolean cache) {
jexl = new JadeJexlEngine(cache ? MAX_ENTRIES : 0);
}
public void clearCache() {
jexl.clearCache();
}
}
| true |
25d64bb5101d46b18f498ac27fc5cd527c9cdba8 | Java | hradecek/booking-manager | /booking-manager-api/src/main/java/cz/muni/fi/pa165/dto/CreateHotelDto.java | UTF-8 | 861 | 2.84375 | 3 | [] | no_license | package cz.muni.fi.pa165.dto;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
/**
* Data transfer object for creating a <i>hotel</i> item.
*
* @author Ivo Hradek
*/
public class CreateHotelDto {
@NotNull
@Size(min = 3, max = 50)
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof CreateHotelDto)) return false;
final CreateHotelDto hotel = (CreateHotelDto) o;
return hotel.getName().equals(getName());
}
@Override
public int hashCode() {
int result;
result = 31 + ((null == getName()) ? 0 : getName().hashCode());
return result;
}
}
| true |
b7fc6833fa96852ab63529905137e03b7739954b | Java | jheimes-silveira/LocacaoVeiculo | /app/src/main/java/br/com/unitri/jheimesilveira/locacaoveiculo/bo/VeiculoBO.java | UTF-8 | 572 | 1.945313 | 2 | [] | no_license | package br.com.unitri.jheimesilveira.locacaoveiculo.bo;
import android.content.Context;
import java.sql.SQLException;
import br.com.unitri.jheimesilveira.locacaoveiculo.db.GenericCRUD;
import br.com.unitri.jheimesilveira.locacaoveiculo.domain.Categoria;
import br.com.unitri.jheimesilveira.locacaoveiculo.domain.Veiculo;
/**
* Created by jheimes on 04/04/17.
*/
public class VeiculoBO extends GenericCRUD<Veiculo, Integer> {
public VeiculoBO(Context context) throws SQLException {
super(context, Veiculo.class, Veiculo.class.getSimpleName());
}
}
| true |
970fc659c19f23300d0c1591b70d87b6043e579d | Java | secondzc/myAlgorithm | /src/main/java/com/tongyuan/collection/TestHashmap.java | UTF-8 | 826 | 3.40625 | 3 | [] | no_license | package com.tongyuan.collection;
import java.util.HashMap;
import java.util.Iterator;
/**
* Created by zhangcy on 2018/5/9
* 遍历map时删除元素的做法:更新迭代器
* fail-fast的作用是一个线程在迭代时,若另外的线程改变了容器的结构,就会ConcurrentModificationException异常
*/
public class TestHashmap {
public static void main(String[] args) {
HashMap<String,Object> map = new HashMap<>();
map.put("1",1);
map.put("2",2);
map.put("3",3);
Iterator<String> it = map.keySet().iterator();
while(it.hasNext()){
String str = it.next();
System.out.println(str);
if(str.equals("1")){
map.remove("1");
//it = map.keySet().iterator();
}
}
}
}
| true |
826821cb7e577798f80b5ffcdc430e20ff925c42 | Java | ayushnigamsworld/ds_algo | /anonymous/src/ikm/PersonTest.java | UTF-8 | 954 | 3.140625 | 3 | [] | no_license | package ikm;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
public class PersonTest {
static List<Person> people = Arrays.asList(new Person("bob", 1), new Person(2), new Person("Jane", 3));
static int x;
public static void main(String[] args) {
people.stream().reduce((e1, e2) -> {
x = e1.id;
if (e1.id > e2.id) {
return e1;
}
x = e2.id;
return e2;
}).flatMap(e -> Optional.ofNullable(e.name)).map(y -> new Person(y, x)).ifPresent(System.out::println);
}
}
class Person {
String name;
Integer id;
Person(int i) {
name = null;
id = i;
}
Person(String n,int i) {
name = n;
id = i;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", id=" + id +
'}';
}
}
| true |
6eacb40115a171b6e1af7bce91bda80c21db8740 | Java | to-explore-future/MySqlTest1 | /src/Main.java | UTF-8 | 1,628 | 2.625 | 3 | [] | no_license | import hierarchyDemo.util.SqlUtil;
import hierarchyDemo.view.TransferView;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
public class Main {
public static void main(String[] args) throws Exception{
// simpleTest();
SqlMethodTest sqlMethodTest = new SqlMethodTest();
sqlMethodTest.init();
sqlMethodTest.insert();
sqlMethodTest.update();
sqlMethodTest.delete();
new SqlInjection().login();
SqlInjectionMethods sqlInjectionMethods = new SqlInjectionMethods();
sqlInjectionMethods.insert();
sqlInjectionMethods.update();
sqlInjectionMethods.delete();
DBUtilTest dbUtilTest = new DBUtilTest();
dbUtilTest.insert();
dbUtilTest.update();
dbUtilTest.delete();
dbUtilTest.query();
Transaction transaction = new Transaction();
// transaction.transferAccounts();
transaction.transferAccountsByDBUtils();
System.out.println("\n\n\n");
TransferView transferView = new TransferView();
transferView.transfer();
}
private static void simpleTest() throws Exception {
Connection connection = SqlUtil.getConnection();
Statement statement = connection.createStatement();
String selectTest = "select * from country";
ResultSet resultSet = statement.executeQuery(selectTest);
while (resultSet.next()) {
Object name = resultSet.getObject("Name");
System.out.print(name + "\t");
}
SqlUtil.closeAll(connection,resultSet,statement);
}
}
| true |
81f016cb65b7c8274fa7d2541beafb7ef8cf31f6 | Java | kpkk/Java-sample-porjects | /src/main/java/LamdaExpressionExample.java | UTF-8 | 694 | 3.484375 | 3 | [] | no_license | import java.util.ArrayList;
import java.util.Collections;
public class LamdaExpressionExample {
public static void main(String[] args) {
LambdaExpressions ll=()->{
System.out.println("draw method implementation");
};
ll.draw();
ArrayList<String> list=new ArrayList<String>();
list.add("pradeep");
list.add("roger");
list.add("rafa");
list.add("abc");
list.forEach((n)->System.out.println(n));
System.out.println("printing the names in sorting order by name");
Collections.sort(list,(p1,p2)->{
return p1.compareTo(p2);
});
//System.out.println("after sort");
list.forEach(m->System.out.println(m));
}
}
| true |
512e05dbf1fc0a9756fae00b95835a4a187fa4ea | Java | booknara/BatteryChecker | /src/com/booknara/android/batterychecker/MainActivity.java | UTF-8 | 3,422 | 2.328125 | 2 | [
"Apache-2.0"
] | permissive | package com.booknara.android.batterychecker;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
private TextView mPlugged;
private TextView mStatus;
private TextView mLevel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPlugged = (TextView) findViewById(R.id.plugged_text);
mStatus = (TextView) findViewById(R.id.status_text);
mLevel = (TextView) findViewById(R.id.level_text);
registerReceiver(batterReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
@Override
protected void onStop() {
super.onStop();
unregisterReceiver(batterReceiver);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private BroadcastReceiver batterReceiver = new BroadcastReceiver() {
Intent intent = null;
@Override
public void onReceive(Context context, Intent intent) {
this.intent = intent;
mPlugged.setText("Battery Plugged : " + getPlugged());
mStatus.setText("Battery Status : " + getStatus());
mLevel.setText("Battery Level : " + getLevel());
}
public String getPlugged() {
int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
String pluggedStr = "";
switch (plugged) {
case BatteryManager.BATTERY_PLUGGED_AC:
pluggedStr = "BATTERY_PLUGGED_AC";
break;
case BatteryManager.BATTERY_PLUGGED_USB:
pluggedStr = "BATTERY_PLUGGED_USB";
break;
default:
break;
}
return pluggedStr;
}
public String getStatus() {
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
String statusStr = "";
switch (status) {
case BatteryManager.BATTERY_STATUS_CHARGING:
statusStr = "BATTERY_STATUS_CHARGING";
break;
case BatteryManager.BATTERY_STATUS_DISCHARGING:
statusStr = "BATTERY_STATUS_DISCHARGING";
break;
case BatteryManager.BATTERY_STATUS_FULL:
statusStr = "BATTERY_STATUS_FULL";
break;
case BatteryManager.BATTERY_STATUS_NOT_CHARGING:
statusStr = "BATTERY_STATUS_NOT_CHARGING";
break;
case BatteryManager.BATTERY_STATUS_UNKNOWN:
statusStr = "BATTERY_STATUS_UNKNOWN";
break;
default:
break;
}
return statusStr;
}
public String getLevel() {
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
if(level == -1 || scale == -1) {
return "0%";
}
return "" + ((float)level / (float)scale) * 100.0f + "%";
}
};
} | true |
69bb019f441dc08881c400538499fcce21912b45 | Java | cms-sw/hlt-confdb | /src/confdb/converter/ascii/AsciiPathWriter.java | UTF-8 | 843 | 2.71875 | 3 | [] | no_license | package confdb.converter.ascii;
import confdb.converter.ConverterEngine;
import confdb.converter.IPathWriter;
import confdb.data.Path;
public class AsciiPathWriter implements IPathWriter
{
public String toString( Path path, ConverterEngine converterEngine, String indent )
{
String str = indent;
if ( path.isEndPath() )
str += "endpath ";
else if ( path.isFinalPath() )
str += "finalpath ";
else
str += "path";
str += decorateName( path.name() ) + " = { ";
for ( int i = 0; i < path.entryCount(); i++ )
{
str += decorate( path.entry(i).name() );
if ( i + 1 < path.entryCount() )
str += " & ";
}
str += " }" + converterEngine.getNewline();
return str;
}
protected String decorate( String name )
{
return name;
}
protected String decorateName( String name )
{
return name;
}
}
| true |
3d8104f9d3c4d4f578740d03c011fca6fa8eb205 | Java | arnonmoscona/iqfeed | /src/main/java/com/moscona/trading/adapters/iqfeed/IqFeedConfig.java | UTF-8 | 13,913 | 1.8125 | 2 | [
"Apache-2.0"
] | permissive | package com.moscona.trading.adapters.iqfeed;
import com.moscona.events.EventPublisher;
import com.moscona.exceptions.InvalidArgumentException;
import com.moscona.exceptions.InvalidStateException;
import com.moscona.test.util.TestResourceHelper;
import com.moscona.trading.IServicesBundle;
import com.moscona.trading.IServicesBundleManager;
import com.moscona.trading.ServicesBundle;
import com.moscona.trading.ServicesBundleManager;
import com.moscona.trading.formats.deprecated.MarketTree;
import com.moscona.trading.formats.deprecated.MasterTree;
import com.moscona.util.IAlertService;
import com.moscona.util.monitoring.stats.IStatsService;
import com.moscona.util.monitoring.stats.SimpleStatsService;
import com.moscona.util.monitoring.stats.SynchronizedDelegatingStatsService;
import org.apache.commons.beanutils.BeanMap;
import org.apache.commons.lang3.ClassUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.LogFactory;
import java.io.IOException;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by Arnon on 5/13/2014.
* This is a temporary bridging solution. A subset of the old ServerConfig, this class implements the base minimum to
* pass the relevant EasyB test.
* It should be refactored heavily to separate between the loadable configuration, the dependency injection and
* factory method aspects, and the generic service method aspects.
* FIXME separate the loadable config aspects from factory methods, dependency injection, plugin support
*/
public class IqFeedConfig implements IDtnIQFeedConfig {
private final boolean configFullyLoaded;
/**
* Configuration parameters for components that need additional configuration
*/
private HashMap componentConfig;
/**
* A list of class names keyed by their associated attributes that are initialized as plugin components at the very
* end of the load sequence
* FIXME may not be needed
*/
private HashMap<String, String> pluginComponents;
private UserOverrides userOverrides;
/**
* The default servicesBundle bundle to use
*/
private ServicesBundle servicesBundle;
private IServicesBundleManager servicesBundleManager;
private TestResourceHelper testResourceHelper = null;
private String alertServiceClassName; // FIXME should be proper dependency injection
private String statsServiceClassName; // FIXME should be proper dependency injection
private EventPublisher eventPublisher; // FIXME Should replace EventPublisher with something cleaner
private SynchronizedDelegatingStatsService lookupStatsService;
private String streamDataStoreRoot; // FIXME rename. I think it's used for logging root only
private LogFactory logFactory;
private MarketTree marketTree; // FIXME get rid of dependency on MarketTree
private MasterTree masterTree; // FIXME get rid of dependency on MarketTree
public IqFeedConfig() {
configFullyLoaded = false; // FIXME implement the entire plugin loading and configuration cycle
eventPublisher = new EventPublisher();
eventPublisher.clearSubscribers();
}
/**
* A convenience service method that returns the component specific configuration info
* @param component the name of the component
* @return the entry in the component config hash (it's up to the component to determine validity of this
*/
@Override
public Object getComponentConfigFor(String component) {
return componentConfig.get(component);
}
/**
* A utility methods to make it easier for components to configure themselves using the componentConfig
* configuration and user overrides. It covers the most common case, where the configuration is a HashMap
* that maps String to String and the override property is a string as well.
* @param componentNode the key in the componentConfig hash for this component
* @param key the key in the component node for the configuration item
* @param overrideProperty the property name in the UserOverrides class. May be null. If not must exist.
* @return the value, with the override applied if the override exists and is not blank
* @throws InvalidArgumentException
*/
@Override
public String simpleComponentConfigEntryWithOverride(String componentNode, String key, String overrideProperty) throws InvalidArgumentException, InvalidStateException, IOException {
String retval = null;
try {
HashMap componentConfig = (HashMap) getComponentConfigFor(componentNode);
if (componentConfig != null) {
retval = componentConfig.get(key).toString();
}
if (userOverrides != null && overrideProperty != null) {
BeanMap overrides = new BeanMap(userOverrides);
if (overrides.containsKey(overrideProperty)) {
Object value = overrides.get(overrideProperty);
String overrideValue = (value == null) ? null : value.toString();
if (!StringUtils.isBlank(overrideValue)) {
retval = overrideValue;
}
}
}
} catch (ClassCastException e) {
throw new InvalidArgumentException("Class cast problem in simpleComponentConfigEntryWithOverride() - most likely a mismatch between waht you expect the config or the overrides to contain and what they actually contain: " + e, e);
}
retval = interpolate(retval);
return retval;
}
@Override
public String simpleComponentConfigEntryWithOverride(String componentNode, String key) throws InvalidArgumentException, InvalidStateException, IOException {
return simpleComponentConfigEntryWithOverride(componentNode, key, key);
}
@Override
public ServicesBundle getServicesBundle() throws InvalidArgumentException, InvalidStateException {
if (servicesBundle == null) {
servicesBundle = getServicesBundleManager().createServicesBundle();
}
return servicesBundle;
}
public void setServicesBundle(ServicesBundle servicesBundle) {
this.servicesBundle = servicesBundle;
}
public void initServicesBundle() throws InvalidArgumentException, InvalidStateException {
servicesBundleManager = new ServicesBundleManager(this);
servicesBundle = servicesBundleManager.createServicesBundle();
}
@Override
public IAlertService getAlertService() throws InvalidStateException, InvalidArgumentException {
return getServicesBundle().getAlertService();
}
public void setAlertService(IAlertService alertService) {
if (servicesBundle == null) {
servicesBundle = new ServicesBundle();
}
servicesBundle.setAlertService(alertService);
}
@Override
public IStatsService getStatsService() throws InvalidStateException, InvalidArgumentException {
return getServicesBundle().getStatsService();
}
public void setStatsService(IStatsService statsService) {
if (servicesBundle == null) {
servicesBundle = new ServicesBundle();
}
servicesBundle.setStatsService(statsService);
}
/**
* A factory method to create services bundles compatible with the configuration. Used to create the default
* services bundle but also for any code that needs to create private instances, predominantly required for
* anything that runs in a separate thread.
* @return a new instance of a a services bundle
* @throws com.moscona.exceptions.InvalidStateException if cannot construct the appropriate classes
*/
@Override
public ServicesBundle createServicesBundle() throws InvalidStateException, InvalidArgumentException {
return getServicesBundleManager().createServicesBundle();
}
private synchronized IServicesBundleManager getServicesBundleManager() throws InvalidArgumentException {
if (servicesBundleManager == null) {
servicesBundleManager = new ServicesBundleManager<IDtnIQFeedConfig>(this);
}
return servicesBundleManager;
}
@Override
public EventPublisher getEventPublisher() {
return eventPublisher;
}
@Override
public synchronized IStatsService getLookupStatsService() {
if (lookupStatsService == null) {
lookupStatsService = new SynchronizedDelegatingStatsService(new SimpleStatsService());
}
return lookupStatsService;
}
@Override
public String getStreamDataStoreRoot() throws InvalidStateException, InvalidArgumentException, IOException {
// FIXME Rename this. I think it's used only as a logging root in this context. When renaming need to change YAML fixtures
String storeRoot = streamDataStoreRoot;
if (userOverrides != null && !StringUtils.isBlank(userOverrides.getStreamDataStoreRoot())) {
storeRoot = userOverrides.getStreamDataStoreRoot();
}
return interpolate(storeRoot);
}
public void setStreamDataStoreRoot(String streamDataStoreRoot) {
this.streamDataStoreRoot = streamDataStoreRoot;
}
@Override
public HashMap getComponentConfig() {
return componentConfig;
}
public void setComponentConfig(HashMap componentConfig) {
this.componentConfig = componentConfig;
}
/**
* Interpolates strings used in configuration like: "#SystemProperty{user.home}/intellitrade_alerts.log".
* The key pattern is #type{value} - the type being a supported type of interpolation and the value is the argument
* for this interpolation.
* <br/>Supported types:
* <ul>
* <li>SystemProperty - a value from the java system properties</li>
* <li>ProjectRoot - the IntelliJ IDEA project root - used only in testing context</li>
* </ul>
* @param arg the string to interpolate
* @return a new string with all the possible interpolation expanded and the original "macro" parts removed
* @throws InvalidArgumentException is you try to use an interpolation type that is not supported
* @throws com.moscona.exceptions.InvalidStateException if happens below
*/
public String interpolate(String arg) throws InvalidArgumentException, InvalidStateException, IOException {
// todo need spec
String retval = arg;
Pattern pattern = Pattern.compile("(.*)#([a-zA-Z]+)\\{(.*)\\}(.*)");
Matcher matcher = pattern.matcher(arg);
int maxIterations = 100;
while (matcher.matches()) {
String interpolationType = matcher.group(2);
if (interpolationType.equals("SystemProperty")) {
String property = matcher.group(3);
String value = System.getProperty(property);
if (value == null) {
throw new InvalidArgumentException("ServerConfig.interpolate(): System property \"" + property + "\" does not exist when interpolating \"" + arg + "\"");
}
retval = matcher.group(1) + value + matcher.group(4);
} else if (interpolationType.equals("ProjectRoot")) {
// FIXME this whole section is suspicious and should be probably removed
// String classPath = "/com/intellitrade/server/ServerConfig.class";
// String outputPath = "/out/production/server" + classPath;
// String value = ServerConfig.class.getResource(classPath).toString().replaceAll(outputPath, "").replaceAll("file:/", "");
// retval = matcher.group(1) + value + matcher.group(4);
retval = getTestResourceHelper().getProjectRootPath();
} else if (interpolationType.equals("streamDataStoreRoot")) {
retval = matcher.group(1) + getStreamDataStoreRoot() + matcher.group(4);
} else {
throw new InvalidArgumentException("ServerConfig.interpolate() does not support interpolation type " + interpolationType + " in the string: \"" + arg + "\"");
}
matcher = pattern.matcher(retval);
if (maxIterations-- <= 0) {
throw new InvalidStateException("ServerConfig.interpolate() iterated too many times without resolving \"" + arg + "\"");
}
}
return retval;
}
private synchronized TestResourceHelper getTestResourceHelper() throws IOException {
if (testResourceHelper == null) {
testResourceHelper = new TestResourceHelper();
}
return testResourceHelper;
}
@Override
public String getAlertServiceClassName() {
return alertServiceClassName;
}
public void setAlertServiceClassName(String alertServiceClassName) {
this.alertServiceClassName = alertServiceClassName;
}
@Override
public String getStatsServiceClassName() {
return statsServiceClassName;
}
public void setStatsServiceClassName(String statsServiceClassName) {
this.statsServiceClassName = statsServiceClassName;
}
@Override
public LogFactory getLogFactory() {
return logFactory;
}
public void setLogFactory(LogFactory logFactory) {
this.logFactory = logFactory;
}
@Override
public MarketTree getMarketTree() { // FIXME get rid of this method
return marketTree;
}
public void setMarketTree(MarketTree marketTree) { // FIXME get rid of this method
this.marketTree = marketTree;
}
@Override
public MasterTree getMasterTree() { // FIXME get rid of this method
return masterTree;
}
public void setMasterTree(MasterTree masterTree) { // FIXME get rid of this method
this.masterTree = masterTree;
}
}
| true |