text
stringlengths 10
2.72M
|
|---|
package com.zhowin.miyou.recommend.adapter;
import android.content.Context;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.zhowin.miyou.R;
import com.zhowin.miyou.recommend.callback.OnRoomMemberItemClickListener;
import com.zhowin.miyou.rongIM.constant.MicState;
import com.zhowin.miyou.rongIM.model.MicBean;
import java.util.List;
/**
* author : zho
* date :2020/10/24
* desc : 聊天室排麦列表的adapter
*/
public class AudienceListAdapter extends BaseQuickAdapter<MicBean, BaseViewHolder> {
public AudienceListAdapter(@Nullable List<MicBean> data) {
super(R.layout.include_room_audience_item_view, data);
}
private OnRoomMemberItemClickListener onRoomMemberItemClickListener;
public void setOnRoomMemberItemClickListener(OnRoomMemberItemClickListener onRoomMemberItemClickListener) {
this.onRoomMemberItemClickListener = onRoomMemberItemClickListener;
}
@Override
protected void convert(@NonNull BaseViewHolder helper, MicBean item) {
if (0 == helper.getAdapterPosition()) {
helper.setImageResource(R.id.civAudienceHeadImage, R.drawable.room_boss_icon)
.setGone(R.id.tvHeatNumber, false)
.setText(R.id.AudienceName, "老板位");
} else {
loadLiveRoomMember(mContext, item.getPortrait(), helper.getView(R.id.civAudienceHeadImage));
helper.setText(R.id.AudienceName, helper.getAdapterPosition() + "号麦")
.setGone(R.id.tvHeatNumber, !TextUtils.isEmpty(item.getUserId()))
.setText(R.id.tvHeatNumber, item.getCharmValue() + "");
}
helper.getView(R.id.llRoomMemberItemLayout).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (onRoomMemberItemClickListener != null) {
//第一个是在界面中的position,第二个是融云返回的position
onRoomMemberItemClickListener.onMemberItemClick(helper.getAdapterPosition(), item.getPosition(), item);
}
}
});
}
public static void loadLiveRoomMember(Context context, Object photoUrl, ImageView imageView) {
RequestOptions options = new RequestOptions()
.placeholder(R.drawable.room_put_icon)
.error(R.drawable.room_put_icon)
.diskCacheStrategy(DiskCacheStrategy.NONE);
Glide.with(context)
.load(photoUrl)
.apply(options)
.into(imageView);
}
}
|
package com.tencent.mm.plugin.freewifi.ui;
import android.os.Looper;
import com.tencent.mm.modelgeo.c;
import com.tencent.mm.plugin.freewifi.ui.c.1;
import com.tencent.mm.plugin.freewifi.ui.c.2;
import com.tencent.mm.sdk.platformtools.ag;
import com.tencent.mm.sdk.platformtools.x;
public final class d {
public static void xP() {
try {
c aPC = c.aPC();
1 1 = new 1();
if (!aPC.bgH) {
aPC.bgH = true;
aPC.jnm = c.OB();
if (aPC.jnm == null) {
x.e(c.TAG, "doGeoLocation fail, iGetLocation is null");
return;
}
if (aPC.fRk == null) {
aPC.fRk = new 1(aPC, 1);
}
if (aPC.jnn == null) {
aPC.jnn = new ag(Looper.myLooper());
}
aPC.jnn.postDelayed(new 2(aPC), 20000);
aPC.jnm.a(aPC.fRk);
}
} catch (Exception e) {
x.e("MicroMsg.FreeWifi.FreeWifiLocationReporter", "report location error. " + e.getMessage());
}
}
}
|
package org.aion.avm.core;
import java.math.BigInteger;
import org.aion.avm.api.ABIEncoder;
import org.aion.avm.core.util.CodeAndArguments;
import org.aion.avm.core.util.Helpers;
import org.aion.avm.api.Address;
import org.aion.avm.core.util.TestingHelper;
import org.aion.kernel.Block;
import org.aion.kernel.KernelInterfaceImpl;
import org.aion.kernel.TransactionContextImpl;
import org.aion.kernel.Transaction;
import org.aion.kernel.TransactionContext;
import org.aion.kernel.TransactionResult;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.Arrays;
import static org.junit.Assert.assertEquals;
public class AvmImplDeployAndRunTest {
private byte[] from = KernelInterfaceImpl.PREMINED_ADDRESS;
private long energyLimit = 5000000;
private long energyPrice = 1;
private Block block = new Block(new byte[32], 1, Helpers.randomBytes(Address.LENGTH), System.currentTimeMillis(), new byte[0]);
private KernelInterfaceImpl kernel;
private Avm avm;
@Before
public void setup() {
this.kernel = new KernelInterfaceImpl();
this.avm = CommonAvmFactory.buildAvmInstance(this.kernel);
}
@After
public void tearDown() {
this.avm.shutdown();
}
public TransactionResult deployHelloWorld() {
byte[] jar = Helpers.readFileToBytes("../examples/build/com.example.helloworld.jar");
byte[] txData = new CodeAndArguments(jar, null).encodeToBytes();
Transaction tx = Transaction.create(from, kernel.getNonce(from), BigInteger.ZERO, txData, energyLimit, energyPrice);
TransactionContextImpl context = new TransactionContextImpl(tx, block);
return avm.run(new TransactionContext[] {context})[0].get();
}
@Test
public void testDeployWithClinitCall() {
byte[] jar = Helpers.readFileToBytes("../examples/build/com.example.helloworld.jar");
byte[] arguments = ABIEncoder.encodeMethodArguments("", 100);
byte[] txData = new CodeAndArguments(jar, arguments).encodeToBytes();
Transaction tx = Transaction.create(from, kernel.getNonce(from), BigInteger.ZERO, txData, energyLimit, energyPrice);
TransactionContextImpl context = new TransactionContextImpl(tx, block);
TransactionResult result = avm.run(new TransactionContext[] {context})[0].get();
assertEquals(TransactionResult.Code.SUCCESS, result.getStatusCode());
}
@Test
public void testDeployAndMethodCalls() {
TransactionResult deployResult = deployHelloWorld();
assertEquals(TransactionResult.Code.SUCCESS, deployResult.getStatusCode());
// call the "run" method
byte[] txData = ABIEncoder.encodeMethodArguments("run");
Transaction tx = Transaction.call(from, deployResult.getReturnData(), kernel.getNonce(from), BigInteger.ZERO, txData, energyLimit, energyPrice);
TransactionContextImpl context = new TransactionContextImpl(tx, block);
TransactionResult result = avm.run(new TransactionContext[] {context})[0].get();
assertEquals(TransactionResult.Code.SUCCESS, result.getStatusCode());
assertEquals("Hello, world!", new String((byte[]) TestingHelper.decodeResult(result)));
// test another method call, "add" with arguments
txData = ABIEncoder.encodeMethodArguments("add", 123, 1);
tx = Transaction.call(from, deployResult.getReturnData(), kernel.getNonce(from), BigInteger.ZERO, txData, energyLimit, energyPrice);
context = new TransactionContextImpl(tx, block);
result = avm.run(new TransactionContext[] {context})[0].get();
assertEquals(TransactionResult.Code.SUCCESS, result.getStatusCode());
assertEquals(124, TestingHelper.decodeResult(result));
}
public TransactionResult deployTheDeployAndRunTest() {
byte[] jar = Helpers.readFileToBytes("../examples/build/com.example.deployAndRunTest.jar");
byte[] txData = new CodeAndArguments(jar, null).encodeToBytes();
Transaction tx = Transaction.create(from, kernel.getNonce(from), BigInteger.ZERO, txData, energyLimit, energyPrice);
TransactionContextImpl context = new TransactionContextImpl(tx, block);
return avm.run(new TransactionContext[] {context})[0].get();
}
@Test
public void testDeployAndRunTest() {
TransactionResult deployResult = deployTheDeployAndRunTest();
assertEquals(TransactionResult.Code.SUCCESS, deployResult.getStatusCode());
// test encode method arguments with "encodeArgs"
byte[] txData = ABIEncoder.encodeMethodArguments("encodeArgs");
Transaction tx = Transaction.call(from, deployResult.getReturnData(), kernel.getNonce(from), BigInteger.ZERO, txData, energyLimit, energyPrice);
TransactionContextImpl context = new TransactionContextImpl(tx, block);
TransactionResult result = avm.run(new TransactionContext[] {context})[0].get();
assertEquals(TransactionResult.Code.SUCCESS, result.getStatusCode());
byte[] expected = ABIEncoder.encodeMethodArguments("addArray", new int[]{123, 1}, 5);
boolean correct = Arrays.equals((byte[])(TestingHelper.decodeResult(result)), expected);
assertEquals(true, correct);
// test another method call, "addArray" with 1D array arguments
tx = Transaction.call(from, deployResult.getReturnData(), kernel.getNonce(from), BigInteger.ZERO, expected, energyLimit, energyPrice);
context = new TransactionContextImpl(tx, block);
result = avm.run(new TransactionContext[] {context})[0].get();
assertEquals(TransactionResult.Code.SUCCESS, result.getStatusCode());
assertEquals(129, TestingHelper.decodeResult(result));
// test another method call, "addArray2" with 2D array arguments
int[][] a = new int[2][];
a[0] = new int[]{123, 4};
a[1] = new int[]{1, 2};
txData = ABIEncoder.encodeMethodArguments("addArray2", TestingHelper.construct2DWrappedArray(a));
tx = Transaction.call(from, deployResult.getReturnData(), kernel.getNonce(from), BigInteger.ZERO, txData, energyLimit, energyPrice);
context = new TransactionContextImpl(tx, block);
result = avm.run(new TransactionContext[] {context})[0].get();
assertEquals(TransactionResult.Code.SUCCESS, result.getStatusCode());
assertEquals(124, TestingHelper.decodeResult(result));
// test another method call, "concatenate" with 2D array arguments and 1D array return data
char[][] chars = new char[2][];
chars[0] = "cat".toCharArray();
chars[1] = "dog".toCharArray();
txData = ABIEncoder.encodeMethodArguments("concatenate", TestingHelper.construct2DWrappedArray(chars));
tx = Transaction.call(from, deployResult.getReturnData(), kernel.getNonce(from), BigInteger.ZERO, txData, energyLimit, energyPrice);
context = new TransactionContextImpl(tx, block);
result = avm.run(new TransactionContext[] {context})[0].get();
assertEquals(TransactionResult.Code.SUCCESS, result.getStatusCode());
assertEquals("catdog", new String((char[]) TestingHelper.decodeResult(result)));
// test another method call, "concatString" with String array arguments and String return data
txData = ABIEncoder.encodeMethodArguments("concatString", "cat", "dog"); // Note - need to cast String[] into Object, to pass it as one argument to the varargs method
tx = Transaction.call(from, deployResult.getReturnData(), kernel.getNonce(from), BigInteger.ZERO, txData, energyLimit, energyPrice);
context = new TransactionContextImpl(tx, block);
result = avm.run(new TransactionContext[] {context})[0].get();
assertEquals(TransactionResult.Code.SUCCESS, result.getStatusCode());
assertEquals("catdog", TestingHelper.decodeResult(result));
// test another method call, "concatStringArray" with String array arguments and String return data
txData = ABIEncoder.encodeMethodArguments("concatStringArray", TestingHelper.construct1DWrappedStringArray((new String[]{"cat", "dog"}))); // Note - need to cast String[] into Object, to pass it as one argument to the varargs method
tx = Transaction.call(from, deployResult.getReturnData(), kernel.getNonce(from), BigInteger.ZERO, txData, energyLimit, energyPrice);
context = new TransactionContextImpl(tx, block);
result = avm.run(new TransactionContext[] {context})[0].get();
assertEquals(TransactionResult.Code.SUCCESS, result.getStatusCode());
assertEquals("catdog", ((String[])TestingHelper.decodeResult(result))[0]);
assertEquals("perfect", ((String[])TestingHelper.decodeResult(result))[1]);
// test another method call, "swap" with 2D array arguments and 2D array return data
txData = ABIEncoder.encodeMethodArguments("swap", TestingHelper.construct2DWrappedArray(chars));
tx = Transaction.call(from, deployResult.getReturnData(), kernel.getNonce(from), BigInteger.ZERO, txData, energyLimit, energyPrice);
context = new TransactionContextImpl(tx, block);
result = avm.run(new TransactionContext[] {context})[0].get();
assertEquals(TransactionResult.Code.SUCCESS, result.getStatusCode());
assertEquals("dog", new String(((char[][]) TestingHelper.decodeResult(result))[0]));
assertEquals("cat", new String(((char[][]) TestingHelper.decodeResult(result))[1]));
// test a method call to "setBar", which does not have a return type (void)
txData = ABIEncoder.encodeMethodArguments("setBar", 20);
tx = Transaction.call(from, deployResult.getReturnData(), kernel.getNonce(from), BigInteger.ZERO, txData, energyLimit, energyPrice);
context = new TransactionContextImpl(tx, block);
result = avm.run(new TransactionContext[] {context})[0].get();
assertEquals(TransactionResult.Code.SUCCESS, result.getStatusCode());
}
@Test
public void testBalanceTransfer() {
assertEquals(KernelInterfaceImpl.PREMINED_AMOUNT, kernel.getBalance(from));
// account1 get 10000
byte[] account1 = Helpers.randomBytes(Address.LENGTH);
Transaction tx = Transaction.balanceTransfer(from, account1, kernel.getNonce(from), BigInteger.valueOf(100000L), energyPrice);
TransactionContextImpl context = new TransactionContextImpl(tx, block);
TransactionResult result = avm.run(new TransactionContext[] {context})[0].get();
assertEquals(TransactionResult.Code.SUCCESS, result.getStatusCode());
assertEquals(BigInteger.valueOf(100000L), kernel.getBalance(account1));
// account1 transfers 1000 to account2
byte[] account2 = Helpers.randomBytes(Address.LENGTH);
tx = Transaction.balanceTransfer(account1, account2, kernel.getNonce(account1), BigInteger.valueOf(1000L), energyPrice);
context = new TransactionContextImpl(tx, block);
result = avm.run(new TransactionContext[] {context})[0].get();
assertEquals(TransactionResult.Code.SUCCESS, result.getStatusCode());
assertEquals(BigInteger.valueOf(100000L - 1000L - energyPrice * 21000L), kernel.getBalance(account1));
assertEquals(BigInteger.valueOf(1000L), kernel.getBalance(account2));
}
@Test
public void testCreateAndCallWithBalanceTransfer() {
// deploy the Dapp with 100000 value transfer; create with balance transfer
byte[] jar = Helpers.readFileToBytes("../examples/build/com.example.deployAndRunTest.jar");
byte[] txData = new CodeAndArguments(jar, null).encodeToBytes();
Transaction tx = Transaction.create(from, kernel.getNonce(from), BigInteger.valueOf(100000L), txData, energyLimit, energyPrice);
TransactionContextImpl context = new TransactionContextImpl(tx, block);
TransactionResult deployResult = avm.run(new TransactionContext[] {context})[0].get();
assertEquals(TransactionResult.Code.SUCCESS, deployResult.getStatusCode());
assertEquals(BigInteger.valueOf(100000L), kernel.getBalance(deployResult.getReturnData()));
// account1 get 300000; pure balance transfer
byte[] account1 = Helpers.randomBytes(Address.LENGTH);
tx = Transaction.balanceTransfer(from, account1, kernel.getNonce(from), BigInteger.valueOf(300000L), energyPrice);
context = new TransactionContextImpl(tx, block);
TransactionResult result = avm.run(new TransactionContext[] {context})[0].get();
assertEquals(TransactionResult.Code.SUCCESS, result.getStatusCode());
assertEquals(BigInteger.valueOf(300000L), kernel.getBalance(account1));
// account1 to call the Dapp and transfer 50000 to it; call with balance transfer
txData = ABIEncoder.encodeMethodArguments("encodeArgs");
tx = Transaction.call(account1, deployResult.getReturnData(), kernel.getNonce(account1), BigInteger.valueOf(50000L), txData, 200000L, energyPrice);
context = new TransactionContextImpl(tx, block);
result = avm.run(new TransactionContext[] {context})[0].get();
assertEquals(TransactionResult.Code.SUCCESS, result.getStatusCode());
assertEquals(BigInteger.valueOf(150000L), kernel.getBalance(deployResult.getReturnData()));
assertEquals(BigInteger.valueOf(300000L - 50000L - result.getEnergyUsed()), kernel.getBalance(account1));
}
}
|
package com.ana.utils;
/**
* This file contains all type of used <b>view widgets, api elements and chat sections</b>.
* ex-{api methods- <b>GET,POST</b>}
* @Author ANA
* @version 1.0
* @since 29-06-2017
*/
public class Constants {
public static final String MAP_KEY = "AIzaSyBl66AnJ4_icH3gxI_ATc8031pveSTGWcg";
public interface SectionType{
String TYPE_TEXT = "Text";
String TYPE_TYPING = "Typing";
String TYPE_IMAGE = "Image";
String TYPE_AUDIO = "Audio";
String TYPE_VIDEO = "Video";
String TYPE_HEADER = "Header";
String TYPE_CARD = "Card";
String TYPE_ADDRESS_CARD = "AddressCard";
String TYPE_UNCONFIRMED_CARD = "UnConfirmedCard";
String TYPE_UNCONFIRMED_ADDR_CARD = "UnConfirmedAddressCard";
String TYPE_PRINT_OTP = "PrintOTP";
}
public interface ApiType{
String TYPE_GET = "GET";
String TYPE_POST = "POST";
}
public interface NodeType{
String TYPE_API_CALL = "ApiCall";
String TYPE_CARD = "Card";
String TYPE_COMBINATION = "Combination";
}
public interface ButtonType{
String TYPE_GET_TEXT = "GetText";
String TYPE_GET_NUMBER = "GetNumber";
String TYPE_NEXT_NODE = "NextNode";
String TYPE_GET_ADDR = "GetAddress";
String TYPE_GET_IMAGE = "GetImage";
String TYPE_DEEP_LINK = "DeepLink";
String TYPE_GET_ITEM_FROM_SOURCE = "GetItemFromSource";
String TYPE_GET_EMAIL = "GetEmail";
String TYPE_GET_PHONE_NUMBER = "GetPhoneNumber";
String TYPE_GET_AUDIO = "GetAudio";
String TYPE_GET_VIDEO = "GetVideo";
}
public interface DeepLinkUrl{
String ASK_LOC_PERM = "asklocationpermission";
String LOGIN = "login";
}
public interface LocationConstants {
int SUCCESS_RESULT = 0;
int FAILURE_RESULT = 1;
String PACKAGE_NAME = "com.ana";
String RECEIVER = PACKAGE_NAME + ".RECEIVER";
String RESULT_DATA_KEY = PACKAGE_NAME + ".RESULT_DATA_KEY";
String LOCATION_DATA_EXTRA = PACKAGE_NAME + ".LOCATION_DATA_EXTRA";
String LOCATION_DATA_AREA = PACKAGE_NAME + ".LOCATION_DATA_AREA";
String LOCATION_DATA_CITY = PACKAGE_NAME + ".LOCATION_DATA_CITY";
String LOCATION_DATA_STREET = PACKAGE_NAME + ".LOCATION_DATA_STREET";
String LOCATION_DATA_COUNTRY = PACKAGE_NAME + ".LOCATION_DATA_COUNTRY";
String LOCATION_DATA_PIN = PACKAGE_NAME + ".LOCATION_DATA_PIN";
String LOCATION_DATA_LOCALITY = PACKAGE_NAME + ".LOCATION_DATA_LOCALITY";
String LOCATION_DATA_HOUSE_NUMBER = PACKAGE_NAME + ".LOCATION_DATA_HOUSE_NUMBER";
String LOCATION_DATA_LANDMARK = PACKAGE_NAME + ".LOCATION_DATA_LANDMARK";
}
public interface ConfirmationType{
String BIZ_NAME = "biz_name";
String ADDRESS_ENTRY = "address_entry";
}
}
|
package com.dorothy.railway999.api.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.dorothy.railway999.annotation.Auth;
import com.dorothy.railway999.service.MyTravelTimeService;
import com.dorothy.railway999.vo.MyTravelTimeVo;
@Controller
@RequestMapping("/api/travel")
public class MyTravelTimeController {
@Autowired
MyTravelTimeService myTravelTimeService;
@Auth(role ="")
@ResponseBody
@RequestMapping("/list")
public Map<String,Object> travelList(@RequestParam(value="no", required = true, defaultValue = "") long no){
List<MyTravelTimeVo> list = myTravelTimeService.travelList(no);
Map<String,Object> map=new HashMap<String, Object>();
map.put("jsonTxt", list);
return map;
}
@Auth(role ="")
@ResponseBody
@RequestMapping("/add")
public Map<String, Object> travelAdd(@ModelAttribute MyTravelTimeVo vo){
myTravelTimeService.insert(vo);
Map<String,Object> map=new HashMap<String, Object>();
map.put("result", "success");
map.put("data", vo);
return map;
}
@Auth(role ="")
@ResponseBody
@RequestMapping(value="/remove", method=RequestMethod.POST)
public Map<String, Object> travelRemove(
@RequestParam(value = "travelNo", required = true, defaultValue = "") long travelNo){
long result = myTravelTimeService.delete(travelNo);
Map<String, Object> map=new HashMap<String, Object>();
map.put("result", "success");
map.put("data", result);
return map;
}
@Auth(role ="")
@ResponseBody
@RequestMapping("/modify")
public Map<String, Object> travelModify(@ModelAttribute MyTravelTimeVo vo){
long result=myTravelTimeService.modify(vo);
Map<String, Object> map=new HashMap<String, Object>();
map.put("result", "success");
map.put("data", result);
return map;
}
@Auth(role ="")
@ResponseBody
@RequestMapping("/get")
public Map<String, Object> travelGet(@RequestParam(value="no",required=true,defaultValue="")long no){
MyTravelTimeVo myTravelTimeVo =myTravelTimeService.get(no);
Map<String, Object> map=new HashMap<String, Object>();
map.put("result", "success");
map.put("get", myTravelTimeVo);
return map;
}
}
|
import java.util.*;
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
Map<Integer, Integer>
nodeLevelMap = new HashMap();
public List<List<Integer>> verticalTraversal(TreeNode root) {
TreeMap<Integer, PriorityQueue<Integer>> map = new TreeMap();
List<List<Integer>>
verticalNodesList = new ArrayList();
populateMap(root, map, 0, 0);
for(Integer entry: map.keySet()) {
PriorityQueue<Integer>
temp = map.get(entry);
List<Integer>
t = new ArrayList();
while(temp.size() != 0)
{
t.add(temp.poll());
}
verticalNodesList.add(t);
}
return verticalNodesList;
}
void populateMap(TreeNode node, TreeMap<Integer, PriorityQueue<Integer>> map, int level, int cur)
{
if(node == null)
return;
nodeLevelMap.put(node.val, level);
if(map.containsKey(cur))
{
map.get(cur).offer(node.val);
}
else
{
PriorityQueue<Integer> pq = new PriorityQueue
((n1,n2) -> (nodeLevelMap.get(n1) == nodeLevelMap.get(n2) ? (int)n1-(int)n2 :
nodeLevelMap.get(n1) - nodeLevelMap.get(n2)));
pq.offer(node.val);
map.put(cur, pq);
}
populateMap(node.left, map, level + 1, cur - 1);
populateMap(node.right, map, level + 1, cur + 1);
}
}
|
module demo {
exports com.example.demo.dao;
exports com.example.demo;
exports com.example.demo.service;
requires spring.beans;
requires spring.boot;
requires spring.boot.autoconfigure;
requires spring.context;
requires spring.core;
}
|
package linnbank.pages;
import linnbank.utilities.Driver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class LoginPage extends CommonWebElements{
@FindBy(id = "account-menu")
public WebElement loginDropdown;
@FindBy(xpath = "//*[text()='Sign in']")
public WebElement signInButton;
@FindBy(id = "username")
public WebElement username;
@FindBy( id = "password")
public WebElement password;
@FindBy(xpath = "//*[@class='btn btn-primary']")
public WebElement loginButton;
@FindBy(xpath="//a/span[text()='Sign out']")
public WebElement signOutLink;
@FindBy(xpath="//button/span[text()='Cancel']")
public WebElement cancelBtn;
public boolean validateSignOutLink(){
Driver.waitForClickablility(profileIcon,3).click();
return Driver.waitForVisibility(signOutLink,3).isDisplayed();
}
public void clickCancelBtn(){
Driver.waitForClickablility(cancelBtn,3).click();
}
public boolean validateCancelBtnVisibility(){
Driver.waitForClickablility(profileIcon,3).click();
return Driver.waitForClickablility(signInLink,5).isDisplayed();
}
}
|
package com.zen.spark.etl.conf.bill;
/**
* Created by Tom
* Date 2017-03-27
* 活动信息
*/
public class BI208001 {
/*activeid -1是活动中心,其他值代表具体活动
imei 设备号
imsi 手机卡唯一标识
type -1无意义 -2表示查看活动 1表示参加活动 2表示活动行为一 3表示活动行为二 4表示活动行为三(PS:2和3是不同的行为统计,请把它们分别做在oss上)
活动框架:10发道具
gifttype 0是默认值没有具体意义 1是游戏币 2是兑换卷 3是道具 (活动发放游戏豆、兑换券或者道具)
giftsubtype 当gifttype等于3是道具的时候,则giftsubtype是道具ID 10015是1天vip卡 10017是5天vip卡 198是7天vip卡 7是流量卡
giftnum 发放数量 这个字段与gifttype相对应(当gifttype等于1 giftnum是游戏豆发放数量,当gifttype等于2 giftnum是兑换券发放数量,当gifttype等于3 giftnum是道具发放数量)
backGifttype 0是默认值没有具体意义 1是游戏币 2是兑换卷(活动回收游戏豆、兑换券)
backGiftnum 回收数量 这个字段与backGifttype相对应(当backGifttype等于1 backGiftnum是游戏豆回收数量,当backGifttype等于2 backGiftnum是兑换券回收数量)
money 默认是0表示没有充值 大于0的数值则表示用户充值的具体金额
extra 不同活动的额外信息,活动的具体额外信息会以#号*/
public static int billId = 0;
public static int ts = 1;
public static int gameId = 2;
public static int userId = 3;
public static int activeid = 4;
public static int channelId = 5;
public static int version = 6;
public static int sdkVersion = 7;
public static int apkVersion = 8;
public static int imei = 9;// -1是活动中心,其他值代表具体活动
public static int imsi=10 ;
public static int type = 11;
public static int gifttype = 12;
public static int giftsubtype = 13;
public static int giftnum = 14;
public static int backGifttype = 15;
public static int backGiftnum = 16;
public static int money = 17;
public static int extra = 18;
}
|
package com.ncda.entity.ext;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.springframework.format.annotation.DateTimeFormat;
import java.math.BigDecimal;
import java.util.Date;
/**
* Chart 图数据
*/
public class ChartEntiey {
private Integer id;
private String itemName;
@JsonFormat(pattern="yyyy-MM-dd", timezone = "GMT+8")
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date date;
private BigDecimal money;
private String typeOneName;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public BigDecimal getMoney() {
return money;
}
public void setMoney(BigDecimal money) {
this.money = money;
}
public String getTypeOneName() {
return typeOneName;
}
public void setTypeOneName(String typeOneName) {
this.typeOneName = typeOneName;
}
}
|
package com.mundo.data.support;
import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.exception.MemcachedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.TimeoutException;
/**
* MemcacheClientUtil
*
* @author maodh
* @since 2018/7/22
*/
public class MemcacheClientUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(MemcacheClientUtil.class);
private MemcachedClient memcachedClient;
public MemcacheClientUtil(MemcachedClient memcachedClient) {
this.memcachedClient = memcachedClient;
}
public <T> T get(final String key) {
try {
return memcachedClient.get(key);
} catch (TimeoutException | InterruptedException | MemcachedException e) {
LOGGER.error("MemcacheClient get key(" + key + ") error!", e);
return null;
}
}
public boolean add(final String key, final Object value, final int exp) {
try {
return memcachedClient.add(key, exp, value);
} catch (TimeoutException | InterruptedException | MemcachedException e) {
LOGGER.error("MemcacheClient add key(" + key + ") error!", e);
return false;
}
}
public boolean replace(final String key, final Object value, final int exp) {
try {
return memcachedClient.replace(key, exp, value);
} catch (TimeoutException | InterruptedException | MemcachedException e) {
LOGGER.error("MemcacheClient replace key(" + key + ") error!", e);
return false;
}
}
public boolean set(final String key, final Object value, final int exp) {
try {
return memcachedClient.set(key, exp, value);
} catch (TimeoutException | InterruptedException | MemcachedException e) {
LOGGER.error("MemcacheClient set key(" + key + ") error!", e);
return false;
}
}
public boolean delete(final String key) {
try {
return memcachedClient.delete(key);
} catch (TimeoutException | InterruptedException | MemcachedException e) {
LOGGER.error("MemcacheClient delete key(" + key + ") error!", e);
return false;
}
}
}
|
package com.onesignal.influence;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.onesignal.OSSharedPreferences;
import com.onesignal.OneSignalRemoteParams;
import com.onesignal.influence.model.OSInfluenceType;
import org.json.JSONArray;
import org.json.JSONException;
/**
* Setter and Getter of Notifications received
*/
class OSInfluenceDataRepository {
// OUTCOMES KEYS
// Outcomes Influence Ids
protected static final String PREFS_OS_LAST_ATTRIBUTED_NOTIFICATION_OPEN = "PREFS_OS_LAST_ATTRIBUTED_NOTIFICATION_OPEN";
protected static final String PREFS_OS_LAST_NOTIFICATIONS_RECEIVED = "PREFS_OS_LAST_NOTIFICATIONS_RECEIVED";
protected static final String PREFS_OS_LAST_IAMS_RECEIVED = "PREFS_OS_LAST_IAMS_RECEIVED";
// Outcomes Influence params
protected static final String PREFS_OS_NOTIFICATION_LIMIT = "PREFS_OS_NOTIFICATION_LIMIT";
protected static final String PREFS_OS_IAM_LIMIT = "PREFS_OS_IAM_LIMIT";
protected static final String PREFS_OS_NOTIFICATION_INDIRECT_ATTRIBUTION_WINDOW = "PREFS_OS_INDIRECT_ATTRIBUTION_WINDOW";
protected static final String PREFS_OS_IAM_INDIRECT_ATTRIBUTION_WINDOW = "PREFS_OS_IAM_INDIRECT_ATTRIBUTION_WINDOW";
// Outcomes Influence enable params
protected static final String PREFS_OS_DIRECT_ENABLED = "PREFS_OS_DIRECT_ENABLED";
protected static final String PREFS_OS_INDIRECT_ENABLED = "PREFS_OS_INDIRECT_ENABLED";
protected static final String PREFS_OS_UNATTRIBUTED_ENABLED = "PREFS_OS_UNATTRIBUTED_ENABLED";
// Outcomes Channel Influence types
protected static final String PREFS_OS_OUTCOMES_CURRENT_NOTIFICATION_INFLUENCE = "PREFS_OS_OUTCOMES_CURRENT_SESSION";
protected static final String PREFS_OS_OUTCOMES_CURRENT_IAM_INFLUENCE = "PREFS_OS_OUTCOMES_CURRENT_IAM_INFLUENCE";
private OSSharedPreferences preferences;
public OSInfluenceDataRepository(OSSharedPreferences preferences) {
this.preferences = preferences;
}
/**
* Cache a influence type enum for Notification as a string
*/
void cacheNotificationInfluenceType(@NonNull OSInfluenceType influenceType) {
preferences.saveString(
preferences.getPreferencesName(),
PREFS_OS_OUTCOMES_CURRENT_NOTIFICATION_INFLUENCE,
influenceType.toString()
);
}
/**
* Get the current cached influence type string, convert it to the influence type enum, and return it
*/
@NonNull
OSInfluenceType getNotificationCachedInfluenceType() {
String influenceType = preferences.getString(
preferences.getPreferencesName(),
PREFS_OS_OUTCOMES_CURRENT_NOTIFICATION_INFLUENCE,
OSInfluenceType.UNATTRIBUTED.toString()
);
return OSInfluenceType.fromString(influenceType);
}
/**
* Cache a influence type enum for IAM as a string
*/
void cacheIAMInfluenceType(@NonNull OSInfluenceType influenceType) {
preferences.saveString(
preferences.getPreferencesName(),
PREFS_OS_OUTCOMES_CURRENT_IAM_INFLUENCE,
influenceType.toString()
);
}
/**
* Get the current cached influence type string, convert it to the influence type enum, and return it
*/
@NonNull
OSInfluenceType getIAMCachedInfluenceType() {
String influenceType = preferences.getString(
preferences.getPreferencesName(),
PREFS_OS_OUTCOMES_CURRENT_IAM_INFLUENCE,
OSInfluenceType.UNATTRIBUTED.toString()
);
return OSInfluenceType.fromString(influenceType);
}
/**
* Cache attributed notification opened
*/
void cacheNotificationOpenId(@Nullable String id) {
preferences.saveString(
preferences.getPreferencesName(),
PREFS_OS_LAST_ATTRIBUTED_NOTIFICATION_OPEN,
id
);
}
/**
* Get the current cached notification id, null if not direct
*/
@Nullable
String getCachedNotificationOpenId() {
return preferences.getString(
preferences.getPreferencesName(),
PREFS_OS_LAST_ATTRIBUTED_NOTIFICATION_OPEN,
null
);
}
void saveNotifications(@NonNull JSONArray notifications) {
preferences.saveString(
preferences.getPreferencesName(),
PREFS_OS_LAST_NOTIFICATIONS_RECEIVED,
notifications.toString());
}
void saveIAMs(@NonNull JSONArray iams) {
preferences.saveString(
preferences.getPreferencesName(),
PREFS_OS_LAST_IAMS_RECEIVED,
iams.toString());
}
JSONArray getLastNotificationsReceivedData() throws JSONException {
String notificationsReceived = preferences.getString(
preferences.getPreferencesName(),
PREFS_OS_LAST_NOTIFICATIONS_RECEIVED,
"[]");
return notificationsReceived != null ? new JSONArray(notificationsReceived) : new JSONArray();
}
JSONArray getLastIAMsReceivedData() throws JSONException {
String iamReceived = preferences.getString(
preferences.getPreferencesName(),
PREFS_OS_LAST_IAMS_RECEIVED,
"[]");
return iamReceived != null ? new JSONArray(iamReceived) : new JSONArray();
}
int getNotificationLimit() {
return preferences.getInt(
preferences.getPreferencesName(),
PREFS_OS_NOTIFICATION_LIMIT,
OneSignalRemoteParams.DEFAULT_NOTIFICATION_LIMIT
);
}
int getIAMLimit() {
return preferences.getInt(
preferences.getPreferencesName(),
PREFS_OS_IAM_LIMIT,
OneSignalRemoteParams.DEFAULT_NOTIFICATION_LIMIT
);
}
int getNotificationIndirectAttributionWindow() {
return preferences.getInt(
preferences.getPreferencesName(),
PREFS_OS_NOTIFICATION_INDIRECT_ATTRIBUTION_WINDOW,
OneSignalRemoteParams.DEFAULT_INDIRECT_ATTRIBUTION_WINDOW
);
}
int getIAMIndirectAttributionWindow() {
return preferences.getInt(
preferences.getPreferencesName(),
PREFS_OS_IAM_INDIRECT_ATTRIBUTION_WINDOW,
OneSignalRemoteParams.DEFAULT_INDIRECT_ATTRIBUTION_WINDOW
);
}
boolean isDirectInfluenceEnabled() {
return preferences.getBool(
preferences.getPreferencesName(),
PREFS_OS_DIRECT_ENABLED,
false
);
}
boolean isIndirectInfluenceEnabled() {
return preferences.getBool(
preferences.getPreferencesName(),
PREFS_OS_INDIRECT_ENABLED,
false
);
}
boolean isUnattributedInfluenceEnabled() {
return preferences.getBool(
preferences.getPreferencesName(),
PREFS_OS_UNATTRIBUTED_ENABLED,
false
);
}
void saveInfluenceParams(OneSignalRemoteParams.InfluenceParams influenceParams) {
preferences.saveBool(
preferences.getPreferencesName(),
PREFS_OS_DIRECT_ENABLED,
influenceParams.isDirectEnabled()
);
preferences.saveBool(
preferences.getPreferencesName(),
PREFS_OS_INDIRECT_ENABLED,
influenceParams.isIndirectEnabled()
);
preferences.saveBool(
preferences.getPreferencesName(),
PREFS_OS_UNATTRIBUTED_ENABLED,
influenceParams.isUnattributedEnabled()
);
preferences.saveInt(
preferences.getPreferencesName(),
PREFS_OS_NOTIFICATION_LIMIT,
influenceParams.getNotificationLimit()
);
preferences.saveInt(
preferences.getPreferencesName(),
PREFS_OS_NOTIFICATION_INDIRECT_ATTRIBUTION_WINDOW,
influenceParams.getIndirectNotificationAttributionWindow()
);
preferences.saveInt(
preferences.getPreferencesName(),
PREFS_OS_IAM_LIMIT,
influenceParams.getIamLimit()
);
preferences.saveInt(
preferences.getPreferencesName(),
PREFS_OS_IAM_INDIRECT_ATTRIBUTION_WINDOW,
influenceParams.getIndirectIAMAttributionWindow()
);
}
}
|
package com.tavisca.workshops.pratham.rover;
public class MarsRover {
private Vector vector;
public MarsRover(Vector initialVector)
{
vector = initialVector;
}
public void rove(char command) {
switch (command) {
case 'M':
vector = vector.OneMove();
break;
case 'R':
vector = vector.right();
break;
case 'L':
vector = vector.left();
break;
}
// return vector;
}
public Vector vector(){
return vector;
}
}
|
package com.maia.bank.controllers;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class ApiOn {
@GetMapping("/on")
public String testApi() {
return "Api On!";
}
}
|
/**
* This package provides some classes for dealing with
* {@link de.zarncke.lib.value.Type types}
* {@link de.zarncke.lib.value.Ref references} and
* {@link de.zarncke.lib.value.Default default values}.
*/
package de.zarncke.lib.util;
|
package com.mounika.task;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import java.util.ArrayList;
/**
* Created by Mounika on 6/9/2017.
*/
import android.content.Context;
import android.graphics.Color;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by Mounika on 6/9/2017.
*/
public class MilestoneAdapter extends RecyclerView.Adapter<MilestoneAdapter.ViewHolder>{
public ArrayList<String> Content=new ArrayList<>();
Context context1;
public MilestoneAdapter(Context context2, ArrayList<String> content)
{
this.Content = content;
context1 = context2;
}
public class ViewHolder extends RecyclerView.ViewHolder
{
public TextView contentTv;
public View view;
public ViewHolder(View v)
{
super(v);
contentTv = (TextView) v.findViewById(R.id.milecard);
}
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
View view1 = LayoutInflater.from(context1).inflate(R.layout.milestone_adapter,parent,false);
ViewHolder viewHolder1 = new ViewHolder(view1);
return viewHolder1;
}
@Override
public void onBindViewHolder(final ViewHolder Vholder, final int position) {
Vholder.contentTv.setText(Content.get(position));
}
@Override
public int getItemCount() {
return Content.size();
}
}
|
package com.shakeboy.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.shakeboy.pojo.User;
import org.springframework.stereotype.Repository;
// 在对应的mapper上继承基本的类BaseMapper
@Repository //代表持久层
public interface UserMapper extends BaseMapper<User> {
// 所有的CURD已经完成 JPA,tk-mapper
// 不需要再配置以前的xml文件
}
|
package br.com.beblue.lojadisco.http.corporesposta;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.util.List;
/**
* Classe que mapeia o corpo da resposta do endpoint de busca de cliente
* da API do Spotify
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class Artistas {
List<ItemArtista> items;
public List<ItemArtista> getItems() {
return items;
}
public void setItems(List<ItemArtista> items) {
this.items = items;
}
}
|
package com.example.InventoryManagementSystem.Controller;
import com.example.InventoryManagementSystem.*;
import javafx.application.Platform;
import javafx.concurrent.Task;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
public class LoginController {
@FXML
private TextField username;
@FXML
private PasswordField password;
@FXML
private Label promptMsg;
@FXML
private AnchorPane root;
private void switchToMainStage() throws IOException {
Stage stage = StageManager.switchToStage(StageInfo.MAIN_STAGE);
Stage thisStage = (Stage) root.getScene().getWindow();
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
Platform.runLater(() -> {
stage.show();
stage.setOnCloseRequest(evt -> Platform.exit());
thisStage.hide();
});
timer.cancel();
}
}, 500);
}
@FXML
protected void login() throws IOException {
Task<Void> login = new Task<Void>() {
boolean check;
@Override
protected Void call() throws Exception {
check = LoginVerifier.verify(username.getText(), password.getText());
promptMsg.getStyleClass().removeAll("lbl", "lbl-danger", "lbl-success");
return null;
}
@Override
protected void succeeded() {
if (check) {
promptMsg.getStyleClass().addAll("lbl", "lbl-success");
promptMsg.setText(" - Login successful! - ");
Session.setUsername(username.getText());
try {
switchToMainStage();
}
catch (IOException e) {
System.err.println("No way");
}
}
else {
promptMsg.getStyleClass().addAll("lbl", "lbl-danger");
promptMsg.setText(" - Login failed! - ");
}
}
};
new Thread(login).start();
}
@FXML
protected void kbdLogin(KeyEvent event) throws IOException{
if (event.getCode() == KeyCode.ENTER) {
login();
}
}
}
|
package be.thomaswinters.goofer;
import org.junit.Test;
import be.thomaswinters.goofer.data.Template;
import be.thomaswinters.goofer.data.TemplateValues;
import static org.junit.Assert.assertEquals;
public class TemplateTest {
@Test
public void apply_test() {
Template template = new Template("Hello ", ", I'm ", ".");
assertEquals("Hello John, I'm Thomas.", template.apply(new TemplateValues("John", "Thomas")));
}
}
|
package day08ShortHandOperators;
public class relationalOperators {
public static void main(String[] args) {
/*Relational Operators; return boolean expression
* >; greater than
* >=: greater then or equal
* < ; less than
* <= : less than or equal
* == : equal
* != : not equal
*
* = : assign
* !: exclamation mark means logical opposite, not
*
*/
System.out.println(10>9);//
boolean resultA= 10>9;
System.out.println(resultA);
System.out.println(10>=9);// greater or equal
boolean resultB= 10>=9;
System.out.println(resultB);
boolean resultC = 10<=9;
System.out.println(resultC);//false
boolean resultD = 1100<1200;//less than
System.out.println(resultD);//true
boolean resultE= 1000<1000;
System.out.println(resultE);//false
boolean resultF= 1000<=1000;
System.out.println(resultF);//true
//== equal
boolean resultG= 19==19;
System.out.println(resultG);//true
//!= represent not equal
boolean resultH= 20 !=20;
System.out.println(resultH);//false
boolean A = true== !false;
System.out.println(A);//true
boolean B =!false;
System.out.println(B);//true
/*
in java true ==true, false==false
!false = true
!true=false
so therefore: !false != !true;
true = !false
*/
boolean S= !false != !true;
System.out.println("S is " +S);//true
boolean X = true == !false;
System.out.println(X);
boolean V = !(!false);//true
System.out.println(V);
System.out.println("===========");
boolean F = 10>9==9<10;
System.out.println(F);//!false=true
//practice !(not)
boolean g = false;
System.out.println(!g);//true because of the !
System.out.println(!true==false);//true
boolean h = "Batch 12"== "Batch13";//false
System.out.println(h);
System.out.println("batch12"=="Batch12");//false java is case sensitive
System.out.println("cybertek " != "club");//true
System.out.println("kuzzat"=="bad guy");//false
System.out.println("Asiistant teachers in class" == "awesome");//false
}
}
|
package com.jadn.cc.ui;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import com.jadn.cc.R;
import com.jadn.cc.core.CarCastApplication;
public class FeedbackHelp extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.feedback_help);
}
@Override
protected void onDestroy() {
super.onDestroy();
}
public void quickTour(View view) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse("http://jadn.com/cc/walk/"));
startActivity(i);
}
public void qanda(View view) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse("http://jadn.com/cc/QandA/"));
startActivity(i);
}
public void email(View view) {
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setType("plain/text");
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] { "carcast-devs@googlegroups.com" });
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, CarCastApplication.getAppTitle()+": feedback "+CarCastApplication.getVersion());
startActivity(Intent.createChooser(emailIntent, "Email about podcast"));
}
public void ccwebsite(View view) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse("http://jadn.com/cc/"));
startActivity(i);
}
}
|
package com.yeahbunny.stranger.server.services.impl;
import java.util.List;
import java.util.stream.Collectors;
import javax.inject.Inject;
import javax.persistence.EntityNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.yeahbunny.stranger.server.controller.dto.response.StrangersEvent;
import com.yeahbunny.stranger.server.controller.dto.response.StrangersPlainEvent;
import com.yeahbunny.stranger.server.controller.dto.response.UserEventRelation;
import com.yeahbunny.stranger.server.model.Event;
import com.yeahbunny.stranger.server.model.User;
import com.yeahbunny.stranger.server.repositories.EventRepository;
import com.yeahbunny.stranger.server.repositories.UserRepository;
import com.yeahbunny.stranger.server.services.EventMessageService;
import com.yeahbunny.stranger.server.services.EventService;
@Service
@Transactional
public class EventServiceImpl implements EventService {
@Inject
EventRepository eventRepo;
@Inject
UserRepository userRepo;
@Inject
EventMessageService eventMessageService;
@Override
public List<Event> findAllEventsLazy() {
return eventRepo.findAll();
}
@Override
public List<Event> findAllEventsEagerly() {
List<Event> events = eventRepo.findAll();
// Eager fetching children entities
for (Event event : events) {
event.getEventAttenders().size();
event.getEventMessages().size();
}
return events;
}
@Override
public Event findEventById(long id) {
return eventRepo.findOne(id);
}
@Override
public Event findEventByIdEagerly(long id) {
Event event = eventRepo.findOne(id);
if (event != null) {
event.getEventAttenders().size();
event.getEventMessages().size();
}
return event;
}
@Override
public List<Event> findEventsCreatedByUser(String username) {
User creator = userRepo.findByUsername(username);
return creator.getEvents();
}
@Override
public List<Event> findEventsAttendedByUser(String username) {
User creator = userRepo.findByUsername(username);
List<Event> events = creator.getEventAttenders()
.stream()
.map(eventAttender -> {
return eventAttender.getEvent();
})
.collect(Collectors.toList());
return events;
}
@Override
public Long save(Event event) {
Event saved = eventRepo.save(event);
return saved.getIdEvent();
}
@Override
public StrangersEvent findUserStrangerEventAndRefreshTimestamp(long id, String username)
throws EntityNotFoundException {
Event event = null;
User user = null;
if((event = findEventByIdEagerly(id)) == null || (user = userRepo.findByUsername(username)) == null)
throw new EntityNotFoundException();
UserEventRelation usEvRelation = getUserEventRelation(user, event);
eventMessageService.refreshUnreadCommentsTimestamp(user, event, usEvRelation);
return new StrangersEvent(event, usEvRelation);
}
@Override
public List<StrangersPlainEvent> findAllActiveEvents() {
List<StrangersPlainEvent> activeEvents;
activeEvents = eventRepo.findAllActive().stream().map(ev -> new StrangersPlainEvent(ev)).collect(Collectors.toList());
return activeEvents;
}
private UserEventRelation getUserEventRelation(User user, Event event) {
UserEventRelation usEvRelation;
if (user.getIdUser().equals(event.getCreator().getIdUser()))
usEvRelation = UserEventRelation.OWNER;
else if(user.getEventAttenders().stream().anyMatch(evAt -> evAt.getEvent().equals(event)))
usEvRelation = UserEventRelation.ATTENDER;
else
usEvRelation = UserEventRelation.STRANGER;
return usEvRelation;
}
}
|
package com.nosuchteam.service;
import com.nosuchteam.bean.Product;
import com.nosuchteam.bean.RequestList;
import java.util.List;
/**
* yuexia
* 2018/12/7
* 17:41
*/
public interface ProductService {
List<Product> findAllProduct();
Product selectByPrimaryKey(String productId);
List<Product> findProductList(RequestList requestList);
int findTotalProductNum();
int updateByPrimaryKeySelective(Product product);
int deleteByPrimaryKey(String ids);
}
|
package compilador.analisador.sintatico;
import compilador.analisador.lexico.Token;
import compilador.estruturas.ListaLigada;
import compilador.estruturas.String;
public class Submaquina {
/**
* Indica um estado inv‡lido.
*/
public static final int ESTADO_INVALIDO = -1;
/**
* Indica que a transiŤ‹o ocorreu normalmente.
*/
public static final int TRANSICAO_OK = 10;
/**
* Indica que a transiŤ‹o normal falhou. Deve ocorrer ent‹o um retorno ou chamada de subm‡quina.
*/
public static final int TRANSICAO_FALHOU = 11;
/**
* O nome da subm‡quina.
*/
private String nome;
/**
* O estado inicial da subm‡quina.
*/
private int estadoInicial;
/**
* Array com os estados iniciais da subm‡quina.
*/
private int[] estadosFinais;
/**
* Estado atual da subm‡quina.
*/
private int estadoAtual;
/**
* Tabela de transiŤ‹o de estados da subm‡quina.
*/
private int[][][] tabelaTransicao;
/**
* Tabela com a relaŤ‹o de quais subm‡quinas podem ser chamadas em cada estado.
*/
private int[][] tabelaChamadaSubmaquinas;
public Submaquina(String nome, int estadoInicial, int[] estadosFinais, int[][][] tabelaTransicao, int[][] tabelaChamadaSubmaquinas) {
this.nome = nome;
this.estadoInicial = this.estadoAtual = estadoInicial;
this.estadosFinais = estadosFinais;
this.tabelaTransicao = tabelaTransicao;
this.tabelaChamadaSubmaquinas = tabelaChamadaSubmaquinas;
}
/**
* @return o nome da subm‡quina.
*/
public String getNome() {
return this.nome;
}
/**
* @return o estado inicial da subm‡quina.
*/
public int getEstadoInicial() {
return this.estadoInicial;
}
/**
* @return o array de estados finais.
*/
public int[] getEstadosFinais() {
return this.estadosFinais;
}
/**
* @return o estado atual da subm‡quina.
*/
public int getEstadoAtual() {
return this.estadoAtual;
}
/**
* Seta o estado atual da sum‡quina.
*
* @param estadoAtual
*/
public void setEstadoAtual(int estadoAtual) {
this.estadoAtual = estadoAtual;
}
/**
* Executa uma transiŤ‹o na subm‡quina.
*
* @param token
* @return
*/
public int transicao(Token token) {
try{
int proximoEstado = this.tabelaTransicao[this.estadoAtual][token.getClasse()][token.getID()];
if(proximoEstado == ESTADO_INVALIDO) {
// Deve tentar chamar uma subm‡quina.
return TRANSICAO_FALHOU;
} else {
// H‡ transiŤ‹o dispon’vel.
this.estadoAtual = proximoEstado;
return TRANSICAO_OK;
}
} catch(Exception e) {
System.exit(0);
}
return TRANSICAO_FALHOU;
}
/**
* Identifica qual subm‡quina deve ser chamada.
*
* @param token
* @return o identificador da subm‡quina a ser chamada.
*/
public ListaLigada<Integer> possiveisSubmaquinas(Token token) {
ListaLigada<Integer> possiveisSubmaquinas = new ListaLigada<Integer>();
// Identificar as subm‡quinas que podem ser chamadas neste estado.
for(int i = 0; i < this.tabelaChamadaSubmaquinas[this.estadoAtual].length; i++)
if(this.tabelaChamadaSubmaquinas[this.estadoAtual][i] != -1)
possiveisSubmaquinas.put(i);
return possiveisSubmaquinas;
}
/**
* Verifica se a subm‡quina possui transiŤ‹o no estado atual para o token dado.
*
* @param token
* @return <code>true</code>, caso exista a transiŤ‹o. <code>false</code>, caso n‹o exista.
*/
public boolean haTransicao(Token token) {
int proximoEstado = this.tabelaTransicao[this.estadoAtual][token.getClasse()][token.getID()];
if(proximoEstado == ESTADO_INVALIDO)
return false;
return true;
}
/**
* Verifica se a subm‡quina possui, no estado atual, chamada de outra subm‡quina.
*
* @return <code>true</code>, caso exista a chamada. <code>false</code>, caso n‹o exista.
*/
public boolean haChamadaSubmaquina() {
for(int i = 0; i < this.tabelaChamadaSubmaquinas[this.estadoAtual].length; i++)
if(this.tabelaChamadaSubmaquinas[this.estadoAtual][i] != ESTADO_INVALIDO)
return true;
return false;
}
/**
* Executa uma transiŤ‹o de estado baseada em chamada de subm‡quina.
* N‹o chama efetivamente outra subm‡quina, apenas verifica a possibilidade e muda para o estado de retorno.
*
* @param idSubmaquina
* @return <code>true</code>, caso seja possivel chamar a subm‡quina. <code>false</code>, caso n‹o exista.
*/
public boolean chamarSubmaquina(int idSubmaquina) {
int proximoEstado = this.tabelaChamadaSubmaquinas[this.estadoAtual][idSubmaquina];
if(proximoEstado == ESTADO_INVALIDO)
return false;
this.estadoAtual = proximoEstado;
return true;
}
}
|
package com.tt.option.v;
import android.content.Context;
import com.tt.miniapp.AppbrandApplicationImpl;
import com.tt.miniapp.settings.data.SettingsDAO;
import com.tt.miniapp.settings.keys.Settings;
import com.tt.miniapphost.AppbrandContext;
import com.tt.miniapphost.entity.AppInfoEntity;
import java.util.List;
public final class c {
private static boolean a;
private List<String> b;
private List<String> c;
private c() {
if (AppbrandContext.getInst().getApplicationContext() != null) {
this.b = SettingsDAO.getListString((Context)AppbrandContext.getInst().getApplicationContext(), new Enum[] { (Enum)Settings.BDP_LAUNCH_APP_SCENE_LIST, (Enum)Settings.BdpLaunchSceneList.WHITE_LIST });
this.c = SettingsDAO.getListString((Context)AppbrandContext.getInst().getApplicationContext(), new Enum[] { (Enum)Settings.BDP_LAUNCH_APP_SCENE_LIST, (Enum)Settings.BdpLaunchSceneList.GRAY_LIST });
}
}
public static c a() {
return a.a;
}
public final boolean b() {
AppInfoEntity appInfoEntity = AppbrandApplicationImpl.getInst().getAppInfo();
if (appInfoEntity != null)
if (this.b.contains(appInfoEntity.scene)) {
a = true;
} else if (!this.c.contains(appInfoEntity.scene)) {
a = false;
}
return a;
}
static final class a {
public static c a = new c();
}
}
/* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\option\v\c.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
|
package com.mycompany.tripler_merge;
/**
* Created by Vidya Prabhu on 19-07-2017.
*/
public class trips {
private String location;
private String date;
public trips(String location, String date) {
this.location = location;
this.date = date;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
|
package com.caicai;
/**
* @author caicai
* @Date 2021/4/7 下午9:26
*/
public class paymentApplication {
}
|
/**
*
*/
package restaurante;
import java.io.Serializable;
import java.util.ArrayList;
/**
* @author Gabriel Alves
* @author Joao Carlos
* @author Melissa Diniz
* @author Thais Nicoly
*/
public class Refeicao extends TiposDeRefeicoes implements Serializable{
private static final long serialVersionUID = 1L;
private ArrayList<Prato> componentes;
public Refeicao(String nome, String descricao, ArrayList<Prato> componentes) {
super(nome,descricao);
this.componentes = componentes;
}
/**
* Metodo que faz o calculo do preco de uma refeicao
*/
@Override
public double getPreco(){
double precoRef = 0.0;
for (Prato prato : componentes) {
precoRef += prato.getPreco();
}
return precoRef * 0.9;
}
@Override
public String getDescricao() {
return super.getDescricao() + " Serao servidos: " + toStringPratos() + ".";
}
/**
* @return the componentes
*/
public ArrayList<Prato> getComponentes() {
return componentes;
}
/**
* @param componentes the componentes to set
*/
public void setComponentes(ArrayList<Prato> componentes) {
this.componentes = componentes;
}
/**
*
* @return Strind de pratos
*/
private String toStringPratos(){
String toPratos = "";
for (int i = 0; i < componentes.size(); i++) {
toPratos += ", ";
toPratos += "(" + (i + 1) + ") " + componentes.get(i).getNome();
}
return toPratos.substring(2);
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Nome: " + getNome() + " Preco: R$" + getPrecoFormatado() + "\r\n" + "Descricao: " +
getDescricao() + " \r\n" + imprimePratos();
}
private String imprimePratos(){
String stringPratos = " ";
for (Prato prato : this.getComponentes()) {
stringPratos += prato.getNome() + ", ";
}
return "Pratos: " + stringPratos.substring(0, stringPratos.length() - 2) + " \r\n";
}
}
|
package com.example.employeemanager;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class ThemNVActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_them_nv);
//chuyen den man hinh Menu khi Khong them
Button btn4= (Button) this.findViewById(R.id.button4);
btn4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent4= new Intent(ThemNVActivity.this, MenuActivity.class);
ThemNVActivity.this.startActivity(intent4);
}
});
//xu ly khi button THEM
Button btn3= (Button) this.findViewById(R.id.button3);
btn3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//xu ly thong tin dau vao
//hien thi thong bao khi them thanh cong su dung TOAST
Toast.makeText(ThemNVActivity.this,"Đã thêm thành công!",Toast.LENGTH_LONG).show();
}
});
}
}
|
package com.fireblaze.foodiee.fragments;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TextInputEditText;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Patterns;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.fireblaze.foodiee.Constants;
import com.fireblaze.foodiee.R;
import com.fireblaze.foodiee.UserOperations;
/**
* Created by chait on 6/7/2016.
*/
public abstract class SignInBaseFragment extends Fragment {
public Button mSignInButton;
public TextView mForgotPasswordText;
public TextInputEditText mEmailField;
public TextInputEditText mPasswordField, mOrganizerVerification;
public Button mGoogleSignInButton;
public Button mBecomeOrganizerButton;
public boolean isOrganizer = false;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View rootView = inflater.inflate(R.layout.fragment_layout_login,container,false);
//Get Views
mSignInButton = (Button) rootView.findViewById(R.id.btn_sign_in);
mForgotPasswordText = (TextView) rootView.findViewById(R.id.text_forgot_password);
mEmailField = (TextInputEditText) rootView.findViewById(R.id.field_email);
mPasswordField = (TextInputEditText) rootView.findViewById(R.id.field_password);
mGoogleSignInButton = (Button) rootView.findViewById(R.id.sign_in_google_button);
mBecomeOrganizerButton = (Button) rootView.findViewById(R.id.become_an_organizer_button);
mOrganizerVerification = (TextInputEditText) rootView.findViewById(R.id.field_organizer_verification);
return rootView;
}
protected boolean validateForm(){
boolean result = true;
String email = mEmailField.getText().toString().trim();
String password = mEmailField.getText().toString();
if(TextUtils.isEmpty(email)){
mEmailField.setError("Required");
Toast.makeText(getActivity(), "Email Field is empty", Toast.LENGTH_SHORT).show();
result = false;
} else if(!Patterns.EMAIL_ADDRESS.matcher(email).matches()){
mEmailField.setError("Email should be in format xyz@abc.com");
Toast.makeText(getActivity(), "Email should be in format xyz@abc.com", Toast.LENGTH_SHORT).show();
result = false;
}
else{
mEmailField.setError(null);
}
if(TextUtils.isEmpty(password)){
mPasswordField.setError("Required");
Toast.makeText(getActivity(), "Password is empty", Toast.LENGTH_SHORT).show();
result = false;
} else if(password.length() < 5){
mPasswordField.setError("Enter a password with at least 5 characters");
Toast.makeText(getActivity(), "Enter a password with at least 5 characters", Toast.LENGTH_SHORT).show();
result = false;
}
else {
mPasswordField.setError(null);
}
if(isOrganizer) {
if (!validateOrganizer()) {
result = false;
}else {
Toast.makeText(getActivity(), "Restaurant code incorrect", Toast.LENGTH_SHORT).show();
}
}
return result;
}
public boolean validateOrganizer(){
String verification = mOrganizerVerification.getText().toString().trim();
if(verification.isEmpty()){
mOrganizerVerification.setError("Please enter the code provided to you");
return false;
} else if(!verification.equals(Constants.VERIFICATION_CODE)){
mOrganizerVerification.setError("Please enter the correct code");
return false;
}
mOrganizerVerification.setError(null);
return true;
}
public String getUid(){
return UserOperations.getUid();
}
}
|
package com.guptas.android.datahelper;
import android.app.Activity;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
import com.firebase.client.Query;
import com.firebase.ui.FirebaseRecyclerAdapter;
import com.guptas.android.R;
import com.guptas.android.model.Users;
/**
* Created by pavitra on 14/4/16.
*/
public class UserPointsViewHolder extends RecyclerView.ViewHolder {
public TextView name = null;
public TextView points = null;
public UserPointsViewHolder(View v) {
super(v);
name = (TextView) v.findViewById(R.id.userName);
points = (TextView) v.findViewById(R.id.userPoints);
}
}
|
package com.qunchuang.carmall.controller;
import com.qunchuang.carmall.domain.Customer;
import com.qunchuang.carmall.service.CustomerService;
import graphql.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
/**
* @author Curtain
* @date 2019/1/18 8:30
*/
@RunWith(SpringRunner.class)
@SpringBootTest
//@Transactional
public class CustomerControllerTest {
@Autowired
private CustomerService customerService;
@Test
public void register() throws Exception {
Customer customer = new Customer();
customer.setOpenid("xxxxxxxxxxxxxxxxx");
// customer.setGender("女");
// customer.setIntegral(0);
// customer.setName("小月");
// customer.setPhone("13812345678");
Assert.assertNotNull(customerService.register(customer));
}
@Test
public void consult() throws Exception {
}
@Test
public void modify() throws Exception {
Customer customer = customerService.findOne("LEVpYTiIHEuaaQa4VmNuw2C01");
customer.setIntegral(1);
Assert.assertNotNull(customerService.modify(customer));
}
@Test
public void delete() throws Exception {
Assert.assertNotNull(customerService.delete("LEVpYTiIHEuaaQa4VmNuw2C01"));
}
}
|
package com.bucares.barcode.model;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
@Entity
@Table(name = "estudiante")
public class Estudiante {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(length = 16)
private String name;
@Column(length = 16)
private String lastname;
@Column(length = 11)
private String telefono;
@ManyToOne
@JoinColumn(name = "seccion_id", nullable = false)
private Seccion seccion;
@OneToOne
private Notas nota;
public Estudiante(){ /**/ }
/*
public Seccion getSeccion(){
return seccion;
}
public void setSeccion(Seccion seccion){
this.seccion = seccion;
}*/
public Long getId(){
return id;
}
public void setId(Long id){
this.id = id;
}
public String getLastname() {
return lastname;
}
public String getTelefono() {
return telefono;
}
public void setTelefono(String telefono) {
this.telefono = telefono;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public Estudiante(String name, String lastname, String telefono, Seccion seccion) {
this.name = name;
this.lastname = lastname;
this.telefono = telefono;
this.seccion = seccion;
}
}
|
package com.beiyelin.person.repository;
import com.beiyelin.commonsql.jpa.BaseAbstractRepository;
import com.beiyelin.commonsql.jpa.BaseAbstractRepository;
import com.beiyelin.commonsql.jpa.BaseDomainRepository;
import com.beiyelin.person.entity.Nation;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* @Author: xinsh
* @Description: 民族
* @Date: Created in 16:38 2018/02/21.
*/
@Repository
public interface NationRepository extends BaseDomainRepository<Nation,String> {
}
|
package pp_fp05.cd;
public class CDDemo {
public static void main(String[] args) {
Artist artist1 = new Artist("Artista 1", "German", "1977-03-04");
Artist[] artists = {artist1};
Track track1 = new Track(1, "Ho Hey", 90, "Lumineers");
Track track2 = new Track(2, "Stubborn Love", 105, "Wesley Schltz");
Track[] tracks = {track1, track2};
CD cd1 = new CD("The Lumineers", "The Lumineers", 480, 2012, "Dualtone Records", artists, tracks);
cd1.tracks[0] = track1;
cd1.tracks[14] = track2;
System.out.println("Nome do cd: " + cd1.name);
System.out.println("Ano de lançamento: " + cd1.year);
System.out.println("Editora: " + cd1.editor);
int nTracks = cd1.tracks.length;
for (int i = 0; i < nTracks; i++) {
if (cd1.tracks[i] != null) {
Track t = cd1.tracks[i];
System.out.println("Música número: " + t.number + " com titulo: " + t.name);
System.out.println("Duração (em segundos): " + t.duration);
System.out.println("Autor da música: " + t.author);
}
}
}
}
|
import java.util.Scanner;
//**********************************************
// CoinCounter.java
//
// Reads integer values that represent quarters,
// dimes, nickels and pennies. Prints the total
// in dollars and cents.
//**********************************************
public class CoinCounter {
public static void main(String[] args) {
Scanner inputMoney = new Scanner(System.in);
int quarters, dimes, nickels, pennies;
double quarter, dime, nickel, penny;
double totalMoney = 0.00;
System.out.print("Enter the number of quarters: ");
quarters = inputMoney.nextInt();
quarter = (double) quarters * 0.25;
System.out.print("Enter the number of dimes: ");
dimes = inputMoney.nextInt();
dime = (double) dimes * 0.10;
System.out.print("Enter the number of nickels: ");
nickels = inputMoney.nextInt();
nickel = (double) nickels * 0.05;
System.out.print("Enter the number of pennies: ");
pennies = inputMoney.nextInt();
penny = (double) pennies * 0.01;
totalMoney = quarter + dime + nickel + penny;
System.out.println("You have $" + totalMoney + ".");
}
}
|
package twitteranalysis;
/**
*
* @author Fraser
*/
public class EncodeChromosome {
private String ogUserName;
private String ogStatus;
private String comment;
private int followersCount;
private int favouriteCount;
private int friendCount;
private int location;
private int isVerified;
private int hasSwear;
private int hasPositiveWord;
private int hasNegativeWord;
private int hasPositiveEmoji;
private int hasNegativeEmoji;
public EncodeChromosome() {
}
public void setOgUserName(String ogUserName) {
this.ogUserName = ogUserName;
}
public void setOgStatus(String status) {
this.ogStatus = status;
}
public void setComment(String comment) {
this.comment = comment;
}
public void setFollowersCount(int followersCount) {
if ((followersCount >= 0) && (followersCount <= 10)) {
this.followersCount = 0;
} else if ((followersCount > 10) && (followersCount <= 100)) {
this.followersCount = 1;
} else if ((followersCount > 100) && (followersCount <= 300)) {
this.followersCount = 2;
} else if (followersCount > 300) {
this.followersCount = 3;
}
}
public void setFavouriteCount(int favouriteCount) {
if (favouriteCount == 0) {
this.favouriteCount = 0;
} else {
this.favouriteCount = 1;
}
}
public void setFriendCount(int friendCount) {
if ((friendCount >= 0) && (friendCount <= 10)) {
this.friendCount = 0;
} else if ((friendCount > 10) && (friendCount <= 100)) {
this.friendCount = 1;
} else if ((friendCount > 100) && (friendCount <= 300)) {
this.friendCount = 2;
} else if (friendCount > 300) {
this.friendCount = 3;
}
}
public void setLocation(Country location) {
if (location.getContinentCode().equals("AF")) {
this.location = 0;
} else if (location.getContinentCode().equals("AS")) {
this.location = 1;
} else if (location.getContinentCode().equals("OC")) {
this.location = 2;
} else if (location.getContinentCode().equals("EU")) {
this.location = 3;
} else if (location.getContinentCode().equals("NA")) {
this.location = 4;
} else if (location.getContinentCode().equals("SA")) {
this.location = 5;
}
}
public void setIsVerified(boolean verified) {
if (verified) {
this.isVerified = 1;
} else {
this.isVerified = 0;
}
}
public void setHasSwear(boolean swear) {
if (swear) {
this.hasSwear = 1;
} else {
this.hasSwear = 0;
}
}
public void setHasPositiveWord(boolean posWord) {
if (posWord) {
this.hasPositiveWord = 1;
} else {
this.hasPositiveWord = 0;
}
}
public void setHasNegativeWord(boolean negWord) {
if (negWord) {
this.hasNegativeWord = 1;
} else {
this.hasNegativeWord = 0;
}
}
public void setHasPositiveEmoji(boolean posEmoji) {
if (posEmoji) {
this.hasPositiveEmoji = 1;
} else {
this.hasPositiveEmoji = 0;
}
}
public void setHasnegativeEmoji(boolean negEmoji) {
if (negEmoji) {
this.hasNegativeEmoji = 1;
} else {
this.hasNegativeEmoji = 0;
}
}
public String getOgUserName() {
return ogUserName;
}
public String getOgStatus() {
return ogStatus;
}
public String getComment() {
return comment;
}
public int getFollowersCount() {
return followersCount;
}
public int getFavouriteCount() {
return favouriteCount;
}
public int getFriendCount() {
return friendCount;
}
public int getLocation() {
return location;
}
public int getIsVerified() {
return isVerified;
}
public int getHasSwear() {
return hasSwear;
}
public int getHasPositiveWord() {
return hasPositiveWord;
}
public int getHasNegativeWord() {
return hasNegativeWord;
}
public int getHasPositiveEmoji() {
return hasPositiveEmoji;
}
public int getHasNegativeEmoji() {
return hasNegativeEmoji;
}
}
|
package pages;
import io.appium.java_client.android.AndroidDriver;
import io.qameta.allure.Step;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import pages_utils.ElementsActions;
import pages_utils.Logger;
public class Fatura_Login_Page {
private final AndroidDriver<WebElement> driver;
private final By login_page_title = By.id("toolbar_title");
private final By phoneNumber_txt_Field = By.id("textinput_placeholder");
private final By password_txt_Field = By.id("password_TextInputEditText");
private final By signin_submit_btn = By.id("btn_signin");
private final By errorMessageTxt = By.id("");
public Fatura_Login_Page(AndroidDriver<WebElement> driver) {
this.driver = driver;
}
//Methods
@Step("User Login with Phone number and Password credentials")
public Fatura_Home_Page userLogin(String phoneNumber, String password) {
sendEmailCredentials(phoneNumber);
sendPasswordCredentials(password);
clickOnSignInButton();
return new Fatura_Home_Page(driver);
}
@Step("User Login with invalid Phone number and Password credentials")
public Fatura_Login_Page userInvalidLogin(String phoneNumber, String password) {
sendEmailCredentials(phoneNumber);
sendPasswordCredentials(password);
clickOnSignInButton();
return this;
}
@Step("Get The login page title")
public String getLoginPageTitle() {
driver.navigate().back();
String title = ElementsActions.getText(driver, login_page_title);
Logger.logMessage("The Home page title is" + title);
return title;
}
@Step("Send Phone number credentials to email text field")
public void sendEmailCredentials(String phoneNumber) {
ElementsActions.type(driver, phoneNumber_txt_Field, phoneNumber, true);
}
@Step("Send password credentials to password text field")
public void sendPasswordCredentials(String password) {
ElementsActions.type(driver, password_txt_Field, password, true);
}
@Step("Click on Sign in button")
public void clickOnSignInButton() {
ElementsActions.click(driver, signin_submit_btn);
}
@Step("Get error message text")
public String getErrorMessageTxt() {
String errorTxt = ElementsActions.getText(driver, errorMessageTxt);
Logger.logMessage("The Error message error is" + errorTxt);
return errorTxt;
}
}
|
package ch.fhnw.edu.cpib.errors;
public class SyntaxError extends Exception {
public SyntaxError(String e) {
super(e);
}
}
|
package risingWaters;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.stage.Stage;
import javafx.scene.Group;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.text.Text;
import javafx.scene.text.Font;
import javafx.scene.paint.Color;
import javafx.scene.control.*;
import java.util.*;
/** Displays room 1 of the game where the user learns how to prepare for a flood.
*
* @version Final
* @author Cindy Liu and Emily Hu
* Due date: June 10th, 2019
* Time Spent: 6 hours
*/
public class Level1 {
// array of the images on the cards
private Image[] cardImage;
// array of the explanations for the matches of items
private String[] explanations;
// the number of cards left on the board
private int cardsLeft;
// array of the position of the cards on the board
private int[] board;
// the total amount of pairs of cards
private final int TOTAL_TERMS = 12;
// score of the user
private int userScore;
/** Constructs a new level. Initializes the global variables and calls the Level 1 intro screen.
*
* @param root Groups each object together on the screen
* @param scene Holds the current scene on the screen
* @param stage Holds the stage as a platform for output
*/
public Level1(Group root, Scene scene, Stage stage) {
cardImage = new Image [TOTAL_TERMS * 2];
explanations = new String[TOTAL_TERMS];
board = new int[TOTAL_TERMS * 2];
cardsLeft = 24;
loadImages();
loadExplanations();
shuffle();
level1Intro(root, scene, stage);
}
/**
* Loads the images from the bin folder into the program.
*/
public void loadImages() {
// loads the images of the cards
cardImage [0] = new Image(ResourceLoader.getResourceLocation("Water.jpg"));
cardImage [1] = new Image(ResourceLoader.getResourceLocation("Food.jpg"));
cardImage [2] = new Image(ResourceLoader.getResourceLocation("Radio.jpg"));
cardImage [3] = new Image(ResourceLoader.getResourceLocation("Flashlight.jpg"));
cardImage [4] = new Image(ResourceLoader.getResourceLocation("Battery.jpg"));
cardImage [5] = new Image(ResourceLoader.getResourceLocation("Whistle.jpg"));
cardImage [6] = new Image(ResourceLoader.getResourceLocation("Tape.jpg"));
cardImage [7] = new Image(ResourceLoader.getResourceLocation("Mask.jpg"));
cardImage [8] = new Image(ResourceLoader.getResourceLocation("Tool.jpg"));
cardImage [9] = new Image(ResourceLoader.getResourceLocation("Map.jpg"));
cardImage [10] = new Image(ResourceLoader.getResourceLocation("Cellphone.jpg"));
cardImage [11] = new Image(ResourceLoader.getResourceLocation("Charger.jpg"));
for (int x = 12; x < TOTAL_TERMS * 2; x++) {
cardImage [x] = new Image(ResourceLoader.getResourceLocation("Text".concat(Integer.toString(x-11))+".jpg"));
}
}
/**
* Loads the explanations from the text file.
*/
public void loadExplanations() {
explanations[0] = "Water is important to keep you hydrated and alive.";
explanations[1] = "Non-perishable food is important to give you energy.";
explanations[2] = "A radio is important to keep you updated on the current situation.";
explanations[3] = "A flashlight is important in case the electricity goes out.";
explanations[4] = "Batteries are important in case old ones run out.";
explanations[5] = "A whistle is important for someone to be able to locate you.";
explanations[6] = "Duct tape is important as it is multi-functional.";
explanations[7] = "A dust mask is important as dust and debris may fill the air.";
explanations[8] = "Tools are important in case you need to fix or build something.";
explanations[9] = "A map is important in order to evacuate the location.";
explanations[10] = "A cell phone is important to help contact others and gather information.";
explanations[11] = "A charger is important in case an electronic runs out of power.";
}
/**
* Shuffles the cards on the board.
*/
public void shuffle() {
ArrayList<Integer> count = new ArrayList<Integer>();
boolean check = false;
int rand = 0;
// shuffles the cards randomly
for (int x = 0; x < TOTAL_TERMS * 2; x++) {
check = false;
while (check == false) {
check = true;
rand = (int) (Math.random() * 24);
for (Integer n : count) {
if (n == rand) {
check = false;
}
}
}
board[x] = rand;
count.add(rand);
}
}
/** Checks whether the two cards are a match.
*
* @param cardNum1 the position of the first card
* @param cardNum2 the position of the second card
* @return whether the two cards match
*/
public boolean checkMatch(int cardNum1, int cardNum2) {
// checks if the two cards are a match
if (board[cardNum1] % 12 == board[cardNum2] % 12) {
if (board[cardNum1] == -1 && board[cardNum2] == -1) {
return false;
} else {
return true;
}
} else {
return false;
}
}
/** Displays the intro screen for level 1.
*
* @param root Groups each object together on the screen
* @param scene Holds the current scene on the screen
* @param stage Holds the stage as a platform for output
*/
public void level1Intro (Group root, Scene scene, Stage stage) {
// creates the background
Image background = new Image(ResourceLoader.getResourceLocation("Level1Intro.jpg"));
ImageView bg = new ImageView(background);
root.getChildren().add(bg);
// creates the continue button
Button cont = new Button();
cont.setText("Continue");
cont.setLayoutX (880);
cont.setLayoutY (600);
cont.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
level1 (root, scene, stage);
}
});
root.getChildren().add(cont);
stage.setScene(scene);
stage.sizeToScene();
stage.show();
}
/** Displays the outro screen for level 1.
*
* @param root Groups each object together on the screen
* @param scene Holds the current scene on the screen
* @param stage Holds the stage as a platform for output
*/
public void level1Outro (Group root, Scene scene, Stage stage) {
writeScore();
// creates the background
Image background = new Image(ResourceLoader.getResourceLocation("Level1Outro.jpg"));
ImageView bg = new ImageView(background);
root.getChildren().add(bg);
// creates the score
Text score = new Text (530, 340, "Score: " + userScore);
score.setFont(Font.font ("Montserrat", 36));
root.getChildren().add(score);
// creates the continue button
Button cont = new Button();
cont.setText("Continue");
cont.setLayoutX (880);
cont.setLayoutY (600);
cont.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
new Level2 (root, scene, stage);
}
});
root.getChildren().add(cont);
stage.setScene(scene);
stage.sizeToScene();
stage.show();
}
/** Writes the score onto the Player class.
*
*/
public void writeScore()
{
Introduction.p.setPoints1(userScore);
}
/** Displays the level 1 game.
*
* @param root Groups each object together on the screen
* @param scene Holds the current scene on the screen
* @param stage Holds the stage as a platform for output
*/
public void level1 (Group root, Scene scene, Stage stage) {
if (cardsLeft == 0) {
userScore = 100;
level1Outro (root, scene, stage);
}
else {
// creating a background image
Image background = new Image(ResourceLoader.getResourceLocation("GreyBackground.jpg"));
ImageView wb = new ImageView(background);
root.getChildren().add(wb);
// creates an array of cards
Image image = new Image(ResourceLoader.getResourceLocation("Card.png"));
ImageView imageView[] = new ImageView [24];
// displays the cards on the screen
int count = 0;
for (int y = 150; y < 600; y += 130) {
for (int x = 50; x < 800; x+=130) {
if (board[count] != -1){
imageView [count] = new ImageView(image);
imageView [count].setX(x);
imageView [count].setY(y);
imageView [count].setFitHeight(110);
imageView [count].setFitWidth(90);
root.getChildren().add(imageView [count]);
Text num = new Text (x + 10, y + 20, Integer.toString (count + 1));
num.setFont(Font.font ("Montserrat", 14));
num.setFill(Color.WHITE);
root.getChildren().add(num);
}
count++;
}
}
// creates the title
Text title = new Text (450, 100, "Level 1");
title.setFont(Font.font ("Montserrat", 64));
root.getChildren().add(title);
// creates a new text to help the user
Text selectedCards = new Text (880, 350, "Selected Cards: ");
selectedCards.setFont(Font.font ("Montserrat", 20));
root.getChildren().add(selectedCards);
// creates a new text field for the user to enter the first card
TextField userInput1 = new TextField();
userInput1.setLayoutX (880);
userInput1.setLayoutY (370);
root.getChildren().add(userInput1);
// creates a new text field for the user to enter the second card
TextField userInput2 = new TextField();
userInput2.setLayoutX (880);
userInput2.setLayoutY (405);
root.getChildren().add(userInput2);
// creates an error message
Text invalid = new Text (880, 540, "Invalid input!");
invalid.setFont(Font.font ("Montserrat", 18));
invalid.setVisible (false);
root.getChildren().add(invalid);
// creates a new button to check if the cards are a match
Button check = new Button();
check.setText("Check Match");
check.setLayoutX (880);
check.setLayoutY (450);
check.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
String text = userInput1.getText();
String text2 = userInput2.getText();
int cardNum1 = 0;
int cardNum2 = 0;
try {
cardNum1 = Integer.parseInt (text) - 1;
cardNum2 = Integer.parseInt (text2) - 1;
if (cardNum1 >= 0 && cardNum1 < 24 && cardNum2 >= 0 && cardNum2 < 24 && cardNum1 != cardNum2) {
if (checkMatch (cardNum1, cardNum2) && board[cardNum1] != -1){
right (root, scene, stage, cardNum1, cardNum2);
cardsLeft -= 2;
board[cardNum1] = -1;
board[cardNum2] = -1;
}
else if (board[cardNum1] != -1 && board[cardNum2] != -1) {
wrong(root, scene, stage, cardNum1, cardNum2);
}
else {
invalid.setVisible (true);
}
}
else {
invalid.setVisible (true);
}
}
catch (NumberFormatException e) {
invalid.setVisible (true);
}
}
});
root.getChildren().add(check);
// creates a new button to give up
Button giveUp = new Button();
giveUp.setText("Give Up");
giveUp.setLayoutX (880);
giveUp.setLayoutY (490);
giveUp.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
userScore = 0;
level1Outro(root, scene, stage);
}
});
root.getChildren().add(giveUp);
stage.setTitle("Rising Waters");
stage.setScene(scene);
stage.show();
}
}
/** Displays a message if the answer is correct.
*
* @param root Groups each object together on the screen
* @param scene Holds the current scene on the screen
* @param stage Holds the stage as a platform for output
* @param cardNum1 Holds the number of the first card
* @param cardNum2 Holds the number of the second card
*/
public void right (Group root, Scene scene, Stage stage, int cardNum1, int cardNum2) {
ImageView iv = new ImageView();
Image bg = new Image(ResourceLoader.getResourceLocation("RightScreen.png"));
iv.setImage(bg);
iv.setX(0);
iv.setY(0);
int card1 = board[cardNum1];
int card2 = board[cardNum2];
// creates the first card's picture
ImageView picture1 = new ImageView();
picture1.setImage(cardImage[card1]);
picture1.setX(265);
picture1.setY(225);
// creates the second card's picture
ImageView picture2 = new ImageView();
picture2.setImage(cardImage[card2]);
picture2.setX(595);
picture2.setY(225);
// creates a new explanation for the match
Text expl;
if (card1 < card2)
expl = new Text(270, 570, explanations[card1]);
else
expl = new Text(270, 570, explanations[card2]);
expl.setFont(Font.font("Montserrat", 18));
expl.setVisible(true);
// creates the number of the first card
Text num1 = new Text(270, 240, Integer.toString(cardNum1 + 1));
num1.setFont(Font.font("Montserrat", 18));
// creates the number of the second card
Text num2 = new Text(600, 240, Integer.toString(cardNum2 + 1));
num2.setFont(Font.font("Montserrat", 18));
// creates a new continue button
Button cont = new Button();
cont.setText("Continue");
cont.setLayoutX (880);
cont.setLayoutY (600);
cont.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
level1 (root, scene, stage);
}
});
root.getChildren().add(iv);
root.getChildren().add(picture1);
root.getChildren().add(picture2);
root.getChildren().add(expl);
root.getChildren().add(num1);
root.getChildren().add(num2);
root.getChildren().add(cont);
stage.setScene(scene);
stage.sizeToScene();
stage.show();
}
/** Displays a message if the answer is wrong.
*
* @param root Groups each object together on the screen
* @param scene Holds the current scene on the screen
* @param stage Holds the stage as a platform for output
* @param cardNum1 Holds the number of the first card
* @param cardNum2 Holds the number of the second card
*/
public void wrong (Group root, Scene scene, Stage stage, int cardNum1, int cardNum2)
{
ImageView iv = new ImageView();
Image bg = new Image(ResourceLoader.getResourceLocation("WrongScreen.png"));
iv.setImage(bg);
int card1 = board[cardNum1];
int card2 = board[cardNum2];
// creates the first card's picture
ImageView picture1 = new ImageView();
picture1.setImage(cardImage[card1]);
picture1.setX(265);
picture1.setY(225);
// creates the second card's picture
ImageView picture2 = new ImageView();
picture2.setImage(cardImage[card2]);
picture2.setX(595);
picture2.setY(225);
// creates the number of the first card
Text num1 = new Text(270, 240, Integer.toString(cardNum1 + 1));
num1.setFont(Font.font("Montserrat", 18));
// creates the number of the second card
Text num2 = new Text(600, 240, Integer.toString(cardNum2 + 1));
num2.setFont(Font.font("Montserrat", 18));
// creates new continue button
Button cont = new Button();
cont.setText("Continue");
cont.setLayoutX (880);
cont.setLayoutY (600);
cont.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
level1 (root, scene, stage);
}
});
root.getChildren().add(iv);
root.getChildren().add(picture1);
root.getChildren().add(picture2);
root.getChildren().add(num1);
root.getChildren().add(num2);
root.getChildren().add(cont);
stage.setScene(scene);
stage.sizeToScene();
stage.show();
}
}
|
package com.eCommerce.eComApp.model;
import lombok.Data;
import org.springframework.data.mongodb.core.mapping.Document;
import java.util.List;
public @Data class Client extends User{
private List<String> shippingAddress;
private List<CreditCard> creditCard;
}
|
package de.julian.main;
public enum SchoolSubject {
//TODO Adding School Subjects
M("Mathematik", 0),
E("Englisch", 0),
D("Deutsch", 0),
EK("Erdkunde", 0),
GE("Geschichte", 0),
IF("Informatik", 0),
FREI("Freistunde", 0),
KR("Religion", 0),
PH("Physik", 0),
SP("Sport", 0),
PJK("Auschwitz", 0),
KU("Kunst", 0);
String name;
int id;
HomeWork homeWork;
SchoolSubject(String name, int id) {
setName(name);
setId(id);
}
public void addHomeWork(String task) {
homeWork = new HomeWork();
this.homeWork.setTask(task);
}
public HomeWork getHomeWork() {
return homeWork;
}
public boolean hasHomeWork() {
if(getHomeWork()==null) {
return false;
} else {
return true;
}
}
public String getHomeWorkTask() {
return this.homeWork.getTask();
}
public boolean isHomeWorkDone() {
return this.homeWork.isDone();
}
public void finishHomeWork() {
this.homeWork.setDone(true);
}
public void setName(String name) {
this.name = name;
}
public void setId(int id) { this.id = id; }
public String getName() {
return name;
}
public int getId() {
return id;
}
}
|
package com.osce.service.biz.training.res.model;
import com.osce.api.biz.training.res.model.PfModelService;
import com.osce.dto.biz.training.res.model.FaultDto;
import com.osce.dto.biz.training.res.model.ModelDto;
import com.osce.dto.biz.training.res.model.RepairDto;
import com.osce.dto.common.PfBachChangeStatusDto;
import com.osce.entity.ErpDevice;
import com.osce.entity.ErpDeviceCase;
import com.osce.entity.ErpDeviceFault;
import com.osce.entity.ErpDeviceRepair;
import com.osce.orm.biz.training.res.model.PfModelDao;
import com.osce.param.PageParam;
import com.osce.result.PageResult;
import com.osce.result.ResultFactory;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.util.List;
/**
* @ClassName: PfModelServiceImpl
* @Description: 教学模型
* @Author yangtongbin
* @Date 2019-05-12
*/
@Service
public class PfModelServiceImpl implements PfModelService {
@Resource
private PfModelDao pfModelDao;
@Override
public PageResult pageModels(ModelDto dto) {
PageParam.initPageDto(dto);
return ResultFactory.initPageResultWithSuccess(pfModelDao.countModel(dto),
pfModelDao.listModels(dto));
}
@Override
public Long addModel(ErpDevice dto) {
if (dto.getIdDevice() == null) {
pfModelDao.addModel(dto);
} else {
pfModelDao.editModel(dto);
}
return dto.getIdDevice();
}
@Override
public boolean delModel(PfBachChangeStatusDto dto) {
int num = pfModelDao.delModel(dto);
return num >= 1 ? true : false;
}
@Override
public PageResult pageModelDevice(ModelDto dto) {
PageParam.initPageDto(dto);
return ResultFactory.initPageResultWithSuccess(0L,
pfModelDao.listModelDevice(dto));
}
@Override
public Long addModelDevice(ErpDeviceCase dto) {
if (dto.getIdDeviceCase() == null) {
pfModelDao.addModelDevice(dto);
} else {
pfModelDao.editModelDevice(dto);
}
return dto.getIdDeviceCase();
}
@Override
public boolean delModelDevice(PfBachChangeStatusDto dto) {
int num = pfModelDao.delModelDevice(dto);
return num >= 1 ? true : false;
}
@Override
public List<ErpDeviceFault> listDeviceFault(ModelDto dto) {
return pfModelDao.listDeviceFault(dto);
}
@Override
public List<ErpDeviceRepair> listDeviceRepair(ModelDto dto) {
return pfModelDao.listDeviceRepair(dto);
}
@Override
public boolean saveDeviceFault(FaultDto dto) {
List<ErpDeviceFault> list = dto.getList();
if (CollectionUtils.isEmpty(list)) {
return true;
}
for (ErpDeviceFault erpDeviceFault : list) {
if (erpDeviceFault.getIdDeviceFault() == null) {
pfModelDao.addDeviceFault(erpDeviceFault);
} else {
pfModelDao.editDeviceFault(erpDeviceFault);
}
}
return true;
}
@Override
public boolean saveDeviceRepair(RepairDto dto) {
List<ErpDeviceRepair> list = dto.getList();
if (CollectionUtils.isEmpty(list)) {
return true;
}
for (ErpDeviceRepair erpDeviceRepair : list) {
if (erpDeviceRepair.getIdRepair() == null) {
pfModelDao.addDeviceRepair(erpDeviceRepair);
} else {
pfModelDao.editDeviceRepair(erpDeviceRepair);
}
}
return true;
}
@Override
public boolean delDeviceFault(PfBachChangeStatusDto dto) {
return pfModelDao.delDeviceFault(dto) >= 1 ? true : false;
}
@Override
public boolean delDeviceRepair(PfBachChangeStatusDto dto) {
return pfModelDao.delDeviceRepair(dto) >= 1 ? true : false;
}
}
|
package com.example.android.dreamdestinations;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;
import com.example.android.dreamdestinations.Model.Itineraries;
import org.json.JSONException;
import java.util.ArrayList;
import static android.provider.BaseColumns._ID;
import static com.example.android.dreamdestinations.FavouritesContract.FavouritesEntry.COLUMN_DEST_ID;
import static com.example.android.dreamdestinations.FavouritesContract.FavouritesEntry.COLUMN_DEST_NAME;
import static com.example.android.dreamdestinations.FavouritesContract.FavouritesEntry.COLUMN_FROM_DATE;
import static com.example.android.dreamdestinations.FavouritesContract.FavouritesEntry.COLUMN_ORIGIN_ID;
import static com.example.android.dreamdestinations.FavouritesContract.FavouritesEntry.COLUMN_ORIGIN_NAME;
import static com.example.android.dreamdestinations.FavouritesContract.FavouritesEntry.COLUMN_TO_DATE;
import static com.example.android.dreamdestinations.FavouritesContract.FavouritesEntry.CONTENT_URI;
import static com.example.android.dreamdestinations.FavouritesContract.FavouritesPriceEntry.COLUMN_PRICE;
import static com.example.android.dreamdestinations.FavouritesContract.FavouritesPriceEntry.COLUMN_TRIP_ID;
import static com.example.android.dreamdestinations.Utilities.PredictionJsonUtils.getItinerariesFromJson;
public class ResultActivity extends AppCompatActivity {
public static final String ITINERARIES = "itineraries";
public static final String PARAMS = "params";
public static String flight;
public static String[] params;
private SQLiteDatabase mDb;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
TextView itinerary = findViewById(R.id.itinerary);
if (savedInstanceState == null) {
/* Intent intent = getIntent();
if (intent == null) {
closeOnError();
}
flight = intent.getStringExtra(ITINERARIES); */
Log.e("flight", flight);
itinerary.setText("Flying from " + params[4] + " to " + params[5] +
" on " + params[2] + " to " + params[3]);
//itinerary.setText("Flying from \n San Francisco International to London Heathrow\n" +
// " on\n 2018-11-01 to 2018-11-11");
ResultActivityFragment resultFragment = new ResultActivityFragment();
resultFragment.setItineraries(flight);
resultFragment.setParams(params);
//Use a FragmentManager and transaction to add the fragment to the screen
FragmentManager fragmentManager = getSupportFragmentManager();
//Fragment transaction
fragmentManager.beginTransaction()
.add(R.id.fragment_result, resultFragment, "Result")
.commit();
} else {
flight = savedInstanceState.getString(ITINERARIES);
params = savedInstanceState.getStringArray(PARAMS);
itinerary.setText("Flying from " + params[4] + " to " + params[5] +
" on " + params[2] + " to " + params[3]);
//itinerary.setText("Flying from \n San Francisco International to London Heathrow\n" +
// " on\n 2018-11-01 to 2018-11-11");
ResultActivityFragment resultFragment = (ResultActivityFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_result);
resultFragment.setItineraries(flight);
resultFragment.setParams(params);
//Use a FragmentManager and transaction to add the fragment to the screen
FragmentManager fragmentManager = getSupportFragmentManager();
//Fragment transaction
fragmentManager.beginTransaction()
.replace(R.id.fragment_result, resultFragment)
.commit();
}
// Create a DB helper (this will create the DB if run for the first time)
FavouritesDbHelper dbHelper = new FavouritesDbHelper(this);
// Keep a reference to the mDb until paused or killed. Get a writable database
// because you will be adding restaurant customers
mDb = dbHelper.getWritableDatabase();
//favourite
// from the website https://alvinalexander.com/source-code/android/android-checkbox-listener-setoncheckedchangelisteneroncheckedchangelistener-exam
CheckBox checkBox = (CheckBox) findViewById(R.id.favbutton);
//query the database to check the checkbox if is favourite
if (params != null) {
final int tripId = getTrip(params);
if (tripId > 0) {
checkBox.setChecked(true);
}
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// update your model (or other business logic) based on isChecked
if (isChecked) {
addTrip(params);
Log.e("add", "add to database");
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = preferences.edit();
editor.putString("params", "Flying from " + params[4] + " to " +
params[5] + " on " + params[2] + " to " + params[3]);
editor.apply();
} else {
if (tripId > 0 ) {
if (removeTrip(tripId) ) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = preferences.edit();
editor.putString("params", "");
editor.apply();
} else {
Log.e("remove", "not removed");
}
}
}
}
});
}
}
private void closeOnError() {
finish();
Toast.makeText(this, R.string.result_error_message, Toast.LENGTH_SHORT).show();
}
@Override
public void onSaveInstanceState(Bundle outState) {
outState.putString(ITINERARIES, flight);
outState.putStringArray(PARAMS, params);
super.onSaveInstanceState(outState);
}
private int getTrip(String[] params) {
Cursor cursor = getContentResolver()
.query(CONTENT_URI,null,
COLUMN_ORIGIN_ID + "=? and " +
COLUMN_DEST_ID + "=? and " +
COLUMN_FROM_DATE + "=? and " +
COLUMN_TO_DATE+ "=? "
, new String[] {
params[0],
params[1],
params[2],
params[3]},null);
if (cursor != null && cursor.moveToFirst()) {
int id = cursor.getInt(cursor.getColumnIndex(_ID));
return id;
} else {
return -1;
}
}
private Uri addTrip(String[] params) {
ArrayList<Itineraries> itinerariesJsonData = null;
try {
itinerariesJsonData = getItinerariesFromJson(getApplicationContext(), flight);
} catch (JSONException e) {
e.printStackTrace();
}
String pricing = itinerariesJsonData.get(0).getPricingOptions().get(0).getPrice();
//create ContentValues to pass values onto insert query
ContentValues cv = new ContentValues();
//call put to insert name value with the key COLUMN_TITLE
cv.put(COLUMN_ORIGIN_ID, params[0]);
cv.put(COLUMN_DEST_ID, params[1]);
cv.put(COLUMN_FROM_DATE, params[2]);
cv.put(COLUMN_TO_DATE, params[3]);
cv.put(COLUMN_ORIGIN_NAME, params[4]);
cv.put(COLUMN_DEST_NAME, params[5]);
//call insert to run an insert query on TABLE_NAME with content values
Uri uri = getContentResolver().insert(FavouritesContract.FavouritesEntry.CONTENT_URI, cv);
long id = ContentUris.parseId(uri);
ContentValues cv2 = new ContentValues();
//call put to insert name value with the key COLUMN_TITLE
cv2.put(COLUMN_TRIP_ID, (int) id);
cv2.put(COLUMN_PRICE, pricing);
// Uri uri2 = getContentResolver().insert(FavouritesContract.FavouritesPriceEntry.CONTENT_URI, cv2);
return getContentResolver().insert(FavouritesContract.FavouritesPriceEntry.CONTENT_URI, cv2);
}
private boolean removeTrip(int id) {
int rows = getContentResolver()
.delete(FavouritesContract.FavouritesEntry.buildTripUriWithId(String.valueOf(id)),_ID,
new String[]{String.valueOf(id)});
int rows2 = getContentResolver()
.delete(FavouritesContract.FavouritesPriceEntry.buildPriceUriWithId(String.valueOf(id)),
COLUMN_TRIP_ID, new String[]{String.valueOf(id)});
if (rows > 0 && rows2 > 0 ) {
return true;
} else {
return false;
}
}
}
|
package smart.lib.payment;
import java.util.Map;
public interface Payment {
/**
* 获取英文简称
*
* @return 英文简称
*/
String getName();
/**
* 获取中文简称
*
* @return 中文简称
*/
String getName1();
/**
* 初始化参数(全局只需设置一次)
*/
void setConfig(Map<String, String> map);
/**
* 获取收款码,需要转换成QR二维码使用
*
* @param title 交易标题
* @param orderNo 订单号
* @param amount 订单金额
* @return 收款码
* @throws Exception error
*/
String getQRCode(String title, String orderNo, long amount) throws Exception;
/**
* 成功信息短语
*
* @return 返会成功信息短语
*/
String getSuccessResponse();
/**
* 处理异步通知
*
* @param map 通知参数
* @return 是否成功
*/
boolean notify(Map<String, String> map);
/**
* 退款
*
* @param orderNo 订单号
* @param amount 退款金额
* @return null成功, 或失败信息
*/
String refund(long orderNo, long amount);
}
|
package com.tencent.mm.plugin.wxpay;
import com.tencent.mm.bg.c;
import com.tencent.mm.kernel.b.f;
import com.tencent.mm.kernel.b.g;
import com.tencent.mm.kernel.c.e;
import com.tencent.mm.model.p;
import com.tencent.mm.plugin.aa.b;
import com.tencent.mm.plugin.mall.a.d;
import com.tencent.mm.plugin.offline.k;
import com.tencent.mm.plugin.wallet_core.model.o;
import com.tencent.mm.plugin.wxpay.a.a;
public class PluginWxPay extends f implements a {
public String name() {
return "plugin-wxpay";
}
public void installed() {
alias(a.class);
}
public void dependency() {
}
public void configure(g gVar) {
if (gVar.ES()) {
pin(new p(b.class));
pin(new p(com.tencent.mm.plugin.collect.a.a.class));
pin(new p(com.tencent.mm.plugin.luckymoney.a.a.class));
pin(new p(d.class));
pin(new p(k.class));
pin(new p(com.tencent.mm.plugin.order.a.b.class));
pin(new p(com.tencent.mm.plugin.product.a.a.class));
pin(new p(com.tencent.mm.plugin.recharge.a.a.class));
pin(new p(com.tencent.mm.plugin.remittance.a.b.class));
pin(new p(com.tencent.mm.plugin.wallet.a.p.class));
pin(new p(o.class));
pin(new p(com.tencent.mm.plugin.wallet_index.a.a.class));
pin(new p(com.tencent.mm.plugin.wallet_payu.a.d.class));
pin(new p(com.tencent.mm.plugin.wxcredit.a.class));
pin(new p(com.tencent.mm.plugin.fingerprint.a.class));
pin(new p(com.tencent.mm.plugin.wallet_ecard.a.class));
pin(new p(com.tencent.mm.plugin.honey_pay.a.class));
}
com.tencent.mm.kernel.g.a(com.tencent.mm.plugin.luckymoney.appbrand.a.class, new e(new com.tencent.mm.plugin.luckymoney.appbrand.b()));
}
public void execute(g gVar) {
if (gVar.ES()) {
c.Um("wallet");
c.Um("mall");
c.Um("wxcredit");
c.Um("offline");
c.Um("recharge");
c.Um("wallet_index");
c.Um("order");
c.Um("product");
c.Um("remittance");
c.Um("collect");
c.Um("wallet_payu");
c.Um("luckymoney");
c.Um("fingerprint");
}
}
}
|
/**
* @author Erik Andreas Barreto de Vera.
* E-mail: alu0100774054@ull.edu.es
* Fecha: 18/05/2016
* Asignatura: Programación de Aplicaciones Interactivas.
* Comentario: Clase que contiene el panel donde se muestra el mundo.
*/
package es.esit.ull.GOL;
public class Main {
public static void main(String[] args) {
Interfaz interfaz = new Interfaz(Integer.parseInt(args[0]), Integer.parseInt(args[1]));
interfaz.setVisible(true);
}
}
|
package net.minecraft.item.crafting;
import com.google.common.collect.Maps;
import java.util.Map;
import net.minecraft.block.Block;
import net.minecraft.block.BlockStoneBrick;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.EnumDyeColor;
import net.minecraft.item.Item;
import net.minecraft.item.ItemFishFood;
import net.minecraft.item.ItemStack;
public class FurnaceRecipes {
private static final FurnaceRecipes SMELTING_BASE = new FurnaceRecipes();
private final Map<ItemStack, ItemStack> smeltingList = Maps.newHashMap();
private final Map<ItemStack, Float> experienceList = Maps.newHashMap();
public static FurnaceRecipes instance() {
return SMELTING_BASE;
}
private FurnaceRecipes() {
addSmeltingRecipeForBlock(Blocks.IRON_ORE, new ItemStack(Items.IRON_INGOT), 0.7F);
addSmeltingRecipeForBlock(Blocks.GOLD_ORE, new ItemStack(Items.GOLD_INGOT), 1.0F);
addSmeltingRecipeForBlock(Blocks.DIAMOND_ORE, new ItemStack(Items.DIAMOND), 1.0F);
addSmeltingRecipeForBlock((Block)Blocks.SAND, new ItemStack(Blocks.GLASS), 0.1F);
addSmelting(Items.PORKCHOP, new ItemStack(Items.COOKED_PORKCHOP), 0.35F);
addSmelting(Items.BEEF, new ItemStack(Items.COOKED_BEEF), 0.35F);
addSmelting(Items.CHICKEN, new ItemStack(Items.COOKED_CHICKEN), 0.35F);
addSmelting(Items.RABBIT, new ItemStack(Items.COOKED_RABBIT), 0.35F);
addSmelting(Items.MUTTON, new ItemStack(Items.COOKED_MUTTON), 0.35F);
addSmeltingRecipeForBlock(Blocks.COBBLESTONE, new ItemStack(Blocks.STONE), 0.1F);
addSmeltingRecipe(new ItemStack(Blocks.STONEBRICK, 1, BlockStoneBrick.DEFAULT_META), new ItemStack(Blocks.STONEBRICK, 1, BlockStoneBrick.CRACKED_META), 0.1F);
addSmelting(Items.CLAY_BALL, new ItemStack(Items.BRICK), 0.3F);
addSmeltingRecipeForBlock(Blocks.CLAY, new ItemStack(Blocks.HARDENED_CLAY), 0.35F);
addSmeltingRecipeForBlock((Block)Blocks.CACTUS, new ItemStack(Items.DYE, 1, EnumDyeColor.GREEN.getDyeDamage()), 0.2F);
addSmeltingRecipeForBlock(Blocks.LOG, new ItemStack(Items.COAL, 1, 1), 0.15F);
addSmeltingRecipeForBlock(Blocks.LOG2, new ItemStack(Items.COAL, 1, 1), 0.15F);
addSmeltingRecipeForBlock(Blocks.EMERALD_ORE, new ItemStack(Items.EMERALD), 1.0F);
addSmelting(Items.POTATO, new ItemStack(Items.BAKED_POTATO), 0.35F);
addSmeltingRecipeForBlock(Blocks.NETHERRACK, new ItemStack(Items.NETHERBRICK), 0.1F);
addSmeltingRecipe(new ItemStack(Blocks.SPONGE, 1, 1), new ItemStack(Blocks.SPONGE, 1, 0), 0.15F);
addSmelting(Items.CHORUS_FRUIT, new ItemStack(Items.CHORUS_FRUIT_POPPED), 0.1F);
byte b;
int i;
ItemFishFood.FishType[] arrayOfFishType;
for (i = (arrayOfFishType = ItemFishFood.FishType.values()).length, b = 0; b < i; ) {
ItemFishFood.FishType itemfishfood$fishtype = arrayOfFishType[b];
if (itemfishfood$fishtype.canCook())
addSmeltingRecipe(new ItemStack(Items.FISH, 1, itemfishfood$fishtype.getMetadata()), new ItemStack(Items.COOKED_FISH, 1, itemfishfood$fishtype.getMetadata()), 0.35F);
b++;
}
addSmeltingRecipeForBlock(Blocks.COAL_ORE, new ItemStack(Items.COAL), 0.1F);
addSmeltingRecipeForBlock(Blocks.REDSTONE_ORE, new ItemStack(Items.REDSTONE), 0.7F);
addSmeltingRecipeForBlock(Blocks.LAPIS_ORE, new ItemStack(Items.DYE, 1, EnumDyeColor.BLUE.getDyeDamage()), 0.2F);
addSmeltingRecipeForBlock(Blocks.QUARTZ_ORE, new ItemStack(Items.QUARTZ), 0.2F);
addSmelting((Item)Items.CHAINMAIL_HELMET, new ItemStack(Items.field_191525_da), 0.1F);
addSmelting((Item)Items.CHAINMAIL_CHESTPLATE, new ItemStack(Items.field_191525_da), 0.1F);
addSmelting((Item)Items.CHAINMAIL_LEGGINGS, new ItemStack(Items.field_191525_da), 0.1F);
addSmelting((Item)Items.CHAINMAIL_BOOTS, new ItemStack(Items.field_191525_da), 0.1F);
addSmelting(Items.IRON_PICKAXE, new ItemStack(Items.field_191525_da), 0.1F);
addSmelting(Items.IRON_SHOVEL, new ItemStack(Items.field_191525_da), 0.1F);
addSmelting(Items.IRON_AXE, new ItemStack(Items.field_191525_da), 0.1F);
addSmelting(Items.IRON_HOE, new ItemStack(Items.field_191525_da), 0.1F);
addSmelting(Items.IRON_SWORD, new ItemStack(Items.field_191525_da), 0.1F);
addSmelting((Item)Items.IRON_HELMET, new ItemStack(Items.field_191525_da), 0.1F);
addSmelting((Item)Items.IRON_CHESTPLATE, new ItemStack(Items.field_191525_da), 0.1F);
addSmelting((Item)Items.IRON_LEGGINGS, new ItemStack(Items.field_191525_da), 0.1F);
addSmelting((Item)Items.IRON_BOOTS, new ItemStack(Items.field_191525_da), 0.1F);
addSmelting(Items.IRON_HORSE_ARMOR, new ItemStack(Items.field_191525_da), 0.1F);
addSmelting(Items.GOLDEN_PICKAXE, new ItemStack(Items.GOLD_NUGGET), 0.1F);
addSmelting(Items.GOLDEN_SHOVEL, new ItemStack(Items.GOLD_NUGGET), 0.1F);
addSmelting(Items.GOLDEN_AXE, new ItemStack(Items.GOLD_NUGGET), 0.1F);
addSmelting(Items.GOLDEN_HOE, new ItemStack(Items.GOLD_NUGGET), 0.1F);
addSmelting(Items.GOLDEN_SWORD, new ItemStack(Items.GOLD_NUGGET), 0.1F);
addSmelting((Item)Items.GOLDEN_HELMET, new ItemStack(Items.GOLD_NUGGET), 0.1F);
addSmelting((Item)Items.GOLDEN_CHESTPLATE, new ItemStack(Items.GOLD_NUGGET), 0.1F);
addSmelting((Item)Items.GOLDEN_LEGGINGS, new ItemStack(Items.GOLD_NUGGET), 0.1F);
addSmelting((Item)Items.GOLDEN_BOOTS, new ItemStack(Items.GOLD_NUGGET), 0.1F);
addSmelting(Items.GOLDEN_HORSE_ARMOR, new ItemStack(Items.GOLD_NUGGET), 0.1F);
addSmeltingRecipe(new ItemStack(Blocks.STAINED_HARDENED_CLAY, 1, EnumDyeColor.WHITE.getMetadata()), new ItemStack(Blocks.field_192427_dB), 0.1F);
addSmeltingRecipe(new ItemStack(Blocks.STAINED_HARDENED_CLAY, 1, EnumDyeColor.ORANGE.getMetadata()), new ItemStack(Blocks.field_192428_dC), 0.1F);
addSmeltingRecipe(new ItemStack(Blocks.STAINED_HARDENED_CLAY, 1, EnumDyeColor.MAGENTA.getMetadata()), new ItemStack(Blocks.field_192429_dD), 0.1F);
addSmeltingRecipe(new ItemStack(Blocks.STAINED_HARDENED_CLAY, 1, EnumDyeColor.LIGHT_BLUE.getMetadata()), new ItemStack(Blocks.field_192430_dE), 0.1F);
addSmeltingRecipe(new ItemStack(Blocks.STAINED_HARDENED_CLAY, 1, EnumDyeColor.YELLOW.getMetadata()), new ItemStack(Blocks.field_192431_dF), 0.1F);
addSmeltingRecipe(new ItemStack(Blocks.STAINED_HARDENED_CLAY, 1, EnumDyeColor.LIME.getMetadata()), new ItemStack(Blocks.field_192432_dG), 0.1F);
addSmeltingRecipe(new ItemStack(Blocks.STAINED_HARDENED_CLAY, 1, EnumDyeColor.PINK.getMetadata()), new ItemStack(Blocks.field_192433_dH), 0.1F);
addSmeltingRecipe(new ItemStack(Blocks.STAINED_HARDENED_CLAY, 1, EnumDyeColor.GRAY.getMetadata()), new ItemStack(Blocks.field_192434_dI), 0.1F);
addSmeltingRecipe(new ItemStack(Blocks.STAINED_HARDENED_CLAY, 1, EnumDyeColor.SILVER.getMetadata()), new ItemStack(Blocks.field_192435_dJ), 0.1F);
addSmeltingRecipe(new ItemStack(Blocks.STAINED_HARDENED_CLAY, 1, EnumDyeColor.CYAN.getMetadata()), new ItemStack(Blocks.field_192436_dK), 0.1F);
addSmeltingRecipe(new ItemStack(Blocks.STAINED_HARDENED_CLAY, 1, EnumDyeColor.PURPLE.getMetadata()), new ItemStack(Blocks.field_192437_dL), 0.1F);
addSmeltingRecipe(new ItemStack(Blocks.STAINED_HARDENED_CLAY, 1, EnumDyeColor.BLUE.getMetadata()), new ItemStack(Blocks.field_192438_dM), 0.1F);
addSmeltingRecipe(new ItemStack(Blocks.STAINED_HARDENED_CLAY, 1, EnumDyeColor.BROWN.getMetadata()), new ItemStack(Blocks.field_192439_dN), 0.1F);
addSmeltingRecipe(new ItemStack(Blocks.STAINED_HARDENED_CLAY, 1, EnumDyeColor.GREEN.getMetadata()), new ItemStack(Blocks.field_192440_dO), 0.1F);
addSmeltingRecipe(new ItemStack(Blocks.STAINED_HARDENED_CLAY, 1, EnumDyeColor.RED.getMetadata()), new ItemStack(Blocks.field_192441_dP), 0.1F);
addSmeltingRecipe(new ItemStack(Blocks.STAINED_HARDENED_CLAY, 1, EnumDyeColor.BLACK.getMetadata()), new ItemStack(Blocks.field_192442_dQ), 0.1F);
}
public void addSmeltingRecipeForBlock(Block input, ItemStack stack, float experience) {
addSmelting(Item.getItemFromBlock(input), stack, experience);
}
public void addSmelting(Item input, ItemStack stack, float experience) {
addSmeltingRecipe(new ItemStack(input, 1, 32767), stack, experience);
}
public void addSmeltingRecipe(ItemStack input, ItemStack stack, float experience) {
this.smeltingList.put(input, stack);
this.experienceList.put(stack, Float.valueOf(experience));
}
public ItemStack getSmeltingResult(ItemStack stack) {
for (Map.Entry<ItemStack, ItemStack> entry : this.smeltingList.entrySet()) {
if (compareItemStacks(stack, entry.getKey()))
return entry.getValue();
}
return ItemStack.field_190927_a;
}
private boolean compareItemStacks(ItemStack stack1, ItemStack stack2) {
return (stack2.getItem() == stack1.getItem() && (stack2.getMetadata() == 32767 || stack2.getMetadata() == stack1.getMetadata()));
}
public Map<ItemStack, ItemStack> getSmeltingList() {
return this.smeltingList;
}
public float getSmeltingExperience(ItemStack stack) {
for (Map.Entry<ItemStack, Float> entry : this.experienceList.entrySet()) {
if (compareItemStacks(stack, entry.getKey()))
return ((Float)entry.getValue()).floatValue();
}
return 0.0F;
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\item\crafting\FurnaceRecipes.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/
|
package nl.jtosti.hermes.location.controller;
import nl.jtosti.hermes.company.Company;
import nl.jtosti.hermes.company.CompanyServiceInterface;
import nl.jtosti.hermes.config.V1ApiController;
import nl.jtosti.hermes.location.Location;
import nl.jtosti.hermes.location.LocationServiceInterface;
import nl.jtosti.hermes.location.dto.ExtendedLocationDTO;
import nl.jtosti.hermes.location.dto.LocationDTO;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.stream.Collectors;
@RestController
@V1ApiController
public class LocationController {
private final ModelMapper modelMapper;
private final LocationServiceInterface locationService;
private final CompanyServiceInterface companyService;
@Autowired
LocationController(LocationServiceInterface locationService, ModelMapper modelMapper, CompanyServiceInterface companyService) {
this.locationService = locationService;
this.modelMapper = modelMapper;
this.companyService = companyService;
}
/**
* @return DTO List of all locations
*/
@GetMapping("/locations")
@ResponseStatus(HttpStatus.OK)
public List<LocationDTO> getAllLocations() {
List<Location> locations = locationService.getAllLocations();
return locations.stream()
.map(this::convertToExtendedDTO)
.collect(Collectors.toList());
}
/**
* @param locationDTO Location data
* @param companyId Id of the to be parent company
* @return Created location
*/
@PostMapping("/companies/{companyId}/locations")
@ResponseStatus(HttpStatus.CREATED)
public LocationDTO addLocation(@RequestBody ExtendedLocationDTO locationDTO, @PathVariable Long companyId) {
Location location = convertToEntity(locationDTO);
Company company = companyService.getCompanyById(companyId);
location.setCompany(company);
Location newLocation = locationService.save(location);
return convertToExtendedDTO(newLocation);
}
/**
* @param companyId Company id to return the locations of
* @return List of locations from the company
*/
@GetMapping("/companies/{companyId}/locations")
@ResponseStatus(HttpStatus.OK)
public List<LocationDTO> getLocationsByCompanyId(@PathVariable Long companyId) {
List<Location> locations = locationService.getLocationsByCompanyId(companyId);
return locations.stream()
.map(this::convertToDTO)
.collect(Collectors.toList());
}
/**
* @param locationId Location id to return
* @return location
*/
@GetMapping("/locations/{locationId}")
@ResponseStatus(HttpStatus.OK)
public LocationDTO getSingleLocation(@PathVariable Long locationId) {
return convertToExtendedDTO(locationService.getLocationById(locationId));
}
/**
* @param locationDTO updated location data
* @param locationId location id to be updated
* @return updated location
*/
@PutMapping("/locations/{locationId}")
@ResponseStatus(HttpStatus.OK)
public LocationDTO updateLocation(@RequestBody ExtendedLocationDTO locationDTO, @PathVariable Long locationId) {
Location location = convertToEntity(locationDTO);
location.setId(locationId);
Location updatedLocation = locationService.update(location);
return convertToExtendedDTO(updatedLocation);
}
/**
* @param locationId location id to be deleted
*/
@DeleteMapping("/locations/{locationId}")
@ResponseStatus(HttpStatus.OK)
public void deleteLocation(@PathVariable Long locationId) {
locationService.delete(locationId);
}
/**
* @param locationId Location with company to be removed
* @param companyId Company to be removed from location
* @return updated location
*/
@DeleteMapping("/locations/{locationId}/advertising/{companyId}")
@ResponseStatus(HttpStatus.OK)
public ExtendedLocationDTO removeAdvertisingCompanyFromLocation(@PathVariable Long locationId, @PathVariable Long companyId) {
Location location = locationService.getLocationById(locationId);
Company company = companyService.getCompanyById(companyId);
return convertToExtendedDTO(locationService.removeAdvertisingCompanyFromLocation(location, company));
}
/**
* @param companyId company id
* @return list of advertising companies from the company
*/
@GetMapping("/companies/{companyId}/advertising")
@ResponseStatus(HttpStatus.OK)
public List<ExtendedLocationDTO> getAdvertisingLocationsByCompanyId(@PathVariable Long companyId) {
List<Location> locations = locationService.getAdvertisingLocationsByCompanyId(companyId);
return locations.stream()
.map(this::convertToExtendedDTO)
.collect(Collectors.toList());
}
/**
* @param userId user to get locations
* @return list of all personal and advertising location from user
*/
@GetMapping("/users/{userId}/locations")
@ResponseStatus(HttpStatus.OK)
public List<ExtendedLocationDTO> getAllLocationsByUserId(@PathVariable Long userId) {
List<Location> locations = locationService.getAllLocationsByUserId(userId);
return locations.stream()
.map(this::convertToExtendedDTO)
.collect(Collectors.toList());
}
/**
* @param userId user to get advertising locations
* @return list of all advertising locations from user
*/
@GetMapping("/users/{userId}/locations/advertising")
@ResponseStatus(HttpStatus.OK)
public List<ExtendedLocationDTO> getAdvertisingLocationsByUserId(@PathVariable Long userId) {
List<Location> locations = locationService.getAdvertisingLocationsByUserId(userId);
return locations.stream()
.map(this::convertToExtendedDTO)
.collect(Collectors.toList());
}
/**
* @param userId user to get personal locations
* @return list of all personal locations from user
*/
@GetMapping("/users/{userId}/locations/personal")
@ResponseStatus(HttpStatus.OK)
public List<ExtendedLocationDTO> getPersonalLocationsByUserId(@PathVariable Long userId) {
List<Location> locations = locationService.getPersonalLocationsByUserId(userId);
return locations.stream()
.map(this::convertToExtendedDTO)
.collect(Collectors.toList());
}
/**
* @param location location to be turned into {@link ExtendedLocationDTO}
* @return LocationDTO
*/
private ExtendedLocationDTO convertToExtendedDTO(Location location) {
return modelMapper.map(location, ExtendedLocationDTO.class);
}
/**
* @param location location to be turned into {@link LocationDTO}
* @return LocationDTO
*/
private LocationDTO convertToDTO(Location location) {
return modelMapper.map(location, LocationDTO.class);
}
/**
* @param locationDTO DTO to be turned into {@link Location}
* @return location
*/
private Location convertToEntity(LocationDTO locationDTO) {
return modelMapper.map(locationDTO, Location.class);
}
}
|
package com.hjtech.base.retroft.provide.impl;
import android.content.Context;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.google.gson.GsonBuilder;
import com.hjtech.base.retroft.Constant;
import com.hjtech.base.retroft.provide.OkHttpClientProvide;
import com.hjtech.base.retroft.provide.RetrofitProvide;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;
/*
* 项目名: HjtechARouterFrame
* 包名 com.hjtech.base.retroft
* 文件名: RetrofitProvide
* 创建者: ZJB
* 创建时间: 2017/10/25 on 17:45
* 描述: TODO
*/
@Route(path = "/net/retrofit")
public class RetrofitProvideImpl implements RetrofitProvide {
@Autowired
OkHttpClientProvide okHttpClientProvide;
@Override
public Retrofit getRetrofit(String url) {
return new Retrofit.Builder()
//字符串支持
.addConverterFactory(ScalarsConverterFactory.create())
//Gson支持
.addConverterFactory(GsonConverterFactory.create(new GsonBuilder()
.setLenient()
.create()
))
//支持RxJava
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(okHttpClientProvide.getOkHttpClient())
.baseUrl(url)
.build();
}
@Override
public Retrofit getRetrofit() {
return new Retrofit.Builder()
//字符串支持
.addConverterFactory(ScalarsConverterFactory.create())
//Gson支持
.addConverterFactory(GsonConverterFactory.create(new GsonBuilder()
.setLenient()
.create()
))
//支持RxJava
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(okHttpClientProvide.getOkHttpClient())
.baseUrl(Constant.BASE_URL)
.build();
}
@Override
public void init(Context context) {
ARouter.getInstance().inject(this);
}
}
|
package ch.fhnw.edu.cpib.cst.interfaces;
import ch.fhnw.edu.cpib.scanner.enumerations.Types;
public interface ICastOpr extends IProduction {
Types toAbsSyntax();
}
|
import java.util.Scanner;
public class MagicNumber {
static boolean isMagic(long N)
{
long num = N;
int digits = 0;
while(num > 0){
digits++;
num = num / 10;
}
num = N;
while(true) {
long remainder = num % 10;
long division = num / 10;
num = (long)Math.pow(10, digits - 1) * remainder + division;
if (num == N) break;
if (num % N != 0) return false;
}
return true;
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
long N = in.nextLong();
if (isMagic(N))
System.out.print("Yes");
else
System.out.print("No");
}
}
|
package com.example.radio.Interface;
import com.example.radio.Activity.Response;
import retrofit2.Call;
import retrofit2.http.POST;
public interface RetrofitApi {
@POST("/api/v1.0/email/send")
Call<Response> SendData();
}
|
package com.tencent.mm.plugin.soter_mp.a;
import android.app.Activity;
import com.tencent.mm.plugin.soter_mp.b.d;
import com.tencent.mm.plugin.soter_mp.b.e;
import com.tencent.mm.sdk.platformtools.ad;
import com.tencent.mm.sdk.platformtools.x;
import java.lang.ref.WeakReference;
public final class a {
public static final int oob = 1;
private static final /* synthetic */ int[] ooc = new int[]{oob};
public static c a(Activity activity, d dVar, e eVar) {
if ((dVar.oot & 1) != 0 && com.tencent.d.a.a.hy(ad.getContext())) {
return new b(new WeakReference(activity), dVar, eVar);
}
x.e("MicroMsg.SoterControllerFactory", "hy: no matching: %d", new Object[]{Byte.valueOf(dVar.oot)});
return null;
}
}
|
package com.jlgproject.model;
import java.io.Serializable;
/**
* Created by sunbeibei on 2017/6/28.
* 新增经营实体类
*/
public class ManageStateRequest implements Serializable {
private Long debtId;// 债事人ID
private String legalPersonName; //法人名称
private String phoneNumber;// 联系电话
private String taxNumber; //税号
private String address; // 联系地址
private String year;//所属年度
private String lastSales;// 上季度销售额
private String lastElectricityBills;//年度电费
private String perCapita;// 年度人均总值
private String employeeNum;// 现有人员总数
private String profitMargin;// 利润率
public Long getDebtId() {
return debtId;
}
public void setDebtId(Long debtId) {
this.debtId = debtId;
}
public String getLegalPersonName() {
return legalPersonName;
}
public void setLegalPersonName(String legalPersonName) {
this.legalPersonName = legalPersonName;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getTaxNumber() {
return taxNumber;
}
public void setTaxNumber(String taxNumber) {
this.taxNumber = taxNumber;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public String getLastSales() {
return lastSales;
}
public void setLastSales(String lastSales) {
this.lastSales = lastSales;
}
public String getLastElectricityBills() {
return lastElectricityBills;
}
public void setLastElectricityBills(String lastElectricityBills) {
this.lastElectricityBills = lastElectricityBills;
}
public String getPerCapita() {
return perCapita;
}
public void setPerCapita(String perCapita) {
this.perCapita = perCapita;
}
public String getEmployeeNum() {
return employeeNum;
}
public void setEmployeeNum(String employeeNum) {
this.employeeNum = employeeNum;
}
public String getProfitMargin() {
return profitMargin;
}
public void setProfitMargin(String profitMargin) {
this.profitMargin = profitMargin;
}
public String getGross() {
return gross;
}
public void setGross(String gross) {
this.gross = gross;
}
public String getTotalInvestment() {
return totalInvestment;
}
public void setTotalInvestment(String totalInvestment) {
this.totalInvestment = totalInvestment;
}
private String gross;// 总收入
private String totalInvestment;// 总投资
}
|
package com.one.sugarcane.sellerlogin.service;
import java.util.Set;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.one.sugarcane.sellerlogin.dao.SellerLoginDaoImpl;
import com.one.sugarcane.entity.SellerLogin;
import com.one.sugarcane.entity.SellerLoginLog;
import com.one.sugarcane.MD5Util.MD5Util;
/**
* 培训机构注册
* @author 张梦洲,王晟宇,崔允松
* @throws IOException
* @date 2018/4/30
*/
@Service
@Transactional(readOnly=false)
public class SellerLoginServiceImpl {
@Resource
private SellerLoginDaoImpl sellerLoginDaoImpl;
public SellerLogin Login(String name,String password){
SellerLogin sellerLogin = this.sellerLoginDaoImpl.findByName(name);
MD5Util md5 = new MD5Util();
if(sellerLogin != null){
if(md5.verify(password,sellerLogin.getPassword())){
return sellerLogin;
}else{
return null;
}
}
return null;
}
public void saveSellerLogin(SellerLogin sellerLogin) {
this.sellerLoginDaoImpl.saveSellerLogin(sellerLogin);
}
public void saveSellerLoginLog(SellerLoginLog sellerLoginLog) {
this.sellerLoginDaoImpl.saveSellerLoginLog(sellerLoginLog);
}
}
|
package com.tencent.mm.ac;
import com.tencent.mm.ab.b;
import com.tencent.mm.ab.b.a;
import com.tencent.mm.ab.e;
import com.tencent.mm.ab.l;
import com.tencent.mm.network.k;
import com.tencent.mm.network.q;
import com.tencent.mm.protocal.c.bgl;
import com.tencent.mm.protocal.c.bgm;
import com.tencent.mm.protocal.c.bgn;
import java.util.LinkedList;
public final class x extends l implements k {
private b diG;
private e diJ;
public x(LinkedList<bgl> linkedList) {
a aVar = new a();
aVar.dIG = new bgm();
aVar.dIH = new bgn();
aVar.uri = "/cgi-bin/micromsg-bin/reportcommand";
aVar.dIF = 2592;
aVar.dII = 176;
aVar.dIJ = 1000000176;
this.diG = aVar.KT();
((bgm) this.diG.dID.dIL).rtB = linkedList;
com.tencent.mm.sdk.platformtools.x.i("MicroMsg.NetSceneReportBrandSession", "reportcommand MsgReport size %d", new Object[]{Integer.valueOf(r0.rtB.size())});
}
public final void a(int i, int i2, int i3, String str, q qVar, byte[] bArr) {
this.diJ.a(i2, i3, str, this);
}
public final int getType() {
return 2592;
}
public final int a(com.tencent.mm.network.e eVar, e eVar2) {
this.diJ = eVar2;
return a(eVar, this.diG, this);
}
}
|
package com.pxene;
import java.util.List;
public class AmaxDevice {
private static final Character spacers = 0x09;
private static final Character charSpacers= 0x01;
private static final Character NULL = 0x02;
private String did;
private String dpid;
private String mac;
private String ua;
private String ip;
private String country;
private String carrier;
private String language;
private String make;
private String model;
private String os;
private String osv;
private Integer connectiontype;
private Integer devicetype;
private String loc;
private Float density;
private Integer sw;
private Integer sh;
private Integer orientation;
public String getDid() {
return did;
}
public void setDid(String did) {
this.did = did;
}
public String getDpid() {
return dpid;
}
public void setDpid(String dpid) {
this.dpid = dpid;
}
public String getMac() {
return mac;
}
public void setMac(String mac) {
this.mac = mac;
}
public String getUa() {
return ua;
}
public void setUa(String ua) {
this.ua = ua;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getCarrier() {
return carrier;
}
public void setCarrier(String carrier) {
this.carrier = carrier;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getOs() {
return os;
}
public void setOs(String os) {
this.os = os;
}
public String getOsv() {
return osv;
}
public void setOsv(String osv) {
this.osv = osv;
}
public Integer getConnectiontype() {
return connectiontype;
}
public void setConnectiontype(Integer connectiontype) {
this.connectiontype = connectiontype;
}
public Integer getDevicetype() {
return devicetype;
}
public void setDevicetype(Integer devicetype) {
this.devicetype = devicetype;
}
public String getLoc() {
return loc;
}
public void setLoc(String loc) {
this.loc = loc;
}
public Float getDensity() {
return density;
}
public void setDensity(Float density) {
this.density = density;
}
public Integer getSw() {
return sw;
}
public void setSw(Integer sw) {
this.sw = sw;
}
public Integer getSh() {
return sh;
}
public void setSh(Integer sh) {
this.sh = sh;
}
public Integer getOrientation() {
return orientation;
}
public void setOrientation(Integer orientation) {
this.orientation = orientation;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(this.isNull(this.getDid())).append(spacers)
.append(this.isNull(this.getDpid())).append(spacers)
.append(this.isNull(this.getMac())).append(spacers)
.append(this.isNull(this.getUa())).append(spacers)
.append(this.isNull(this.getIp())).append(spacers)
.append(this.isNull(this.getCountry())).append(spacers)
.append(this.isNull(this.getCarrier())).append(spacers)
.append(this.isNull(this.getLanguage())).append(spacers)
.append(this.isNull(this.getMake())).append(spacers)
.append(this.isNull(this.getModel())).append(spacers)
.append(this.isNull(this.getOs())).append(spacers)
.append(this.isNull(this.getOsv())).append(spacers)
.append(this.isNull(this.getConnectiontype())).append(spacers)
.append(this.isNull(this.getDevicetype())).append(spacers)
.append(this.isNull(this.getSw())).append(spacers)
.append(this.isNull(this.getSh())).append(spacers)
.append(this.isNull(this.getOrientation())).append(spacers)
.append(this.isNull(this.getDensity())).append(spacers)
.append(this.isNull(this.getLoc()));
return sb.toString();
}
@SuppressWarnings("unchecked")
private Object isNull(Object obj) {
String regexStr = String.valueOf(spacers);
if (null == obj) {
return NULL;
}
if (obj instanceof List) {
String result = "";
for (String string : (List<String>)obj) {
if (string.indexOf(regexStr) > -1) {
string.replaceAll(regexStr, "");
}
result += (string + charSpacers);
}
return result.substring(0, result.length() -1);
}
if (obj instanceof String) {
return ((String)obj).replaceAll(regexStr, "");
}
return obj;
}
}
|
package com.wanglu.movcat.util.constant;
public enum CountEnum {
commentCount("commentCount","评论数"),
praiseCount("praiseCount","点赞数"),
shareCount("shareCount","分享数"),
totalBrowsingCount("totalBrowsingCount","总浏览数"),
todayBrowsingCount("todayBrowsingCount","今日浏览数");
private String value;
private String name;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private CountEnum(String value, String name) {
this.value = value;
this.name = name;
}
}
|
package ru.nikozavr.auto.adapter;
import android.content.Context;
import android.graphics.Canvas;
import android.widget.ImageView;
import ru.nikozavr.auto.model.Model;
/**
* Created by nikozavr on 4/1/14.
*/
public class ImageForScrolling extends ImageView {
private Model _model;
public ImageForScrolling(Context context, Model model){
super(context);
_model = model;
setImageBitmap(_model.getTitleImage().getBitmap());
}
@Override
protected void onDraw(Canvas canvas)
{
// TODO Auto-generated method stub
setImageBitmap(_model.getTitleImage().getBitmap());
super.onDraw(canvas);
}
public Model getModel() { return _model; }
}
|
package com.tencent.mm.plugin.emoji.ui.v2;
import com.tencent.mm.model.am.b.a;
import com.tencent.mm.model.au;
import com.tencent.mm.model.c;
import com.tencent.mm.sdk.platformtools.x;
class EmojiStoreV2DesignerUI$8 implements a {
final /* synthetic */ EmojiStoreV2DesignerUI ipH;
EmojiStoreV2DesignerUI$8(EmojiStoreV2DesignerUI emojiStoreV2DesignerUI) {
this.ipH = emojiStoreV2DesignerUI;
}
public final void x(String str, boolean z) {
x.i("MicroMsg.emoji.EmojiStoreV2DesignerUI", "getContactCallBack username:%s,succ:%b", new Object[]{str, Boolean.valueOf(z)});
if (z) {
EmojiStoreV2DesignerUI emojiStoreV2DesignerUI = this.ipH;
au.HU();
EmojiStoreV2DesignerUI.a(emojiStoreV2DesignerUI, c.FR().Yg(str));
EmojiStoreV2DesignerUI.a(this.ipH);
}
}
}
|
package primerproyecto;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import javax.swing.JOptionPane;
import primerproyecto.Arbol_Binario.ArbolBinario;
import primerproyecto.Arbol_Binario.TercerProyecto;
public class Mensajeria extends javax.swing.JFrame {
public Mensajeria() {
initComponents();
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
Receptor = new javax.swing.JTextArea();
jScrollPane2 = new javax.swing.JScrollPane();
Asunto = new javax.swing.JTextArea();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jScrollPane3 = new javax.swing.JScrollPane();
NombreLista = new javax.swing.JTextArea();
jScrollPane5 = new javax.swing.JScrollPane();
Mensaje = new javax.swing.JTextArea();
Enviar = new javax.swing.JButton();
jLabel5 = new javax.swing.JLabel();
Regresar = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setFont(new java.awt.Font("Arial Black", 1, 24)); // NOI18N
jLabel1.setText("Enviar Mensajes usuario");
Receptor.setColumns(20);
Receptor.setRows(5);
jScrollPane1.setViewportView(Receptor);
Asunto.setColumns(20);
Asunto.setRows(5);
jScrollPane2.setViewportView(Asunto);
jLabel2.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel2.setText("Para:");
jLabel3.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel3.setText("Asunto:");
jLabel4.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel4.setText("Nombre Lista:");
NombreLista.setColumns(20);
NombreLista.setRows(5);
jScrollPane3.setViewportView(NombreLista);
Mensaje.setColumns(20);
Mensaje.setRows(5);
jScrollPane5.setViewportView(Mensaje);
Enviar.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
Enviar.setText("Enviar");
Enviar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
EnviarActionPerformed(evt);
}
});
jLabel5.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabel5.setText("Mensaje:");
Regresar.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
Regresar.setText("Regresar");
Regresar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
RegresarActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(Regresar, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 496, Short.MAX_VALUE)
.addComponent(jScrollPane5, javax.swing.GroupLayout.DEFAULT_SIZE, 496, Short.MAX_VALUE)
.addComponent(Enviar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(35, 35, 35)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 496, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 496, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addContainerGap(77, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 406, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(147, 147, 147))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(21, 21, 21)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, 34, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(4, 4, 4)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane5, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(Enviar, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(50, 50, 50)
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(Regresar, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(55, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void RegresarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RegresarActionPerformed
MensajeriaListas mj = new MensajeriaListas();
mj.setVisible(true);
this.setVisible(false);
}//GEN-LAST:event_RegresarActionPerformed
private void EnviarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EnviarActionPerformed
String receptor = Receptor.getText().toString();
String asunto = Asunto.getText().toString();
String nombreLista = NombreLista.getText().toString();
String mensaje = Mensaje.getText().toString();
if(receptor.length()>0 && asunto.length()>0 &&nombreLista.length()>0&&mensaje.length()>0)
{
TercerProyecto t = new TercerProyecto();
boolean condicion = t.Busqueda(nombreLista, receptor);
if(condicion == true)
{
DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
String fecha = dtf.format(now)+"";
//(String emisor,String receptor,String mensaje,String asunto,String adjunto,String fecha)
String emisor = "";
t.ArchivoTipoArbolBinario(emisor, receptor, mensaje, asunto,nombreLista, fecha,"0");
MensajeriaListas m = new MensajeriaListas();
m.setVisible(true);
this.setVisible(false);
}
if(condicion == false)
{
JOptionPane.showMessageDialog(null,"Usuario No existente pruebe de nuevo");
NombreLista.setText("");
Receptor.setText("");
}
}
else
{
JOptionPane.showMessageDialog(null,"Debe de llenar todos los campos");
}
}//GEN-LAST:event_EnviarActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Mensajeria.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Mensajeria.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Mensajeria.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Mensajeria.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Mensajeria().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTextArea Asunto;
private javax.swing.JButton Enviar;
private javax.swing.JTextArea Mensaje;
private javax.swing.JTextArea NombreLista;
private javax.swing.JTextArea Receptor;
private javax.swing.JButton Regresar;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JScrollPane jScrollPane5;
// End of variables declaration//GEN-END:variables
}
|
/**
* My solution is sample, just create a new N * N matrix to store the new matrix.
* just move the column of matrix to the top
*/
public class Solution07 {
public static int[][] rotatematrix(int[][] matrix) {
int n = matrix.length;
int[][] result = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
result[j][n-1-i] = matrix[i][j];
}
}
return result;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[][] martrix = new int[5][5];
for (int i = 0; i < 5; i++)
for (int j = 0; j < 5; j++)
martrix[i][j] = i+j;
System.out.println("Before rotation:");
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
System.out.print(martrix[i][j]);
}
System.out.println();
}
System.out.println("After rotation: ");
int[][] afterrotate = rotatematrix(martrix);
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
System.out.print(afterrotate[i][j]);
}
System.out.println();
}
}
}
|
package com.lc.exstreetseller.activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import com.lc.exstreetseller.R;
import com.lc.exstreetseller.base.BaseActivity;
import com.lc.exstreetseller.constant.Constant;
import com.lc.exstreetseller.view.CountDownTextView;
import butterknife.BindView;
import butterknife.OnClick;
public class BindPhoneActivity extends BaseActivity {
@BindView(R.id.tv_bind_phone_old_phone)
TextView oldPhoneTv;
@BindView(R.id.et_bind_phone_old_phone_msg_code)
EditText oldPhoneMsgCodeEt;
@BindView(R.id.tv_bind_phone_get_old_phone_msg_code)
CountDownTextView getOldPhoneMsgCodeTv;
@BindView(R.id.et_bind_phone_new_phone)
EditText newPhoneEt;
@BindView(R.id.et_bind_phone_new_phone_msg_code)
EditText newPhoneMsgCodeEt;
@BindView(R.id.tv_bind_phone_get_new_phone_msg_code)
CountDownTextView getNewPhoneMsgCodeTv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bind_phone);
initView();
}
private void initView() {
setETitle("更换绑定手机");
getTitleView().setLeftIcon(R.mipmap.black_fh);
oldPhoneTv.setText("123456789");
}
@OnClick({R.id.tv_bind_phone_get_old_phone_msg_code,
R.id.tv_bind_phone_get_new_phone_msg_code,
R.id.tv_bind_phone_sure})
public void click(View v) {
switch (v.getId()) {
case R.id.tv_bind_phone_get_old_phone_msg_code:
getOldPhoneMsgCodeTv.startCountDown(Constant.get_msg_code_count_down_time);
break;
case R.id.tv_bind_phone_get_new_phone_msg_code:
getNewPhoneMsgCodeTv.startCountDown(Constant.get_msg_code_count_down_time);
break;
case R.id.tv_bind_phone_sure:
showToast("确定");
break;
default:
break;
}
}
}
|
package com.rms.risproject.vo;
import lombok.Data;
import java.io.Serializable;
@Data
public class BaseUserVO implements Serializable{
private static final long serialVersionUID = 1L;
private String keyId;
private String code;
private String name;
private String phoneNo;
}
|
/*
* 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 com.hilman.test.etiqa.sql_module.service;
import com.hilman.test.etiqa.sql_module.service.pojo.auth.LoginRequest;
import com.hilman.test.etiqa.sql_module.service.pojo.auth.Response;
/**
*
* @author hilmananwarsah
*/
public interface AuthService {
public Response<String> login(LoginRequest mLoginRequest);
public Response<String> loginTeacher(LoginRequest mLoginRequest);
public Response<String> loginAdmin(LoginRequest mLoginRequest);
}
|
package com.demo.invoicescanner.controller;
import com.demo.invoicescanner.entities.CustomerInvoice;
import com.demo.invoicescanner.entities.Item;
import com.demo.invoicescanner.service.CustomerInvoiceService;
import com.demo.invoicescanner.util.InvoiceScannerUtility;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
@RestController
@RequestMapping("/customer")
public class CustomerInvoiceController {
@Autowired
private CustomerInvoiceService operations;
@PostMapping(value = "/upload", produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public void uploadInvoice(@RequestBody MultipartFile file) {
operations.uploadInvoice(InvoiceScannerUtility.storeFile(file));
}
@PostMapping(value = "/uploadTemp")
public void uploadInvoice() {
operations.uploadInvoice(InvoiceScannerUtility.storeFile(null));
}
@GetMapping(value = "/getInvoice/{id}")
public CustomerInvoice getInvoice(@PathVariable long id) {
return operations.getInvoice(id);
}
@GetMapping(value = "/getItems/{id}")
public List<Item> getInvoiceItems(@PathVariable long id) {
return operations.getInvoiceItems(id);
}
@GetMapping(value = "/getStatus/{id}")
public boolean getInvoiceStatus(long id) {
return operations.getInvoiceStatus(id);
}
}
|
package com.jj.dw.restful.resource;
import com.jj.dw.ServiceLogic.TableOps;
import com.jj.dw.dbClient.ClientFactory;
import com.jj.dw.dbClient.MyClient;
import com.jj.dw.dbClient.ToJson;
import com.jj.dw.restful.util.GlobalConf;
import com.jj.dw.restful.util.JsonExtractor;
import com.jj.dw.restful.util.PageTools;
import org.apache.hadoop.conf.Configuration;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.util.List;
/**
* Created by weizh on 2016/8/17.
*/
@Path("table")
public class table {
GlobalConf gc = GlobalConf.getGlobalConf();
Configuration conf = gc.conf;
String mySqlUrl = conf.get("com.jj.dw.mysql","ip_instead_tmp:3306");
String storeDb = conf.get("com.jj.dw.mysql.db", "WZH");
String subjectTabName = conf.get("com.jj.dw.mysql.subjectTableName","subject");
String virtual_dbTabName = conf.get("com.jj.dw.mysql.virtual_dbTableName","virtual_db");
String tableTabName = conf.get("com.jj.dw.mysql.tableTableName","table");
String subDbTabName = conf.get("com.jj.dw.mysql.sub_dbTabName","sub_db");
String dbTabTabName = conf.get("com.jj.dw.mysql.db_tableTabName","db_table");
String url = "jdbc:mysql://" + mySqlUrl;
MyClient mj = new ClientFactory().createClient("mysqljdbc") ;
String errorInfo = null;
/**
* "tables" Table Structrue :
* id | name | phy_src_location | table_meta |
* restful sample:
* [Path]/{"name":"table_name","dbserver":"ip_instead_tmp:10000","dbname":"DbName",
* "subject":"Subject", "subtitle":"SubTitle", "tablemeta":JsonString }
**/
@GET
@Path("{table}")
@Produces(MediaType.APPLICATION_JSON)
public String ShowTable(@PathParam("table") String table,
@Context org.glassfish.grizzly.http.server.Request request) {
String name = JsonExtractor.getStrVal(table, "name");
String dbServer = JsonExtractor.getStrVal(table, "dbserver");
String dbname = JsonExtractor.getStrVal(table, "dbname");
if( name == null || dbServer == null || dbname == null ) {
errorInfo = "Require {\"name\":\"table_name\",\"dbserver\":\"ip_instead_tmp:10000\",\"dbname\":\"DbName\"} ";
return errorInfo;
}
String location = dbServer + ":" + dbname;
String sql = "select * from " + storeDb + "." + tableTabName + " where name='" + name
+ "' and phy_src_location='" + location + "'" ;
List<Object> res = mj.output(url,sql);
String logInfo = mySqlUrl + " " + sql;
System.out.println(PageTools.printLog(PageTools.getIpAddr(request), logInfo));
return ToJson.toJson(res) ;
}
@POST
@Path("{table}")
@Produces(MediaType.APPLICATION_JSON)
public String AddTable( @PathParam("table") String table,
@Context org.glassfish.grizzly.http.server.Request request) {
System.out.println("Debug Info : " + table);
String name = JsonExtractor.getStrVal(table, "name");
System.out.println("Debug Info : " + name);
String subject = JsonExtractor.getStrVal(table, "subject");
String dbServer = JsonExtractor.getStrVal(table, "dbserver");
String dbname = JsonExtractor.getStrVal(table, "dbname");
System.out.println("Debug Info : " + dbname);
String tableMeta = JsonExtractor.getStrVal(table, "tablemeta");
//String tableMeta ="123456";
String subtitle = JsonExtractor.getStrVal(table, "subtitle");
System.out.println("Debug Info : " + tableMeta);
if(name == null || subject == null || dbServer == null || dbname == null || tableMeta == null ){
errorInfo = "Info is not complete! Require: {\"name\":\"table_name\"," +
"\"dbserver\":\"ip_instead_tmp:10000\",\"dbname\":\"DbName\",\n" +
" * \"subject\":\"Subject\", \"subtitle\":\"SubTitle\", \"tablemeta\":JsonString }";
return errorInfo;
}
boolean res = TableOps.AddTableRow(subject, subtitle, name, dbServer, dbname, tableMeta );
if(!res) {
errorInfo = "Add table" + name +" failed, Plz check log ";
}else {
errorInfo = "Add table " + name +" successfully!";
}
System.out.println(PageTools.printLog(PageTools.getIpAddr(request), errorInfo));
return errorInfo ;
}
@DELETE
@Path("{table}")
@Produces(MediaType.APPLICATION_JSON)
public String DelTable(@PathParam("table") String table,
@Context org.glassfish.grizzly.http.server.Request request) {
String name = JsonExtractor.getStrVal(table, "name");
String dbServer = JsonExtractor.getStrVal(table, "dbserver");
String dbname = JsonExtractor.getStrVal(table, "dbname");
if( name == null || dbServer == null || dbname == null ) {
errorInfo = "Require {\"name\":\"table_name\",\"dbserver\":\"ip_instead_tmp:10000\",\"dbname\":\"DbName\"} ";
return errorInfo;
}
String location = dbServer + ":" + dbname;
String tabId = TableOps.GetTableId(name,location);
if(tabId == null) {
errorInfo = PageTools.errorMsgMaker("tabid", name);
System.out.println(PageTools.printLog(PageTools.getIpAddr(request), errorInfo));
return errorInfo;
}
String sql = "delete from " + storeDb + "." + tableTabName + " where table_id='" + tabId + "'";
List<Object> res = mj.output(url,sql);
String logInfo = mySqlUrl + " " + sql;
System.out.println(PageTools.printLog(PageTools.getIpAddr(request), logInfo));
sql = "delete from " + storeDb + "." + tableTabName +" where id='" + tabId + "'";
res = mj.output(url,sql);
logInfo = logInfo + "\n" + mySqlUrl + " " + sql;
System.out.println(PageTools.printLog(PageTools.getIpAddr(request), logInfo));
return ToJson.toJson(res);
}
}
|
package com.translator.domain.model.numeral;
import com.translator.domain.model.credits.Credits;
import java.util.List;
import static com.translator.domain.model.credits.Credits.credits;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
public enum RomanNumeral implements Cost {
M(credits(1000.0)),
D(credits(500.0)),
C(credits(100.0), canBeSubtractedFrom(M,D)),
L(credits(50.0)),
X(credits(10.0), canBeSubtractedFrom(C,L)),
V(credits(5.0)),
I(credits(1.0), canBeSubtractedFrom(X,V));
private Credits value;
private List<RomanNumeral> canSubtract;
RomanNumeral(Credits value) {
this.value = value;
this.canSubtract = emptyList();
}
RomanNumeral(Credits value, List<RomanNumeral> canSubtract) {
this.value = value;
this.canSubtract = canSubtract;
}
public Credits value() {
return value;
}
public Credits operation(Credits number) {
return value().plus(number);
}
public Cost next(Cost nextElement) {
Cost next = nextElement;
for(Cost subtractableNumeral : canSubtract) {
if(subtractableNumeral.equals(nextElement)) {
next = formula(subtractableNumeral);
}
}
return next;
}
public boolean greaterThanOrEqualTo(RomanNumeral anotherNumeral) {
return this.value.greaterThanOrEqualTo(anotherNumeral.value);
}
private static List<RomanNumeral> canBeSubtractedFrom(RomanNumeral... numerals) {
return asList(numerals);
}
private Cost formula(final Cost numeral) {
final Credits val = value();
return new Cost() {
public Credits value() {
return numeral.value().minus(val.multipliedByTwo());
}
public Credits operation(Credits number) {
return value().plus(number);
}
public Cost next(Cost nextElement) {
return nextElement;
}
};
}
}
|
package width_calc;
public class Square implements Width {
private int value1;
private int value2;
@Override
public void setData(int value1, int value2) {
this.value1 = value1;
this.value2 = value2;
}
@Override
public double cale() {
return (double)this.value1 * (double)this.value2;
}
}
|
import java.lang.reflect.Array;
import java.util.ArrayList;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceDialog;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Dialog;
import javafx.scene.control.Label;
import javafx.scene.control.TableCell;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.paint.PhongMaterial;
import javafx.scene.shape.Sphere;
import javafx.stage.Stage;
import javafx.stage.Window;
public class Main_page extends Application{
static ArrayList<Player> playerlist;
static ArrayList<Player> playerlistfinal;
public static void main(String[] args) {
playerlist=new ArrayList<Player>();
playerlist.add(new Player(0,Color.RED));
playerlist.add(new Player(1,Color.GREEN));
playerlist.add(new Player(2,Color.BROWN));
playerlist.add(new Player(3,Color.BLUE));
playerlist.add(new Player(4,Color.GRAY));
playerlist.add(new Player(5,Color.ORANGE));
playerlist.add(new Player(6,Color.DARKMAGENTA));
playerlist.add(new Player(7,Color.WHITE));
playerlistfinal =new ArrayList<Player>();
launch(args);
}
@Override
public void start(Stage primarystage) throws Exception {
primarystage.setTitle("Chain Reaction");
GridPane page=new GridPane();
page.setAlignment(Pos.TOP_CENTER);
ComboBox<String> nopd = new ComboBox<String>();
nopd.getItems().addAll(
"2",
"3",
"4",
"5",
"6",
"7",
"8"
);
nopd.setTranslateX(-50);
nopd.setTranslateY(15);
nopd.setPrefHeight(20);
nopd.setPrefWidth(30);
Label nop = new Label("No Of Players");
nop.setTranslateX(-150);
nop.setTranslateY(15);
page.getChildren().add(nop);
ComboBox<String> gridsize=new ComboBox<String>();
gridsize.getItems().addAll(
"9 * 6",
"15 * 10"
);
gridsize.setTranslateX(-50);
gridsize.setTranslateY(30);
gridsize.setPrefHeight(20);
gridsize.setPrefWidth(80);
Label gridsizel = new Label("Grid Size");
page.getChildren().add(gridsizel);
gridsizel.setTranslateX(-150);
gridsizel.setTranslateY(60);
Button newgame = new Button();
newgame.setTranslateX(-100);
newgame.setTranslateY(120);
newgame.setText("New Game");
Button settings = new Button();
settings.setTranslateX(-180);
settings.setTranslateY(120);
settings.setText("Settings");
settings.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Settings s = new Settings();
s.initializesettingspage(Integer.parseInt(nopd.getSelectionModel().getSelectedItem()));
}
});
Button resume = new Button();
resume.setTranslateX(-10);
resume.setTranslateY(120);
resume.setText("Resume");
page.add(nopd, 1,0);
page.add(gridsize, 1, 1);
page.add(newgame, 1, 1);
page.add(settings, 1, 1);
page.add(resume, 1, 1);
Sphere s=new Sphere(15);
PhongMaterial mat=new PhongMaterial();
mat.setDiffuseColor(Color.WHITE);
//mat.setDiffuseColor(Color.RED);
s.setMaterial(mat);
Scene scene=new Scene(page, 500, 500);
newgame.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
if(nopd.getSelectionModel().isEmpty()) {
Dialog<String> warning=new Dialog<String>();
warning.setContentText("Please Choose Number of players");
warning.show();
Window window = warning.getDialogPane().getScene().getWindow();
window.setOnCloseRequest(Event -> window.hide());
}else if (gridsize.getSelectionModel().isEmpty()) {
Dialog<String> warning=new Dialog<String>();
warning.setContentText("Please Choose GridSize");
warning.show();
Window window = warning.getDialogPane().getScene().getWindow();
window.setOnCloseRequest(Event -> window.hide());
}
else if(gridsize.getValue().equals("9 * 6")) {
for(int i=0;i<Integer.parseInt(nopd.getSelectionModel().getSelectedItem());i++) {
playerlistfinal.add(playerlist.get(i));
}
Grid3d gsmall=new Grid3d();
primarystage.close();
}else if(gridsize.getValue().equals("15 * 10")) {
for(int i=0;i<Integer.parseInt(nopd.getSelectionModel().getSelectedItem());i++) {
playerlistfinal.add(playerlist.get(i));
}
Grid3Dbig gbig=new Grid3Dbig();
primarystage.close();
}
}
});
primarystage.setScene(scene);
primarystage.show();
}
}
|
/*
* 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 com.hoc.model;
import java.math.BigDecimal;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import org.hibernate.annotations.Cascade;
/**
*
* @author patience
*/
@Entity
public class Invoice extends BaseEntity {
@ManyToOne //see available options
private User user;
@OneToOne //see available options
private Address address;
@OneToMany
@Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE, org.hibernate.annotations.CascadeType.DELETE})
private List<PurchaseOrder> orders;
private BigDecimal total;
@OneToOne ///see available options
private Payment paymentMethod;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public List<PurchaseOrder> getOrders() {
return orders;
}
public void setOrders(List<PurchaseOrder> orders) {
this.orders = orders;
}
public BigDecimal getTotal() {
return total;
}
public void setTotal(BigDecimal total) {
this.total = total;
}
public Payment getPaymentMethod() {
return paymentMethod;
}
public void setPaymentMethod(Payment paymentMethod) {
this.paymentMethod = paymentMethod;
}
}
|
package com.purchase;
import com.purchase.entity.PurchaseOrderDetailEntity;
import com.system.util.JsonUtil;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.WebApplicationContext;
import java.util.Date;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@WebAppConfiguration
@Transactional
@RunWith(SpringRunner.class)
@SpringBootTest
public class PurchaseOrderDetailControllerTest {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setUp() {
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
@Test
public void findListTest() throws Exception {
String result = mockMvc.perform(
get("/purchaseOrderDetail/findList")
).andExpect(status().isOk())
.andExpect(jsonPath("$.success").value(true))
.andReturn()
.getResponse()
.getContentAsString();
System.out.println("返回结果{" + result + "}");
}
@Test
public void findInfoTest() throws Exception {
String result = mockMvc.perform(
get("/purchaseOrderDetail/findInfo")
.param("purchaseDetailId", "1")
).andExpect(status().isOk())
.andExpect(jsonPath("$.success").value(true))
.andReturn()
.getResponse()
.getContentAsString();
System.out.println("返回结果{" + result + "}");
}
@Test
public void doInsertTest() throws Exception {
PurchaseOrderDetailEntity entity = new PurchaseOrderDetailEntity();
entity.setCreateTime(new Date());
entity.setUpdateTime(new Date());
entity.setColorName("红色");
entity.setCustomCode("0001");
entity.setProductBarcode("00000000");
entity.setProductDetailId(1);
entity.setProductPrice(188.0);
entity.setProductDiscount(1.0);
entity.setStoreId(1);
entity.setSizeName("27m");
String result = mockMvc.perform(
post("/purchaseOrderDetail/doInsert")
.contentType(MediaType.APPLICATION_PROBLEM_JSON_UTF8)
.content(JsonUtil.toJson(entity))
).andExpect(status().isOk())
.andExpect(jsonPath("$.success").value(true))
.andReturn()
.getResponse()
.getContentAsString();
System.out.println("返回结果{" + result + "}");
}
@Test
public void doUpdateTest() throws Exception {
PurchaseOrderDetailEntity entity = new PurchaseOrderDetailEntity();
entity.setCreateTime(new Date());
entity.setUpdateTime(new Date());
entity.setColorName("红色");
entity.setCustomCode("0001");
entity.setProductBarcode("00000000");
entity.setProductDetailId(1);
entity.setProductPrice(188.0);
entity.setProductDiscount(1.0);
entity.setStoreId(1);
entity.setSizeName("27m");
entity.setProductDetailId(1);
String result = mockMvc.perform(
post("/purchaseOrderDetail/doUpdate")
.contentType(MediaType.APPLICATION_PROBLEM_JSON_UTF8)
.content(JsonUtil.toJson(entity))
).andExpect(status().isOk())
.andExpect(jsonPath("$.success").value(true))
.andReturn()
.getResponse()
.getContentAsString();
System.out.println("返回结果{" + result + "}");
}
@Test
public void doDeleteTest() throws Exception {
String result = mockMvc.perform(
post("/purchaseOrderDetail/doUpdate")
.param("purchaseDetailId", "1")
).andExpect(status().isOk())
.andExpect(jsonPath("$.success").value(true))
.andReturn()
.getResponse()
.getContentAsString();
System.out.println("返回结果{" + result + "}");
}
}
|
package us.cownet.jforth;
import java.util.Scanner;
public class Terminal extends Word {
private static String operator = "([\\+\\-\\<\\>\\,\\.\\=\\!\\@\\#\\$%\\^\\&\\*\\(\\)\\[\\]\\{\\}]+)";
private static String keyword = "(\\w+\\:+)";
Scanner inputScanner = new Scanner(System.in);
public Terminal() {
}
public Token nextToken() {
if (inputScanner.hasNextInt()) {
return new Token(TokenType.NUMBER, inputScanner.nextInt());
} else if (inputScanner.hasNext(operator)) {
return new Token(TokenType.OPERATOR, inputScanner.next(operator));
} else if (inputScanner.hasNext(keyword)) {
return new Token(TokenType.KEWORD, inputScanner.next(keyword));
} else {
return new Token(TokenType.IDENTIFIER, inputScanner.next());
}
}
public void print(String message) {
System.out.println(message);
}
public enum TokenType {
UNKNOWN(0),
NUMBER(1),
OPERATOR(2),
KEWORD(3),
IDENTIFIER(4);
public int value;
TokenType(int value) {
this.value = value;
}
;
}
public static class Token {
public TokenType type;
public String value;
public int intValue;
public Token(TokenType type, String value) {
this.type = type;
this.value = value;
}
public Token(TokenType type, int value) {
this.type = type;
this.intValue = value;
}
public String toString() {
return "Token(" + type + ", " + value + ", " + intValue + ")";
}
}
public static void nextToken(ExecutionContext context) {
// ( terminal -- value type )
Token t = context.getTerminal().nextToken();
switch (t.type) {
case KEWORD:
case OPERATOR:
context.push(t.value);
break;
case NUMBER:
context.push(t.intValue);
break;
default:
context.push((Word) null);
break;
}
context.push(t.type.value);
}
public static void printString(ExecutionContext context) {
context.getTerminal().print(context.pop().toString());
}
}
|
package leetcode;
/*
* Given an unsorted integer array, find the smallest missing positive integer.
Example 1:
Input: [1,2,0]
Output: 3
Example 2:
Input: [3,4,-1,1]
Output: 2
Example 3:
Input: [7,8,9,11,12]
Output: 1
Note:
Your algorithm should run in O(n) time and uses constant extra space.
*/
public class _41_First_Missing_Positive {
public static void main(String[] args) {
// TODO Auto-generated method stub
_41_First_Missing_Positive o =new _41_First_Missing_Positive();
int nums[]={3,4,-1,1};
int ret= o.firstMissingPositive(nums);
System.out.println(ret);
}
public int firstMissingPositive(int[] nums) {
for(int i = 0; i < nums.length; i++){
while(nums[i] > 0 && nums[i] - 1 < nums.length && nums[i] - 1 != i && nums[nums[i]-1] != nums[i]){
swap(nums, i, nums[i] - 1);
}
}
int i = 0;
for(; i < nums.length; i++){
if(i + 1 != nums[i]) break;
}
return i + 1;
}
void swap(int[] nums, int i, int j){
int t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
}
|
package com.hedong.hedongwx.web.controller;
import java.io.IOException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.http.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.github.wxpay.sdk.WXPay;
import com.hedong.hedongwx.config.AlipayConfig;
import com.hedong.hedongwx.config.CommonConfig;
import com.hedong.hedongwx.dao.ChargeRecordHandler;
import com.hedong.hedongwx.dao.Equipmenthandler;
import com.hedong.hedongwx.dao.TradeRecordHandler;
import com.hedong.hedongwx.dao.UserHandler;
import com.hedong.hedongwx.entity.AllPortStatus;
import com.hedong.hedongwx.entity.Area;
import com.hedong.hedongwx.entity.ChargeRecord;
import com.hedong.hedongwx.entity.Equipment;
import com.hedong.hedongwx.entity.InCoins;
import com.hedong.hedongwx.entity.MerchantDetail;
import com.hedong.hedongwx.entity.TradeRecord;
import com.hedong.hedongwx.entity.User;
import com.hedong.hedongwx.entity.UserEquipment;
import com.hedong.hedongwx.mqtt.MqttPushClient;
import com.hedong.hedongwx.service.AllPortStatusService;
import com.hedong.hedongwx.service.AreaService;
import com.hedong.hedongwx.service.AuthorityService;
import com.hedong.hedongwx.service.ChargeRecordService;
import com.hedong.hedongwx.service.EquipmentService;
import com.hedong.hedongwx.service.GeneralDetailService;
import com.hedong.hedongwx.service.InCoinsService;
import com.hedong.hedongwx.service.MerchantDetailService;
import com.hedong.hedongwx.service.OfflineCardService;
import com.hedong.hedongwx.service.TradeRecordService;
import com.hedong.hedongwx.service.UserEquipmentService;
import com.hedong.hedongwx.service.UserService;
import com.hedong.hedongwx.thread.Server;
import com.hedong.hedongwx.utils.CommUtil;
import com.hedong.hedongwx.utils.DisposeUtil;
import com.hedong.hedongwx.utils.HttpRequest;
import com.hedong.hedongwx.utils.JedisUtils;
import com.hedong.hedongwx.utils.JsSignUtil;
import com.hedong.hedongwx.utils.PageUtils;
import com.hedong.hedongwx.utils.SendMsgUtil;
import com.hedong.hedongwx.utils.StringUtil;
import com.hedong.hedongwx.utils.TempMsgUtil;
import com.hedong.hedongwx.utils.WXPayConfigImpl;
import com.hedong.hedongwx.utils.WeiXinConfigParam;
import com.hedong.hedongwx.utils.WeixinUtil;
import com.hedong.hedongwx.utils.WolfHttpRequest;
import com.hedong.hedongwx.utils.XMLUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
@Controller
@EnableScheduling
public class HelloController {
@Autowired
private static final Logger logger = LoggerFactory.getLogger(HelloController.class);
@Autowired
private EquipmentService equipmentService;
@Autowired
private UserService userService;
@Autowired
private UserEquipmentService userEquipmentService;
@Autowired
private HttpServletRequest request;
@Autowired
private AllPortStatusService allPortStatusService;
@Autowired
private OfflineCardService offlineCardService;
@Autowired
private InCoinsService inCoinsService;
@Autowired
private MerchantDetailService merchantDetailService;
@Autowired
private TradeRecordService tradeRecordService;
@Autowired
private AreaService areaService;
@Autowired
private AuthorityService authorityService;
@Autowired
private ChargeRecordService chargeRecordService;
@Autowired
private GeneralDetailService generalDetailService;
@RequestMapping("/wolfConstomSendData")
@ResponseBody
public Map<String, Object> wolfConstomSendData(String param, String devicenum) {
SendMsgUtil.send_Param(param, devicenum);
return CommUtil.responseBuild(200, "数据发送成功", null);
}
@RequestMapping("/wolfchargeInfo")
@ResponseBody
public Map<String,String> wolfchargeInfo(String ordernum) {
Map<String, String> chargeInfoMap = JedisUtils.hgetAll(ordernum);
if (!DisposeUtil.checkMapIfHasValue(chargeInfoMap)) {
chargeInfoMap = new HashMap<>();
chargeInfoMap.put("wolfcode", "1001");
} else {
chargeInfoMap.put("wolfcode", "1000");
}
return chargeInfoMap;
}
/**
* @Description:设置设备当前的参数 0x32
* @param code: 设备号
* @param type: 0x01,表示 温度报警温度, 0x02表示 烟感的阈值 0x03 表示 当前设备的总功率
* @param value: 参数的值
* @author: origin
* @createTime:2020年5月11日下午4:48:13
*/
@RequestMapping("/setDeviceArgument")
@ResponseBody
public Map<String,String> setdeviceargument(String code, Byte type, Integer value) {
if (type == null) {
type = 0x01;
}
if (value == null) {
value = 0x00000064;
}
SendMsgUtil.send_0x32(type, value, code);
Map<String,String> map = new HashMap<>();
long currentTime = System.currentTimeMillis();
boolean flag = true;
int temp = 0;
while (flag) {
if (temp >=20) {
map.put("code", "0");
break;
}
Map<String, String> mapReply = Server.thresholdvalue.get(code);
if (mapReply == null || mapReply.size() < 1) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
temp++;
continue;
}
long udpatetime = Long.parseLong(mapReply.get("insttime"));
if ((udpatetime - currentTime) > 0 && (udpatetime - currentTime) < 20000) {
map.putAll(mapReply);
map.put("readtime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
flag = false;
break;
} else {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
temp++;
continue;
}
}
System.out.println("设置设备当前的参数 setDeviceArgument "+map);
return map;
}
/**
* @Description:上传当前充电桩温度(0x33)
* @param code: 设备号 NOW_TEMP(now_temp):当前充电桩温度
* @author: origin
* @createTime:2020年5月11日下午4:49:13
* @comment:
*/
@RequestMapping(value = "/uploadingTempe")
@ResponseBody
public Map<String, String> uploadingTempe(String code) {
Map<String, String> hashMap = new HashMap<>();
hashMap.put("code", code);
// Map<String, String> map = WolfHttpRequest.httpconnectwolf(hashMap, WolfHttpRequest.SEND_READSYSTEM_URL);
SendMsgUtil.send_0x33(code);
long currentTime = System.currentTimeMillis();
boolean flag = true;
int temp = 0;
Map<String, String> map = new HashMap<>();
while (flag) {
if (temp >=20) {
map.put("status", "0");
break;
}
Map<String, String> mapRevice = Server.uploadingMap.get(code);
if (mapRevice == null || mapRevice.size() < 1) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
temp++;
continue;
}
long udpatetime = Long.parseLong(mapRevice.get("insttime"));
if ((udpatetime - currentTime) > 0 && (udpatetime - currentTime) < 20000) {
map.putAll(mapRevice);
map.put("readtime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
flag = false;
Server.readsystemMap.remove(code);
break;
} else {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
temp++;
continue;
}
}
System.out.println("===" + JSON.toJSONString(map));
System.out.println("上传当前充电桩温度 uploadingTempe "+map);
return map;
}
/**
* @Description:获取当前设备的参数 0x34
* @param code:设备号
* @param type [设置参数类型] 0x01,表示 当前温度;0x02表示 当前烟量;0x03 表示 当前设备的总功率;0x04 表示 当前设备电表电量
* @author: origin
* @createTime:2020年5月11日下午4:51:43
* @comment:
*/
@RequestMapping(value = "/getDeviceNowArgument")
@ResponseBody
public Map<String, String> getDeviceNowArgument(byte type, String code) {
Map<String, String> hashMap = new HashMap<>();
hashMap.put("code", code);
// Map<String, String> map = WolfHttpRequest.httpconnectwolf(hashMap, WolfHttpRequest.SEND_READSYSTEM_URL);
SendMsgUtil.send_0x34(type, code);
long currentTime = System.currentTimeMillis();
boolean flag = true;
int temp = 0;
Map<String, String> map = new HashMap<>();
while (flag) {
if (temp >=20) {
map.put("status", "0");
break;
}
Map<String, String> mapRevice = Server.getParameMap.get(code);
if (mapRevice == null || mapRevice.size() < 1) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
temp++;
continue;
}
long udpatetime = Long.parseLong(mapRevice.get("insttime"));
if ((udpatetime - currentTime) > 0 && (udpatetime - currentTime) < 20000) {
map.putAll(mapRevice);
map.put("readtime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
flag = false;
Server.readsystemMap.remove(code);
break;
} else {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
temp++;
continue;
}
}
System.out.println("===" + JSON.toJSONString(map));
System.out.println("获取当前设备的参数度 getDeviceNowArgument "+map);
return map;
}
/**
* @Description:获取设备设置的参数 0x35
* @param type(设置参数类型):0x01,表示 板子保存的报警温度;0x02表示 板子保存的报警烟感;0x03 表示 板子保存的报警总功率
* @param code 设备号
* @author: origin 2020年5月11日下午5:27:42
*/
@RequestMapping(value = "/getDeviceSetArgument")
@ResponseBody
public Map<String, String> getDeviceSetArgument( byte type, String code) {
Map<String, String> hashMap = new HashMap<>();
hashMap.put("code", code);
// Map<String, String> map = WolfHttpRequest.httpconnectwolf(hashMap, WolfHttpRequest.SEND_READSYSTEM_URL);
SendMsgUtil.send_0x35( type, code);
long currentTime = System.currentTimeMillis();
boolean flag = true;
int temp = 0;
Map<String, String> map = new HashMap<>();
while (flag) {
if (temp >=20) {
map.put("status", "0");
break;
}
Map<String, String> mapRevice = Server.getArgumentMap.get(code);
if (mapRevice == null || mapRevice.size() < 1) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
temp++;
continue;
}
long udpatetime = Long.parseLong(mapRevice.get("insttime"));
if ((udpatetime - currentTime) > 0 && (udpatetime - currentTime) < 20000) {
map.putAll(mapRevice);
map.put("readtime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
flag = false;
Server.readsystemMap.remove(code);
break;
} else {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
temp++;
continue;
}
}
System.out.println("===" + JSON.toJSONString(map));
System.out.println("获取设备设置的参数 getDeviceSetArgument "+map);
return map;
}
/**
*
* @Description:报警(温度烟感功率保险丝继电器报警) 0x36
* @param type(设置参数类型): 0x01,温度报警;0x02烟量报警;0x03总功率报警;0x04 继电器粘连报警;0x05 保险丝断掉报警
* @param port: 端口号,参数只在TYPE为0x04和0x05时使用,其他为0xFF
* @param value: 温度 烟感 总功率的值 TYPE为0x04和0x05时 为0xffffffff
* @param code
* @author: origin 2020年5月11日下午5:29:39
*/
@RequestMapping(value = "/giveAnAlarm")
@ResponseBody
public Map<String, String> giveAnAlarm( byte type, byte port, int value, String code) {
Map<String, String> hashMap = new HashMap<>();
hashMap.put("code", code);
// Map<String, String> map = WolfHttpRequest.httpconnectwolf(hashMap, WolfHttpRequest.SEND_READSYSTEM_URL);
if(type==4 || type==5){
// 温度 烟感 总功率的值 TYPE为0x04和0x05时 为0xffffffff
value = 0xffffffff;
}else{
port = (byte) 0xFF;
}
SendMsgUtil.send_0x36(type, port, value, code);
long currentTime = System.currentTimeMillis();
boolean flag = true;
int temp = 0;
Map<String, String> map = new HashMap<>();
while (flag) {
if (temp >=20) {
map.put("status", "0");
break;
}
Map<String, String> mapRevice = Server.alarmMap.get(code);
if (mapRevice == null || mapRevice.size() < 1) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
temp++;
continue;
}
long udpatetime = Long.parseLong(mapRevice.get("insttime"));
if ((udpatetime - currentTime) > 0 && (udpatetime - currentTime) < 20000) {
map.putAll(mapRevice);
map.put("readtime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
flag = false;
Server.readsystemMap.remove(code);
break;
} else {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
temp++;
continue;
}
}
System.out.println("===" + JSON.toJSONString(map));
System.out.println("报警(温度烟感功率保险丝继电器报警) giveAnAlarm "+map);
return map;
}
@RequestMapping("/updradeInform")
@ResponseBody
public Map<String,String> updradeInform(String code) {
// SendMsgUtil.send_0x2F(code);
Map<String,String> map = new HashMap<>();
map.put("wolfcode", "1000");
map.put("wolfmsg", "success");
return map;
}
@RequestMapping("/updradeDataSend")
@ResponseBody
public Map<String,String> updradeDataSend() {
Map<String,String> map = new HashMap<>();
try {
MqttPushClient.sendUpgradeData();
map.put("wolfcode", "1000");
map.put("wolfmsg", "success");
} catch (Exception e) {
map.put("wolfcode", "1001");
map.put("wolfmsg", "fail");
}
return map;
}
@RequestMapping("/wolfmaininfo")
@ResponseBody
public Map<String,String> maininfo(String code) {
Map<String,String> map = new HashMap<>();
map.put("code", code);
return WolfHttpRequest.httpconnectwolf(map, WolfHttpRequest.SEND_MAININFO_URL);
// SendMsgUtil.send_0x23(code);
// long nowTime = System.currentTimeMillis();
// boolean flag = true;
// int temp = 0;
// while (flag) {
// if (temp >= 20) {
// Map<String,String> map = new HashMap<>();
// map.put("wolferror", "1001");
// map.put("wolfmsg", "连接超时,请检查设备是否在线或设备不含此功能");
// return map;
// }
// if (Server.maininfoMap != null) {
// Map<String, String> map = Server.maininfoMap.get(code);
// if (map != null) {
// long updateTime = Long.parseLong(map.get("updateTime"));
// if (updateTime - nowTime <= 20000 && updateTime - nowTime >= 0) {
// return map;
// } else {
// temp++;
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// continue;
// }
// } else {
// temp++;
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// continue;
// }
// } else {
// temp++;
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// continue;
// }
// }
// return null;
}
@RequestMapping("/wolfsetsys")
@ResponseBody
public Map<String, String> wolfsetsys(String code,int cst,int elec_pri) {
Map<String,String> map = new HashMap<>();
map.put("code", code);
map.put("cst", cst + "");
map.put("elec_pri", elec_pri + "");
return WolfHttpRequest.httpconnectwolf(map, WolfHttpRequest.SEND_NEWREADSYS_URL);
// SendMsgUtil.send_0x2a(code, (short)cst, (short)elec_pri);
// long nowTime = System.currentTimeMillis();
// boolean flag = true;
// int temp = 0;
// while (flag) {
// if (temp >= 20) {
// Map<String,String> map = new HashMap<>();
// map.put("wolferror", "1001");
// map.put("wolfmsg", "连接超时,请检查设备是否在线或设备不含此功能");
// return map;
// }
// if (Server.maininfoMap != null) {
// Map<String, String> map = Server.setSystemMap.get(code);
// if (map != null) {
// long updateTime = Long.parseLong(map.get("updateTime"));
// if (updateTime - nowTime <= 20000 && updateTime - nowTime >= 0) {
// return map;
// } else {
// temp++;
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// continue;
// }
// } else {
// temp++;
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// continue;
// }
// } else {
// temp++;
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// continue;
// }
// }
// return null;
}
@RequestMapping("/wolfreadsys")
@ResponseBody
public Map<String,String> wolfreadsys(String code) {
Map<String,String> map = new HashMap<>();
map.put("code", code);
return WolfHttpRequest.httpconnectwolf(map, WolfHttpRequest.SEND_NEWREADSYS_URL);
// SendMsgUtil.send_0x2b(code);
// long nowTime = System.currentTimeMillis();
// boolean flag = true;
// int temp = 0;
// while (flag) {
// if (temp >= 20) {
// Map<String,String> map = new HashMap<>();
// map.put("wolferror", "1001");
// map.put("wolfmsg", "连接超时,请检查设备是否在线或设备不含此功能");
// return map;
// }
// if (Server.maininfoMap != null) {
// Map<String, String> map = Server.readsystemMap.get(code);
// if (map != null) {
// long updateTime = Long.parseLong(map.get("updateTime"));
// if (updateTime - nowTime <= 20000 && updateTime - nowTime >= 0) {
// return map;
// } else {
// temp++;
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// continue;
// }
// } else {
// temp++;
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// continue;
// }
// } else {
// temp++;
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// continue;
// }
// }
// return null;
}
@RequestMapping("/wolftestpay")
@ResponseBody
public String wolftestpay(String code,int port,int money, int time, int elec, int chargeType) {
SendMsgUtil.send_0x27((byte)port, (short)money, (short)time, (short)elec, code, (byte)chargeType);
return "发送远程充电成功";
}
@RequestMapping("/getLocationBySendData")
@ResponseBody
public String getLocationBySendData(String code) {
SendMsgUtil.send_0x29(code);
return "1";
}
@RequestMapping("/getNormalAccessToken")
@ResponseBody
public String getNormalAccessToken() {
String accessToken = "";
try {
accessToken = WeixinUtil.getBasicAccessToken();
} catch (Exception e) {
e.printStackTrace();
}
return accessToken;
}
@RequestMapping("/wolfquery")
@ResponseBody
public Object wolfquery() {
System.out.println("---" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "---");
return Equipmenthandler.getAllSoftVersionIs00();
}
// @Scheduled(cron = "0 0 0 * * *")
@RequestMapping("/packageMonthTodaynumResetTask")
@ResponseBody
public Object packageMonthTodaynumReset() {
try {
userService.everydaynumReset();
System.out.println("每日重置包月当日剩余次数");
equipmentService.everydayResetEquEarn();
System.out.println("每日重置当日设备在线和投币收益");
userService.everydayResetNowEarn();
System.out.println("每日重置当日商户在线和投币收益");
List<Area> selectAllArea = areaService.selectAllArea();
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - 1);
Date today = calendar.getTime();
for (Area area : selectAllArea) {
areaService.insertAreastatistics(area.getId(), area.getNowOnlineEarn(), area.getNowCoinsEarn(),
area.getWalletEarn(), area.getEquEarn(), area.getCardEarn(), today);
}
areaService.everydayAreaReset();
System.out.println("每日重置当日小区在线和投币收益");
return CommUtil.responseBuildInfo(200, "重置成功", null);
} catch (Exception e) {
return CommUtil.responseBuildInfo(201, "重置失败:" + e.getMessage(), null);
}
}
// @Scheduled(cron = "0 0 1 * * *")
@RequestMapping(value="/deleteRedundanceLogsTask")
@ResponseBody
public Object deleteRedundanceLogs() {
try {
System.out.println("删除日志开始");
chargeRecordService.delectRealChargeByTime(DisposeUtil.getPastDate(6, 2));
System.out.println("删除日志结束");
return CommUtil.responseBuildInfo(200, "删除日志完成", null);
} catch (Exception e) {
return CommUtil.responseBuildInfo(201, "删除日志失败", null);
}
}
// @Scheduled(cron = "0 0/5 * * * *")
@RequestMapping(value="/wolfChargeTask")
@ResponseBody
public Object timer(){
try {
//获取当前时间
logger.info("每隔5分钟扫描事件触发");
//查询最近10分钟之内的投币记录没有回复且没有退款的记录
List<InCoins> incoinsList = inCoinsService.selectInCoinsNoReply();
if (incoinsList != null && incoinsList.size() > 0) {
logger.info("已搜索到最近10分钟没有回复且没有退款的记录,记录长度===" + incoinsList.size());
for (InCoins incoins : incoinsList) {
Integer merchantid = incoins.getMerchantid();
long time = incoins.getBeginTime().getTime();
long currentTime = System.currentTimeMillis();
if ((currentTime - time) > 120000) {
Integer incoinRefund = authorityService.selectIncoinRefund(merchantid);
if (incoinRefund == null || incoinRefund == 1) {
logger.info(incoins.getOrdernum() + "--可退款--时间比较==" + currentTime + ":" + time);
if (incoins.getHandletype() == 1) {
WXPayConfigImpl config;
try {
config = WXPayConfigImpl.getInstance();
WXPay wxpay = new WXPay(config);
String total_fee = "";
String out_trade_no = "";
String moneyStr = String.valueOf(incoins.getMoney() * 100);
int idx = moneyStr.lastIndexOf(".");
total_fee = moneyStr.substring(0, idx);
out_trade_no = incoins.getOrdernum();// 退款订单号
SortedMap<String, String> params = new TreeMap<>();
params.put("appid", WeiXinConfigParam.FUWUAPPID);
params.put("mch_id", WeiXinConfigParam.MCHID);
params.put("sub_mch_id", WeiXinConfigParam.SUBMCHID);
params.put("out_trade_no", out_trade_no);
params.put("nonce_str", HttpRequest.getRandomStringByLength(30));
String sign = HttpRequest.createSign("UTF-8", params);
params.put("sign", sign);
String url = "https://api.mch.weixin.qq.com/pay/orderquery";
String canshu = HttpRequest.getRequestXml(params);
String sr = HttpRequest.sendPost(url, canshu);
Map<String, String> resultMap = XMLUtil.doXMLParse(sr);
if (resultMap.get("return_code").toString().equalsIgnoreCase("SUCCESS")) {
HashMap<String, String> data = new HashMap<String, String>();
data.put("appid", WeiXinConfigParam.FUWUAPPID);
data.put("mch_id", WeiXinConfigParam.MCHID);
data.put("sub_mch_id", WeiXinConfigParam.SUBMCHID);
data.put("transaction_id", resultMap.get("transaction_id"));
data.put("out_trade_no", out_trade_no);// 定单号
data.put("out_refund_no", "t" + out_trade_no);
data.put("total_fee", total_fee);
data.put("refund_fee", total_fee);
data.put("refund_fee_type", "CNY");
data.put("op_user_id", config.getMchID());
try {
Map<String, String> r = wxpay.refund(data);
// 处理退款后的订单 成功
if ("SUCCESS".equals(r.get("result_code"))) {
inCoinsService.updateInCoinsStatus(out_trade_no, (byte) 4);
if (incoins.getHandletype() != 4 && incoins.getHandletype() != 9) {
//脉冲退费
String ordernum = CommUtil.toString(out_trade_no);
String devicenum = CommUtil.toString(incoins.getEquipmentnum());
Integer uid = CommUtil.toInteger(incoins.getUid());
Integer merid = CommUtil.toInteger(incoins.getMerchantid());
Double paymoney = CommUtil.toDouble(incoins.getMoney());
Integer orderid = CommUtil.toInteger(incoins.getId());
Date datetime = new Date();
String strtime = CommUtil.toDateTime(datetime);
Integer paysource = MerchantDetail.INCOINSSOURCE;
Integer paytype = MerchantDetail.WEIXINPAY;
Integer paystatus = MerchantDetail.REFUND;
Double mermoney = 0.00;
String devicehard = "";
TradeRecord traderecord = tradeRecordService.getTraderecord(incoins.getOrdernum());
String comment = CommUtil.toString(traderecord.getComment());
try {
Equipment equipment = equipmentService.getEquipmentById(devicenum);
devicehard = CommUtil.toString(equipment.getHardversion());
Integer aid = CommUtil.toInteger(equipment.getAid());
if (aid != null && aid != 0) {
areaService.updateAreaEarn(0, paymoney, aid,null,paymoney,null);
}
} catch (Exception e) {
logger.warn("小区修改余额错误===" + e.getMessage());
}
try {
equipmentService.updateEquEarn(devicenum, paymoney, 0);
} catch (Exception e) {
logger.warn("设备收益修改异常");
}
//脉冲退费处理数据
dealerIncomeRefund(comment, merid, paymoney, ordernum, datetime, paysource, paytype, paystatus);
mermoney = traderecord.getMermoney();
Double partmoney = traderecord.getManmoney();
Integer manid = partmoney == 0 ? 0 : -1;
tradeRecordService.insertToTrade(merid, manid, uid, ordernum, paymoney, mermoney, partmoney, devicenum, 2, traderecord.getPaytype(), 2, devicehard, comment);
String urltem = CommonConfig.ZIZHUCHARGE+"/general/sendmsgdetails?source=3&id="+orderid;
returnMsgTemp(uid, devicenum, ordernum, urltem, strtime, paymoney);
// }
// mermoney = traderecord.getMermoney();
// Double partmoney = traderecord.getManmoney();
// Integer manid = partmoney == 0 ? 0 : -1;
// if (wolfkey == 3) {
// tradeRecordService.insertToTrade(merid, manid, uid, ordernum, paymoney, mermoney, partmoney, devicenum, 2, 4, 2, devicehard, comment);
// } else {
// tradeRecordService.insertToTrade(merid, manid, uid, ordernum, paymoney, mermoney, partmoney, devicenum, 2, 2, 2, devicehard, comment);
// }
// }
// if( null==manid || manid==0){
// userService.updateUserEarnings(0, incoins.getMoney(), user.getId());
// user.setEarnings((user.getEarnings() * 100 - incoins.getMoney() * 100) / 100);
// merchantDetailService.insertMerEarningDetail(user.getId(), incoins.getMoney(), user.getEarnings(),
// out_trade_no, new Date(), MerchantDetail.INCOINSSOURCE, MerchantDetail.WEIXINPAY, MerchantDetail.REFUND);
// Equipment equipmentById = equipmentService.getEquipmentById(incoins.getEquipmentnum());
// tradeRecordService.insertTrade(user.getId(), incoins.getUid(), out_trade_no, incoins.getMoney(), incoins.getMoney(),
// incoins.getEquipmentnum(), 2, 2, 2, equipmentById.getHardversion());
// try {
// userService.updateMerAmount(0, incoins.getMoney(), incoins.getMerchantid());
// } catch (Exception e) {
// logger.warn("商户总计更改出错");
// }
// }else{
// User manuser = userService.selectUserById(manid);
// userService.updateUserEarnings(0, traderecord.getMermoney(), user.getId());
// userService.updateUserEarnings(0, traderecord.getManmoney(), manid);
// manuser.setEarnings((manuser.getEarnings() * 100 - traderecord.getManmoney() * 100) / 100);
// user.setEarnings((user.getEarnings() * 100 - traderecord.getMermoney() * 100) / 100);
// merchantDetailService.insertMerEarningDetail(user.getId(), traderecord.getMermoney(), user.getEarnings(),
// out_trade_no, new Date(), MerchantDetail.INCOINSSOURCE, MerchantDetail.WEIXINPAY, MerchantDetail.REFUND);
// merchantDetailService.insertMerEarningDetail(manuser.getId(), traderecord.getManmoney(), manuser.getEarnings(),
// out_trade_no, new Date(), MerchantDetail.INCOINSSOURCE, MerchantDetail.WEIXINPAY, MerchantDetail.REFUND);
// Equipment equipmentById = equipmentService.getEquipmentById(incoins.getEquipmentnum());
// tradeRecordService.insertToTrade(user.getId(), manid, incoins.getUid(), out_trade_no, incoins.getMoney(),
// traderecord.getMermoney(),traderecord.getManmoney(), incoins.getEquipmentnum(), 2, 2, 2, equipmentById.getHardversion());
// try {
// userService.updateMerAmount(0, traderecord.getMermoney(), user.getId());
// userService.updateMerAmount(0, traderecord.getManmoney(), manid);
// } catch (Exception e) {
// logger.warn("商户总计更改出错");
// }
// }
}
// String urltem = CommonConfig.ZIZHUCHARGE+"/general/sendmsgdetails?source=3&id="+incoins.getId();
// returnMsgTemp(incoins.getUid(), incoins.getEquipmentnum(), incoins.getOrdernum(), urltem, StringUtil.toDateTime(), incoins.getMoney());
}
if ("FAIL".equals(r.get("result_code"))) {
// ChargeRecordHandler.updateChargeRefundNumer(endChargeId);
}
} catch (Exception e) {
logger.error(incoins.getOrdernum() + e.getMessage() + "微信退款失败");
}
}
} catch (Exception e) {
logger.error(incoins.getOrdernum() + e.getMessage() + "微信退款失败");
}
} else if (incoins.getHandletype() == 2) {
aliRefund(incoins.getOrdernum(), 2, 1);
}
} else {
logger.info("商户设置不开启系统自动扫描退款");
}
} else {
logger.info(incoins.getOrdernum() + "--不可退款--时间比较==" + currentTime + ":" + time);
}
}
} else {
logger.info("未搜索到最近10分钟没有回复且没有退款的记录");
}
chargeQueryNoReply();
return CommUtil.responseBuildInfo(200, "success", null);
} catch (Exception e) {
return CommUtil.responseBuildInfo(201, "fail", null);
}
}
public boolean checkUserIfRich(TradeRecord tradeRecord) {
Integer manid = tradeRecord.getManid();
Integer merid = tradeRecord.getMerid();
Double manmoney = tradeRecord.getManmoney();
Double mermoney = tradeRecord.getMermoney();
Double money = tradeRecord.getMoney();
if (manid != null && manid != 0) {
User manUser = userService.selectUserById(manid);
User merUser = userService.selectUserById(merid);
if ((manUser.getEarnings() >= manmoney) && (merUser.getEarnings() >= mermoney)) {
return true;
} else {
return false;
}
} else {
User merUser = userService.selectUserById(merid);
if ((merUser.getEarnings() >= money)) {
return true;
} else {
return false;
}
}
}
/**
* 支付宝退款
* @param ordernum 订单号
* @param type 支付类型,1、充电 2、脉冲投币
*/
public void aliRefund(String ordernum,int type,int orderid) {
AlipayClient alipayClient = null;
alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", AlipayConfig.APPID,
AlipayConfig.RSA_PRIVATE_KEY, "json", "GBK", AlipayConfig.ALIPAY_PUBLIC_KEY, "RSA2");
AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
TradeRecord traderecord = tradeRecordService.getTraderecord(ordernum);
Double money = traderecord.getMoney();
if ((traderecord == null) || (checkUserIfRich(traderecord) == false)) {
logger.warn("扫描退款失败,商户或合伙人余额不足");
return;
}
request.setBizContent("{" + "\"out_trade_no\":\"" + ordernum + "\"," + "\"refund_amount\":" + money + " }");
AlipayTradeRefundResponse response;
try {
response = alipayClient.execute(request);
if (response.isSuccess()) {
if (type == 1) {
ChargeRecord chargeRecord = chargeRecordService.chargeRecordOne(orderid);
ordernum = CommUtil.toString(ordernum);
//修改本地数据
String devicenum = CommUtil.toString(chargeRecord.getEquipmentnum());
Integer uid = CommUtil.toInteger(chargeRecord.getUid());
Integer merid = CommUtil.toInteger(chargeRecord.getMerchantid());
Double paymoney = CommUtil.toDouble(chargeRecord.getExpenditure());
orderid = CommUtil.toInteger(orderid);
Date time = new Date();
//String strtime = CommUtil.toDateTime(time);
Integer paysource = MerchantDetail.CHARGESOURCE;
Integer paytype = MerchantDetail.ALIPAY;
Integer paystatus = MerchantDetail.REFUND;
Double mermoney = 0.00;
String devicehard = "";
chargeRecordService.updateNumberById(null, 1, orderid, null, null, paymoney, CommUtil.toDateTime(), CommUtil.toDateTime());
try {
equipmentService.updateEquEarn(devicenum, paymoney, 0);
} catch (Exception e) {
logger.warn("设备收益修改异常");
}
if (chargeRecord.getNumber() != 1) {
String comment = traderecord.getComment();
try {
Equipment equipment = equipmentService.getEquipmentById(devicenum);
devicehard = CommUtil.toString(equipment.getHardversion());
Integer aid = CommUtil.toInteger(equipment.getAid());
if (aid != null && aid != 0) {
areaService.updateAreaEarn(0, paymoney, aid,null,paymoney,null);
}
//充电退费数据
dealerIncomeRefund(comment, merid, paymoney, ordernum, time, paysource, paytype, paystatus);
} catch (Exception e) {
logger.warn("小区修改余额错误===" + e.getMessage());
}
mermoney = traderecord.getMermoney();
Double partmoney = traderecord.getManmoney();
Integer manid = partmoney == 0 ? 0 : -1;
tradeRecordService.insertToTrade(merid, manid, uid, ordernum, paymoney, mermoney, partmoney, devicenum, 1, 3, 2, devicehard, comment);
}
} else if (type == 2) {
inCoinsService.updateInCoinsStatus(ordernum, (byte) 5);
orderid = CommUtil.toInteger(orderid);
Date time = new Date();
InCoins incoins = inCoinsService.selectInCoinsRecordByOrdernum(ordernum);
//修改本地数据
String devicenum = CommUtil.toString(incoins.getEquipmentnum());
Integer uid = CommUtil.toInteger(incoins.getUid());
Integer merid = CommUtil.toInteger(incoins.getMerchantid());
Double paymoney = CommUtil.toDouble(incoins.getMoney());
Integer paysource = MerchantDetail.INCOINSSOURCE;
Integer paytype = MerchantDetail.ALIPAY;
Integer paystatus = MerchantDetail.REFUND;
Double mermoney = 0.00;
String devicehard = "";
Integer aid = 0;
try {
equipmentService.updateEquEarn(devicenum, traderecord.getMoney(), 0);
} catch (Exception e) {
logger.warn("设备收益修改异常");
}
// if (incoins.getHandletype() != 5 && incoins.getHandletype() != 10) {
try {
Equipment equipment = equipmentService.getEquipmentById(devicenum);
devicehard = CommUtil.toString(equipment.getHardversion());
aid = CommUtil.toInteger(equipment.getAid());
String comment = CommUtil.toString(traderecord.getComment());
if (aid != null && aid != 0) {
areaService.updateAreaEarn(0, traderecord.getMoney(), aid,null,traderecord.getMoney(),null);
}
//脉冲退费处理数据
dealerIncomeRefund(comment, merid, paymoney, ordernum, time, paysource, paytype, paystatus);
mermoney = traderecord.getMermoney();
Double partmoney = traderecord.getManmoney();
Integer manid = partmoney == 0 ? 0 : aid;
tradeRecordService.insertToTrade(merid, manid, uid, ordernum, paymoney, mermoney, partmoney, devicenum, 2, 3, 2, devicehard, comment);
} catch (Exception e) {
logger.warn("小区修改余额错误===" + e.getMessage());
}
// }
// Integer manid = traderecord.getManid();
// try {
// Equipment equipment = equipmentService.getEquipmentById(traderecord.getCode());
// Integer aid = equipment.getAid();
// if (aid != null && aid != 0) {
// areaService.updateAreaEarn(0, traderecord.getMoney(), aid,null,traderecord.getMoney(),null);
// }
// } catch (Exception e) {
// logger.warn("小区修改余额错误===" + e.getMessage());
// }
// try {
// equipmentService.updateEquEarn(traderecord.getCode(), traderecord.getMoney(), 0);
// } catch (Exception e) {
// logger.warn("设备收益修改异常");
// }
// if( null==manid || manid==0){
// User user = userService.selectUserById(traderecord.getMerid());
// user.setEarnings((user.getEarnings() * 100 - traderecord.getMoney() * 100) / 100);
// userService.updateUserEarnings(0, traderecord.getMoney(), traderecord.getMerid());
// try {
// userService.updateMerAmount(0, traderecord.getMoney(), traderecord.getMerid());
// } catch (Exception e) {
// logger.warn("商户总计更改出错");
// }
// merchantDetailService.insertMerEarningDetail(user.getId(), traderecord.getMoney(), user.getEarnings(), ordernum, new Date(), MerchantDetail.INCOINSSOURCE, MerchantDetail.ALIPAY, MerchantDetail.REFUND);
// tradeRecordService.insertTrade(user.getId(), 0, ordernum, traderecord.getMoney(), traderecord.getMoney(), traderecord.getCode(), 2, 3, 2,equipmentService.getEquipmentById(traderecord.getCode()).getHardversion());
// }else{
// User manuser = userService.selectUserById(manid);
// manuser.setEarnings((manuser.getEarnings() * 100 - traderecord.getManmoney() * 100) / 100);
// User user = userService.selectUserById(traderecord.getMerid());
// user.setEarnings((user.getEarnings() * 100 - traderecord.getMermoney() * 100) / 100);
// userService.updateUserEarnings(0, traderecord.getManmoney(), traderecord.getManid());
// userService.updateUserEarnings(0, traderecord.getMermoney(), traderecord.getMerid());
// try {
// userService.updateMerAmount(0, traderecord.getManmoney(), traderecord.getManid());
// userService.updateMerAmount(0, traderecord.getMermoney(), traderecord.getMerid());
// } catch (Exception e) {
// logger.warn("商户总计更改出错");
// }
// merchantDetailService.insertMerEarningDetail(user.getId(), traderecord.getMermoney(), user.getEarnings(),
// ordernum, new Date(), MerchantDetail.INCOINSSOURCE, MerchantDetail.ALIPAY, MerchantDetail.REFUND);
// merchantDetailService.insertMerEarningDetail(manuser.getId(), traderecord.getManmoney(), manuser.getEarnings(), ordernum,
// new Date(), MerchantDetail.INCOINSSOURCE, MerchantDetail.ALIPAY, MerchantDetail.REFUND);
// tradeRecordService.insertToTrade(user.getId(), manid, 0, ordernum, traderecord.getMoney(), traderecord.getMermoney(),
// traderecord.getManmoney(), traderecord.getCode(), 2, 3, 2, equipmentService.getEquipmentById(traderecord.getCode()).getHardversion());
// System.out.println("--- 支付宝分成 脉冲退费 修改成功---");
// }
}
} else {
}
} catch (AlipayApiException e) {
logger.error(e.getMessage() + e.getStackTrace()[0].getLineNumber());
}
}
public void chargeQueryNoReply() {
try {
List<ChargeRecord> chargelist = chargeRecordService.selectChargeNoReply();
if (chargelist != null && chargelist.size() != 0) {
long currentTime = System.currentTimeMillis();
for (ChargeRecord chargeRecord : chargelist) {
Integer merid = chargeRecord.getMerchantid();
long begintime = chargeRecord.getBegintime().getTime();
Double money = chargeRecord.getExpenditure();
String ordernum = chargeRecord.getOrdernum();
Integer port = chargeRecord.getPort();
String equipmentnum = chargeRecord.getEquipmentnum();
// AllPortStatus portStatus = allPortStatusService.findPortStatusByEquipmentnumAndPort(equipmentnum, port);
Map<String, String> codeMap = JedisUtils.hgetAll(equipmentnum);
if (codeMap == null || codeMap.size() == 0) {
break;
}
Map<String, String> parse = (Map<String, String>) JSON.parse(codeMap.get(port + ""));
if (parse != null && parse.size() > 0) {
Short time = Short.parseShort(parse.get("time"));
Short elec = Short.parseShort(parse.get("elec"));
int portstatus = Integer.parseInt(parse.get("portStatus"));
int ratedTime = Integer.parseInt(chargeRecord.getDurationtime());
int ratedElec = chargeRecord.getQuantity();
if ((time == ratedTime && elec == ratedElec) || portstatus == 1) {
if ((currentTime - begintime) > 210000) {
TradeRecord traderecord = tradeRecordService.getTraderecord(ordernum);
logger.info(ordernum + "--可退款--时间比较==" + currentTime + ":" + begintime);
if (chargeRecord.getPaytype() == 2) {
WXPayConfigImpl config;
try {
// 获取商家的ID
Integer merId = CommUtil.toInteger(traderecord.getMerid());
String subMchId = null;
User merUser = null;
if (merId != 0) {
// 查询商家信息,判断商户是否为特约商户
merUser = userService.selectUserById(merId);
if(merUser != null && merUser.getSubMer() == 1){
Map<String, Object> configData = userService.selectSubMerConfigById(merId);
subMchId = CommUtil.toString(configData.get("submchid"));
}else{
subMchId = WeiXinConfigParam.SUBMCHID;
}
}else{
subMchId = WeiXinConfigParam.SUBMCHID;
}
config = WXPayConfigImpl.getInstance();
WXPay wxpay = new WXPay(config);
String total_fee = "";
String out_trade_no = "";
String moneyStr = String.valueOf(money * 100);
int idx = moneyStr.lastIndexOf(".");
total_fee = moneyStr.substring(0, idx);
out_trade_no = ordernum;// 退款订单号
SortedMap<String, String> params = new TreeMap<>();
params.put("appid", WeiXinConfigParam.FUWUAPPID);
params.put("mch_id", WeiXinConfigParam.MCHID);
params.put("sub_mch_id", subMchId);
params.put("out_trade_no", out_trade_no);
params.put("nonce_str", HttpRequest.getRandomStringByLength(30));
String sign = HttpRequest.createSign("UTF-8", params);
params.put("sign", sign);
String url = "https://api.mch.weixin.qq.com/pay/orderquery";
String canshu = HttpRequest.getRequestXml(params);
String sr = HttpRequest.sendPost(url, canshu);
Map<String, String> resultMap = XMLUtil.doXMLParse(sr);
if (resultMap.get("return_code").toString().equalsIgnoreCase("SUCCESS")) {
HashMap<String, String> data = new HashMap<String, String>();
data.put("appid", WeiXinConfigParam.FUWUAPPID);
data.put("mch_id", WeiXinConfigParam.MCHID);
data.put("sub_mch_id", subMchId);
data.put("transaction_id", resultMap.get("transaction_id"));
data.put("out_trade_no", out_trade_no);// 定单号
data.put("out_refund_no", "t" + out_trade_no);
data.put("total_fee", total_fee);
data.put("refund_fee", total_fee);
data.put("refund_fee_type", "CNY");
data.put("op_user_id", config.getMchID());
try {
Map<String, String> r = wxpay.refund(data);
// 处理退款后的订单 成功
if ("SUCCESS".equals(r.get("result_code"))) {
ordernum = CommUtil.toString(out_trade_no);
//修改本地数据
String devicenum = CommUtil.toString(chargeRecord.getEquipmentnum());
Integer uid = CommUtil.toInteger(chargeRecord.getUid());
merid = CommUtil.toInteger(chargeRecord.getMerchantid());
Double paymoney = CommUtil.toDouble(chargeRecord.getExpenditure());
Integer orderid = CommUtil.toInteger(chargeRecord.getId());
Date datetime = new Date();
String strtime = CommUtil.toDateTime(datetime);
Integer paysource = MerchantDetail.CHARGESOURCE;
Integer paytype = MerchantDetail.WEIXINPAY;
Integer paystatus = MerchantDetail.REFUND;
Double mermoney = 0.00;
String devicehard = "";
equipmentService.updateEquEarn(devicenum, paymoney, 0);
if (chargeRecord.getEndtime() == null) {
chargeRecordService.updateNumberById(null, 1, orderid, null, null, paymoney, CommUtil.toDateTime(), CommUtil.toDateTime());
} else {
chargeRecordService.updateNumberById(null, 1, orderid, null, null, paymoney, null, CommUtil.toDateTime());
}
if (chargeRecord.getNumber() != 1) {
String comment = traderecord.getComment();
try {
Equipment equipment = equipmentService.getEquipmentById(devicenum);
devicehard = CommUtil.toString(equipment.getHardversion());
Integer aid = CommUtil.toInteger(equipment.getAid());
if (aid != null && aid != 0) {
areaService.updateAreaEarn(0, paymoney, aid,null,paymoney,null);
}
// 特约商户修改退费数据
if(merUser != null && merUser.getSubMer() == 1){
//商户收益总额 1为加 0为减
userService.updateMerAmount(0, paymoney, merid);
merchantDetailService.insertMerEarningDetail(merid, paymoney, merUser.getEarnings(), ordernum, datetime, paysource, paytype, paystatus);
}else{
//充电退费数据
dealerIncomeRefund(comment, merid, paymoney, ordernum, datetime, paysource, paytype, paystatus);
}
} catch (Exception e) {
logger.warn("小区修改余额错误===" + e.getMessage());
}
mermoney = traderecord.getMermoney();
Double partmoney = traderecord.getManmoney();
Integer manid = partmoney == 0 ? 0 : -1;
tradeRecordService.insertToTrade(merid, manid, uid, ordernum, paymoney, mermoney, partmoney, devicenum, 1, 2, 2, devicehard, comment);
}
String urltem = CommonConfig.ZIZHUCHARGE+"/general/sendmsgdetails?source=1&id="+chargeRecord.getId();
returnMsgTemp(chargeRecord.getUid(), chargeRecord.getEquipmentnum(), chargeRecord.getOrdernum(), urltem, StringUtil.toDateTime(), chargeRecord.getExpenditure());
}
if ("FAIL".equals(r.get("result_code"))) {
// ChargeRecordHandler.updateChargeRefundNumer(endChargeId);
}
} catch (Exception e) {
logger.error(ordernum + e.getMessage() + "微信退款失败1");
e.printStackTrace();
}
}
} catch (Exception e) {
logger.error(ordernum + e.getMessage() + "微信退款失败2");
e.printStackTrace();
}
} else if (chargeRecord.getPaytype() == 3) {
aliRefund(ordernum,1,chargeRecord.getId());
} else if (chargeRecord.getPaytype() == 1) {
Integer uid = chargeRecord.getUid();
User user = userService.selectUserById(uid);
Double userBalance = CommUtil.toDouble(user.getBalance());
Double usersendmoney = CommUtil.toDouble(user.getSendmoney());
Double opermoney = CommUtil.toDouble(money);
Double opersendmoney = 0.00;
Double opertomoney = CommUtil.addBig(opermoney, opersendmoney);
Double topupbalance = CommUtil.addBig(opermoney, userBalance);
Double givebalance = CommUtil.addBig(opersendmoney, usersendmoney);
Double operbalance = CommUtil.addBig(topupbalance, givebalance);
user.setBalance(topupbalance);
user.setSendmoney(givebalance);
userService.updateUserById(user);
generalDetailService.insertGenWalletDetail(user.getId(), user.getMerid(), opermoney, opersendmoney, opertomoney, operbalance, topupbalance, givebalance , ordernum, new Date(), 5);
tradeRecordService.insertToTrade(traderecord.getMerid(), traderecord.getManid(), traderecord.getUid(), traderecord.getOrdernum(), opertomoney, traderecord.getMermoney(),
traderecord.getManmoney(), traderecord.getCode(), traderecord.getPaysource(), traderecord.getPaytype(), 2, traderecord.getHardver());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
chargeRecordService.updateNumberById(null, 1, chargeRecord.getId(), null, null,
chargeRecord.getExpenditure(), sdf.format(chargeRecord.getBegintime()), CommUtil.toDateTime());
}
} else {
logger.info(ordernum + "--不可退款--时间比较==" + currentTime + ":" + begintime);
}
} else {
logger.info(ordernum + "--不可退款--端口时间或电量已改变");
}
} else {
logger.info(ordernum + "端口状态不在空闲不予退款");
}
}
} else {
logger.info("未搜到10分钟内付款成功设备为回复的订单");
}
} catch (Exception e) {
logger.warn("扫描充电未回复退款异常");
e.printStackTrace();
}
}
public void returnMsgTemp(Integer uid, String code, String order, String url, String time, Double money){//退费模板
try {
User user = userService.selectUserById(uid);
if(null!=user){
String oppenid = user.getOpenid();
UserEquipment uscode = userEquipmentService.getUserEquipmentByCode(code);
User meruser = userService.selectUserById(uscode.getUserId());
JSONObject json = new JSONObject();
json.put("first", TempMsgUtil.inforData("您好,您的退费请求已受理,资金将原路返回到您的账户中","#FF3333"));
json.put("keyword1", TempMsgUtil.inforData("充电退费","#0044BB"));
json.put("keyword2", TempMsgUtil.inforData(order,"#0044BB"));
json.put("keyword3", TempMsgUtil.inforData(time,"#0044BB"));
json.put("keyword4", TempMsgUtil.inforData("¥ "+String.format("%.2f", money),"#0044BB"));
json.put("keyword5", TempMsgUtil.inforData(meruser.getPhoneNum(),"#0044BB"));
json.put("remark", TempMsgUtil.inforData("如有疑问可咨询服务商。","#0044BB"));
TempMsgUtil.sendTempMsg(oppenid, TempMsgUtil.TEMP_IDTUI, url, json);
}
} catch (Exception e) {
logger.warn(e.getMessage());
}
}
@RequestMapping("/a")
public String login() {
return "computer/login";
}
@RequestMapping("/onLogin")
@ResponseBody
public JSONObject onLogin(String code) {
JSONObject weChatToken = null;
try {
weChatToken = WeixinUtil.smallWeChatToken(code);
} catch (Exception e) {
}
return weChatToken;
}
@RequestMapping("/bluetooth1")
public String bluetooth1(Model model) {
try {
Map<String, String> map = JsSignUtil.sign(CommonConfig.ZIZHUCHARGE+"/bluetooth1");
model.addAttribute("nonceStr", map.get("nonceStr"));
model.addAttribute("timestamp", map.get("timestamp"));
model.addAttribute("signature", map.get("signature"));
model.addAttribute("appId", map.get("appId"));
} catch (Exception e) {
e.printStackTrace();
}
return "bluetooth/bluetooth1";
}
@RequestMapping("/")
public String home() {
return "home";
}
@RequestMapping("/testTemp")
public String testTemp() {
return "testTemp";
}
@RequestMapping("/helpdoc")
public String helpdoc() {
return "helpdoc";
}
@RequestMapping("/testpay")
public String testpay() {
return "testpay";
}
@RequestMapping("selectHardversion")
public String selectHardversion() {
return "selectHardversion";
}
@RequestMapping("incoins")
@ResponseBody
public Map<String, String> incoins(String code,Byte money) {
money = money == null ? 0 : money;
// SendMsgUtil.send_0x83(code, (byte)1, money);
Map<String, String> map = WolfHttpRequest.sendIncoinsPaydata(code, (byte)1, money);
// long nowTime = System.currentTimeMillis();
// boolean flag = true;
// int temp = 0;
// Map<String, String> map = new HashMap<>();
// while (flag) {
// map = Server.inCoinsMap.get(code);
// if (temp >= 15) {
// map = new HashMap<>();
// map.put("err", "1");
// map.put("errinfo", "连接超时...");
// flag = false;
// break;
// }
// if (map == null || map.size() == 0) {
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// System.out.println(e.getMessage());
// }
// temp++;
// continue;
// } else {
// String testNowtime = map.get("testNowtime");
// if (testNowtime != null) {
// long nowtimes = Long.parseLong(map.get("testNowtime"));
// if (nowtimes - nowTime > 0 && nowtimes - nowTime < 20000) {
// flag = false;
// break;
// } else {
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// System.out.println(e.getMessage());
// }
// temp++;
// continue;
// }
// } else {
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// System.out.println(e.getMessage());
// }
// temp++;
// continue;
// }
// }
// }
return map;
}
@RequestMapping(value = "/connectInCoins",method = RequestMethod.POST)
@ResponseBody
public Map<String, String> connectInCoins(String code,String nowtime) {
long nowTime = System.currentTimeMillis();
if (nowtime != null) {
nowTime = Long.parseLong(nowtime);
}
boolean flag = true;
int temp = 0;
Map<String, String> map = new HashMap<>();
while (flag) {
map = Server.inCoinsMap.get(code);
if (temp >= 15) {
map = new HashMap<>();
map.put("err", "1");
map.put("errinfo", "连接超时...");
flag = false;
break;
}
if (map == null || map.size() == 0) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
temp++;
continue;
} else {
if (map.get("nowtime") == null) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
temp++;
continue;
}
long nowtimes = Long.parseLong(map.get("nowtime"));
if (nowtimes - nowTime > 0 && nowtimes - nowTime < 20000) {
flag = false;
break;
} else {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
temp++;
continue;
}
}
}
return map;
}
@RequestMapping("/connectus")
public String connectus() {
return "connectus";
}
@RequestMapping("/offlineCard")
public String offlineCard(Model model) {
model.addAttribute("code", "000001");
return "offlineCard";
}
/**
* 离线卡充值前的查询
* @param code 设备号
* @param openid 用户的openid
* @param nowtime 系统时间
* @return {@link Map}
*
*/
@RequestMapping("/queryOfflineCard")
@ResponseBody
public Map<String, String> queryOfflineCard(String code,String openid,String nowtime) {
String ordernum = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
//查询记录
offlineCardService.insertQueryOfflineCardRecord(ordernum, code,openid);
SendMsgUtil.send_0x22(code, 0, (short) 0, (byte) 2);
// Map<String, String> hashMap = new HashMap<>();
// hashMap.put("code", code);
// Map<String, String> map = WolfHttpRequest.httpconnectwolf(hashMap, WolfHttpRequest.SEND_QUERYOFFLINECARD_URL);
long nowTime = Long.parseLong(nowtime);
boolean flag = true;
int temp = 0;
Map<String, String> map = new HashMap<>();
while (flag) {
map = Server.offlineMap.get(code);
if (temp >= 10) {
map = new HashMap<>();
map.put("err", "1");
map.put("errinfo", "连接超时...");
flag = false;
System.out.println("----查询超时已退出----");
break;
}
if (map == null || map.size() == 0) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
temp++;
continue;
} else {
long nowtimes = Long.parseLong(map.get("nowtime"));
if (nowtimes - nowTime > 0 && nowtimes - nowTime < 20000) {
if (map.get("err") != null && "1".equals(map.get("err"))) {
return map;
}
double card_surp = Double.parseDouble(map.get("card_surp")) / 10;
int recycletype = Integer.parseInt(map.get("result"));
offlineCardService.updateQueryOfflineCardRecord(ordernum, map.get("card_id"), card_surp,recycletype);
flag = false;
break;
} else {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
temp++;
continue;
}
}
}
return map;
}
@RequestMapping("/chargeCard")
@ResponseBody
public Map<String, String> chargeCard(String code,String card_id,Short card_surp,Byte card_ope) {
Map<String,String> map = new HashMap<>();
map.put("code", code);
map.put("card_id", card_id);
map.put("card_surp", card_surp * 10 + "");
map.put("card_ope", card_ope + "");
return WolfHttpRequest.httpconnectwolf(map, WolfHttpRequest.SEND_CHARGEOFFLINECARD_URL);
// Map<String, String> map = new HashMap<>();
// try {
// int parseLong = (int) Long.parseLong(card_id,16);
// SendMsgUtil.send_0x22(code, parseLong, (short) (card_surp * 10), card_ope);
// boolean flag = true;
// long nowTime = System.currentTimeMillis();
// int temp = 0;
// while (flag) {
// map = Server.offlineMap.get(code);
// if (temp >= 10) {
// map = new HashMap<>();
// map.put("err", "1");
// map.put("errinfo", "连接超时...");
// flag = false;
// System.out.println("----查询超时已退出----");
// break;
// }
// if (map == null || map.size() == 0) {
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// System.out.println(e.getMessage());
// }
// temp++;
// continue;
// } else {
// long nowtimes = Long.parseLong(map.get("nowtime"));
// if (nowtimes - nowTime > 0 && nowtimes - nowTime < 20000) {
// flag = false;
// break;
// } else {
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// System.out.println(e.getMessage());
// }
// temp++;
// continue;
// }
// }
// }
// return map;
// } catch (Exception e) {
// map.put("err", "1");
// map.put("errinfo", "充值异常");
// return map;
// }
}
@RequestMapping("/chargingByUid")
public String chargingByUid() {
return "record/chargingByUid";
}
@RequestMapping("/getuseragent")
public void getuseragent() {
String parameter = request.getHeader("user-agent");
System.out.println(parameter);
}
@RequestMapping(value = "/lunbo")
public String lunbo() {
return "lunbo";
}
@RequestMapping(value = "/pcequlist")
public String equlists(HttpServletRequest request, HttpServletResponse response,Model model){
PageUtils<Equipment> pageBean = equipmentService.selectEquipment(request);
List<Equipment> equipment = equipmentService.getEquipmentList();
int online = 0;
int binding = 0;
for(Equipment eqm : equipment){
if(eqm.getState()==1){//在线
online += 1;
}
if(eqm.getBindtype()==1){//绑定
binding += 1;
}
}
model.addAttribute("online", online);
model.addAttribute("disonline", equipment.size() - online);
model.addAttribute("binding", binding);
model.addAttribute("disbinding", equipment.size() - binding);
model.addAttribute("totalRows", equipment.size());
model.addAttribute("pageBean", pageBean);
model.addAttribute("username", request.getParameter("username"));
model.addAttribute("state", request.getParameter("state"));
model.addAttribute("code", request.getParameter("code"));
model.addAttribute("imei", request.getParameter("imei"));
model.addAttribute("ccid", request.getParameter("ccid"));
model.addAttribute("hardversion", request.getParameter("hardversion"));
model.addAttribute("softversionnum", request.getParameter("softversionnum"));
model.addAttribute("csq", request.getParameter("csq"));
model.addAttribute("phoneNum", request.getParameter("phoneNum"));
model.addAttribute("line", request.getParameter("line"));
model.addAttribute("equipmentList",pageBean.getList());
return "computer/equlist";
}
// @RequestMapping(value = "/equlist")
// public String equlist(@RequestParam(value = "pageNum",defaultValue = "1")int pageNum,Model model) {
// int pageSize = 10;
// PageBean<Equipment> pageBean = equipmentService.findAllEquipmentPage(pageNum, pageSize);
// model.addAttribute("pageBean", pageBean);
// model.addAttribute("equipmentList", pageBean.getList());
// return "equlist";
// }
/*
* @RequestMapping("/oauth2")
* @ResponseBody public void oauth2() throws Exception { String url =
* URLEncoder.encode("http://www.he360.com.cn", "utf-8"); String str =
* "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx3debe4a9c562c52a&"
* + "redirect_uri=" + url +
* "&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect"; //
* request.getRequestDispatcher(str); response.sendRedirect(str); }
*/
@RequestMapping("/roarwolf")
public String roarwolf(HttpServletRequest request) {
return "home";
}
@RequestMapping(value = "/index")
public String index(Model model) {
model.addAttribute("name", "xiaobao");
return "user/index";
}
@RequestMapping(value = "scancode")
public Object scancode(Model model) {
try {
Map<String, String> map = JsSignUtil.sign("http://www.he360.com.cn/scancode/");
// Map<String, Object> map = JsSignUtil.sign("");
model.addAttribute("nonceStr", map.get("nonceStr"));
model.addAttribute("timestamp", map.get("timestamp"));
model.addAttribute("signature", map.get("signature"));
model.addAttribute("jsapi_ticket", map.get("jsapi_ticket"));
model.addAttribute("appId", map.get("appId"));
model.addAttribute("url", map.get("url"));
} catch (Exception e) {
e.printStackTrace();
}
return "scancode";
}
@RequestMapping(value = "/hello")
public String hello(Map<String, Object> map) {
map.put("test", "God is a gril");
return "hello";
}
@RequestMapping(value = "/qrcode")
public String qrcode(Model model) {
model.addAttribute("qrcodeinfo", "It's me!!!");
return "qrcode";
}
/**
* 判断是微信还是支付宝扫的二维码 ,随后进入相应的控制层
*
* @param request
* @return
*/
@RequestMapping("/wolf")
public String wolf(HttpServletRequest request) {
System.out.println(request.getHeader("User-Agent"));
String userAgent = request.getHeader("User-Agent");
if (userAgent.contains("MicroMessenger")) {
return "agency/index";
} else if (userAgent.contains("AlipayClient")) {
return "redirect:/user/list";
} else {
return "index";
}
}
@RequestMapping("/pctest")
public String test(@RequestParam("code") String code, Model model) {
model.addAttribute("code", code);
Equipment equipment = equipmentService.getEquipmentById(code);
// int neednum = EquipmentController.getAllportNeednum(equipment.getHardversion());
// List<AllPortStatus> allPortStatusList = allPortStatusService.findPortStatusListByEquipmentnum(code,neednum);
List<Map<String, String>> allPortStatusList = DisposeUtil.addPortStatus(code, equipment.getHardversion());
System.out.println("设备---" + code + "共有" + allPortStatusList.size() + "路");
model.addAttribute("allPortStatusList", allPortStatusList);
model.addAttribute("equipment", equipment);
UserEquipment userEquipment = userEquipmentService.getUserEquipmentByCode(code);
if (userEquipment == null) {
model.addAttribute("username", "0");
return "computer/test";
}
User user = userService.selectUserById(userEquipment.getUserId());
if (user != null) {
model.addAttribute("username", user.getUsername());
} else {
model.addAttribute("username", "0");
}
return "computer/test";
}
@RequestMapping(value = "/getinfo")
@ResponseBody
public Map<String, String> getinfo(String code) {
Map<String, Map> map = Server.getMap();
Map map2 = map.get(code);
return map2;
}
@RequestMapping(value = "/testmutual", method = RequestMethod.POST)
@ResponseBody
public Map<String, String> testMutual(String param, Model model, String code) throws Exception {
// Class<?> clazz = Class.forName("com.hedong.hedongwx.utils.SendMsgUtil");
// SendMsgUtil sendMsgUtil = (SendMsgUtil) clazz.newInstance();
// Method method = clazz.getMethod("send_" + param, String.class);
// method.invoke(sendMsgUtil, code);
// Map<String, Map> map = Server.getMap();
// Map map2 = map.get(code);
return null;
}
@RequestMapping(value = "/testpaytoport", method = RequestMethod.POST)
@ResponseBody
public Map<String,String> testpaytoport(byte payport,short time,double elec,String code) {
String elecstr = elec * 100 + "";
String elecClac = elecstr.substring(0, elecstr.indexOf("."));
Short elecs = Short.valueOf(elecstr.substring(0, elecstr.indexOf(".")));
Map<String,String> map = new HashMap<>();
// map.put("port", payport + "");
// map.put("money", "10");
// map.put("time", time + "");
// map.put("elec", elecs + "");
// map.put("code", code);
// WolfHttpRequest.httpconnectwolf(map, WolfHttpRequest.SEND_PAY_URL);
try {
SendMsgUtil.send_0x14(payport,(short) 10,time,(short) (elecs * 100),code);
map.put("wolfcode", "1000");
map.put("wolfmsg", "success");
// return WolfHttpRequest.sendChargePaydata(payport, time, "10", elecClac, code, 1);
} catch (Exception e) {
map.put("wolfcode", "1001");
map.put("wolfmsg", "fail");
}
return map;
}
@RequestMapping(value = "/querystate", method = RequestMethod.POST)
@ResponseBody
public Map<String,String> querystate(byte port,String code) {
// Map<String,String> hashMap = new HashMap<>();
// hashMap.put("port", port + "");
// hashMap.put("code", code);
// try {
// return WolfHttpRequest.httpconnectwolf(hashMap, WolfHttpRequest.SEND_QUERYPORTCHARGESTATUS_URL);
// } catch (Exception e) {
// HashMap<String,String> map = new HashMap<>();
// map.put("wolfcode", "1001");
// map.put("wolfmsg", "fail");
// return map;
// }
long currentTime = System.currentTimeMillis();
// SendMsgUtil.send_21(port,code);
if (port == 2) {
port = 0;
}
SendMsgUtil.send_0x2E(code, port);
boolean flag = true;
int temp = 0;
while (flag) {
try {
if (temp > 20) {
Map<String, String> map = new HashMap<>();
map.put("wolfcode", "1001");
map.put("wolfmsg", "网络连接失败,稍后请重试...");
return map;
}
Map map = Server.recycleMap.get(code);
if (map == null) {
temp++;
Thread.sleep(1000);
continue;
}
Map portmap = (Map) map.get("port" + port);
if (portmap == null) {
temp++;
Thread.sleep(1000);
continue;
}
String updatetime = (String) portmap.get("updatetime");
long updatetimelong = Long.parseLong(updatetime);
System.out.println("指令回复时间---" + updatetimelong + "发起时间---" + currentTime);
if (updatetime == null || "".equals(updatetime)) {
temp++;
Thread.sleep(1000);
continue;
} else if ((updatetimelong - currentTime) > 0 && (updatetimelong - currentTime) < 20000) {
flag = false;
break;
} else {
temp++;
Thread.sleep(1000);
continue;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Map<String,Map<String,String>> map = Server.recycleMap.get(code);
Map<String, String> portmap = map.get("port" + port);
return portmap;
}
@RequestMapping(value = "/seticandcoin", method = RequestMethod.POST)
@ResponseBody
public String seticandcoin(byte setcoin, byte setic, String code) {
SendMsgUtil.send_9(setcoin, setic, code);
return "设置成功";
}
@RequestMapping(value = "/lock", method = RequestMethod.POST)
@ResponseBody
public Map<String,String> lock(byte port, byte status,String code) {
// long currentTime = System.currentTimeMillis();
AllPortStatus allPortStatus = allPortStatusService.findPortStatusByEquipmentnumAndPort(code, (int) port);
Byte portStatus = allPortStatus.getPortStatus();
Map<String, String> hashMap = new HashMap<>();
if (portStatus != 1 && portStatus != 2) {
if (status == 0) {
hashMap.put("err", "1");
hashMap.put("errinfo", "当前端口已锁定或有故障,不可再次锁定");
return hashMap;
}
} else if (portStatus == 1 || portStatus == 2) {
if (status == 1) {
hashMap.put("err", "1");
hashMap.put("errinfo", "当前端口正常使用,解锁失效");
return hashMap;
}
}
// SendMsgUtil.send_12(port, status, code);
hashMap.put("code", code);
hashMap.put("port", port + "");
hashMap.put("status", status + "");
Map<String, String> map = WolfHttpRequest.httpconnectwolf(hashMap, WolfHttpRequest.SEND_SETPORTSTATUS_URL);
// boolean flag = true;
// int temp = 0;
// while (flag) {
// try {
// if (temp > 20) {
// Map<String, String> map = new HashMap<>();
// map.put("err", "0");
// map.put("errinfo", "网络连接错误,稍后请重试...");
// return map;
// }
// Map<String, Map<String,String>> map = Server.islockMap.get(code);
// if (map == null) {
// temp++;
// Thread.sleep(1000);
// continue;
// }
// Map<String,String> portmap = map.get("port" + port);
// if (portmap == null) {
// temp++;
// Thread.sleep(1000);
// continue;
// }
// String updatetime = portmap.get("updatetime");
// long updatetimelong = Long.parseLong(updatetime);
// if (updatetime == null || "".equals(updatetime)) {
// temp++;
// Thread.sleep(1000);
// continue;
// } else if ((updatetimelong - currentTime) > 0 && (updatetimelong - currentTime) < 20000) {
// flag = false;
// break;
// } else {
// temp++;
// Thread.sleep(1000);
// continue;
// }
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
if (status == 0) {
allPortStatus.setPortStatus((byte) 3);
allPortStatus.setElec((short) 0);
allPortStatus.setPower((short) 0);
allPortStatus.setTime((short) 0);
} else if (status == 1) {
allPortStatus.setPortStatus((byte) 1);
}
allPortStatusService.updateAllPortStatus(allPortStatus);
return map;
}
/*@RequestMapping(value = "/lock2", method = RequestMethod.POST)
@ResponseBody
public String lock2(byte port, byte status) {
SendMsgUtil.send_12(port, status);
if (SendMsgUtil.LOCK) {
return SendMsgUtil.getTwolock();
} else {
return "";
}
}*/
@RequestMapping(value = "/stopRechargeByPort", method = RequestMethod.POST)
@ResponseBody
public Map<String,String> stopRechargeByPort(byte port, String code) {
Map<String,String> map = new HashMap<>();
map.put("port", port + "");
map.put("code", code);
Map<String,String> resultmap = new HashMap<>();
try {
SendMsgUtil.send_13(port, code);
resultmap.put("wolfcode", "1000");
resultmap.put("wolfmsg", "success");
// return WolfHttpRequest.httpconnectwolf(map, WolfHttpRequest.SEND_STOPPORTLOAD_URL);
} catch (Exception e) {
resultmap.put("wolfcode", "1001");
resultmap.put("wolfmsg", "fail");
}
return resultmap;
}
@RequestMapping(value = "/setsystem", method = RequestMethod.POST)
@ResponseBody
public Map<String,String> setsystem(Short coin_min, Short card_min, Byte coin_elec, Byte card_elec, Byte cst, Short power_max_1,
Short power_max_2, Short power_max_3, Short power_max_4, Byte power_2_tim, Byte power_3_tim,
Byte power_4_tim, Byte sp_rec_mon, Byte sp_full_empty, Byte full_power_min, Byte full_charge_time,
String elec_time_first, String code) {
if (coin_min == null) {
coin_min = 0;
}
if (card_min == null) {
card_min = 0;
}
if (coin_elec == null) {
coin_elec = 0;
}
if (card_elec == null) {
card_elec = 0;
}
if (cst == null) {
cst = 0;
}
if (power_max_1 == null) {
power_max_1 = 0;
}
if (power_max_2 == null) {
power_max_2 = 0;
}
if (power_max_3 == null) {
power_max_3 = 0;
}
if (power_max_4 == null) {
power_max_4 = 0;
}
if (power_2_tim == null) {
power_2_tim = 0;
}
if (power_3_tim == null) {
power_3_tim = 0;
}
if (power_4_tim == null) {
power_4_tim = 0;
}
if (sp_rec_mon == null) {
sp_rec_mon = 0;
}
if (sp_full_empty == null) {
sp_full_empty = 0;
}
if (full_power_min == null) {
full_power_min = 0;
}
if (full_charge_time == null) {
sp_full_empty = 0;
}
System.out.println("elec_time_first===" + elec_time_first);
Byte elec_time_firsts = (byte) 0xff;
if (elec_time_first == null || elec_time_first.indexOf('-') != -1) {
elec_time_firsts = (byte) 0xff;
} else if ("1".equals(elec_time_first) || "0".equals(elec_time_first)) {
elec_time_firsts = Byte.parseByte(elec_time_first);
}
SendMsgUtil.send_24(coin_min, card_min, coin_elec, card_elec, cst, power_max_1, power_max_2, power_max_3,
power_max_4, power_2_tim, power_3_tim, power_4_tim, sp_rec_mon, sp_full_empty, full_power_min,
full_charge_time, elec_time_firsts, code);
long currentTime = System.currentTimeMillis();
boolean flag = true;
int temp = 0;
Map<String, String> map = new HashMap<>();
while (flag) {
if (temp >=20) {
map.put("status", "0");
break;
}
Map<String, String> mapRecive = Server.setSystemMap.get(code);
if (mapRecive == null || mapRecive.size() < 1) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
temp++;
continue;
}
long udpatetime = Long.parseLong(mapRecive.get("updatetime"));
if ((udpatetime - currentTime) > 0 && (udpatetime - currentTime) < 20000) {
map.putAll(mapRecive);
flag = false;
Server.setSystemMap.remove(code);
break;
} else {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
temp++;
continue;
}
}
return map;
}
@RequestMapping(value = "/readsysteminfo")
@ResponseBody
public Map<String, String> readsysteminfo(String code) {
Map<String, String> hashMap = new HashMap<>();
hashMap.put("code", code);
Map<String, String> map = WolfHttpRequest.httpconnectwolf(hashMap, WolfHttpRequest.SEND_READSYSTEM_URL);
// SendMsgUtil.send_30(code);
// long currentTime = System.currentTimeMillis();
// boolean flag = true;
// int temp = 0;
// Map<String, String> map = new HashMap<>();
// while (flag) {
// if (temp >=20) {
// map.put("status", "0");
// break;
// }
// Map<String, String> mapRevice = Server.readsystemMap.get(code);
// if (mapRevice == null || mapRevice.size() < 1) {
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// temp++;
// continue;
// }
// long udpatetime = Long.parseLong(mapRevice.get("updatetime"));
// if ((udpatetime - currentTime) > 0 && (udpatetime - currentTime) < 20000) {
// map.putAll(mapRevice);
// map.put("readtime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
// flag = false;
// Server.readsystemMap.remove(code);
// break;
// } else {
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// temp++;
// continue;
// }
//
// }
System.out.println("===" + JSON.toJSONString(map));
return map;
}
@RequestMapping(value = "/portstate")
@ResponseBody
public Map<String,String> portstate(String code) {
Map<String, Map<String,String>> everyportMap = Server.everyportMap;
if (everyportMap != null) {
Map<String,String> map = everyportMap.get(code);
if (map != null) {
int temp = 0;
Set<Entry<String,String>> entrySet = map.entrySet();
for (Entry<String, String> entry : entrySet) {
temp++;
}
if ((temp - 1) == 2) {
Equipment equipment = equipmentService.getEquipmentById(code);
if (!"00".equals(equipment.getHardversion()) && equipment.getTempid() == 0) {
Equipment equipment2 = new Equipment();
equipment2.setCode(code);
equipment2.setTempid(1);
equipmentService.updateEquipment(equipment2);
}
}
return map;
} else {
return null;
}
} else {
return null;
}
}
@RequestMapping(value = "/portstate1")
@ResponseBody
public Map<String,String> portstate1(String code) {
boolean flag = true;
int temp = 0;
String nowtime = request.getParameter("nowtime");
// Map<String,String> map = new HashMap<>();
// map.put("code", code);
// map.put("nowtime", nowtime);
// Map<String, String> hashMap = WolfHttpRequest.httpconnectwolf(map, WolfHttpRequest.SEND_QUERYALLPORTSTATUS_URL);
SendMsgUtil.send_15(code);
System.out.println("当前时间:" + nowtime);
int i = 0;
while (flag) {
if (temp >= 10) {
System.out.println("等待回复超时");
HashMap<String,String> hashMap = new HashMap<>();
hashMap.put("state", "error");
return hashMap;
}
Map<String, Map<String,String>> everyportMap = Server.everyportMap;
Map<String,String> map = everyportMap.get(code);
if (map == null || map.size() < 1) {
if (i >= 10) {
HashMap<String,String> hashMap = new HashMap<>();
hashMap.put("state", "error");
return hashMap;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
i++;
continue;
}
if (map == null || map.size() < 1) {
HashMap<String,String> hashMap = new HashMap<>();
hashMap.put("state", "error");
return hashMap;
}
if (nowtime == null || "".equals(nowtime)) {
HashMap<String,String> hashMap = new HashMap<>();
hashMap.put("state", "error");
return hashMap;
} else {
String replytime = (String) map.get("paramdate");
long nowtimeparseLong = Long.parseLong(nowtime);
long replytimeparseLong = Long.parseLong(replytime);
if ((replytimeparseLong - nowtimeparseLong) < 0) {
temp++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
continue;
} else if ((replytimeparseLong - nowtimeparseLong) > 0 && (replytimeparseLong - nowtimeparseLong) < 10000) {
Map<String, Map<String,String>> everyportMap1 = Server.everyportMap;
Map<String,String> map1 = everyportMap1.get(code);
return map1;
} else if ((replytimeparseLong - nowtimeparseLong) < 0 && (replytimeparseLong - nowtimeparseLong) > -2000) {
Map<String, Map<String,String>> everyportMap1 = Server.everyportMap;
Map<String,String> map1 = everyportMap1.get(code);
return map1;
}
}
}
HashMap<String,String> hashMap = new HashMap<>();
hashMap.put("state", "error");
return hashMap;
}
@RequestMapping(value = "/portstate2")
@ResponseBody
public Map<String,String> portstate2(String code,Integer port) {
boolean flag = true;
int temp = 0;
String nowtime = request.getParameter("nowtime");
System.out.println("当前时间:" + nowtime);
// Map<String,String> map = new HashMap<>();
// map.put("code", code);
// map.put("nowtime", nowtime);
// map.put("port", port + "");
// Map<String, String> hashMap = WolfHttpRequest.httpconnectwolf(map, WolfHttpRequest.SEND_QUERYPORTSTATUS_URL);
SendMsgUtil.send_15(code);
int i = 0;
while (flag) {
if (temp >= 10) {
System.out.println("等待回复超时");
HashMap<String,String> hashMap = new HashMap<>();
hashMap.put("state", "error");
return hashMap;
}
Map<String, Map<String,String>> everyportMap = Server.everyportMap;
Map<String,String> map = everyportMap.get(code);
if (map == null || map.size() < 1) {
if (i >= 10) {
HashMap<String,String> hashMap = new HashMap<>();
hashMap.put("state", "error");
return hashMap;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
i++;
continue;
}
if (map == null || map.size() < 1) {
HashMap<String,String> hashMap = new HashMap<>();
hashMap.put("state", "error");
return hashMap;
}
if (nowtime == null || "".equals(nowtime)) {
HashMap<String,String> hashMap = new HashMap<>();
hashMap.put("state", "error");
return hashMap;
} else {
String replytime = (String) map.get("paramdate");
long nowtimeparseLong = Long.parseLong(nowtime);
long replytimeparseLong = Long.parseLong(replytime);
if ((replytimeparseLong - nowtimeparseLong) < 0) {
temp++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
continue;
} else if ((replytimeparseLong - nowtimeparseLong) > 0 && (replytimeparseLong - nowtimeparseLong) < 10000) {
Map<String, Map<String,String>> everyportMap1 = Server.everyportMap;
Map<String,String> map1 = everyportMap1.get(code);
String portstatus = map1.get("param" + port);
map1.put("portstatus", portstatus);
return map1;
} else if ((replytimeparseLong - nowtimeparseLong) < 0 && (replytimeparseLong - nowtimeparseLong) > -2000) {
Map<String, Map<String,String>> everyportMap1 = Server.everyportMap;
Map<String,String> map1 = everyportMap1.get(code);
String portstatus = map1.get("param" + port);
map1.put("portstatus", portstatus);
return map1;
}
}
}
HashMap<String,String> hashMap = new HashMap<>();
hashMap.put("state", "error");
return hashMap;
}
@RequestMapping(value = "/readeveryport")
@ResponseBody
public Map<String, String> readeveryport(String code) {
Map<String, Map> isfreeMap = Server.isfreeMap;
Map map = isfreeMap.get(code);
return map;
}
// @RequestMapping(value = "/stateall")
// @ResponseBody
// public Map<String, String> stateall(String code) {
// Map<String, List<String>> stateMap = Server.stateMap;
// Map<String, String> map = new HashMap<>();
// List<String> list2 = stateMap.get(code);
// if (list2 != null) {
// int temp = 1;
// for (String string : list2) {
// map.put("param" + temp, string);
// temp++;
// }
// }
// return map;
// }
@RequestMapping(value = "/modelinfo")
@ResponseBody
public Map<String, List<String>> modelinfo(String code) {
Map<String, Map> infoMap = Server.infoMap;
Map map = infoMap.get(code);
return map;
}
/**
* @Description: 退费(商户或商户与合伙)数据处理
* @author: origin 创建时间: 2019年9月21日 下午4:07:16
*/
public static Object dealerIncomeRefund(String comment, Integer merid, Double money, String ordernum,
Date time, Integer paysource, Integer paytype, Integer paystatus) {
Integer type = 1;
List<Map<String, Object>> merchlist = new ArrayList<>();
try {
JSONArray jsona = JSONArray.fromObject(comment);
for (int i = 0; i < jsona.size(); i++) {
Map<String, Object> map = new HashMap<>();
JSONObject item = jsona.getJSONObject(i);
Integer partid = CommUtil.toInteger(item.get("partid"));
Integer mercid = CommUtil.toInteger(item.get("merid"));
// String percent = CommUtil.toString(item.get("percent"));
Double partmoney = CommUtil.toDouble(item.get("money"));
if(partid!=0){//合伙人信息
merEearningCalculate( partid, partmoney, type, ordernum, time, paysource, paytype, paystatus);
}else{//商户信息
merEearningCalculate( mercid, partmoney, type, ordernum, time, paysource, paytype, paystatus);
}
map = item;
merchlist.add(map);
}
} catch (Exception e) {
e.printStackTrace();
logger.info(CommUtil.getExceptInfo(e));
}
return JSON.toJSON(merchlist);
}
// ORIGIN
// /**
// * @Description: 收入信息处理
// * @author: origin 创建时间: 2019年9月15日 上午11:44:49
// */
// public static Map<String, Object> partnerIncomeDispose(List<Map<String, Object>> partInfo, Integer merid, Double money, String ordernum,
// Date time, Integer paysource, Integer paytype, Integer paystatus) {
// Double mermoney = 0.00;//商户金额
// Double manmoney = 0.00;//商户金额
// Double tolpercent = 0.00;//分成比
// Map<String, Object> mapresult = new HashMap<>();
// List<Map<String, Object>> merchlist = new ArrayList<>();
// try {
// if(partInfo.size()>0){//分成
// System.out.println("输出分成");
// for(Map<String, Object> item : partInfo){
// Map<String, Object> map = new HashMap<>();
// Integer partid = CommUtil.toInteger(item.get("partid"));
// Double percent = CommUtil.toDouble(item.get("percent"));
// Double partmoney = CommUtil.toDouble((money * (percent*100))/100);
// map.put("partid", partid);
// map.put("percent", percent);
// map.put("money", partmoney);
// merchlist.add(map);
// tolpercent = tolpercent + percent;
// merEearningCalculate( partid, partmoney, 3, ordernum, time, paysource, paytype, paystatus);
// }
// }
// mermoney = CommUtil.toDouble((money *100 * (1- tolpercent))/100);
// manmoney = CommUtil.subBig(money, mermoney);
// logger.info("输出商户收益mermoney "+mermoney+" **** "+manmoney);
// Map<String, Object> map = new HashMap<>();
// map.put("merid", merid);
// map.put("percent", (1-tolpercent));
// map.put("money", mermoney);
// merchlist.add(map);
// merEearningCalculate( merid, mermoney, 3, ordernum, time, paysource, paytype, paystatus);
// mapresult.put("partmoney", manmoney);
// mapresult.put("json", JSON.toJSON(merchlist));
// } catch (Exception e) {
// e.printStackTrace();
// logger.info(CommUtil.getExceptInfo(e));
// }
// return mapresult;
// }
/**
* @Description: 商户收益计算
* @author: origin 创建时间: 2019年9月12日 下午5:54:22
* @return
*/
public static void merEearningCalculate(Integer merid, Double money, Integer type, String ordernum, Date operattime,
Integer paysource, Integer paytype, Integer status){
try {
//查询商户余额
Double merEarnings = CommUtil.toDouble(UserHandler.getUserEarningsById(merid));
//修改商户余额 1:商户收益减少 2:用户钱包金额添加 3:商户收益添加
ChargeRecordHandler.updateUserMoney(money, merid, null, type);
Double nowEarnings = 0.00;
if(merEarnings!=0){
if(type==1){
nowEarnings = (merEarnings * 100 - money * 100) / 100;
}else if(type==3){
nowEarnings = (merEarnings * 100 + money * 100) / 100;
}
}
try {
UserHandler.merAmountRefund(merid, money);
} catch (Exception e) {
logger.warn("修改商户总计表失败-_-");
}
//添加商户余额明细
UserHandler.addMerDetail(merid, ordernum, money, nowEarnings, paysource, paytype, status);
} catch (Exception e) {
e.printStackTrace();
logger.info(CommUtil.getExceptInfo(e));
}
}
}
|
package br.com.volvo.view;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import org.primefaces.context.RequestContext;
import com.google.gson.Gson;
import br.com.volvo.api.data.Department;
@ManagedBean(name = "departmentMB")
@ViewScoped
public class DepartmentMB implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
public List<Department> departments;
public Department departmentSelected;
public Department newDepartment;
public DepartmentMB() {
this.newDepartment = new Department();
this.listDepartments();
}
public void listDepartments() {
try {
Gson gson = new Gson();
departments = new ArrayList<>();
URL url = new URL("http://localhost:8080/jrws/rest/department/list");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
Department[] mcArray = gson.fromJson(br, Department[].class);
departments = new ArrayList<>(Arrays.asList(mcArray));
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void deleteDepartment(long id) {
try {
URL url = new URL("http://localhost:8080/jrws/rest/department/delete/"+id);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
this.listDepartments();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void openEditModal(Department department) {
setDepartmentSelected(department);
setNewDepartment(new Department());
RequestContext context = RequestContext.getCurrentInstance();
context.execute("PF('dlgEditDepartment').show()");
}
public void openCreateModal() {
setNewDepartment(new Department());
setDepartmentSelected(new Department());
RequestContext context = RequestContext.getCurrentInstance();
context.execute("PF('dlgCreateDepartment').show()");
}
public void saveDepartment() {
try {
URL url = new URL("http://localhost:8080/jrws/rest/department/save/"
+newDepartment.getName()+"/"+newDepartment.getDescription());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
this.listDepartments();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void editDepartment() {
try {
URL url = new URL("http://localhost:8080/jrws/rest/department/update/"
+departmentSelected.getId()+"/"+departmentSelected.getName()+"/"+departmentSelected.getDescription());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
this.listDepartments();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public List<Department> getDepartments() {
return departments;
}
public void setDepartments(List<Department> departments) {
this.departments = departments;
}
public Department getDepartmentSelected() {
return departmentSelected;
}
public void setDepartmentSelected(Department departmentSelected) {
this.departmentSelected = departmentSelected;
}
public Department getNewDepartment() {
return newDepartment;
}
public void setNewDepartment(Department newDepartment) {
this.newDepartment = newDepartment;
}
}
|
package com.demo.rewardsprogram.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({ "customerId", "customerName", "totalTransactionAmount", "totalRewardPoints" })
public class TransactionResponse {
@JsonProperty("customerId")
public Long customerId;
@JsonProperty("customerName")
public String customerName;
@JsonProperty("totalTransactionAmount")
public Long totalTransactionAmount;
@JsonProperty("totalRewardPoints")
public Long totalRewardPoints;
public Long getCustomerId() {
return customerId;
}
public void setCustomerId(Long customerId) {
this.customerId = customerId;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public Long getTotalTransactionAmount() {
return totalTransactionAmount;
}
public void setTotalTransactionAmount(Long totalTransactionAmount) {
this.totalTransactionAmount = totalTransactionAmount;
}
public Long getTotalRewardPoints() {
return totalRewardPoints;
}
public void setTotalRewardPoints(Long totalRewardPoints) {
this.totalRewardPoints = totalRewardPoints;
}
}
|
package com.home.gfg.string;
import java.util.ArrayList;
import java.util.List;
/**
* https://leetcode.com/problems/zigzag-conversion/
* how would a string read when printed zigzag vertically over a give number of rows.
* e.g ankushjain printed over 3 rows would be read as asinuhankj
* a s i
* n u h a n
* k j
*/
public class StringWhenConvertedZigZagVertically {
public static String convertZigZagVertically(String str, int numRows)
{
if (numRows == 1) {
return str;
}
boolean goingDown = false;
int currentRow = 0;
List<StringBuilder> rows = new ArrayList<>();
for (int i=0; i < Math.min(numRows, str.length()); i++)
{
rows.add(new StringBuilder());
}
for (char c : str.toCharArray())
{
rows.get(currentRow).append(c);
if (currentRow==0 || currentRow == (numRows - 1))
{
goingDown = !goingDown;
}
currentRow += goingDown ? 1 : -1;
}
StringBuilder retStr = new StringBuilder();
for (StringBuilder strRow : rows) {
retStr.append(strRow.toString());
}
return retStr.toString();
}
}
|
package odeSolver;
import Exceptions.WrongInputException;
public abstract class LinearMultistep extends GLM {
public LinearMultistep(DifferentialEquation diff, String methodName, String methodType, String methodOrder, int s) throws WrongInputException {
super(diff, methodName, methodType, methodOrder, 0, s);
}
public LinearMultistep(DifferentialEquation diff, String methodName, String methodType, String methodOrder) throws WrongInputException {
super(diff, methodName, methodType, methodOrder);
}
}
|
package com.tencent.mm.sandbox.updater;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.jg.EType;
import com.jg.JgClassChecked;
import com.tencent.mm.sdk.platformtools.ao;
@JgClassChecked(author = 20, fComment = "checked", lastDate = "20141015", reviewer = 20, vComment = {EType.RECEIVERCHECK})
final class UpdaterService$a extends BroadcastReceiver {
UpdaterService$a() {
}
public final void onReceive(Context context, Intent intent) {
if (UpdaterService.chl() != null) {
UpdaterService chl = UpdaterService.chl();
boolean isWifi = ao.isWifi(context);
if (chl.sET.size() > 0) {
for (a la : chl.sET.values()) {
la.la(isWifi);
}
}
}
}
}
|
package com.teaman.accessstillwater.base;
/**
* Created by weava on 3/14/16.
*/
public interface ItemCallback<T> {
void onCallback(T item);
}
|
package com.nurhossen.bdjosbnurassignment.view;
import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.opengl.Visibility;
import android.text.Html;
import android.transition.AutoTransition;
import android.transition.TransitionManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.nurhossen.bdjosbnurassignment.R;
import com.nurhossen.bdjosbnurassignment.service.model.Datum;
import java.util.List;
import eightbitlab.com.blurview.BlurView;
import eightbitlab.com.blurview.RenderScriptBlur;
import static android.content.ContentValues.TAG;
class AdapterView extends RecyclerView.Adapter<AdapterView.CustomView> {
private List<Datum> datalist;
private Context context;
public AdapterView(List<Datum> datalist, Context context) {
this.datalist = datalist;
this.context = context;
}
@NonNull
@Override
public CustomView onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.itemview, parent,false);
return new CustomView(view);
}
@Override
public void onBindViewHolder(@NonNull CustomView holder, int position) {
String orvalue = Html.fromHtml(datalist.get(position).getJobDetails().getApplyInstruction()).toString();
Log.d(TAG, "onBindViewHolder: instruction "+orvalue);
holder.tv_see.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(holder.expandable.getVisibility()== View.GONE){
holder.tv_see.setText("See Less");
TransitionManager.beginDelayedTransition(holder.cardView,new AutoTransition());
holder.expandable.setVisibility(View.VISIBLE);
}else{
holder.tv_see.setText("See Details");
TransitionManager.beginDelayedTransition(holder.cardView,new AutoTransition());
holder.expandable.setVisibility(View.GONE);
}
}
});
if(datalist.get(position).getIsFeatured()==true){
final int sdk = android.os.Build.VERSION.SDK_INT;
if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
holder.tv_companyname.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.heightlit_item) );
holder.tv_deadline.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.heightlit_item) );
holder.tv_salary.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.heightlit_item) );
holder.tv_expreance.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.heightlit_item) );
} else {
holder.tv_companyname.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.heightlit_item) );
holder.tv_deadline.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.heightlit_item) );
holder.tv_salary.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.heightlit_item) );
holder.tv_expreance.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.heightlit_item) );
}
}
holder.tv_jobtitle.setText(datalist.get(position).getJobTitle().toString());
holder.tv_companyname.setText(datalist.get(position).getRecruitingCompanySProfile());
Glide.with(context).load(datalist.get(position).getLogo()).into(holder.logoimage);
if(datalist.get(position).getMinExperience()!=null && datalist.get(position).getMaxExperience()!=null){
holder.tv_expreance.setText("Min "+ datalist.get(position).getMinExperience() + " years to max "+datalist.get(position).getMaxExperience() + " years Required ");
}else if(datalist.get(position).getMinExperience()==null && datalist.get(position).getMaxExperience()!=null){
holder.tv_expreance.setText(" max "+datalist.get(position).getMaxExperience() + " years Required ");
}
else if(datalist.get(position).getMinExperience()!=null && datalist.get(position).getMaxExperience()==null){
holder.tv_expreance.setText(" min "+datalist.get(position).getMinExperience() + " years Required ");
}else if(datalist.get(position).getMinExperience()==null && datalist.get(position).getMaxExperience()==null){
holder.tv_expreance.setText("NA");
}
if(!datalist.get(position).getMinSalary().isEmpty() && !datalist.get(position).getMaxSalary().isEmpty()){
holder.tv_salary.setText(datalist.get(position).getMinSalary() +" To "+ datalist.get(position).getMaxSalary()+"TK" );
}
else if(!datalist.get(position).getMinSalary().isEmpty() && datalist.get(position).getMaxSalary().isEmpty()){
holder.tv_salary.setText(datalist.get(position).getMinSalary() + " TK");
}
else if(datalist.get(position).getMinSalary().isEmpty() && !datalist.get(position).getMaxSalary().isEmpty()){
holder.tv_salary.setText(datalist.get(position).getMaxSalary() + " TK");
}else if(datalist.get(position).getMinSalary().isEmpty() && datalist.get(position).getMaxSalary().isEmpty()) {
holder.tv_salary.setText("Negotiable");
}
//String[] separated = orvalue.split(":");
holder.tv_applyinstruction.setText(orvalue);
}
/*private void blurbackground(CustomView holder) {
float radius = 21f;
View decorView = ((Activity) context).getWindow().getDecorView();
//ViewGroup you want to start blur from. Choose root as close to BlurView in hierarchy as possible.
ViewGroup rootView = (ViewGroup) decorView.findViewById(android.R.id.content);
//Set drawable to draw in the beginning of each blurred frame (Optional).
//Can be used in case your layout has a lot of transparent space and your content
//gets kinda lost after after blur is applied.
Drawable windowBackground = decorView.getBackground();
holder.blurView.setupWith(rootView)
.setFrameClearDrawable(windowBackground)
.setBlurAlgorithm(new RenderScriptBlur(context))
.setBlurRadius(radius)
.setBlurAutoUpdate(true)
.setHasFixedTransformationMatrix(true);
}*/
@Override
public int getItemCount() {
return datalist.size();
}
public class CustomView extends RecyclerView.ViewHolder {
TextView tv_jobtitle,tv_companyname, tv_salary,tv_expreancemin, tv_expreancemax, tv_deadline, tv_applyinstruction,tv_see,tv_expreance;
RelativeLayout expandable;
CardView cardView;
LinearLayout lnlyoutid;
ImageView logoimage;
View mview;
public CustomView(@NonNull View itemView) {
super(itemView);
mview = itemView;
tv_jobtitle=itemView.findViewById(R.id.jobtitleid);
tv_companyname=itemView.findViewById(R.id.companynameid);
tv_salary=itemView.findViewById(R.id.salaryid);
// blurView=itemView.findViewById(R.id.blurView);
tv_deadline=itemView.findViewById(R.id.deadlineid);
tv_applyinstruction=itemView.findViewById(R.id.emailid);
logoimage = itemView.findViewById(R.id.img_logoid);
expandable=itemView.findViewById(R.id.expandable);
tv_see=itemView.findViewById(R.id.seeid);
cardView=itemView.findViewById(R.id.cardviewid);
tv_expreance=itemView.findViewById(R.id.minex);
lnlyoutid=itemView.findViewById(R.id.lnlyoutid);
}
}
}
|
package Day08;
import java.util.Scanner;
public class 게시판 {
Scanner scan = new Scanner(System.in);
// 필드
int 번호;
String 제목;
String 내용;
String 작성자;
int 조회수;
// 생성자 : 생성자의 이름은 클래스명과 동일하게 생성
// 1. 빈생성자
public 게시판() {
// TODO Auto-generated constructor stub
}
// 모든 필드를 받는 생성자
public 게시판(int 번호, String 제목, String 작성자, int 조회수) {
this.번호 = 번호; // 인수로 들어온 번호를 현재클래스의 번호에 넣어주기
this.제목 = 제목;
this.내용 = 내용;
this.작성자 = 작성자;
this.조회수 = 조회수;
}
//메소드
//1. 게시물등록
public void 게시물등록() {
System.out.println("----> 게시물 등록");
System.out.println("제목 : "); String 제목 = scan.next();
System.out.println("내용 : "); String 내용 = scan.next();
System.out.println("작성자 : "); String 작성자 = scan.next();
//객체 생성 : 입력값을 생성자의 인수로 넣어주기
// 게시물 번호 : 리스트의 저장된 객체수의 +1
게시판 temp = new 게시판 ( 1, 제목, 내용, 작성자, 0);
// 여러 게시물 관리해주는 리스트에 저장
Day08_2.게시물목록.add(temp);
}
//2. 게시물출력
public void 게시물출력() {
System.out.println(this.번호+"\t"+this.제목+"\t"+this.조회수);
}
//2. 게시물삭제
public void 게시물삭제(int 번호) { // int 보낸 변수를 int로 받기
System.out.println("----> 목재");
}
//3. 게시물조회수 증가
public void 게시물조회수() {
this.조회수 =
}
//4. 해당 게시물 상세보기
public void 게시물보기(int 번호) {
//인수받기
System.out.println("----> 게시물 상세페이지");
System.out.println(" 제목 :" + temp.제목 +"조회수 : " + temp.조회수);
System.out.println("내용" + temp.내용);
}
}
|
package com.facebook.yoga;
public enum YogaJustify {
CENTER,
FLEX_END,
FLEX_START(0),
SPACE_AROUND(0),
SPACE_BETWEEN(0),
SPACE_EVENLY(0);
private final int mIntValue;
static {
CENTER = new YogaJustify("CENTER", 1, 1);
FLEX_END = new YogaJustify("FLEX_END", 2, 2);
SPACE_BETWEEN = new YogaJustify("SPACE_BETWEEN", 3, 3);
SPACE_AROUND = new YogaJustify("SPACE_AROUND", 4, 4);
SPACE_EVENLY = new YogaJustify("SPACE_EVENLY", 5, 5);
$VALUES = new YogaJustify[] { FLEX_START, CENTER, FLEX_END, SPACE_BETWEEN, SPACE_AROUND, SPACE_EVENLY };
}
YogaJustify(int paramInt1) {
this.mIntValue = paramInt1;
}
public static YogaJustify fromInt(int paramInt) {
if (paramInt != 0) {
if (paramInt != 1) {
if (paramInt != 2) {
if (paramInt != 3) {
if (paramInt != 4) {
if (paramInt == 5)
return SPACE_EVENLY;
StringBuilder stringBuilder = new StringBuilder("Unknown enum value: ");
stringBuilder.append(paramInt);
throw new IllegalArgumentException(stringBuilder.toString());
}
return SPACE_AROUND;
}
return SPACE_BETWEEN;
}
return FLEX_END;
}
return CENTER;
}
return FLEX_START;
}
public final int intValue() {
return this.mIntValue;
}
}
/* Location: C:\Users\august\Desktop\tik\df_rn_kit\classes.jar.jar!\com\facebook\yoga\YogaJustify.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
|
package Action.Chapter16;
/**
* Created by apple on 2019/7/28.
*/
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
public class ReflectDemo01 {
public static void main(String args[]) throws Exception{
Class<?> c = null;
c = Class.forName("Action.Chapter16.SimpleBeanOne");
Method toM = c.getMethod("toString");
Annotation an[] = toM.getAnnotations();
for(Annotation a:an){
System.out.println(a);
}
}
}
|
package com.vilio.bms.common;
import com.vilio.bps.common.service.CommonService;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.Resource;
/**
* Created by xiezhilei on 2017/1/12.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring-mybatis.xml"})
public class CommonServiceTest {
private static Logger logger = Logger.getLogger(CommonServiceTest.class);
@Resource
private CommonService iBpsReceiveDataMapper;
@Test
public void testSelectAllDistributors() throws Exception{
}
}
|
package psk.com.mediaplayerdemo.activity;
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.util.ArrayList;
import psk.com.mediaplayerdemo.MusicPlayerApplication;
import psk.com.mediaplayerdemo.R;
import psk.com.mediaplayerdemo.adapter.MantraListAdapter;
import psk.com.mediaplayerdemo.api.ApiCallback;
import psk.com.mediaplayerdemo.api.ApiImplementation;
import psk.com.mediaplayerdemo.callback.OnPermissionGrantedListener;
import psk.com.mediaplayerdemo.callback.OnSongClickListener;
import psk.com.mediaplayerdemo.model.MantraListModel;
import psk.com.mediaplayerdemo.model.MantraModel;
import psk.com.mediaplayerdemo.model.MantraResponseModel;
import psk.com.mediaplayerdemo.service.MediaService;
import psk.com.mediaplayerdemo.utils.Constants;
import psk.com.mediaplayerdemo.utils.Downloader;
import psk.com.mediaplayerdemo.utils.TimeUtils;
import static psk.com.mediaplayerdemo.MusicPlayerApplication.getMantraModelArrayList;
public class MainActivity extends BaseActivity implements OnSongClickListener, View.OnClickListener, OnPermissionGrantedListener {
private MantraListAdapter adapter;
public BroadcastReceiver updateListReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
ArrayList<Integer> changed = intent.getIntegerArrayListExtra(Constants.CHANGED_LIST_EXTRA);
for (int i = 0; i < changed.size(); i++)
adapter.notifyItemChanged(changed.get(i));
}
};
private ImageButton ibPrevious, ibPlayPause, ibNext, ibStop;
private RecyclerView recyclerViewSongs, recyclerViewNewReleases;
private LinearLayout llMediaPlayer;
private TextView tvCurrentDuration, tvTotalDuration;
private SeekBar seekBarDuration;
public BroadcastReceiver updateMediaPlayerReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String status = intent.getStringExtra(Constants.MEDIA_PLAYER_STATUS_EXTRA);
switch (status) {
case Constants.STATUS_PLAYING:
if (llMediaPlayer.getVisibility() == View.GONE) {
llMediaPlayer.setVisibility(View.VISIBLE);
}
int duration = intent.getIntExtra(Constants.DURATION_EXTRA, 0);
seekBarDuration.setMax(duration);
String totalDuration = TimeUtils.getDuration(duration);
tvTotalDuration.setText(totalDuration);
ibPlayPause.setImageDrawable(ContextCompat.getDrawable(MainActivity.this, R.drawable.uamp_ic_pause_white_48dp));
break;
case Constants.STATUS_PAUSED:
ibPlayPause.setImageDrawable(ContextCompat.getDrawable(MainActivity.this, R.drawable.uamp_ic_play_arrow_white_48dp));
break;
case Constants.STATUS_STOPPED:
llMediaPlayer.setVisibility(View.GONE);
break;
}
}
};
public BroadcastReceiver updateSeekBarReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
int duration = intent.getIntExtra(Constants.DURATION_EXTRA, 0);
seekBarDuration.setProgress(duration);
String currentPosition = TimeUtils.getDuration(duration);
tvCurrentDuration.setText(currentPosition);
}
};
private String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
public BroadcastReceiver updateDownloadStatus = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
long downloadedId = intent.getLongExtra(Constants.DOWNLOAD_ID, -1);
ArrayList<MantraModel> mantraModels = MusicPlayerApplication.getMantraModelArrayList();
for (int i = 0; i < mantraModels.size(); i++) {
MantraModel model = mantraModels.get(i);
if (model.getDownloadId() == downloadedId) {
mantraModels.get(i).setDownloadId(-1);
mantraModels.get(i).setDownloaded(true);
String fileName = model.getMantra().substring(model.getMantra().lastIndexOf('/') + 1);
mantraModels.get(i).setMantra(path + File.separator + fileName);
MusicPlayerApplication.setMantraModelArrayList(mantraModels);
adapter.notifyItemChanged(i);
break;
}
}
}
};
private MantraModel currentModel;
private RelativeLayout rlContainer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerViewSongs = (RecyclerView) findViewById(R.id.recyclerViewSongs);
recyclerViewNewReleases = (RecyclerView) findViewById(R.id.recyclerViewNewReleases);
ibPrevious = (ImageButton) findViewById(R.id.ibPrevious);
ibPlayPause = (ImageButton) findViewById(R.id.ibPlayPause);
ibNext = (ImageButton) findViewById(R.id.ibNext);
ibStop = (ImageButton) findViewById(R.id.ibStop);
llMediaPlayer = (LinearLayout) findViewById(R.id.llMediaPlayer);
seekBarDuration = (SeekBar) findViewById(R.id.seekBarDuration);
tvCurrentDuration = (TextView) findViewById(R.id.tvCurrentDuration);
tvTotalDuration = (TextView) findViewById(R.id.tvTotalDuration);
rlContainer= (RelativeLayout) findViewById(R.id.rlContainer);
recyclerViewNewReleases.setLayoutManager(new LinearLayoutManager(MainActivity.this, LinearLayoutManager.HORIZONTAL, false));
setLayoutManager();
ibPrevious.setOnClickListener(this);
ibPlayPause.setOnClickListener(this);
ibNext.setOnClickListener(this);
ibStop.setOnClickListener(this);
seekBarDuration.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
Intent intent = new Intent(MainActivity.this, MediaService.class);
intent.setAction(Constants.ACTION_SEEK);
intent.putExtra(Constants.SEEK_TO_EXTRA, seekBar.getProgress());
startService(intent);
}
});
if (isMediaServiceRunning(MediaService.class)) {
llMediaPlayer.setVisibility(View.VISIBLE);
MantraModel currentModel = MusicPlayerApplication.getCurrentModel();
int duration = currentModel.getDuration();
seekBarDuration.setMax(duration);
String totalDuration = TimeUtils.getDuration(duration);
tvTotalDuration.setText(totalDuration);
recyclerViewSongs.scrollToPosition(getMantraModelArrayList().indexOf(currentModel));
}
ApiImplementation.getApiImplementation().getAllMantras(new ApiCallback<MantraResponseModel<MantraListModel>>() {
@Override
public void onSuccess(MantraResponseModel<MantraListModel> responseModel) {
if (responseModel.isSuccess()) {
ArrayList<MantraModel> mantraModels = responseModel.getData().mantraList;
for (MantraModel model : mantraModels) {
String fileName = model.getMantra().substring(model.getMantra().lastIndexOf('/') + 1);
if (isDownloaded(fileName)) {
mantraModels.get(mantraModels.indexOf(model)).setDownloaded(true);
mantraModels.get(mantraModels.indexOf(model)).setMantra(path + File.separator + fileName);
}
}
MusicPlayerApplication.setMantraModelArrayList(mantraModels);
//adapter = new MantraAdapter(MainActivity.this, getMantraModelArrayList());
adapter = new MantraListAdapter(MainActivity.this, getMantraModelArrayList());
recyclerViewNewReleases.setAdapter(adapter);
recyclerViewSongs.setAdapter(adapter);
} else {
Toast.makeText(getApplicationContext(), responseModel.getError(), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(int statusCode) {
if (statusCode == 0) {
Toast.makeText(getApplicationContext(), "No Internet Connection", Toast.LENGTH_SHORT).show();
}
}
});
checkPermission(null);
}
private void setLayoutManager() {
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
float dpHeight = displayMetrics.heightPixels / displayMetrics.density;
float dpWidth = displayMetrics.widthPixels / displayMetrics.density;
int cardWidth = 120;
int spanCount = (int) (dpWidth / cardWidth);
int rem = (int) (dpWidth % cardWidth);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
params.setMargins(rem / 2, 0, rem / 2, 0);
rlContainer.setLayoutParams(params);
recyclerViewSongs.setLayoutManager(new GridLayoutManager(this, spanCount));
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
setLayoutManager();
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
setLayoutManager();
}
}
@Override
public void onClick(View view) {
int id = view.getId();
Intent intent = new Intent(MainActivity.this, MediaService.class);
switch (id) {
case R.id.ibPrevious:
intent.setAction(Constants.ACTION_PREVIOUS);
startService(intent);
break;
case R.id.ibPlayPause:
intent.putExtra(Constants.IS_FROM_UI_EXTRA, true);
intent.setAction(Constants.ACTION_PLAY);
startService(intent);
break;
case R.id.ibNext:
intent.setAction(Constants.ACTION_NEXT);
startService(intent);
break;
case R.id.ibStop:
intent.setAction(Constants.ACTION_STOP);
startService(intent);
break;
}
}
private boolean isMediaServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
@Override
public void onSongClick(MantraModel model) {
currentModel = model;
checkPermission(this);
}
@Override
public void onPermissionGranted() {
String fileName = currentModel.getMantra().substring(currentModel.getMantra().lastIndexOf('/') + 1);
if (currentModel.isDownloaded()) {
if (currentModel.getDownloadId() != -1)
return;
MantraModel model = MusicPlayerApplication.getCurrentModel();
if (model != null && model.equals(currentModel)) {
return;
}
//model.setMantra(path + File.separator + fileName);
Intent intent = new Intent(MainActivity.this, MediaService.class);
intent.setAction(Constants.ACTION_PLAY);
intent.putExtra(Constants.SONG_MODEL_EXTRA, currentModel);
startService(intent);
} else {
if (currentModel.getDownloadId() != -1)
return;
Downloader downloader = Downloader.getInstance(this);
long downloadId = downloader.download(currentModel.getMantra(), fileName);
currentModel.setDownloadId(downloadId);
ArrayList<MantraModel> mantraModels = getMantraModelArrayList();
int index = mantraModels.indexOf(currentModel);
mantraModels.get(index).setDownloadId(downloadId);
mantraModels.get(index).setDownloading(true);
adapter.notifyItemChanged(index);
}
}
@Override
public void onPermissionDenied() {
}
private boolean isDownloaded(String fileName) {
File directory = new File(path);
File[] files = directory.listFiles();
if (files != null)
for (File file : files) {
if (file.isFile()) {
if (file.getName().equals(fileName))
return true;
}
}
return false;
}
@Override
protected void onResume() {
super.onResume();
LocalBroadcastManager manager = LocalBroadcastManager.getInstance(MainActivity.this);
manager.registerReceiver(updateListReceiver, new IntentFilter(Constants.UPDATE_LIST_INTENT_FILTER_RECEIVER));
manager.registerReceiver(updateMediaPlayerReceiver, new IntentFilter(Constants.UPDATE_MEDIA_PLAYER_RECEIVER));
manager.registerReceiver(updateSeekBarReceiver, new IntentFilter(Constants.UPDATE_SEEK_BAR_RECEIVER));
manager.registerReceiver(updateDownloadStatus, new IntentFilter(Constants.UPDATE_DOWNLOAD_STATUS));
}
@Override
protected void onPause() {
super.onPause();
LocalBroadcastManager manager = LocalBroadcastManager.getInstance(MainActivity.this);
manager.registerReceiver(updateListReceiver, new IntentFilter(Constants.UPDATE_LIST_INTENT_FILTER_RECEIVER));
manager.registerReceiver(updateMediaPlayerReceiver, new IntentFilter(Constants.UPDATE_MEDIA_PLAYER_RECEIVER));
manager.registerReceiver(updateSeekBarReceiver, new IntentFilter(Constants.UPDATE_SEEK_BAR_RECEIVER));
manager.registerReceiver(updateDownloadStatus, new IntentFilter(Constants.UPDATE_DOWNLOAD_STATUS));
}
}
|
/*
* 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 javaapplication1;
public class JavaApplication1 {
public static void main(String[] args) {
int x=20; //en switch solo se trabaja con byte,short,int,char,string
switch(x){
case 4:System.out.println("4");
default:System.out.println("default");
case 8: System.out.println("8");
case 10: System.out.println("10");
}
}
}
|
package mygit.com.git_demo;
/**
* Hello world!
*
*/
public class App
{ int i=10;
public addData(String data) {
System.out.println("the data is"+data);
if(data.equals(Constant.Data_Type)) {
System.out.println("newly added statement.....from Constant class") ;
System.out.println("statement added on 6th july.....for testing"); ;
System.out.println("Error statement added on 6th july.....now...."); ;
System.out.println("newly added statement from remote....on7th,july");
}
public void hello(){
System.out.println("new method added in the remote repo");
}
public String sayHi(){
return "sayinh hi to git world..............................";
}
}
public static void main( String[] args )
{
System.out.println( "Hello World!" );
}
}
|
package com.example.dialog;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import com.example.NoticeCenter;
import com.example.NoticeCenter.OnDataChangedListener;
import com.example.dialogdemo2.R;
public class TabView3 extends MainTabView{
private TextView textView;
public TabView3(Context context) {
super(context);
View v = LayoutInflater.from(context).inflate(R.layout.tab_context3, null, false);
textView = (TextView) v.findViewById(R.id.text);
NoticeCenter.addOnDataChangedListener(new OnDataChangedListener() {
@Override
public void OnDataChanged(String content) {
textView.setText(content);
}
});
this.addView(v, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
}
}
|
package com.company;
import java.util.Random;
public class Magic extends Hero{
@Override
public void applySuperAbility() {
Random random = new Random();
if(random.nextInt(2) == 0){
System.out.println("Маг использовал силу огня");
}else{
System.out.println("Маг использовал силу воды");
}
}
}
|
package com.cse308.sbuify.customer;
import com.cse308.sbuify.artist.Artist;
import com.cse308.sbuify.user.User;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
import java.util.Optional;
public interface FollowedArtistRepository extends CrudRepository<FollowedArtist, Integer> {
Optional<FollowedArtist> findByCustomerAndArtist_Id(User customer, Integer artistId);
@Modifying
void deleteByCustomerAndArtist_Id(User customer, Integer artistId);
boolean existsByCustomerAndArtist_Id(User customer, Integer artistId);
List<FollowedArtist> findAllByCustomer(User customer);
Integer countByCustomerAndArtist(User customer, Artist artist);
}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*/
package de.hybris.platform.variants.interceptor;
import static java.util.Arrays.asList;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import de.hybris.bootstrap.annotations.UnitTest;
import de.hybris.platform.category.model.CategoryModel;
import de.hybris.platform.core.model.product.ProductModel;
import de.hybris.platform.servicelayer.i18n.L10NService;
import de.hybris.platform.servicelayer.interceptor.InterceptorException;
import de.hybris.platform.variants.model.GenericVariantProductModel;
import de.hybris.platform.variants.model.VariantCategoryModel;
import de.hybris.platform.variants.model.VariantValueCategoryModel;
import java.util.Collection;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.Mockito;
@UnitTest
public class GenericVariantProductValidateInterceptorUnitTest
{
@Rule
public final ExpectedException expectedException = ExpectedException.none();
private GenericVariantProductValidateInterceptor interceptor;
private L10NService l10NService;
@Before
public void setUp()
{
l10NService = mock(L10NService.class);
interceptor = new GenericVariantProductValidateInterceptor();
interceptor.setL10NService(l10NService);
}
@Test
public void testValidateBaseProductSuperCategoriesBaseProductIsNull() throws InterceptorException
{
final String errorString = "error.genericvariantproduct.nobaseproduct";
when(l10NService.getLocalizedString(Mockito.contains(errorString), Mockito.any())).thenReturn(errorString);
final GenericVariantProductModel genericVariant = mock(GenericVariantProductModel.class);
when(genericVariant.getCode()).thenReturn("genericVariantCode");
final Collection<CategoryModel> variantValueCategories = asList(mock(CategoryModel.class));
expectedException.expectMessage(errorString);
interceptor.validateBaseProductSuperCategories(genericVariant, variantValueCategories);
}
@Test
public void testValidateBaseProductSuperCategoriesNotMatchingCategorySize() throws InterceptorException
{
final String errorString = "error.genericvariantproduct.nosameamountofvariantcategories";
when(l10NService.getLocalizedString(Mockito.contains(errorString), Mockito.any())).thenReturn(errorString);
final GenericVariantProductModel genericVariant = mock(GenericVariantProductModel.class);
when(genericVariant.getCode()).thenReturn("genericVariantCode");
final ProductModel productModel = mock(ProductModel.class);
when(genericVariant.getBaseProduct()).thenReturn(productModel);
when(productModel.getSupercategories())
.thenReturn(asList(mock(VariantCategoryModel.class), mock(VariantCategoryModel.class)));
final Collection<CategoryModel> variantValueCategories = asList(mock(VariantCategoryModel.class));
// superCategories.size() != variantValueCategories.size()
expectedException.expectMessage(errorString);
interceptor.validateBaseProductSuperCategories(genericVariant, variantValueCategories);
}
@Test
public void testValidateBaseProductSuperCategoriesNotMatchingSupercategories() throws InterceptorException
{
final String errorString = "error.genericvariantproduct.variantcategorynotinbaseproduct";
when(l10NService.getLocalizedString(Mockito.contains(errorString), Mockito.any())).thenReturn(errorString);
final GenericVariantProductModel genericVariant = mock(GenericVariantProductModel.class);
when(genericVariant.getCode()).thenReturn("genericVariantCode");
final ProductModel productModel = mock(ProductModel.class);
when(genericVariant.getBaseProduct()).thenReturn(productModel);
final VariantCategoryModel variantCategoryModel = mock(VariantCategoryModel.class);
when(productModel.getSupercategories()).thenReturn(asList(mock(CategoryModel.class), variantCategoryModel));
final VariantValueCategoryModel variantValueCategoryModel = mock(VariantValueCategoryModel.class);
final Collection<CategoryModel> variantValueCategories = asList(variantValueCategoryModel);
when(variantValueCategoryModel.getSupercategories()).thenReturn(asList(mock(VariantCategoryModel.class)));
// superCategories.size() == variantValueCategories.size()
expectedException.expectMessage(errorString);
interceptor.validateBaseProductSuperCategories(genericVariant, variantValueCategories);
}
@Test
public void testValidateBaseProductSuperCategoriesSupercategoriesOfNonSupportedType() throws InterceptorException
{
final String errorString = "error.genericvariantproduct.nosameamountofvariantcategories";
when(l10NService.getLocalizedString(Mockito.contains(errorString), Mockito.any())).thenReturn(errorString);
final GenericVariantProductModel genericVariant = mock(GenericVariantProductModel.class);
when(genericVariant.getCode()).thenReturn("genericVariantCode");
final ProductModel productModel = mock(ProductModel.class);
when(genericVariant.getBaseProduct()).thenReturn(productModel);
final VariantCategoryModel variantCategoryModel = mock(VariantCategoryModel.class);
when(productModel.getSupercategories()).thenReturn(asList(mock(CategoryModel.class), variantCategoryModel));
final VariantValueCategoryModel variantValueCategoryModel = mock(VariantValueCategoryModel.class);
final Collection<CategoryModel> variantValueCategories = asList(variantValueCategoryModel);
when(variantValueCategoryModel.getSupercategories()).thenReturn(asList(mock(CategoryModel.class)));
expectedException.expectMessage(errorString);
interceptor.validateBaseProductSuperCategories(genericVariant, variantValueCategories);
}
@Test
public void testValidateBaseProductSuperCategoriesOK() throws InterceptorException
{
final GenericVariantProductModel genericVariant = mock(GenericVariantProductModel.class);
when(genericVariant.getCode()).thenReturn("genericVariantCode");
final ProductModel productModel = mock(ProductModel.class);
when(genericVariant.getBaseProduct()).thenReturn(productModel);
final VariantCategoryModel variantCategoryModel = mock(VariantCategoryModel.class);
when(productModel.getSupercategories()).thenReturn(asList(mock(CategoryModel.class), variantCategoryModel));
final VariantValueCategoryModel variantValueCategoryModel = mock(VariantValueCategoryModel.class);
final Collection<CategoryModel> variantValueCategories = asList(variantValueCategoryModel);
when(variantValueCategoryModel.getSupercategories()).thenReturn(asList(variantCategoryModel));
interceptor.validateBaseProductSuperCategories(genericVariant, variantValueCategories);
}
}
|
package com.intuit.maven.extensions.build.scanner.model;
import lombok.NonNull;
import lombok.Value;
@Value
public class ProjectSummary {
@NonNull private final String groupId, artifactId;
private final SessionSummary latestSessionSummary;
public String getId() {
return groupId + ":" + artifactId;
}
}
|
package example.comparableAndComparator;
import java.util.ArrayList;
import java.util.Collections;
class abc implements Comparable<abc> {
int val;
abc(int a){
this.val = a;
}
@Override
public int compareTo(abc o) {
if (this.val > o.val){
return -1;
} else {
return 1;
}
}
}
public class comparablePrac {
public static void main(String[] args) {
ArrayList<abc> a = new ArrayList<>();
for (int i = 10; i < 15; i++) {
a.add(new abc(i));
}
for (abc temp : a) {
System.out.println(temp.val);
}
Collections.sort(a);
for (abc temp : a) {
System.out.println(temp.val);
}
}
}
|
package com.fleet.hessian.consumer.config;
import com.fleet.hessian.provider.service.UserService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.remoting.caucho.HessianProxyFactoryBean;
/**
* @author April Han
*/
@Configuration
public class HessianConfig {
@Bean
public HessianProxyFactoryBean hessianProxyFactoryBean() {
HessianProxyFactoryBean bean = new HessianProxyFactoryBean();
bean.setServiceUrl("http://localhost:8001/user-service");
bean.setServiceInterface(UserService.class);
return bean;
}
}
|
package com.tencent.mm.plugin.remittance.ui;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import com.tencent.mm.plugin.remittance.model.aa;
class RemittanceOSUI$4 implements OnClickListener {
final /* synthetic */ RemittanceOSUI mCX;
final /* synthetic */ aa mCY;
RemittanceOSUI$4(RemittanceOSUI remittanceOSUI, aa aaVar) {
this.mCX = remittanceOSUI;
this.mCY = aaVar;
}
public final void onClick(DialogInterface dialogInterface, int i) {
this.mCX.KB(this.mCY.mxv);
}
}
|
package cd.com.a.daoImpl;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import cd.com.a.dao.ShopDao;
import cd.com.a.model.adminShopParam;
import cd.com.a.model.shopDesignerDto;
import cd.com.a.model.shopDto;
import cd.com.a.model.shopListParam;
import cd.com.a.model.shopPagingParam;
import cd.com.a.model.shopResvDto;
import cd.com.a.model.shopSellerPagingParam;
import cd.com.a.model.shopSellerResvParam;
import cd.com.a.model.shopShowResvParam;
@Repository
public class ShopDaoImpl implements ShopDao {
@Autowired
SqlSession sqlSession;
String ns ="Shop.";
@Override
public boolean addShop(shopDto shop) {
int n = sqlSession.insert(ns+"addShop", shop);
return n>0?true:false;
}
@Override
public List<shopDto> getShopList(shopListParam param) {
List<shopDto> list = sqlSession.selectList(ns +"getShopList", param);
return list;
}
@Override
public List<shopDto> getSellerShopList(int mem_seq) {
List<shopDto> list = sqlSession.selectList(ns +"getSellerShopList", mem_seq);
return list;
}
@Override
public List<shopDesignerDto> getDesigner(int shop_seq) {
List<shopDesignerDto> deslist = sqlSession.selectList(ns+"getDesigner", shop_seq);
return deslist;
}
@Override
public List<shopDesignerDto> getDesignerAll(int shop_seq) {
List<shopDesignerDto> deslist = sqlSession.selectList(ns+"getDesignerAll", shop_seq);
return deslist;
}
@Override
public List<String> getResv(shopResvDto resvDto) {
List<String> list = sqlSession.selectList(ns+"getShopResv", resvDto);
return list;
}
@Override
public shopDto getShopDetail(int shop_seq) {
shopDto dto = sqlSession.selectOne(ns+"getShopDetail", shop_seq);
return dto;
}
@Override
public boolean addDesigner(shopDesignerDto designer) {
int n = sqlSession.insert(ns+"addDesigner", designer);
return n>0?true:false;
}
@Override
public shopDesignerDto getDesignerInfo(int design_seq) {
shopDesignerDto dto = sqlSession.selectOne(ns+"getDesignerInfo2", design_seq);
return dto;
}
@Override
public int resvShop(shopResvDto shopResv) {
int n = sqlSession.insert(ns+"resvShop", shopResv);
System.out.println("============shopDao:"+shopResv.getShop_resv_seq());
int shop_resv_seq = 0;
if(n>0) {
shop_resv_seq = shopResv.getShop_resv_seq();
}
return shop_resv_seq;
}
@Override
public shopResvDto getShopResv(int shop_resv_seq) {
return sqlSession.selectOne(ns+"getShopResvInfo", shop_resv_seq);
}
@Override
public List<shopShowResvParam> showShopResv(shopPagingParam param) {
List<shopShowResvParam> list = sqlSession.selectList(ns+"showShopResv", param);
return list;
}
@Override
public boolean shopModifyAf(shopDto shop) {
int n = sqlSession.update(ns+"shopModifyAf", shop);
return n>0?true:false;
}
@Override
public int checkDesign(shopDesignerDto designer) {
return sqlSession.selectOne(ns+"checkDesign", designer);
}
@Override
public boolean stopDesignAf(shopDesignerDto designer) {
int n = sqlSession.update(ns+"stopDesignAf", designer);
return n>0?true:false;
}
@Override
public boolean playDesignAf(shopDesignerDto designer) {
int n = sqlSession.update(ns+"playDesignAf", designer);
return n>0?true:false;
}
@Override
public boolean delDesignAf(shopDesignerDto designer) {
int n = sqlSession.update(ns+"delDesignAf", designer);
return n>0?true:false;
}
@Override
public shopDesignerDto getDesignerInfo(shopDesignerDto designer) {
return sqlSession.selectOne(ns+"getDesignerInfo", designer);
}
@Override
public boolean designModify(shopDesignerDto designer) {
int n = sqlSession.update(ns+"designModify", designer);
return n>0?true:false;
}
@Override
public boolean shopStopAf(int shop_seq) {
int n = sqlSession.update(ns+"shopStopAf", shop_seq);
return n>0?true:false;
}
@Override
public boolean cancelShopResv(shopResvDto shopresv) {
int n = sqlSession.update(ns+"cancelShopResv", shopresv);
return n>0?true:false;
}
@Override
public int shopCalcelTimeCheck(shopResvDto shopresv) {
return sqlSession.selectOne(ns+"shopCalcelTimeCheck", shopresv);
}
@Override
public int getShopResvCount(int mem_seq) {
return sqlSession.selectOne(ns+"getShopResvCount", mem_seq);
}
@Override
public int getShopCount() {
return sqlSession.selectOne(ns+"getShopCount");
}
@Override
public int getSellerResvCount(shopSellerPagingParam param) {
return sqlSession.selectOne(ns+"getSellerResvCount", param);
}
@Override
public List<shopSellerResvParam> getSellerShopResvList(shopSellerPagingParam param) {
return sqlSession.selectList(ns+"getSellerShopResvList", param);
}
@Override
public shopSellerResvParam getSellerResvDetail(int shop_resv_seq) {
return sqlSession.selectOne(ns+"getSellerShopResvDetail", shop_resv_seq);
}
@Override
public boolean shopResvUpdate(shopResvDto resv) {
int n = sqlSession.update(ns+"shopResvUpdate", resv);
return n>0?true:false;
}
public List<shopDto> adminShopList(adminShopParam param) {
return sqlSession.selectList(ns+"adminShopList", param);
}
@Override
public int adminShopListCount(adminShopParam param) {
return sqlSession.selectOne(ns+"adminShopListCount", param);
}
@Override
public boolean adminShopOk(int shop_seq) {
int n = sqlSession.update(ns+"adminShopOk", shop_seq);
return n>0?true:false;
}
@Override
public boolean adminShopNo(int shop_seq) {
int n = sqlSession.update(ns+"adminShopNo", shop_seq);
return n>0?true:false;
}
@Override
public List<shopShowResvParam> shopShopCancelResv(shopPagingParam param) {
List<shopShowResvParam> list = sqlSession.selectList(ns+"shopResvCancelList", param);
return list;
}
@Override
public int getShopCancelResvCount(int mem_seq) {
return sqlSession.selectOne(ns+"getShopCancelResvCount", mem_seq);
}
public boolean checkDesigner(int shop_seq) {
int result = sqlSession.selectOne(ns+"checkDesigner",shop_seq);
return result>0?true:false;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.